answer
stringlengths
17
10.2M
package me.foxaice.smartlight.fragments.modes.music_mode; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.constraint.ConstraintSet; import android.text.Html; import android.text.Spanned; import android.text.TextUtils; import android.widget.ImageView; import android.widget.TextView; import java.lang.ref.WeakReference; import me.foxaice.smartlight.R; import me.foxaice.smartlight.fragments.modes.ModeBaseView; import me.foxaice.smartlight.fragments.modes.music_mode.model.IMusicInfo; import me.foxaice.smartlight.fragments.modes.music_mode.presenter.IMusicModePresenter; import me.foxaice.smartlight.fragments.modes.music_mode.presenter.MusicModePresenter; import me.foxaice.smartlight.fragments.modes.music_mode.view.IMusicModeView; import me.foxaice.smartlight.fragments.modes.music_mode.waveformview.WaveFormView; public class MusicModeFragment extends ModeBaseView implements IMusicModeView { public static final String TAG = "MUSIC_MODE_FRAGMENT"; private static final String KEY_IS_PLAYING = "KEY_IS_PLAYING"; private static final int REQUEST_CODE = 300; private final IMusicModePresenter mMusicModePresenter = new MusicModePresenter(); private Handler mHandler; private ImageView mPlayStopButtonImage; private TextView mMaxVolumeText; private TextView mMinVolumeText; private TextView mColorModeText; private TextView mCurrentVolumeText; private TextView mCurrentFrequencyText; private WaveFormView mWaveFormView; private ConstraintSet mCacheWaveformVisibleConstraintSet; private ConstraintLayout mRootLayout; private boolean mIsPlaying; private boolean mIsLandscapeOrientation; @SuppressWarnings("deprecation") public static Spanned getColorModeSpannedFromResources(Context context, @IMusicInfo.ColorMode int name) { int stringId; switch (name) { case IMusicInfo.ColorMode.RGBM: stringId = R.string.RGBM; break; case IMusicInfo.ColorMode.GBRY: stringId = R.string.GBRY; break; case IMusicInfo.ColorMode.BRGC: stringId = R.string.BRGC; break; case IMusicInfo.ColorMode.RBGY: stringId = R.string.RBGY; break; case IMusicInfo.ColorMode.GRBC: stringId = R.string.GRBC; break; case IMusicInfo.ColorMode.BGRM: stringId = R.string.BGRM; break; default: throw new IllegalArgumentException("Wrong Color Mode ModeName!"); } String html = context.getString(stringId); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY); } else { return Html.fromHtml(html); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(KEY_IS_PLAYING, mIsPlaying); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mPlayStopButtonImage.performClick(); } } } @Override public void onResume() { super.onResume(); mMusicModePresenter.loadMusicInfoFromPreferences(); } @Override public void onDestroyView() { super.onDestroyView(); mIsPlaying = false; mMusicModePresenter.onTouchStopButton(); mMusicModePresenter.stopExecutorService(); } @Override public void onDetach() { super.onDetach(); mMusicModePresenter.detachView(); } @Override public void onChangedControllerSettings() { mMusicModePresenter.updateControllerSettings(); } @Override public void drawWaveFormView(double[] data, String color, double max, @IMusicInfo.ViewType int viewType) { mWaveFormView.setAudioBufferColor(color); mWaveFormView.setViewType(viewType); if (viewType == IMusicInfo.ViewType.FREQUENCIES) { max = Math.pow(10, max / 10 > 7 ? 7 : max / 10); mWaveFormView.setMax(max); int shift = 2; int newSize = (int) (data.length * .86); double[] temp = new double[newSize - 2 * shift]; for (int i = 0; i < newSize - 2 * shift; i++) { if (i >= temp.length / 2 - 1 - shift) { temp[i] = temp[temp.length - 1 - i]; } else { temp[i] = data[i + shift]; } } mWaveFormView.setAudioBuffer(temp); } else if (viewType == IMusicInfo.ViewType.WAVEFORM) { mWaveFormView.setMax(max * 8); mWaveFormView.setAudioBuffer(data); } } @Override public void setCurrentVolumeText(double value) { mHandler.sendMessage(Message.obtain(mHandler, MusicModeHandler.SET_VOLUME, value)); } @Override public void setFrequencyText(int value) { mHandler.sendMessage(Message.obtain(mHandler, MusicModeHandler.SET_FREQUENCY, value)); } @Override public void setMaxVolumeText(int value) { mMaxVolumeText.setText(getString(R.string.max_volume_threshold, value)); } @Override public void setMinVolumeText(int value) { mMinVolumeText.setText(getString(R.string.min_volume_threshold, value)); } @Override public void setColorModeText(@IMusicInfo.ColorMode int colorMode) { Spanned spans = getColorModeSpannedFromResources(this.getContext(), colorMode); mColorModeText.setText(TextUtils.concat(getString(R.string.color_mode), spans)); } @Override public void setWaveFormVisible(boolean visible) { if (mRootLayout != null) { float density = getResources().getDisplayMetrics().density; if (mCacheWaveformVisibleConstraintSet == null) { mCacheWaveformVisibleConstraintSet = new ConstraintSet(); mCacheWaveformVisibleConstraintSet.clone(mRootLayout); } if (mIsLandscapeOrientation) { if (visible) { mCacheWaveformVisibleConstraintSet.applyTo(mRootLayout); ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone((ConstraintLayout) mPlayStopButtonImage.getParent()); constraintSet.clear(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.BOTTOM); constraintSet.clear(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.RIGHT); constraintSet.connect(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, (int) (8 * density)); constraintSet.connect(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.BOTTOM, R.id.guidelineHorizontal, ConstraintSet.TOP, (int) (8 * density)); constraintSet.clear(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.TOP); constraintSet.clear(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.LEFT); constraintSet.connect(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, (int) (8 * density)); constraintSet.connect(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.TOP, R.id.guidelineHorizontal, ConstraintSet.BOTTOM, (int) (8 * density)); constraintSet.applyTo((ConstraintLayout) mPlayStopButtonImage.getParent()); } else { ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(mCacheWaveformVisibleConstraintSet); constraintSet.clear(R.id.fragment_music_mode_constraint_music_info, ConstraintSet.RIGHT); constraintSet.connect(R.id.fragment_music_mode_constraint_music_info, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT); constraintSet.connect(R.id.fragment_music_mode_constraint_music_info, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); constraintSet.setVerticalBias(R.id.fragment_music_mode_constraint_music_info, 0.25f); constraintSet.constrainMaxWidth(R.id.fragment_music_mode_constraint_music_info, getResources().getDimensionPixelSize(R.dimen.music_info_max_width)); constraintSet.clear(R.id.fragment_music_mode_constraint_buttons); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.TOP, R.id.fragment_music_mode_constraint_music_info, ConstraintSet.BOTTOM); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.LEFT, R.id.fragment_music_mode_constraint_music_info, ConstraintSet.LEFT); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.RIGHT, R.id.fragment_music_mode_constraint_music_info, ConstraintSet.RIGHT); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); constraintSet.setVerticalBias(R.id.fragment_music_mode_constraint_buttons, 0.1f); constraintSet.constrainWidth(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.MATCH_CONSTRAINT); constraintSet.constrainHeight(R.id.fragment_music_mode_constraint_buttons, getResources().getDimensionPixelSize(R.dimen.music_mode_buttons_size)); constraintSet.setVisibility(R.id.fragment_music_mode_waveform, ConstraintSet.GONE); constraintSet.applyTo(mRootLayout); constraintSet.clone((ConstraintLayout) mPlayStopButtonImage.getParent()); constraintSet.clear(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.BOTTOM); constraintSet.clear(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.RIGHT); constraintSet.connect(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, (int) (8 * density)); constraintSet.connect(R.id.fragment_music_mode_image_play_stop_frequency, ConstraintSet.RIGHT, R.id.guidelineVertical, ConstraintSet.LEFT); constraintSet.clear(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.TOP); constraintSet.clear(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.LEFT); constraintSet.connect(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, (int) (8 * density)); constraintSet.connect(R.id.fragment_music_mode_image_settings_frequency, ConstraintSet.LEFT, R.id.guidelineVertical, ConstraintSet.RIGHT); constraintSet.applyTo((ConstraintLayout) mPlayStopButtonImage.getParent()); } } else { if (visible) { mCacheWaveformVisibleConstraintSet.applyTo(mRootLayout); } else { ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(mRootLayout); constraintSet.clear(R.id.fragment_music_mode_constraint_music_info, ConstraintSet.BOTTOM); constraintSet.connect(R.id.fragment_music_mode_constraint_music_info, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); constraintSet.connect(R.id.fragment_music_mode_constraint_music_info, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); constraintSet.setVerticalBias(R.id.fragment_music_mode_constraint_music_info, 0.25f); constraintSet.constrainMaxWidth(R.id.fragment_music_mode_constraint_music_info, getResources().getDimensionPixelSize(R.dimen.music_info_max_width)); constraintSet.clear(R.id.fragment_music_mode_constraint_buttons); constraintSet.constrainWidth(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.MATCH_CONSTRAINT); constraintSet.constrainHeight(R.id.fragment_music_mode_constraint_buttons, getResources().getDimensionPixelSize(R.dimen.music_mode_buttons_size)); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.TOP, R.id.fragment_music_mode_constraint_music_info, ConstraintSet.BOTTOM); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT); constraintSet.connect(R.id.fragment_music_mode_constraint_buttons, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); constraintSet.setVerticalBias(R.id.fragment_music_mode_constraint_buttons, 0.1f); constraintSet.setVisibility(R.id.fragment_music_mode_waveform, ConstraintSet.GONE); constraintSet.applyTo(mRootLayout); } } } } @Override public String[] getBytesColorsFromResources() { return getResources().getStringArray(R.array.bytes_colors); } private static class MusicModeHandler extends Handler { private static final int SET_FREQUENCY = 0x0001; private static final int SET_VOLUME = 0x0002; private final WeakReference<MusicModeFragment> wrFragment; private final String mFrequencyText; private final String mVolumeText; MusicModeHandler(MusicModeFragment fragment) { this.wrFragment = new WeakReference<>(fragment); mFrequencyText = fragment.getString(R.string.frequency_with_param); mVolumeText = fragment.getString(R.string.volume_with_param); } @Override public void handleMessage(Message msg) { MusicModeFragment fragment = wrFragment.get(); if (fragment != null) { if (msg.what == SET_FREQUENCY) { fragment.mCurrentFrequencyText.setText( String.format(mFrequencyText, msg.obj) ); } else if (msg.what == SET_VOLUME) { fragment.mCurrentVolumeText.setText( String.format(mVolumeText, msg.obj) ); } } } } }
package carbon.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; 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.Path; import android.graphics.Point; import android.graphics.PointF; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.FloatRange; import android.support.annotation.NonNull; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewAnimationUtils; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import com.annimon.stream.Stream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import carbon.Carbon; import carbon.R; import carbon.animation.AnimatedView; import carbon.animation.StateAnimator; import carbon.behavior.Behavior; import carbon.component.Component; import carbon.component.ComponentView; import carbon.drawable.ripple.RippleDrawable; import carbon.drawable.ripple.RippleView; import carbon.internal.ElevationComparator; import carbon.internal.PercentLayoutHelper; import carbon.internal.RevealAnimator; import carbon.shadow.Shadow; import carbon.shadow.ShadowGenerator; import carbon.shadow.ShadowShape; import carbon.shadow.ShadowView; import carbon.view.BehaviorView; import carbon.view.InsetView; import carbon.view.MaxSizeView; import carbon.view.RenderingModeView; import carbon.view.RevealView; import carbon.view.RoundedCornersView; import carbon.view.StateAnimatorView; import carbon.view.StrokeView; import carbon.view.TouchMarginView; import carbon.view.TransformationView; import carbon.view.VisibleView; /** * A FrameLayout implementation with support for material features including shadows, ripples, * rounded corners, insets, custom drawing order, touch margins, state animators and others. */ public class FrameLayout extends android.widget.FrameLayout implements ShadowView, RippleView, TouchMarginView, StateAnimatorView, AnimatedView, InsetView, RoundedCornersView, StrokeView, MaxSizeView, RevealView, VisibleView, TransformationView, BehaviorView { private final PercentLayoutHelper percentLayoutHelper = new PercentLayoutHelper(this); private OnTouchListener onDispatchTouchListener; public FrameLayout(Context context) { super(context, null, R.attr.carbon_frameLayoutStyle); initFrameLayout(null, R.attr.carbon_frameLayoutStyle); } public FrameLayout(Context context, AttributeSet attrs) { super(Carbon.getThemedContext(context, attrs, R.styleable.FrameLayout, R.attr.carbon_frameLayoutStyle, R.styleable.FrameLayout_carbon_theme), attrs, R.attr.carbon_frameLayoutStyle); initFrameLayout(attrs, R.attr.carbon_frameLayoutStyle); } public FrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(Carbon.getThemedContext(context, attrs, R.styleable.FrameLayout, defStyleAttr, R.styleable.FrameLayout_carbon_theme), attrs, defStyleAttr); initFrameLayout(attrs, R.attr.carbon_frameLayoutStyle); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public FrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(Carbon.getThemedContext(context, attrs, R.styleable.FrameLayout, defStyleAttr, R.styleable.FrameLayout_carbon_theme), attrs, defStyleAttr, defStyleRes); initFrameLayout(attrs, defStyleAttr); } private static int[] rippleIds = new int[]{ R.styleable.FrameLayout_carbon_rippleColor, R.styleable.FrameLayout_carbon_rippleStyle, R.styleable.FrameLayout_carbon_rippleHotspot, R.styleable.FrameLayout_carbon_rippleRadius }; private static int[] animationIds = new int[]{ R.styleable.FrameLayout_carbon_inAnimation, R.styleable.FrameLayout_carbon_outAnimation }; private static int[] touchMarginIds = new int[]{ R.styleable.FrameLayout_carbon_touchMargin, R.styleable.FrameLayout_carbon_touchMarginLeft, R.styleable.FrameLayout_carbon_touchMarginTop, R.styleable.FrameLayout_carbon_touchMarginRight, R.styleable.FrameLayout_carbon_touchMarginBottom }; private static int[] insetIds = new int[]{ R.styleable.FrameLayout_carbon_inset, R.styleable.FrameLayout_carbon_insetLeft, R.styleable.FrameLayout_carbon_insetTop, R.styleable.FrameLayout_carbon_insetRight, R.styleable.FrameLayout_carbon_insetBottom, R.styleable.FrameLayout_carbon_insetColor }; private static int[] strokeIds = new int[]{ R.styleable.FrameLayout_carbon_stroke, R.styleable.FrameLayout_carbon_strokeWidth }; private static int[] maxSizeIds = new int[]{ R.styleable.FrameLayout_carbon_maxWidth, R.styleable.FrameLayout_carbon_maxHeight, }; private static int[] elevationIds = new int[]{ R.styleable.FrameLayout_carbon_elevation, R.styleable.FrameLayout_carbon_elevationShadowColor }; private void initFrameLayout(AttributeSet attrs, int defStyleAttr) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FrameLayout, defStyleAttr, R.style.carbon_FrameLayout); Carbon.initRippleDrawable(this, a, rippleIds); Carbon.initElevation(this, a, elevationIds); Carbon.initAnimations(this, a, animationIds); Carbon.initTouchMargin(this, a, touchMarginIds); Carbon.initInset(this, a, insetIds); Carbon.initMaxSize(this, a, maxSizeIds); Carbon.initStroke(this, a, strokeIds); setCornerRadius(a.getDimension(R.styleable.FrameLayout_carbon_cornerRadius, 0)); a.recycle(); setChildrenDrawingOrderEnabled(true); setClipToPadding(false); } private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); private boolean drawCalled = false; RevealAnimator revealAnimator; public Point getLocationOnScreen() { int[] outLocation = new int[2]; super.getLocationOnScreen(outLocation); return new Point(outLocation[0], outLocation[1]); } public Point getLocationInWindow() { int[] outLocation = new int[2]; super.getLocationInWindow(outLocation); return new Point(outLocation[0], outLocation[1]); } public Animator createCircularReveal(android.view.View hotspot, float startRadius, float finishRadius) { int[] location = new int[2]; hotspot.getLocationOnScreen(location); int[] myLocation = new int[2]; getLocationOnScreen(myLocation); return createCircularReveal(location[0] - myLocation[0] + hotspot.getWidth() / 2, location[1] - myLocation[1] + hotspot.getHeight() / 2, startRadius, finishRadius); } @Override public Animator createCircularReveal(int x, int y, float startRadius, float finishRadius) { startRadius = Carbon.getRevealRadius(this, x, y, startRadius); finishRadius = Carbon.getRevealRadius(this, x, y, finishRadius); if (Carbon.IS_LOLLIPOP && renderingMode == RenderingMode.Auto) { Animator circularReveal = ViewAnimationUtils.createCircularReveal(this, x, y, startRadius, finishRadius); circularReveal.setDuration(Carbon.getDefaultRevealDuration()); return circularReveal; } else { revealAnimator = new RevealAnimator(x, y, startRadius, finishRadius); revealAnimator.setDuration(Carbon.getDefaultRevealDuration()); revealAnimator.addUpdateListener(animation -> { RevealAnimator reveal = ((RevealAnimator) animation); reveal.radius = (float) reveal.getAnimatedValue(); reveal.mask.reset(); reveal.mask.addCircle(reveal.x, reveal.y, Math.max((Float) reveal.getAnimatedValue(), 1), Path.Direction.CW); postInvalidate(); }); revealAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationCancel(Animator animation) { revealAnimator = null; } @Override public void onAnimationEnd(Animator animation) { revealAnimator = null; } }); return revealAnimator; } } @Override protected void dispatchDraw(@NonNull Canvas canvas) { boolean r = revealAnimator != null && revealAnimator.isRunning(); boolean c = cornerRadius > 0; // draw not called, we have to handle corners here if (isInEditMode() && !drawCalled && (r || c) && getWidth() > 0 && getHeight() > 0) { Bitmap layer = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas layerCanvas = new Canvas(layer); dispatchDrawInternal(layerCanvas); Bitmap mask = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas maskCanvas = new Canvas(mask); Paint maskPaint = new Paint(0xffffffff); maskCanvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), cornerRadius, cornerRadius, maskPaint); for (int x = 0; x < getWidth(); x++) { for (int y = 0; y < getHeight(); y++) { int maskPixel = mask.getPixel(x, y); layer.setPixel(x, y, Color.alpha(maskPixel) > 0 ? layer.getPixel(x, y) : 0); } } canvas.drawBitmap(layer, 0, 0, paint); } else if (!drawCalled && (r || c) && getWidth() > 0 && getHeight() > 0 && (!Carbon.IS_LOLLIPOP || renderingMode == RenderingMode.Software)) { int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG); if (r) { int saveCount2 = canvas.save(Canvas.CLIP_SAVE_FLAG); canvas.clipRect(revealAnimator.x - revealAnimator.radius, revealAnimator.y - revealAnimator.radius, revealAnimator.x + revealAnimator.radius, revealAnimator.y + revealAnimator.radius); dispatchDrawInternal(canvas); canvas.restoreToCount(saveCount2); } else { dispatchDrawInternal(canvas); } paint.setXfermode(Carbon.CLEAR_MODE); if (c) canvas.drawPath(cornersMask, paint); if (r) canvas.drawPath(revealAnimator.mask, paint); paint.setXfermode(null); canvas.restoreToCount(saveCount); } else { dispatchDrawInternal(canvas); } drawCalled = false; } private void dispatchDrawInternal(@NonNull Canvas canvas) { Collections.sort(getViews(), new ElevationComparator()); super.dispatchDraw(canvas); if (stroke != null) drawStroke(canvas); if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Over) rippleDrawable.draw(canvas); if (insetColor != 0) { paint.setColor(insetColor); paint.setAlpha(255); if (insetLeft != 0) canvas.drawRect(0, 0, insetLeft, getHeight(), paint); if (insetTop != 0) canvas.drawRect(0, 0, getWidth(), insetTop, paint); if (insetRight != 0) canvas.drawRect(getWidth() - insetRight, 0, getWidth(), getHeight(), paint); if (insetBottom != 0) canvas.drawRect(0, getHeight() - insetBottom, getWidth(), getHeight(), paint); } } @Override protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) { // TODO: why isShown() returns false after being reattached? if (child instanceof ShadowView && (!Carbon.IS_LOLLIPOP || ((RenderingModeView) child).getRenderingMode() == RenderingMode.Software || ((ShadowView) child).getElevationShadowColor() != null)) { ShadowView shadowView = (ShadowView) child; shadowView.drawShadow(canvas); } if (child instanceof RippleView) { RippleView rippleView = (RippleView) child; RippleDrawable rippleDrawable = rippleView.getRippleDrawable(); if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless) { int saveCount = canvas.save(); canvas.translate(child.getLeft(), child.getTop()); canvas.concat(child.getMatrix()); rippleDrawable.draw(canvas); canvas.restoreToCount(saveCount); } } return super.drawChild(canvas, child, drawingTime); } @Override protected int getChildDrawingOrder(int childCount, int child) { if (views.size() != childCount) getViews(); return indexOfChild(views.get(child)); } protected boolean isTransformedTouchPointInView(float x, float y, View child, PointF outLocalPoint) { final Rect frame = new Rect(); child.getHitRect(frame); return frame.contains((int) x, (int) y); } // corners private float cornerRadius; private Path cornersMask; public float getCornerRadius() { return cornerRadius; } public void setCornerRadius(float cornerRadius) { this.cornerRadius = cornerRadius; if (getWidth() > 0 && getHeight() > 0) updateCorners(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); layoutAnchoredViews(); if (!changed) return; if (getWidth() == 0 || getHeight() == 0) return; updateCorners(); if (rippleDrawable != null) rippleDrawable.setBounds(0, 0, getWidth(), getHeight()); percentLayoutHelper.restoreOriginalParams(); } private void updateCorners() { if (cornerRadius > 0) { cornerRadius = Math.min(cornerRadius, Math.min(getWidth(), getHeight()) / 2.0f); if (Carbon.IS_LOLLIPOP && renderingMode == RenderingMode.Auto) { setClipToOutline(true); setOutlineProvider(ShadowShape.viewOutlineProvider); } else { cornersMask = new Path(); cornersMask.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), cornerRadius, cornerRadius, Path.Direction.CW); cornersMask.setFillType(Path.FillType.INVERSE_WINDING); } } else if (Carbon.IS_LOLLIPOP) { setOutlineProvider(ViewOutlineProvider.BOUNDS); } } public void drawInternal(@NonNull Canvas canvas) { super.draw(canvas); if (stroke != null) drawStroke(canvas); if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Over) rippleDrawable.draw(canvas); } @SuppressLint("MissingSuperCall") @Override public void draw(@NonNull Canvas canvas) { drawCalled = true; boolean r = revealAnimator != null; boolean c = cornerRadius > 0; if (isInEditMode() && (r || c) && getWidth() > 0 && getHeight() > 0) { Bitmap layer = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas layerCanvas = new Canvas(layer); drawInternal(layerCanvas); Bitmap mask = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas maskCanvas = new Canvas(mask); Paint maskPaint = new Paint(0xffffffff); maskCanvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), cornerRadius, cornerRadius, maskPaint); for (int x = 0; x < getWidth(); x++) { for (int y = 0; y < getHeight(); y++) { int maskPixel = mask.getPixel(x, y); layer.setPixel(x, y, Color.alpha(maskPixel) > 0 ? layer.getPixel(x, y) : 0); } } canvas.drawBitmap(layer, 0, 0, paint); } else if ((r || c) && getWidth() > 0 && getHeight() > 0 && (!Carbon.IS_LOLLIPOP || renderingMode == RenderingMode.Software)) { int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG); if (r) { int saveCount2 = canvas.save(Canvas.CLIP_SAVE_FLAG); canvas.clipRect(revealAnimator.x - revealAnimator.radius, revealAnimator.y - revealAnimator.radius, revealAnimator.x + revealAnimator.radius, revealAnimator.y + revealAnimator.radius); drawInternal(canvas); canvas.restoreToCount(saveCount2); } else { drawInternal(canvas); } paint.setXfermode(Carbon.CLEAR_MODE); if (c) canvas.drawPath(cornersMask, paint); if (r) canvas.drawPath(revealAnimator.mask, paint); paint.setXfermode(null); canvas.restoreToCount(saveCount); } else { drawInternal(canvas); } } // ripple private RippleDrawable rippleDrawable; GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float scrollLeftX = distanceX, scrollLeftY = distanceY; for (Behavior b : behaviors) { PointF scrollLeft = b.onScroll(scrollLeftX, scrollLeftY); scrollLeftX = scrollLeft.x; scrollLeftY = scrollLeft.y; } return super.onScroll(e1, e2, distanceX, distanceY); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return super.onFling(e1, e2, velocityX, velocityY); } }); @Override public boolean dispatchTouchEvent(@NonNull MotionEvent event) { if (onDispatchTouchListener != null && onDispatchTouchListener.onTouch(this, event)) return true; if (rippleDrawable != null && event.getAction() == MotionEvent.ACTION_DOWN) rippleDrawable.setHotspot(event.getX(), event.getY()); return gestureDetector.onTouchEvent(event) || super.dispatchTouchEvent(event); } @Override public RippleDrawable getRippleDrawable() { return rippleDrawable; } @Override public void setRippleDrawable(RippleDrawable newRipple) { if (rippleDrawable != null) { rippleDrawable.setCallback(null); if (rippleDrawable.getStyle() == RippleDrawable.Style.Background) super.setBackgroundDrawable(rippleDrawable.getBackground()); } if (newRipple != null) { newRipple.setCallback(this); newRipple.setBounds(0, 0, getWidth(), getHeight()); if (newRipple.getStyle() == RippleDrawable.Style.Background) super.setBackgroundDrawable((Drawable) newRipple); } rippleDrawable = newRipple; } @Override protected boolean verifyDrawable(@NonNull Drawable who) { return super.verifyDrawable(who) || rippleDrawable == who; } @Override public void invalidateDrawable(@NonNull Drawable drawable) { super.invalidateDrawable(drawable); invalidateParentIfNeeded(); } @Override public void invalidate(@NonNull Rect dirty) { super.invalidate(dirty); invalidateParentIfNeeded(); } @Override public void invalidate(int l, int t, int r, int b) { super.invalidate(l, t, r, b); invalidateParentIfNeeded(); } @Override public void invalidate() { super.invalidate(); invalidateParentIfNeeded(); } private void invalidateParentIfNeeded() { if (getParent() == null || !(getParent() instanceof View)) return; if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless) ((View) getParent()).invalidate(); if (getElevation() > 0 || getCornerRadius() > 0) ((View) getParent()).invalidate(); } @Override public void postInvalidateDelayed(long delayMilliseconds) { super.postInvalidateDelayed(delayMilliseconds); postInvalidateParentIfNeededDelayed(delayMilliseconds); } @Override public void postInvalidateDelayed(long delayMilliseconds, int left, int top, int right, int bottom) { super.postInvalidateDelayed(delayMilliseconds, left, top, right, bottom); postInvalidateParentIfNeededDelayed(delayMilliseconds); } private void postInvalidateParentIfNeededDelayed(long delayMilliseconds) { if (getParent() == null || !(getParent() instanceof View)) return; if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless) ((View) getParent()).postInvalidateDelayed(delayMilliseconds); if (getElevation() > 0 || getCornerRadius() > 0) ((View) getParent()).postInvalidateDelayed(delayMilliseconds); } @Override public void setBackground(Drawable background) { setBackgroundDrawable(background); } @Override public void setBackgroundDrawable(Drawable background) { if (background instanceof RippleDrawable) { setRippleDrawable((RippleDrawable) background); return; } if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Background) { rippleDrawable.setCallback(null); rippleDrawable = null; } super.setBackgroundDrawable(background); } // elevation private float elevation = 0; private float translationZ = 0; private Shadow ambientShadow, spotShadow; private ColorStateList shadowColor; private PorterDuffColorFilter shadowColorFilter; private RectF shadowMaskRect = new RectF(); @Override public float getElevation() { return elevation; } @Override public void setElevation(float elevation) { if (Carbon.IS_LOLLIPOP) { if (shadowColor == null && renderingMode == RenderingMode.Auto) { super.setElevation(elevation); super.setTranslationZ(translationZ); } else { super.setElevation(0); super.setTranslationZ(0); } } else if (elevation != this.elevation && getParent() != null) { ((View) getParent()).postInvalidate(); } this.elevation = elevation; } @Override public float getTranslationZ() { return translationZ; } public void setTranslationZ(float translationZ) { if (translationZ == this.translationZ) return; if (Carbon.IS_LOLLIPOP) { if (shadowColor == null && renderingMode == RenderingMode.Auto) { super.setTranslationZ(translationZ); } else { super.setTranslationZ(0); } } else if (translationZ != this.translationZ && getParent() != null) { ((View) getParent()).postInvalidate(); } this.translationZ = translationZ; } @Override public ShadowShape getShadowShape() { if (cornerRadius == getWidth() / 2 && getWidth() == getHeight()) return ShadowShape.CIRCLE; if (cornerRadius > 0) return ShadowShape.ROUND_RECT; return ShadowShape.RECT; } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); } @Override public boolean hasShadow() { return getElevation() + getTranslationZ() >= 0.01f && getWidth() > 0 && getHeight() > 0; } @Override public void drawShadow(Canvas canvas) { float alpha = getAlpha() * Carbon.getDrawableAlpha(getBackground()) / 255.0f * Carbon.getBackgroundTintAlpha(this) / 255.0f; if (alpha == 0) return; if (!hasShadow()) return; float z = getElevation() + getTranslationZ(); if (ambientShadow == null || ambientShadow.elevation != z || ambientShadow.cornerRadius != cornerRadius) { ambientShadow = ShadowGenerator.generateShadow(this, z / getResources().getDisplayMetrics().density / 4); spotShadow = ShadowGenerator.generateShadow(this, z / getResources().getDisplayMetrics().density); } int saveCount = 0; boolean maskShadow = getBackground() != null && alpha != 1; boolean r = revealAnimator != null && revealAnimator.isRunning(); if (maskShadow) { saveCount = canvas.saveLayer(0, 0, canvas.getWidth(), canvas.getHeight(), null, Canvas.ALL_SAVE_FLAG); } else if (r) { saveCount = canvas.saveLayer(0, 0, canvas.getWidth(), canvas.getHeight(), null, Canvas.ALL_SAVE_FLAG); canvas.clipRect( getLeft() + revealAnimator.x - revealAnimator.radius, getTop() + revealAnimator.y - revealAnimator.radius, getLeft() + revealAnimator.x + revealAnimator.radius, getTop() + revealAnimator.y + revealAnimator.radius); } paint.setAlpha((int) (Shadow.ALPHA * alpha)); Matrix matrix = getMatrix(); canvas.save(); canvas.translate(this.getLeft(), this.getTop()); canvas.concat(matrix); ambientShadow.draw(canvas, this, paint, shadowColorFilter); canvas.restore(); canvas.save(); canvas.translate(this.getLeft(), this.getTop() + z / 2); canvas.concat(matrix); spotShadow.draw(canvas, this, paint, shadowColorFilter); canvas.restore(); if (saveCount != 0) { canvas.translate(this.getLeft(), this.getTop()); canvas.concat(matrix); paint.setXfermode(Carbon.CLEAR_MODE); } if (maskShadow) { shadowMaskRect.set(0, 0, getWidth(), getHeight()); canvas.drawRoundRect(shadowMaskRect, cornerRadius, cornerRadius, paint); } if (r) { canvas.drawPath(revealAnimator.mask, paint); } if (saveCount != 0) { canvas.restoreToCount(saveCount); paint.setXfermode(null); } } @Override public void setElevationShadowColor(ColorStateList shadowColor) { this.shadowColor = shadowColor; shadowColorFilter = shadowColor != null ? new PorterDuffColorFilter(shadowColor.getColorForState(getDrawableState(), shadowColor.getDefaultColor()), PorterDuff.Mode.MULTIPLY) : Shadow.DEFAULT_FILTER; setElevation(elevation); setTranslationZ(translationZ); } @Override public void setElevationShadowColor(int color) { shadowColor = ColorStateList.valueOf(color); shadowColorFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY); setElevation(elevation); setTranslationZ(translationZ); } @Override public ColorStateList getElevationShadowColor() { return shadowColor; } // touch margin private Rect touchMargin = new Rect(); @Override public void setTouchMargin(int left, int top, int right, int bottom) { touchMargin.set(left, top, right, bottom); } @Override public void setTouchMarginLeft(int margin) { touchMargin.left = margin; } @Override public void setTouchMarginTop(int margin) { touchMargin.top = margin; } @Override public void setTouchMarginRight(int margin) { touchMargin.right = margin; } @Override public void setTouchMarginBottom(int margin) { touchMargin.bottom = margin; } @Override public Rect getTouchMargin() { return touchMargin; } final RectF tmpHitRect = new RectF(); public void getHitRect(@NonNull Rect outRect) { Matrix matrix = getMatrix(); if (matrix.isIdentity()) { outRect.set(getLeft(), getTop(), getRight(), getBottom()); } else { tmpHitRect.set(0, 0, getWidth(), getHeight()); matrix.mapRect(tmpHitRect); outRect.set((int) tmpHitRect.left + getLeft(), (int) tmpHitRect.top + getTop(), (int) tmpHitRect.right + getLeft(), (int) tmpHitRect.bottom + getTop()); } outRect.left -= touchMargin.left; outRect.top -= touchMargin.top; outRect.right += touchMargin.right; outRect.bottom += touchMargin.bottom; } // state animators private StateAnimator stateAnimator = new StateAnimator(this); @Override public StateAnimator getStateAnimator() { return stateAnimator; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (rippleDrawable != null && rippleDrawable.getStyle() != RippleDrawable.Style.Background) rippleDrawable.setState(getDrawableState()); if (stateAnimator != null) stateAnimator.setState(getDrawableState()); } // animations private Animator inAnim = null, outAnim = null; private Animator animator; public Animator animateVisibility(final int visibility) { if (visibility == View.VISIBLE && (getVisibility() != View.VISIBLE || animator != null)) { if (animator != null) animator.cancel(); if (inAnim != null) { animator = inAnim; animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator a) { a.removeListener(this); animator = null; } @Override public void onAnimationCancel(Animator a) { a.removeListener(this); animator = null; } }); animator.start(); } setVisibility(visibility); } else if (visibility != View.VISIBLE && (getVisibility() == View.VISIBLE || animator != null)) { if (animator != null) animator.cancel(); if (outAnim == null) { setVisibility(visibility); return null; } animator = outAnim; animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator a) { if (((ValueAnimator) a).getAnimatedFraction() == 1) setVisibility(visibility); a.removeListener(this); animator = null; } @Override public void onAnimationCancel(Animator a) { a.removeListener(this); animator = null; } }); animator.start(); } else { setVisibility(visibility); } return animator; } public Animator getAnimator() { return animator; } public Animator getOutAnimator() { return outAnim; } public void setOutAnimator(Animator outAnim) { if (this.outAnim != null) this.outAnim.setTarget(null); this.outAnim = outAnim; if (outAnim != null) outAnim.setTarget(this); } public Animator getInAnimator() { return inAnim; } public void setInAnimator(Animator inAnim) { if (this.inAnim != null) this.inAnim.setTarget(null); this.inAnim = inAnim; if (inAnim != null) inAnim.setTarget(this); } // insets int insetLeft = INSET_NULL, insetTop = INSET_NULL, insetRight = INSET_NULL, insetBottom = INSET_NULL; int insetColor; private OnInsetsChangedListener onInsetsChangedListener; public int getInsetColor() { return insetColor; } public void setInsetColor(int insetsColor) { this.insetColor = insetsColor; } public void setInset(int left, int top, int right, int bottom) { insetLeft = left; insetTop = top; insetRight = right; insetBottom = bottom; } public int getInsetLeft() { return insetLeft; } public void setInsetLeft(int insetLeft) { this.insetLeft = insetLeft; } public int getInsetTop() { return insetTop; } public void setInsetTop(int insetTop) { this.insetTop = insetTop; } public int getInsetRight() { return insetRight; } public void setInsetRight(int insetRight) { this.insetRight = insetRight; } public int getInsetBottom() { return insetBottom; } public void setInsetBottom(int insetBottom) { this.insetBottom = insetBottom; } @Override protected boolean fitSystemWindows(@NonNull Rect insets) { if (insetLeft == INSET_NULL) insetLeft = insets.left; if (insetTop == INSET_NULL) insetTop = insets.top; if (insetRight == INSET_NULL) insetRight = insets.right; if (insetBottom == INSET_NULL) insetBottom = insets.bottom; insets.set(insetLeft, insetTop, insetRight, insetBottom); if (onInsetsChangedListener != null) onInsetsChangedListener.onInsetsChanged(); postInvalidate(); return super.fitSystemWindows(insets); } public void setOnInsetsChangedListener(OnInsetsChangedListener onInsetsChangedListener) { this.onInsetsChangedListener = onInsetsChangedListener; } // ViewGroup utils List<View> views = new ArrayList<>(); public List<View> getViews() { views.clear(); for (int i = 0; i < getChildCount(); i++) views.add(getChildAt(i)); return views; } public void setOnDispatchTouchListener(OnTouchListener onDispatchTouchListener) { this.onDispatchTouchListener = onDispatchTouchListener; } public Component findComponentById(int id) { List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (child instanceof ComponentView && ((ComponentView) child).getComponent().getView().getId() == id) return ((ComponentView) child).getComponent(); if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return null; } public List<Component> findComponentsById(int id) { List<Component> result = new ArrayList<>(); List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (child instanceof ComponentView && ((ComponentView) child).getComponent().getView().getId() == id) result.add(((ComponentView) child).getComponent()); if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return result; } public Component findComponentOfType(Class type) { List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (child instanceof ComponentView && ((ComponentView) child).getComponent().getClass().equals(type)) return ((ComponentView) child).getComponent(); if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return null; } public List<Component> findComponentsOfType(Class type) { List<Component> result = new ArrayList<>(); List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (child instanceof ComponentView && ((ComponentView) child).getComponent().getClass().equals(type)) result.add(((ComponentView) child).getComponent()); if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return result; } public <Type extends View> Type findViewOfType(Class<Type> type) { List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (child.getClass().equals(type)) return (Type) child; if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return null; } public <Type extends View> List<Type> findViewsOfType(Class<Type> type) { List<Type> result = new ArrayList<>(); List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (child.getClass().equals(type)) result.add((Type) child); if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return result; } public List<View> findViewsById(int id) { List<View> result = new ArrayList<>(); List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (child.getId() == id) result.add(child); if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return result; } public List<View> findViewsWithTag(Object tag) { List<View> result = new ArrayList<>(); List<ViewGroup> groups = new ArrayList<>(); groups.add(this); while (!groups.isEmpty()) { ViewGroup group = groups.remove(0); for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); if (tag.equals(child.getTag())) result.add(child); if (child instanceof ViewGroup) groups.add((ViewGroup) child); } } return result; } // stroke private ColorStateList stroke; private float strokeWidth; private Paint strokePaint; private RectF strokeRect; private void drawStroke(Canvas canvas) { strokePaint.setStrokeWidth(strokeWidth * 2); strokePaint.setColor(stroke.getColorForState(getDrawableState(), stroke.getDefaultColor())); strokeRect.set(0, 0, getWidth(), getHeight()); canvas.drawRoundRect(strokeRect, cornerRadius, cornerRadius, strokePaint); } @Override public void setStroke(ColorStateList colorStateList) { stroke = colorStateList; if (stroke == null) return; if (strokePaint == null) { strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); strokePaint.setStyle(Paint.Style.STROKE); strokeRect = new RectF(); } } @Override public void setStroke(int color) { setStroke(ColorStateList.valueOf(color)); } @Override public ColorStateList getStroke() { return stroke; } @Override public void setStrokeWidth(float strokeWidth) { this.strokeWidth = strokeWidth; } @Override public float getStrokeWidth() { return strokeWidth; } // layout params @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(super.generateDefaultLayoutParams()); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } private void layoutAnchoredViews() { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.anchorView != 0) { View anchorView = findViewById(lp.anchorView); if (anchorView != null && anchorView != child) { int left = child.getLeft(); int right = child.getRight(); int top = child.getTop(); int bottom = child.getBottom(); if ((lp.anchorGravity & Gravity.BOTTOM) == Gravity.BOTTOM) { top = anchorView.getBottom() - lp.height / 2; bottom = top + lp.height; } if ((lp.anchorGravity & Gravity.TOP) == Gravity.TOP) { top = anchorView.getTop() - lp.height / 2; bottom = top + lp.height; } if ((GravityCompat.getAbsoluteGravity(lp.anchorGravity, ViewCompat.getLayoutDirection(child)) & Gravity.LEFT) == Gravity.LEFT) { left = anchorView.getLeft() - lp.width / 2; right = left + lp.width; } if ((GravityCompat.getAbsoluteGravity(lp.anchorGravity, ViewCompat.getLayoutDirection(child)) & Gravity.RIGHT) == Gravity.RIGHT) { left = anchorView.getRight() - lp.width / 2; right = left + lp.width; } child.layout(left, top, right, bottom); } } } } } public static class LayoutParams extends android.widget.FrameLayout.LayoutParams implements PercentLayoutHelper.PercentLayoutParams { private PercentLayoutHelper.PercentLayoutInfo percentLayoutInfo; private int anchorView; private int anchorGravity; private RuntimeException delayedException; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); if (gravity <= 0) gravity = GravityCompat.START | Gravity.TOP; TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.FrameLayout_Layout); anchorView = a.getResourceId(R.styleable.FrameLayout_Layout_carbon_anchor, -1); anchorGravity = a.getInt(R.styleable.FrameLayout_Layout_carbon_anchorGravity, -1); a.recycle(); if (delayedException != null) { percentLayoutInfo = PercentLayoutHelper.getPercentLayoutInfo(c, attrs); if ((percentLayoutInfo.widthPercent == -1.0f || percentLayoutInfo.heightPercent == -1.0f) && percentLayoutInfo.aspectRatio == -1 || (percentLayoutInfo.widthPercent == -1.0f && percentLayoutInfo.heightPercent == -1.0f)) throw delayedException; } } public LayoutParams(int w, int h) { super(w, h); if (gravity <= 0) gravity = GravityCompat.START | Gravity.TOP; } /** * {@inheritDoc} */ public LayoutParams(ViewGroup.LayoutParams source) { super(source); if (gravity == 0) gravity = GravityCompat.START | Gravity.TOP; } /** * {@inheritDoc} */ public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); if (gravity == 0) gravity = GravityCompat.START | Gravity.TOP; } public LayoutParams(android.widget.FrameLayout.LayoutParams source) { super((MarginLayoutParams) source); gravity = source.gravity; if (gravity == 0) gravity = GravityCompat.START | Gravity.TOP; } public LayoutParams(LayoutParams source) { super((MarginLayoutParams) source); gravity = source.gravity; if (gravity == 0) gravity = GravityCompat.START | Gravity.TOP; this.anchorView = source.anchorView; this.anchorGravity = source.anchorGravity; percentLayoutInfo = source.percentLayoutInfo; } @Override protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { try { super.setBaseAttributes(a, widthAttr, heightAttr); } catch (RuntimeException e) { delayedException = e; } } @Override public PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo() { if (percentLayoutInfo == null) { percentLayoutInfo = new PercentLayoutHelper.PercentLayoutInfo(); } return percentLayoutInfo; } public int getAnchorGravity() { return anchorGravity; } public void setAnchorGravity(int anchorGravity) { this.anchorGravity = anchorGravity; } public int getAnchorView() { return anchorView; } public void setAnchorView(int anchorView) { this.anchorView = anchorView; } } // maximum width & height int maxWidth = Integer.MAX_VALUE, maxHeight = Integer.MAX_VALUE; @Override public int getMaximumWidth() { return maxWidth; } @Override public void setMaximumWidth(int maxWidth) { this.maxWidth = maxWidth; requestLayout(); } @Override public int getMaximumHeight() { return maxHeight; } @Override public void setMaximumHeight(int maxHeight) { this.maxHeight = maxHeight; requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { percentLayoutHelper.adjustChildren(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (percentLayoutHelper.handleMeasuredStateTooSmall()) super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (getMeasuredWidth() > maxWidth || getMeasuredHeight() > maxHeight) { if (getMeasuredWidth() > maxWidth) widthMeasureSpec = MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.EXACTLY); if (getMeasuredHeight() > maxHeight) heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } // rendering mode private RenderingMode renderingMode = RenderingMode.Auto; @Override public void setRenderingMode(RenderingMode mode) { this.renderingMode = mode; setElevation(elevation); setTranslationZ(translationZ); updateCorners(); } @Override public RenderingMode getRenderingMode() { return renderingMode; } // transformations List<OnTransformationChangedListener> transformationChangedListeners = new ArrayList<>(); public void addOnTransformationChangedListener(OnTransformationChangedListener listener) { transformationChangedListeners.add(listener); } public void removeOnTransformationChangedListener(OnTransformationChangedListener listener) { transformationChangedListeners.remove(listener); } public void clearOnTransformationChangedListeners() { transformationChangedListeners.clear(); } private void fireOnTransformationChangedListener() { if (transformationChangedListeners == null) return; for (OnTransformationChangedListener listener : transformationChangedListeners) listener.onTransformationChanged(); } @Override public void setRotation(float rotation) { super.setRotation(rotation); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setRotationY(float rotationY) { super.setRotationY(rotationY); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setRotationX(float rotationX) { super.setRotationX(rotationX); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setScaleX(float scaleX) { super.setScaleX(scaleX); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setScaleY(float scaleY) { super.setScaleY(scaleY); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setPivotX(float pivotX) { super.setPivotX(pivotX); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setPivotY(float pivotY) { super.setPivotY(pivotY); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setAlpha(@FloatRange(from = 0.0, to = 1.0) float alpha) { super.setAlpha(alpha); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setTranslationX(float translationX) { super.setTranslationX(translationX); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); invalidateParentIfNeeded(); fireOnTransformationChangedListener(); } public void setWidth(int width) { ViewGroup.LayoutParams layoutParams = getLayoutParams(); if (layoutParams == null) { setLayoutParams(new ViewGroup.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT)); } else { layoutParams.width = width; setLayoutParams(layoutParams); } } public void setHeight(int height) { ViewGroup.LayoutParams layoutParams = getLayoutParams(); if (layoutParams == null) { setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, height)); } else { layoutParams.height = height; setLayoutParams(layoutParams); } } public void setSize(int width, int height) { ViewGroup.LayoutParams layoutParams = getLayoutParams(); if (layoutParams == null) { setLayoutParams(new ViewGroup.LayoutParams(width, height)); } else { layoutParams.width = width; layoutParams.height = height; setLayoutParams(layoutParams); } } public void setBounds(int x, int y, int width, int height) { setSize(width, height); setTranslationX(x); setTranslationY(y); } // dependency private List<Behavior> behaviors = new ArrayList<>(); @Override public void addBehavior(Behavior behavior) { behaviors.add(behavior); } @Override public void removeBehavior(Behavior behavior) { behaviors.remove(behavior); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); Stream.of(behaviors).forEach(Behavior::onDetachedFromWindow); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); Stream.of(behaviors).forEach(Behavior::onAttachedToWindow); } }
package cz.wicketstuff.publicexperiments.bandsearch; import static org.junit.Assert.*; import java.util.LinkedList; import java.util.List; import org.hamcrest.CoreMatchers; import org.junit.Test; public class BandSearchTest { private BandSearch search = new BandSearchImpl(); @Test public void complexTest() { List<Relation> relations = new LinkedList<>(); relations.add(new Relation(1, 2)); relations.add(new Relation(2, 3)); relations.add(new Relation(4, 3)); relations.add(new Relation(4, 1)); relations.add(new Relation(2, 1)); relations.add(new Relation(1, 8)); relations.add(new Relation(7, 5)); relations.add(new Relation(5, 6)); relations.add(new Relation(8, 9)); relations.add(new Relation(10, 10)); assertThat(search.findBandsSize(relations), CoreMatchers.hasItems(6, 3)); } @Test public void findBandsSize_1a() { List<Relation> relations = new LinkedList<>(); relations.add(new Relation(1, 2)); assertThat(search.findBandsSize(relations), CoreMatchers.hasItems(2)); } @Test public void findBandsSize_1b() { List<Relation> relations = new LinkedList<>(); relations.add(new Relation(1, 2)); relations.add(new Relation(1, 3)); assertThat(search.findBandsSize(relations), CoreMatchers.hasItems(3)); } @Test public void findBandsSize_1c() { List<Relation> relations = new LinkedList<>(); relations.add(new Relation(1, 2)); relations.add(new Relation(2, 3)); assertThat(search.findBandsSize(relations), CoreMatchers.hasItems(3)); } @Test public void findBandsSize_2a() { List<Relation> relations = new LinkedList<>(); relations.add(new Relation(1, 2)); relations.add(new Relation(2, 3)); relations.add(new Relation(4, 5)); assertThat(search.findBandsSize(relations), CoreMatchers.hasItems(3, 2)); } @Test public void findBandsSize_2b() { List<Relation> relations = new LinkedList<>(); relations.add(new Relation(1, 2)); relations.add(new Relation(2, 3)); relations.add(new Relation(4, 5)); relations.add(new Relation(6, 1)); relations.add(new Relation(7, 5)); assertThat(search.findBandsSize(relations), CoreMatchers.hasItems(4, 3)); } }
/** * DnsUpdate 30.12.2013 * * @author Philipp Haussleiter * */ package controllers; import java.util.regex.Matcher; import java.util.regex.Pattern; import models.DnsEntry; import play.Logger; import play.mvc.Controller; import play.mvc.Result; public class DnsUpdate extends Controller { private static final Pattern PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); public static Result updateIp(String k, String ip) { DnsEntry entry = DnsEntry.find.where().eq("apiKey", k.trim()) .findUnique(); if (ip == null) { ip = getIp(); } if (validate(ip) && entry != null) { entry.update(ip, k); return ok("will update "+entry.toString()+" to " + ip); } return badRequest(); } public static Result update(String k) { return updateIp(k, null); } private static boolean validate(final String ip) { Matcher matcher = PATTERN.matcher(ip); return matcher.matches(); } private static String getIp() { StringBuilder sb = new StringBuilder(); for(String key : request().headers().keySet()) { if(!key.equals("Authorization")) { sb.append(key).append(" = ").append(request().getHeader(key)).append("\n"); } } Logger.info("headers:\n"+sb.toString()); String ip = request().getQueryString("ip") != null ? request().getQueryString("ip") : request().getHeader("X-Forwarded-For") != null ? request().getHeader("X-Forwarded-For") : request().remoteAddress(); return ip; } }
package org.intermine.bio.dataconversion; import junit.framework.TestCase; import java.io.BufferedReader; import java.io.StringReader; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import org.intermine.xml.full.FullParser; import org.intermine.xml.full.FullRenderer; import org.intermine.dataconversion.DataTranslatorTestCase; import org.intermine.dataconversion.MockItemWriter; import org.intermine.dataconversion.FileConverter; public class FlyAtlasConverterTest extends TestCase { private String ENDL = System.getProperty("line.separator"); public FlyAtlasConverterTest(String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); } public void testProcess() throws Exception { String ENDL = System.getProperty("line.separator"); String input = "Oligo\tbrain vs whole fly - T-Test_Change Direction\tBrainMean\tBrainSEM\tBrainCall\tBrain:fly\thead vs whole fly - T-Test_Change Direction\tHeadMean\tHeadSEM\tHeadCall\tHead:fly\tFlyMean\tFlySEM\tFlyCall" + ENDL + "1616608_a_at\tDown\t1016.15\t23.17392572\t4\t0.696947874\tUp\t1874.55\t85.33788237\t4\t1.285699588\t1458\t127.7786302\t4" + ENDL; MockItemWriter itemWriter = new MockItemWriter(new HashMap()); FileConverter converter = new FlyAtlasConverter(itemWriter); converter.process(new StringReader(input)); converter.close(); // uncomment to write out a new target items file //FileWriter fw = new FileWriter(new File("flyatlas_tgt.xml")); //fw.write(FullRenderer.render(itemWriter.getItems())); //fw.close(); System.out.println(DataTranslatorTestCase.printCompareItemSets(new HashSet(getExpectedItems()), itemWriter.getItems())); assertEquals(new HashSet(getExpectedItems()), itemWriter.getItems()); } protected Collection getExpectedItems() throws Exception { return FullParser.parse(getClass().getClassLoader().getResourceAsStream("test/FlyAtlasConverterTest.xml")); } }
package com.tinkerpop.blueprints.util; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Property; import com.tinkerpop.blueprints.Vertex; import java.util.Objects; import java.util.Optional; public class ElementHelper { public static void validateProperty(final String key, final Object value) throws IllegalArgumentException { if (null == value) throw Property.Exceptions.propertyValueCanNotBeNull(); if (null == key) throw Property.Exceptions.propertyKeyCanNotBeNull(); if (key.equals(Property.Key.ID)) throw Property.Exceptions.propertyKeyIdIsReserved(); if (key.equals(Property.Key.LABEL)) throw Property.Exceptions.propertyKeyLabelIsReserved(); if (key.isEmpty()) throw Property.Exceptions.propertyKeyCanNotBeEmpty(); } public static void legalKeyValues(final Object... keyValues) throws IllegalArgumentException { if (keyValues.length % 2 != 0) throw Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo(); for (int i = 0; i < keyValues.length; i = i + 2) { if (!(keyValues[i] instanceof String) && !(keyValues[i] instanceof Property.Key)) throw Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices(); } } /** * Extracts the value of the {@link Property.Key#ID} key from the list of arguments. * * @param keyValues a list of key/value pairs * @return the value associated with {@link Property.Key#ID} */ public static Optional<Object> getIdValue(final Object... keyValues) { for (int i = 0; i < keyValues.length; i = i + 2) { if (keyValues[i].equals(Property.Key.ID)) return Optional.of(keyValues[i + 1]); } return Optional.empty(); } /** * Extracts the value of the {@link Property.Key#LABEL} key from the list of arguments. * * @param keyValues a list of key/value pairs * @return the value associated with {@link Property.Key#LABEL} */ public static Optional<String> getLabelValue(final Object... keyValues) { for (int i = 0; i < keyValues.length; i = i + 2) { if (keyValues[i].equals(Property.Key.LABEL)) return Optional.of(keyValues[i + 1].toString()); } return Optional.empty(); } public static void attachKeyValues(final Element element, final Object... keyValues) { for (int i = 0; i < keyValues.length; i = i + 2) { if (!keyValues[i].equals(Property.Key.ID) && !keyValues[i].equals(Property.Key.LABEL)) { element.setProperty(keyValues[i].toString(), keyValues[i + 1]); } } } /** * A standard method for determining if two elements are equal. This method should be used by any * {@link Object#equals(Object)} implementation to ensure consistent behavior. * * @param a The first {@link Element} * @param b The second {@link Element} (as an {@link Object}) * @return true if elements and equal and false otherwise */ public static boolean areEqual(final Element a, final Object b) { Objects.requireNonNull(a); Objects.requireNonNull(b); if (a == b) return true; if (!((a instanceof Vertex && b instanceof Vertex) || (a instanceof Edge && b instanceof Edge))) return false; return a.getId().equals(((Element) b).getId()); } /** * Simply tests if the value returned from {@link com.tinkerpop.blueprints.Element#getId()} are {@code equal()}. * * @param a the first {@link Element} * @param b the second {@link Element} * @return true if ids are equal and false otherwise */ public static boolean haveEqualIds(final Element a, final Element b) { return a.getId().equals(b.getId()); } public static boolean areEqual(final Property a, final Object b) { Objects.requireNonNull(a); Objects.requireNonNull(b); if (a == b) return true; if (!(b instanceof Property)) return false; if (!a.isPresent() && !((Property) b).isPresent()) return true; if (!a.isPresent() && ((Property) b).isPresent() || a.isPresent() && !((Property) b).isPresent()) return false; return a.getKey().equals(((Property) b).getKey()) && a.get().equals(((Property) b).get()) && areEqual(a.getElement(), ((Property) b).getElement()); } }
package com.example.e4.rcp.todo.model; public interface TodoRestUriConstants { public static final String GET_todo = "/rest/todo/"; public static final String GET_ALL_TODOS = "/rest/todos/"; public static final String SAVE_todo = "/rest/todo/save/"; public static final String DELETE_todo = "/rest/todo/delete/{id}"; }
package org.gluu.service.custom.script; import com.google.common.base.Optional; import org.gluu.model.custom.script.CustomScriptType; import org.gluu.model.custom.script.model.CustomScript; import org.gluu.persist.PersistenceEntryManager; import org.gluu.search.filter.Filter; import org.gluu.util.OxConstants; import org.slf4j.Logger; import javax.inject.Inject; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public abstract class AbstractCustomScriptService implements Serializable { private static final long serialVersionUID = -6187179012715072064L; @Inject protected Logger log; @Inject protected PersistenceEntryManager persistenceEntryManager; public void add(CustomScript customScript) { persistenceEntryManager.persist(customScript); } public void update(CustomScript customScript) { persistenceEntryManager.merge(customScript); } public void remove(CustomScript customScript) { persistenceEntryManager.remove(customScript); } public CustomScript getCustomScriptByDn(String customScriptDn, String... returnAttributes) { return persistenceEntryManager.find(customScriptDn, CustomScript.class, returnAttributes); } public CustomScript getCustomScriptByDn(Class<?> customScriptType, String customScriptDn) { return (CustomScript) persistenceEntryManager.find(customScriptType, customScriptDn); } public Optional<CustomScript> getCustomScriptByINum(String baseDn, String inum, String... returnAttributes) { final List<Filter> customScriptTypeFilters = new ArrayList<Filter>(); final Filter customScriptTypeFilter = Filter.createEqualityFilter("inum", inum); customScriptTypeFilters.add(customScriptTypeFilter); final Filter filter = Filter.createORFilter(customScriptTypeFilters); final List<CustomScript> result = persistenceEntryManager.findEntries(baseDn, CustomScript.class, filter, returnAttributes); if (result.isEmpty()) { return Optional.absent(); } return Optional.of(result.get(0)); } public List<CustomScript> findAllCustomScripts(String[] returnAttributes) { String baseDn = baseDn(); List<CustomScript> result = persistenceEntryManager.findEntries(baseDn, CustomScript.class, null, returnAttributes); return result; } public List<CustomScript> findCustomScripts(List<CustomScriptType> customScriptTypes, String... returnAttributes) { String baseDn = baseDn(); if ((customScriptTypes == null) || (customScriptTypes.size() == 0)) { return findAllCustomScripts(returnAttributes); } List<Filter> customScriptTypeFilters = new ArrayList<Filter>(); for (CustomScriptType customScriptType : customScriptTypes) { Filter customScriptTypeFilter = Filter.createEqualityFilter("oxScriptType", customScriptType.getValue()); customScriptTypeFilters.add(customScriptTypeFilter); } Filter filter = Filter.createORFilter(customScriptTypeFilters); List<CustomScript> result = persistenceEntryManager.findEntries(baseDn, CustomScript.class, filter, returnAttributes); return result; } public CustomScript getScriptByInum(String inum) { return persistenceEntryManager.find(CustomScript.class, buildDn(inum)); } public List<CustomScript> findCustomAuthScripts(String pattern, int sizeLimit) { String[] targetArray = new String[]{pattern}; Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null); Filter scriptTypeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION); Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null); Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, Filter.createANDFilter(searchFilter, scriptTypeFilter), sizeLimit); } public List<CustomScript> findCustomAuthScripts(int sizeLimit) { Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION.getValue()); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, searchFilter, sizeLimit); } public CustomScript getScriptByDisplayName(String name) { Filter searchFilter = Filter.createEqualityFilter("displayName", name); List<CustomScript> result=persistenceEntryManager.findEntries(baseDn(), CustomScript.class, searchFilter, 1); if(result!=null && !result.isEmpty()){ return result.get(0); } return null; } public int getScriptLevel(CustomScript customScript) { if(customScript!=null){ return customScript.getLevel(); } return -2; } public List<CustomScript> findOtherCustomScripts(String pattern, int sizeLimit) { String[] targetArray = new String[]{pattern}; Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null); Filter scriptTypeFilter = Filter.createNOTFilter( Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION)); Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null); Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, Filter.createANDFilter(searchFilter, scriptTypeFilter), sizeLimit); } public List<CustomScript> findScriptByType(CustomScriptType type, int sizeLimit) { Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, searchFilter, sizeLimit); } public List<CustomScript> findScriptByType(CustomScriptType type) { Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, searchFilter, null); } public List<CustomScript> findScriptByPatternAndType(String pattern, CustomScriptType type, int sizeLimit) { String[] targetArray = new String[]{pattern}; Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null); Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null); Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter); Filter typeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, Filter.createANDFilter(searchFilter, typeFilter), sizeLimit); } public List<CustomScript> findScriptByPatternAndType(String pattern, CustomScriptType type) { String[] targetArray = new String[]{pattern}; Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null); Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null); Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter); Filter typeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, Filter.createANDFilter(searchFilter, typeFilter), null); } public List<CustomScript> findOtherCustomScripts(int sizeLimit) { Filter searchFilter = Filter.createNOTFilter( Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION)); return persistenceEntryManager.findEntries(baseDn(), CustomScript.class, searchFilter, sizeLimit); } public String buildDn(String customScriptId) { final StringBuilder dn = new StringBuilder(); dn.append(String.format("inum=%s,", customScriptId)); dn.append(baseDn()); return dn.toString(); } public abstract String baseDn(); }
// AnimatorOptionsPlugin.java package imagej.core.plugins.axispos; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import net.imglib2.img.Axes; import net.imglib2.img.Axis; import imagej.ImageJ; import imagej.data.Dataset; import imagej.display.DisplayService; import imagej.display.ImageDisplay; import imagej.ext.module.DefaultModuleItem; import imagej.ext.plugin.DynamicPlugin; import imagej.ext.plugin.Menu; import imagej.ext.plugin.Plugin; /** * This class manipulates options that affect the {@link Animator} class' * run() method. * * @author Barry DeZonia */ @Plugin(menu = { @Menu(label = "Image", mnemonic = 'i'), @Menu(label = "Stacks", mnemonic = 's'), @Menu(label = "Tools", mnemonic = 't'), @Menu(label = "Animation Options...") }) public class AnimatorOptionsPlugin extends DynamicPlugin { // -- private constants -- private static final String NAME_KEY = "Axis"; private static final String FIRST_POS_KEY = "First position"; private static final String LAST_POS_KEY = "Last position"; private static final String FPS_KEY = "Speed (0.1 - 1000 fps)"; private static final String BACK_FORTH_KEY = "Loop back and forth"; // -- instance variables -- private ImageDisplay currDisplay; private Dataset dataset; String axisName; private long oneBasedFirst; private long oneBasedLast; private long first; private long last; private double fps; private boolean backForth; private AnimatorOptions options; /** * construct the DynamicPlugin from a Display's Dataset */ public AnimatorOptionsPlugin() { // make sure input is okay final DisplayService displayService = ImageJ.get(DisplayService.class); currDisplay = displayService.getActiveImageDisplay(); if (currDisplay == null) return; dataset = ImageJ.get(DisplayService.class).getActiveDataset(currDisplay); if (dataset == null) return; if (dataset.getImgPlus().numDimensions() <= 2) return; options = Animator.getOptions(currDisplay); // axis name field initialization final DefaultModuleItem<String> name = new DefaultModuleItem<String>(this, NAME_KEY, String.class); final List<Axis> datasetAxes = Arrays.asList(dataset.getAxes()); final ArrayList<String> choices = new ArrayList<String>(); for (final Axis candidateAxis : Axes.values()) { if ((candidateAxis == Axes.X) || (candidateAxis == Axes.Y)) continue; if (datasetAxes.contains(candidateAxis)) choices.add(candidateAxis.getLabel()); } name.setChoices(choices); name.setPersisted(false); addInput(name); setInput(NAME_KEY, new String(options.axis.getLabel())); // first position field initialization final DefaultModuleItem<Long> firstPos = new DefaultModuleItem<Long>(this, FIRST_POS_KEY, Long.class); firstPos.setPersisted(false); firstPos.setMinimumValue(1L); // TODO - can't set max value as it varies based upon the axis the user // selects at dialog run time. Need a callback that can manipulate the // field's max value from chosen axis max. //firstPos.setMaximumValue(new Long(options.total)); addInput(firstPos); setInput(FIRST_POS_KEY, new Long(options.first+1)); // last position field initialization final DefaultModuleItem<Long> lastPos = new DefaultModuleItem<Long>(this, LAST_POS_KEY, Long.class); lastPos.setPersisted(false); lastPos.setMinimumValue(1L); // TODO - can't set max value as it varies based upon the axis the user // selects at dialog run time. Need a callback that can manipulate the // field's max value from chosen axis max. //lastPos.setMaximumValue(new Long(options.total)); addInput(lastPos); setInput(LAST_POS_KEY, new Long(options.last+1)); // frames per second field initialization final DefaultModuleItem<Double> framesPerSec = new DefaultModuleItem<Double>(this, FPS_KEY, Double.class); framesPerSec.setPersisted(false); framesPerSec.setMinimumValue(0.1); framesPerSec.setMaximumValue(1000.0); addInput(framesPerSec); setInput(FPS_KEY, new Double(options.fps)); // back and forth field initialization final DefaultModuleItem<Boolean> backForthBool = new DefaultModuleItem<Boolean>(this, BACK_FORTH_KEY, Boolean.class); backForthBool.setPersisted(false); addInput(backForthBool); setInput(BACK_FORTH_KEY, new Boolean(options.backAndForth)); } /** * Harvests the input values from the user and updates the current * display's set of animation options. Each display has it's own set * of options. Any animation launched on a display will use it's set * of options. Options can be changed during the run of an animation. */ @Override public void run() { if (currDisplay == null) return; harvestInputs(); Axis axis = Axes.get(axisName); final int axisIndex = dataset.getImgPlus().getAxisIndex(axis); if (axisIndex < 0) return; final long totalHyperplanes = dataset.getImgPlus().dimension(axisIndex); setFirstAndLast(totalHyperplanes); options.axis = axis; options.backAndForth = backForth; options.first = first; options.last = last; options.fps = fps; options.total = totalHyperplanes; Animator.optionsUpdated(currDisplay); } // -- private helpers -- /** * Harvest the user's input values from the dialog */ private void harvestInputs() { final Map<String, Object> inputs = getInputs(); axisName = (String) inputs.get(NAME_KEY); oneBasedFirst = (Long) inputs.get(FIRST_POS_KEY); oneBasedLast = (Long) inputs.get(LAST_POS_KEY); fps = (Double) inputs.get(FPS_KEY); backForth = (Boolean) inputs.get(BACK_FORTH_KEY); } /** * Sets the zero-based indices of the first and last frames */ private void setFirstAndLast(final long totalHyperplanes) { first = Math.min(oneBasedFirst, oneBasedLast) - 1; last = Math.max(oneBasedFirst, oneBasedLast) - 1; if (first < 0) first = 0; if (last < 0) last = 0; if (first >= totalHyperplanes) first = totalHyperplanes-1; if (last >= totalHyperplanes) last = totalHyperplanes-1; } }
package io.cloudslang.content.microsoftAD.services; import io.cloudslang.content.microsoftAD.entities.AzureActiveDirectoryCommonInputs; import io.cloudslang.content.microsoftAD.entities.GetUserInputs; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustAllStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.swing.text.html.parser.Entity; import java.io.File; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import static io.cloudslang.content.constants.OutputNames.RETURN_RESULT; import static io.cloudslang.content.microsoftAD.utils.Constants.*; import static org.apache.commons.lang3.StringUtils.EMPTY; public class HttpCommons { private static HostnameVerifier x509HostnameVerifier(String hostnameVerifier) { String x509HostnameVerifierStr = hostnameVerifier.toLowerCase(); HostnameVerifier x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; switch (x509HostnameVerifierStr) { case "strict": x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; break; case "browser_compatible": x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; break; case "allow_all": x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; break; } return x509HostnameVerifier; } public static void setSSLContext(HttpClientBuilder httpClientBuilder, AzureActiveDirectoryCommonInputs commonInputs) { HostnameVerifier hostnameVerifier = x509HostnameVerifier(commonInputs.getX509HostnameVerifier()); if (commonInputs.getTrustAllRoots().equals(BOOLEAN_TRUE)) { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustAllStrategy()).build(); //SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, commonInputs.getTLSVersion,commonInputs.getCipherSuites,hostnameVerifier); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpClientBuilder.setSSLSocketFactory(socketFactory); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } } else { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial( new File(commonInputs.getTrustKeystore()), commonInputs.getTrustPassword().toCharArray()).build(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); //SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, commonInputs.getTLSVersion,commonInputs.getCipherSuites,hostnameVerifier); httpClientBuilder.setSSLSocketFactory(socketFactory); } catch (Exception e) { throw new RuntimeException(e); } } } public static void setProxy(HttpClientBuilder httpClientBuilder, AzureActiveDirectoryCommonInputs commonInputs) { if (commonInputs.getProxyHost().equals(EMPTY)) return; try { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(commonInputs.getProxyHost(), Integer.parseInt(commonInputs.getProxyPort())), new UsernamePasswordCredentials(commonInputs.getProxyUsername(), commonInputs.getProxyPassword())); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setProxy(new HttpHost(commonInputs.getProxyHost(), Integer.parseInt(commonInputs.getProxyPort()))); } catch (NumberFormatException e) { throw new RuntimeException(e); } } public static void setTimeout(HttpClientBuilder httpClientBuilder, AzureActiveDirectoryCommonInputs commonInputs) { if (commonInputs.getKeepAlive().equals(BOOLEAN_TRUE)) httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); try { //Timeout is specified in millis in the javadoc RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(Integer.parseInt(commonInputs.getConnectTimeout()) * 1000) .setSocketTimeout(Integer.parseInt(commonInputs.getSocketTimeout()) * 1000) .build(); httpClientBuilder.setDefaultRequestConfig(requestConfig); } catch (NumberFormatException e) { throw new RuntimeException(e); } } public static void setMaxConnections(HttpClientBuilder httpClientBuilder, AzureActiveDirectoryCommonInputs commonInputs) { try { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(Integer.parseInt(commonInputs.getConnectionsMaxTotal())); connectionManager.setDefaultMaxPerRoute(Integer.parseInt(commonInputs.getConnectionsMaxPerRoute())); httpClientBuilder.setConnectionManager(connectionManager); } catch (NumberFormatException e) { throw new RuntimeException(e); } } public static HttpClient createHttpClient(AzureActiveDirectoryCommonInputs commonInputs) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); setProxy(httpClientBuilder, commonInputs); setSSLContext(httpClientBuilder, commonInputs); setTimeout(httpClientBuilder, commonInputs); setMaxConnections(httpClientBuilder, commonInputs); return httpClientBuilder.build(); } public static Map<String, String> httpPost(AzureActiveDirectoryCommonInputs commonInputs, String url, String body) { Map<String, String> result = new HashMap<>(); try (CloseableHttpClient httpClient = (CloseableHttpClient) createHttpClient(commonInputs)) { HttpPost httpPost = new HttpPost(url); httpPost.setHeader(HttpHeaders.AUTHORIZATION, BEARER + commonInputs.getAuthToken()); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); StringEntity stringEntity = new StringEntity(body,UTF8); stringEntity.setContentType(APPLICATION_JSON); httpPost.setEntity(stringEntity); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { result.put(STATUS_CODE, response.getStatusLine().getStatusCode() + EMPTY); result.put(RETURN_RESULT, EntityUtils.toString(response.getEntity(), commonInputs.getResponseCharacterSet())); return result; } } catch (IOException e) { result.put(STATUS_CODE, EMPTY); result.put(RETURN_RESULT, e.toString()); //e.getMessage returns incomplete exception return result; } } public static Map<String, String> httpDelete(AzureActiveDirectoryCommonInputs commonInputs, String url) { Map<String, String> result = new HashMap<>(); result.put(STATUS_CODE, EMPTY); result.put(RETURN_RESULT, EMPTY); try (CloseableHttpClient httpClient = (CloseableHttpClient) createHttpClient(commonInputs)) { HttpDelete httpDelete = new HttpDelete(url); httpDelete.setHeader(HttpHeaders.AUTHORIZATION, BEARER + commonInputs.getAuthToken()); httpDelete.setHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); try (CloseableHttpResponse response = httpClient.execute(httpDelete)) { result.put(STATUS_CODE, response.getStatusLine().getStatusCode() + EMPTY); //if status code is 204, no return result is provided, otherwise there is a return result int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode > 300) result.put(RETURN_RESULT, EntityUtils.toString(response.getEntity(), commonInputs.getResponseCharacterSet())); return result; } } catch (IOException e) { result.put(STATUS_CODE, EMPTY); result.put(RETURN_RESULT, e.toString()); //e.getMessage returns incomplete exception return result; } } public static Map<String, String> httpGet(GetUserInputs getUserInputsInputs, String url) { Map<String, String> result = new HashMap<>(); result.put(STATUS_CODE, EMPTY); result.put(RETURN_RESULT, EMPTY); try (CloseableHttpClient httpClient = (CloseableHttpClient) createHttpClient(getUserInputsInputs.getCommonInputs())) { HttpGet httpGet = new HttpGet(url); httpGet.setHeader(HttpHeaders.AUTHORIZATION, BEARER + getUserInputsInputs.getCommonInputs().getAuthToken()); httpGet.setHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { result.put(STATUS_CODE, response.getStatusLine().getStatusCode() + EMPTY); result.put(RETURN_RESULT, EntityUtils.toString(response.getEntity(), getUserInputsInputs.getCommonInputs().getResponseCharacterSet())); return result; } } catch (IOException e) { result.put(STATUS_CODE, EMPTY); result.put(RETURN_RESULT, e.toString()); //e.getMessage returns incomplete exception return result; } } }
package io.cloudslang.content.actions; import io.cloudslang.content.entities.WSManRequestInputs; import io.cloudslang.content.services.PowerShellScriptService; import io.cloudslang.content.services.WSManRemoteShellService; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.xpath.XPathExpressionException; import java.io.IOException; import java.net.URISyntaxException; import java.util.Map; import java.util.concurrent.TimeoutException; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.*; import static org.mockito.Mockito.doThrow; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PrepareForTest(PowerShellScriptAction.class) public class PowerShellScriptActionTest { private static final String LOCALHOST = "localhost"; private static final String PORT = "5986"; private static final String HTTPS = "https"; private static final String USER = "user"; private static final String PROXY_HOST = "proxy1"; private static final String PROXY_PORT = "8081"; private static final String PROXY_USER = "proxyUser"; private static final String X_509_HOSTNAME_VERIFIER_STRICT = "strict"; private static final String TRUST_KEYSTORE = "trustKeystorePath"; private static final String PASS = "pass"; private static final String KEYSTORE = "keystorePath"; private static final String MAX_ENVELOPE_SIZE = "153600"; private static final String SCRIPT = "Get-Host"; private static final String MODULES = "Storage"; private static final String WINRM_LOCALE_EN_US = "en-US"; private static final String OPERATION_TIMEOUT = "60"; private static final String RETURN_CODE = "returnCode"; private static final String RETURN_CODE_SUCCESS = "0"; private static final String SCRIPT_EXIT_CODE = "scriptExitCode"; private static final String EMPTY_STRING = ""; private static final String EXCEPTION_MESSAGE = "exceptionMessage"; private static final String EXCEPTION = "exception"; private static final String RETURN_CODE_FAILURE = "-1"; private static final String BASIC_AUTH_TYPE = "Basic"; private static final String KERBEROS_CONF_FILE = "/kerberosConfFile"; private static final String KERBEROS_LOGIN_CONF_FILE = "/kerberosLoginConfFile"; private static final String KERBEROS_SKIP_PORT_FOR_LOOKUP = "true"; private PowerShellScriptAction powerShellScriptAction; @Mock private PowerShellScriptService serviceMock; @Mock private Map<String, String> resultMock; @Mock private WSManRequestInputs wsManRequestInputsMock; @Mock private WSManRequestInputs.WSManRequestInputsBuilder wsManRequestInputsBuilderMock; @Before public void setUp() { powerShellScriptAction = new PowerShellScriptAction(); } @After public void tearDown() { powerShellScriptAction = null; serviceMock = null; resultMock = null; wsManRequestInputsMock = null; wsManRequestInputsBuilderMock = null; } @Test public void testExecute() throws Exception { configureMocksForSuccessTests(); Map<String, String> result = powerShellScriptAction.execute(LOCALHOST, PORT, HTTPS, USER, PASS, BASIC_AUTH_TYPE, PROXY_HOST, PROXY_PORT, PROXY_USER, PASS, Boolean.TRUE.toString(), X_509_HOSTNAME_VERIFIER_STRICT, TRUST_KEYSTORE, PASS, KERBEROS_CONF_FILE, KERBEROS_LOGIN_CONF_FILE, KERBEROS_SKIP_PORT_FOR_LOOKUP, KEYSTORE, PASS, MAX_ENVELOPE_SIZE, SCRIPT, EMPTY_STRING, MODULES, WINRM_LOCALE_EN_US, OPERATION_TIMEOUT); verifyNew(PowerShellScriptService.class).withNoArguments(); verifyMockInteractions(); assertEquals(resultMock, result); } @Test public void testExecuteWithInputDefaultValues() throws Exception { configureMocksForSuccessTests(); Map<String, String> result = powerShellScriptAction.execute(LOCALHOST, EMPTY_STRING, EMPTY_STRING, USER, PASS, BASIC_AUTH_TYPE, PROXY_HOST, PROXY_PORT, PROXY_USER, PASS, EMPTY_STRING, EMPTY_STRING, TRUST_KEYSTORE, PASS, KERBEROS_CONF_FILE, KERBEROS_LOGIN_CONF_FILE, KERBEROS_SKIP_PORT_FOR_LOOKUP, KEYSTORE, PASS, EMPTY_STRING, SCRIPT, EMPTY_STRING, MODULES, EMPTY_STRING, EMPTY_STRING); verifyNew(PowerShellScriptService.class).withNoArguments(); verifyMockInteractions(); assertEquals(resultMock, result); } @Test public void testExecuteThrowsException() throws Exception { whenNew(PowerShellScriptService.class).withNoArguments().thenReturn(serviceMock); doThrow(new RuntimeException(EXCEPTION_MESSAGE)).when(serviceMock).runCommand(any(WSManRequestInputs.class)); Map<String, String> result = powerShellScriptAction.execute(LOCALHOST, EMPTY_STRING, EMPTY_STRING, USER, BASIC_AUTH_TYPE, PASS, PROXY_HOST, PROXY_PORT, PROXY_USER, PASS, EMPTY_STRING, EMPTY_STRING, TRUST_KEYSTORE, PASS, KERBEROS_CONF_FILE, KERBEROS_LOGIN_CONF_FILE, KERBEROS_SKIP_PORT_FOR_LOOKUP, KEYSTORE, PASS, EMPTY_STRING, SCRIPT, EMPTY_STRING, MODULES, EMPTY_STRING, EMPTY_STRING); assertTrue(result.get(EXCEPTION).contains(EXCEPTION_MESSAGE)); assertEquals(RETURN_CODE_FAILURE, result.get(RETURN_CODE)); } @Test public void testExecuteWithFailureScriptExitCode() throws Exception { whenNew(PowerShellScriptService.class).withNoArguments().thenReturn(serviceMock); doReturn(resultMock).when(serviceMock).runCommand(any(WSManRequestInputs.class)); doReturn(null).when(resultMock).put(RETURN_CODE, RETURN_CODE_SUCCESS); doReturn(RETURN_CODE_FAILURE).when(resultMock).get(SCRIPT_EXIT_CODE); Map<String, String> result = powerShellScriptAction.execute(LOCALHOST, EMPTY_STRING, EMPTY_STRING, USER, PASS, BASIC_AUTH_TYPE, PROXY_HOST, PROXY_PORT, PROXY_USER, PASS, EMPTY_STRING, EMPTY_STRING, TRUST_KEYSTORE, PASS, KERBEROS_CONF_FILE, KERBEROS_LOGIN_CONF_FILE, KERBEROS_SKIP_PORT_FOR_LOOKUP, KEYSTORE, PASS, EMPTY_STRING, SCRIPT, EMPTY_STRING, MODULES, EMPTY_STRING, EMPTY_STRING); verifyNew(PowerShellScriptService.class).withNoArguments(); verify(serviceMock, times(1)).runCommand(any(WSManRequestInputs.class)); verify(resultMock, times(1)).put(RETURN_CODE, RETURN_CODE_FAILURE); verify(resultMock, times(1)).get(SCRIPT_EXIT_CODE); assertEquals(resultMock, result); } private void configureMocksForSuccessTests() throws Exception { whenNew(PowerShellScriptService.class).withNoArguments().thenReturn(serviceMock); doReturn(resultMock).when(serviceMock).runCommand(any(WSManRequestInputs.class)); doReturn(null).when(resultMock).put(RETURN_CODE, RETURN_CODE_SUCCESS); doReturn(RETURN_CODE_SUCCESS).when(resultMock).get(SCRIPT_EXIT_CODE); } private void verifyMockInteractions() throws IOException, InterruptedException, ParserConfigurationException, TransformerException, XPathExpressionException, TimeoutException, URISyntaxException, SAXException { verify(serviceMock, times(1)).runCommand(any(WSManRequestInputs.class)); verify(resultMock, times(1)).put(RETURN_CODE, RETURN_CODE_SUCCESS); verify(resultMock, times(1)).get(SCRIPT_EXIT_CODE); } }
package com.brandon.tictactoe.ui; import javax.swing.JButton; import com.brandon.tictactoe.game.State; public class JSquarePanel extends JButton { public JSquarePanel(JBoardPanel pnlBoard, int x, int y) { setState(State.EMPTY); addActionListener(e -> { if (getState() == State.EMPTY) { pnlBoard.setMove(x, y); } }); } public void setState(State state) { setText(state.toString()); setEnabled(state == State.EMPTY); } public State getState() { for (State state : State.values()) { if (state.toString().equals(getText())) { return state; } } return null; } }
package ioke.lang.parser; import java.io.Reader; import java.io.LineNumberReader; import java.io.IOException; import ioke.lang.IokeObject; import ioke.lang.Message; import ioke.lang.Runtime; import ioke.lang.Dict; import ioke.lang.Number; import ioke.lang.Symbol; import ioke.lang.exceptions.ControlFlow; /** * * @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a> */ public class IokeParser { // TODO: line numbers yay! // TODO: good failures yay! private final Runtime runtime; private final LineNumberReader reader; public IokeParser(Runtime runtime, Reader reader) { this.runtime = runtime; this.reader = new LineNumberReader(reader); } public IokeObject parseFully() throws IOException { IokeObject result = parseExpressions(); return result; } private IokeObject parseExpressions() throws IOException { IokeObject c = null; IokeObject last = null; IokeObject head = null; while((c = parseExpression()) != null) { if(head == null) { head = c; last = c; } else { Message.setNext(last, c); Message.setPrev(c, last); last = c; } } return head; } private int saved = -2; private int read() throws IOException { if(saved > -2) { int x = saved; saved = -2; return saved; } return reader.read(); } private int peek() throws IOException { if(saved == -2) { saved = reader.read(); } return saved; } private IokeObject parseExpression() throws IOException { int rr; while(true) { rr = read(); switch(rr) { case '(': return parseEmptyMessageSend(); case '[': return parseSquareMessageSend(); case '{': return parseCurlyMessageSend(); case ' switch(peek()) { case '{': return parseSetMessageSend(); case '/': return parseRegexpLiteral('/'); case '[': return parseText('['); case 'r': return parseRegexpLiteral('r'); case '!': parseComment(); break; default: return parseOperatorChars(' } break; case '"': return parseText('"'); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return parseNumber(rr); case '.': if((rr = peek()) == '.') { return parseRange(); } else if(rr >= '0' && rr <= '9') { return parseNumber('.'); } else { return parseTerminator('.'); } case ';': parseComment(); break; case ' ': case '\u0009': case '\u000b': case '\u000c': break; case '\\': if((rr = peek()) == '\n') { break; } else { fail(); } case '\r': case '\n': return parseTerminator(rr); case '+': case '-': case '*': case '%': case '<': case '>': case '!': case '?': case '~': case '&': case '|': case '^': case '$': case '=': case '@': case '\'': case '`': case '/': return parseOperatorChars(rr); case ':': if(isLetter(rr = peek()) || isIDDigit(rr)) { return parseRegularMessageSend(':'); } else { return parseOperatorChars(':'); } default: return parseRegularMessageSend(rr); } } } private void fail() { throw new RuntimeException(); } private void parseCharacter(int c) { readWhiteSpace(); int rr = read(); if(rr != c) { fail(); } } private IokeObject parseEmptyMessageSend() { List<Object> args = parseExpressionChain(); parseCharacter(')'); IokeObject mx = runtime.createMessage(new Message(runtime, "")); Message.setArguments(mx, args); return mx; } private IokeObject parseSquareMessageSend() { List<Object> args = parseExpressionChain(); parseCharacter(']'); IokeObject mx = runtime.createMessage(new Message(runtime, "[]")); Message.setArguments(mx, args); return mx; } private IokeObject parseCurlyMessageSend() { List<Object> args = parseExpressionChain(); parseCharacter('}'); IokeObject mx = runtime.createMessage(new Message(runtime, "{}")); Message.setArguments(mx, args); return mx; } private IokeObject parseSetMessageSend() { parseCharacter('{'); List<Object> args = parseExpressionChain(); parseCharacter('}'); IokeObject mx = runtime.createMessage(new Message(runtime, "set")); Message.setArguments(mx, args); return mx; } private void parseComment() { int rr; while((rr = peek()) != '\n' && rr != '\r') { read(); } } private final static String[] RANGES = { "", ".", "..", "...", "....", ".....", "......", ".......", "........", ".........", "..........", "...........", "............" }; private IokeObject parseRange() { int count = 2; read(); int rr; while((rr = peek()) == '.') { count++; read(); } String result = null; if(count < 13) { result = RANGES[count]; } else { StringBuilder sb = new StringBuilder(); for(int i = 0; i<count; i++) { sb.append('.'); } result = sb.toString(); } Message m = new Message(runtime, result); return runtime.createMessage(m); } private IokeObject parseTerminator(int indicator) { int rr; if(indicator == '\r') { rr = peek(); if(rr == '\n') { read(); } } // TODO: should parse more than one terminator into one Message m = new Message(runtime, ".", null, Type.TERMINATOR); return runtime.createMessage(m); } private IokeObject parseRegexpLiteral(int indicator) { // TODO: implement return null; } private IokeObject parseText(int indicator) { // TODO: implement return null; } private IokeObject parseOperatorChars(int indicator) { StringBuilder sb = new StringBuilder(); sb.append((char)indicator); int rr; if(indicator == ' while(true) { rr = peek(); switch(rr) { case '+': case '-': case '*': case '%': case '<': case '>': case '!': case '?': case '~': case '&': case '|': case '^': case '$': case '=': case '@': case '\'': case '`': case ':': case ' read(); sb.append((char)rr); break; default: Message m = new Message(runtime, sb.toString()); return runtime.createMessage(m); } } } else { while(true) { rr = peek(); switch(rr) { case '+': case '-': case '*': case '%': case '<': case '>': case '!': case '?': case '~': case '&': case '|': case '^': case '$': case '=': case '@': case '\'': case '`': case '/': case ':': case ' read(); sb.append((char)rr); break; default: Message m = new Message(runtime, sb.toString()); return runtime.createMessage(m); } } } } private IokeObject parseNumber(int indicator) { // TODO: implement return null; } private IokeObject parseRegularMessageSend(int indicator) { StringBuilder sb = new StringBuilder(); sb.append((char)indicator); int rr = -1; while(isLetter(rr = peek()) || isIDDigit(rr) || rr == ':' || rr == '!' || rr == '?' || rr == '$') { read(); sb.append((char)rr); } IokeObject mx = runtime.createMessage(new Message(runtime, sb.toString())); if(rr == '(') { read(); List<Object> args = parseExpressionChain(); parseCharacter(')'); Message.setArguments(mx, args); } return mx; } private boolean isLetter(int c) { return ((c>='A' && c<='Z') || c=='_' || (c>='a' && c<='z') || (c>='\u00C0' && c<='\u00D6') || (c>='\u00D8' && c<='\u00F6') || (c>='\u00F8' && c<='\u1FFF') || (c>='\u2200' && c<='\u22FF') || (c>='\u27C0' && c<='\u27EF') || (c>='\u2980' && c<='\u2AFF') || (c>='\u3040' && c<='\u318F') || (c>='\u3300' && c<='\u337F') || (c>='\u3400' && c<='\u3D2D') || (c>='\u4E00' && c<='\u9FFF') || (c>='\uF900' && c<='\uFAFF')); } private boolean isIDDigit(int c) { return ((c>='0' && c<='9') || (c>='\u0660' && c<='\u0669') || (c>='\u06F0' && c<='\u06F9') || (c>='\u0966' && c<='\u096F') || (c>='\u09E6' && c<='\u09EF') || (c>='\u0A66' && c<='\u0A6F') || (c>='\u0AE6' && c<='\u0AEF') || (c>='\u0B66' && c<='\u0B6F') || (c>='\u0BE7' && c<='\u0BEF') || (c>='\u0C66' && c<='\u0C6F') || (c>='\u0CE6' && c<='\u0CEF') || (c>='\u0D66' && c<='\u0D6F') || (c>='\u0E50' && c<='\u0E59') || (c>='\u0ED0' && c<='\u0ED9') || (c>='\u1040' && c<='\u1049')); } }
package info.tregmine.tools; import java.util.HashMap; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.commands.AbstractCommand; import org.bukkit.ChatColor; import org.bukkit.inventory.ItemStack; public class ToolSpawnCommand extends AbstractCommand { public ToolSpawnCommand(Tregmine tregmine) { super(tregmine, "tool"); } @Override public boolean handlePlayer(TregminePlayer player, String args[]) { if (!player.getRank().canSpawnTools()) return true; if (args.length != 1) { player.sendMessage(ChatColor.RED + "Usage: /tool <lumber/vein/gravity>"); return true; } ItemStack tool = null; switch (args[0]) { case "lumber": tool = ToolsRegistry.LumberAxe(); break; case "vein": tool = ToolsRegistry.VeinMiner(); break; case "aoe": tool = ToolsRegistry.AreaOfEffect(); break; case "gravity": tool = ToolsRegistry.GravityGun(); break; } if (tool == null) { player.sendMessage(ChatColor.RED + "Usage: /tool <lumber/vein/gravity>"); return true; } HashMap<Integer, ItemStack> failedItems = player.getInventory().addItem(tool); if (failedItems.size() > 0) { player.sendMessage(ChatColor.RED + "You have a full inventory, Can't add tool!"); return true; } player.sendMessage(ChatColor.GREEN + "Spawned in tool token successfully!"); return true; } }
package com.dmdirc.ui.textpane; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextLayout; import java.text.AttributedCharacterIterator; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; /** Canvas object to draw text. */ class TextPaneCanvas extends Canvas implements MouseListener, MouseMotionListener { /** * A version number for this class. It should be changed whenever the * class structure is changed (or anything else that would prevent * serialized objects being unserialized with the new class). */ private static final long serialVersionUID = 2; /** Font render context to be used for the text in this pane. */ private final FontRenderContext defaultFRC = new FontRenderContext(null, false, false); /** IRCDocument. */ private IRCDocument document; /** line break measurer, used for line wrapping. */ private LineBreakMeasurer lineMeasurer; /** start character of a paragraph. */ private int paragraphStart; /** end character of a paragraph. */ private int paragraphEnd; /** position of the scrollbar. */ private int scrollBarPosition; /** parent textpane. */ private TextPane textPane; /** Position -> TextLayout. */ private Map<Rectangle, TextLayout> positions; /** TextLayout -> Line numbers. */ private Map<TextLayout, LineInfo> textLayouts; /** Start line of the selection. */ private int selStartLine; /** Start character of the selection. */ private int selStartChar; /** End line of the selection. */ private int selEndLine; /** End character of the selection. */ private int selEndChar; /** * Creates a new text pane canvas. * * @param parent parent text pane for the canvas * @param document IRCDocument to be displayed */ public TextPaneCanvas(final TextPane parent, final IRCDocument document) { this.document = document; scrollBarPosition = 0; textPane = parent; textLayouts = new HashMap<TextLayout, LineInfo>(); positions = new HashMap<Rectangle, TextLayout>(); this.addMouseListener(this); this.addMouseMotionListener(this); } /** * Paints the text onto the canvas. * @param g graphics object to draw onto */ public void paint(final Graphics g) { final Graphics2D graphics2D = (Graphics2D) g; final float formatWidth = getWidth(); final float formatHeight = getHeight(); textLayouts.clear(); positions.clear(); float drawPosY = formatHeight; int startLine = scrollBarPosition; // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } // Iterate through the lines for (int i = startLine; i >= 0; i final AttributedCharacterIterator iterator = document.getLine(i).getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, defaultFRC); lineMeasurer.setPosition(paragraphStart); int wrappedLine = 0; int height = 0; // Work out the number of lines this will take while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); wrappedLine++; height += layout.getDescent() + layout.getLeading() + layout.getAscent(); } // Get back to the start lineMeasurer.setPosition(paragraphStart); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); if (wrappedLine > 1) { drawPosY -= height; } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= layout.getDescent() + layout.getLeading() + layout.getAscent(); } else if (j != 0) { drawPosY += layout.getDescent() + layout.getLeading() + layout.getAscent(); } float drawPosX; // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 0; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY + layout.getAscent() >= 0 || (drawPosY + layout.getDescent() + layout.getLeading()) <= formatHeight) { // If the selection includes this line if (selStartLine <= i && selEndLine >= i) { int firstChar; int lastChar; // Determine the first char we care about if (selStartLine < i || selStartChar < chars) { firstChar = chars; } else { firstChar = selStartChar; } // ... And the last if (selEndLine > i || selEndChar > chars + layout.getCharacterCount()) { lastChar = chars + layout.getCharacterCount(); } else { lastChar = selEndChar; } // If the selection includes the chars we're showing if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) { final int trans = (int) (layout.getLeading() + layout.getAscent() + drawPosY); final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars); graphics2D.setColor(Color.LIGHT_GRAY); graphics2D.translate(0, trans); graphics2D.fill(shape); graphics2D.translate(0, -1 * trans); } } graphics2D.setColor(Color.BLACK); layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent()); textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle( (int) drawPosX, (int) drawPosY, (int) formatHeight, (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()) ), layout); } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= height; } if (drawPosY <= 0) { break; } } } /** * Repaints the canvas offscreen. * @param g graphics object to draw onto */ public void update(final Graphics g) { final Image offScreen = this.createImage(getWidth(), getHeight()); final Graphics graphics = offScreen.getGraphics(); graphics.clearRect(0, 0, this.getWidth(), this.getHeight()); paint(graphics); g.drawImage(offScreen, 0, 0, this); } /** * sets the position of the scroll bar, and repaints if required. * @param position scroll bar position */ public void setScrollBarPosition(final int position) { if (scrollBarPosition != position) { scrollBarPosition = position; this.repaint(); } } /** {@inheritDoc}. */ public void mouseClicked(final MouseEvent e) { //Ignore } /** {@inheritDoc}. */ public void mousePressed(final MouseEvent e) { highlightEvent(true); } /** {@inheritDoc}. */ public void mouseReleased(final MouseEvent e) { highlightEvent(false); } /** {@inheritDoc}. */ public void mouseEntered(final MouseEvent e) { //Ignore } /** {@inheritDoc}. */ public void mouseExited(final MouseEvent e) { //Ignore } /** {@inheritDoc}. */ public void mouseDragged(final MouseEvent e) { highlightEvent(false); } /** {@inheritDoc}. */ public void mouseMoved(final MouseEvent e) { //Ignore } /** * Sets the selection for the given event. * * @param start true = start */ private void highlightEvent(final boolean start) { final Point point = this.getMousePosition(); if (point != null) { int lineNumber = -1; int linePart = -1; int pos = 0; for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) { if (entry.getKey().contains(point)) { lineNumber = textLayouts.get(entry.getValue()).getLine(); linePart = textLayouts.get(entry.getValue()).getPart(); } } for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) { if (textLayouts.get(entry.getValue()).getLine() == lineNumber) { if (textLayouts.get(entry.getValue()).getPart() < linePart) { pos += entry.getValue().getCharacterCount(); } else if (textLayouts.get(entry.getValue()).getPart() == linePart){ pos += entry.getValue().hitTestChar((int) point.getX(), (int) point.getY()).getInsertionIndex(); } } } if (start) { selStartLine = lineNumber; selStartChar = pos; } selEndLine = lineNumber; selEndChar = pos; this.repaint(); } } /** * temporary method to text the textpane. * @param args command line arguments */ public static void main(final String[] args) { final TextPane tpc = new TextPane(); final JFrame frame = new JFrame("Test textpane"); tpc.setDoubleBuffered(true); tpc.setBackground(Color.WHITE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(tpc); frame.setSize(new Dimension(400, 400)); frame.setVisible(true); tpc.addTestText(); } }
package com.ecyrd.jspwiki.parser; import java.io.BufferedReader; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.util.ArrayList; import com.ecyrd.jspwiki.StringTransmutator; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; /** * Provides an abstract interface towards the parser instances. * * @author jalkanen * */ public abstract class MarkupParser { /** Allow this many characters to be pushed back in the stream. In effect, this limits the size of a single heading line. */ private static final int PUSHBACK_BUFFER_SIZE = 10*1024; protected PushbackReader m_in; protected WikiEngine m_engine; protected WikiContext m_context; /** Optionally stores internal wikilinks */ protected ArrayList m_localLinkMutatorChain = new ArrayList(); protected ArrayList m_externalLinkMutatorChain = new ArrayList(); protected ArrayList m_attachmentLinkMutatorChain = new ArrayList(); protected ArrayList m_headingListenerChain = new ArrayList(); protected ArrayList m_linkMutators = new ArrayList(); protected boolean m_inlineImages = true; protected boolean m_parseAccessRules = true; /** If set to "true", allows using raw HTML within Wiki text. Be warned, this is a VERY dangerous option to set - never turn this on in a publicly allowable Wiki, unless you are absolutely certain of what you're doing. */ public static final String PROP_ALLOWHTML = "jspwiki.translatorReader.allowHTML"; /** If set to "true", enables plugins during parsing */ public static final String PROP_RUNPLUGINS = "jspwiki.translatorReader.runPlugins"; /** Lists all punctuation characters allowed in WikiMarkup. These will not be cleaned away. */ protected static final String PUNCTUATION_CHARS_ALLOWED = "._/"; protected MarkupParser( WikiContext context, Reader in ) { m_engine = context.getEngine(); m_context = context; setInputReader( in ); } /** * Replaces the current input character stream with a new one. * @param in New source for input. If null, this method does nothing. * @return the old stream */ public Reader setInputReader( Reader in ) { Reader old = m_in; if( in != null ) { m_in = new PushbackReader( new BufferedReader( in ), PUSHBACK_BUFFER_SIZE ); } return old; } /** * Adds a hook for processing link texts. This hook is called * when the link text is written into the output stream, and * you may use it to modify the text. It does not affect the * actual link, only the user-visible text. * * @param mutator The hook to call. Null is safe. */ public void addLinkTransmutator( StringTransmutator mutator ) { if( mutator != null ) { m_linkMutators.add( mutator ); } } /** * Adds a hook for processing local links. The engine * transforms both non-existing and existing page links. * * @param mutator The hook to call. Null is safe. */ public void addLocalLinkHook( StringTransmutator mutator ) { if( mutator != null ) { m_localLinkMutatorChain.add( mutator ); } } public void addExternalLinkHook( StringTransmutator mutator ) { if( mutator != null ) { m_externalLinkMutatorChain.add( mutator ); } } /** * Adds a hook for processing attachment links. * * @param mutator The hook to call. Null is safe. */ public void addAttachmentLinkHook( StringTransmutator mutator ) { if( mutator != null ) { m_attachmentLinkMutatorChain.add( mutator ); } } public void addHeadingListener( HeadingListener listener ) { if( listener != null ) { m_headingListenerChain.add( listener ); } } public void disableAccessRules() { m_parseAccessRules = false; } /** * Use this to turn on or off image inlining. * @param toggle If true, images are inlined (as per set in jspwiki.properties) * If false, then images won't be inlined; instead, they will be * treated as standard hyperlinks. * @since 2.2.9 */ public void enableImageInlining( boolean toggle ) { m_inlineImages = toggle; } /** * Parses the document. * @return the parsed document, as a WikiDocument * @throws IOException */ public abstract WikiDocument parse() throws IOException; /** * Cleans a Wiki name. * <P> * [ This is a link ] -&gt; ThisIsALink * * @param link Link to be cleared. Null is safe, and causes this to return null. * @return A cleaned link. * * @since 2.0 */ public static String cleanLink( String link ) { StringBuffer clean = new StringBuffer(); if( link == null ) return null; // Remove non-alphanumeric characters that should not // be put inside WikiNames. Note that all valid // Unicode letters are considered okay for WikiNames. // It is the problem of the WikiPageProvider to take // care of actually storing that information. // Also capitalize things, if necessary. boolean isWord = true; // If true, we've just crossed a word boundary for( int i = 0; i < link.length(); i++ ) { char ch = link.charAt(i); if( Character.isLetterOrDigit( ch ) || MarkupParser.PUNCTUATION_CHARS_ALLOWED.indexOf(ch) != -1 ) { // Is a letter if( isWord ) ch = Character.toUpperCase( ch ); clean.append( ch ); isWord = false; } else { isWord = true; } } return clean.toString(); } }
package com.ecyrd.jspwiki.plugin; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.providers.ProviderException; import org.apache.log4j.Category; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.text.ParsePosition; import java.util.*; /** * Builds a simple weblog. * * @since 1.9.21 */ public class WeblogPlugin implements WikiPlugin { private static Category log = Category.getInstance(WeblogPlugin.class); public static final int DEFAULT_DAYS = 7; public String execute( WikiContext context, Map params ) throws PluginException { String weblogName = context.getPage().getName(); Calendar startTime; Calendar stopTime; WikiEngine engine = context.getEngine(); int numDays = TextUtil.parseIntParameter( (String)params.get("days"), DEFAULT_DAYS ); stopTime = Calendar.getInstance(); startTime = Calendar.getInstance(); startTime.add( Calendar.DAY_OF_MONTH, -numDays ); StringBuffer sb = new StringBuffer(); try { Collection blogEntries = findBlogEntries( context.getEngine().getPageManager(), weblogName, startTime.getTime(), stopTime.getTime() ); SimpleDateFormat entryDateFmt = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); sb.append("<DIV CLASS=\"weblog\">\n"); for( Iterator i = blogEntries.iterator(); i.hasNext(); ) { WikiPage p = (WikiPage) i.next(); sb.append("<DIV CLASS=\"weblogheading\">"); Date entryDate = engine.getPage( p.getName(), 1 ).getLastModified(); sb.append( entryDateFmt.format(entryDate) ); // FIXME: Add permalink here. sb.append("</DIV>\n"); sb.append("<DIV CLASS=\"weblogentry\">"); sb.append( engine.getHTML( context, p ) ); sb.append("</DIV>\n"); } sb.append("</DIV>\n"); } catch( ProviderException e ) { log.error( "Could not locate blog entries", e ); throw new PluginException( "Could not locate blog entries: "+e.getMessage() ); } return sb.toString(); } private Collection findBlogEntries( PageManager mgr, String baseName, Date start, Date end ) throws ProviderException { Collection everyone = mgr.getAllPages(); ArrayList result = new ArrayList(); for( Iterator i = everyone.iterator(); i.hasNext(); ) { WikiPage p = (WikiPage)i.next(); StringTokenizer tok = new StringTokenizer(p.getName(),"-"); if( tok.countTokens() < 3 ) continue; try { String name = tok.nextToken(); if( !name.equals(baseName) ) continue; String day = tok.nextToken(); SimpleDateFormat fmt = new SimpleDateFormat("ddMMyy"); Date pageDay = fmt.parse( day, new ParsePosition(0) ); if( pageDay.after(start) && pageDay.before(end) ) { result.add(p); } } catch( NoSuchElementException e ) { // Nope, something odd. } } return result; } }
package fr.ExiaGeek; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import fr.ExiaGeek.Affichage.Plateau; import fr.ExiaGeek.BDD.BDDConnexion; import fr.ExiaGeek.Case.Bordure; import fr.ExiaGeek.Case.Case; import fr.ExiaGeek.Case.CaseVide; import fr.ExiaGeek.Case.Chemin; import fr.ExiaGeek.Case.Entite; public class Partie { private final static int HAUTEUR = 25, LARGEUR = 25; private final Case cases[][]; private final ArrayList<Entite> entites; private final ArrayList<Chemin> chemins; private final Boolean affichageConsole = false; private Plateau plateau; public int ressource; public String pseudo; public int nbVague; private static int score = 0; public Partie() { this.cases = new Case[HAUTEUR][LARGEUR]; this.entites = new ArrayList<>(); this.chemins = new ArrayList<>(); BDDConnexion bdd = new BDDConnexion(); bdd.open(); bdd.selectChemin(this.chemins); bdd.close(); Case uneCase; for(int y = 0; y < HAUTEUR; y++){ for(int x = 0; x < LARGEUR; x++){ if((x == 0) || (x == (LARGEUR - 1)) || ((y == 0) || (y == HAUTEUR - 1))){ uneCase = new Bordure(); }else if(testChemin(chemins, x, y)){ uneCase = new Chemin(); }else{ uneCase = new CaseVide(); } this.setXY(x, y, uneCase); } } this.plateau = new Plateau(HAUTEUR, LARGEUR, this.cases); } private boolean testChemin(ArrayList<Chemin> chemin, int x, int y){ for(int i = 0; i < chemin.size(); i++){ if(chemin.get(i).getX() == x && chemin.get(i).getY() == y){ return true; } } return false; } public void afficher(){ if(this.affichageConsole){ this.afficherConsole(); }else{ this.afficherGraphique(); } } private void afficherConsole(){ for(int y = 0; y < HAUTEUR; y++){ for(int x = 0; x < LARGEUR; x++){ final Entite e = this.getEntite(x, y); if(e == null){ System.out.println(this.getXY(x, y).getDessin()); }else{ System.out.println(e.getDessin()); } } } } private void afficherGraphique(){ this.plateau.rafraichir(); } public Entite getEntite(final int x, final int y){ for(final Entite e : this.entites){ if(e != null){ if((e.getX() == x) && (e.getY() == y)){ return e; } } } return null; } public Case getXY(final int x, final int y){ return this.cases[x][y]; } public void setXY(final int x, final int y, final Case c) { this.cases[x][y] = c; } public void calculerScore() { java.util.Date temps = new java.util.Date (System.currentTimeMillis ()); //Relever l'heure avant le debut du progamme (en milliseconde) try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Date dateFin = new Date (System.currentTimeMillis()); //Relever l'heure a la fin du progamme (en milliseconde) Date duree = new Date (System.currentTimeMillis()); //Pour calculer la diffrence duree.setTime (dateFin.getTime () - temps.getTime ()); //Calcul de la diffrence long secondes = duree.getTime () / 1000; secondes %= 60; System.out.println ("Votre score est: " + secondes); } public static int getScore() { return score; } public void setScore(int score) { Partie.score = score; } }
package com.mpu.spinv.engine.model; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.mpu.spinv.engine.triggers.KeyTrigger; import com.mpu.spinv.utils.Constants; /** * GameObject.java * * @author Brendon Pagano * @date 2017-08-08 */ public class GameEntity implements GameObject { /** * The x and y position of the object in the screen. */ protected int x, y; /** * The direction to update x and y axis. */ protected int dx, dy; /** * The width and height of the game object. */ private int width, height; /** * A list of the object's animations. */ private final Map<String, Animation> animations; /** * A list of the key triggers of the object. */ private final List<KeyTrigger> keyTriggers; /** * The key identifier of the active animation. */ private String actAnimation; /** * The active animation. Currently playing if {@link GameEntity#visible} is * true. */ private Animation animation; /** * In case there is no need for the object to have an animation, use a static * sprite to draw instead. */ private Sprite staticSprite; /** * If true, the object cannot be moved out of the screen. */ private boolean screenBound; /** * Attribute used for checking. Mainly for drawing or not the object accordingly * to it's visibility status. */ private boolean visible; /** * GameObject's constructor. * * @param x * The x position of the object in the screen. * @param y * The y position of the object in the screen. * @param visible * Flag to determine if the object will begin visible or not. */ public GameEntity(int x, int y, boolean visible) { this.x = x; this.y = y; this.visible = visible; // Default params this.dx = 0; this.dy = 0; this.width = 0; this.height = 0; this.animations = new HashMap<String, Animation>(); this.keyTriggers = new ArrayList<KeyTrigger>(); this.animation = null; this.actAnimation = ""; this.staticSprite = null; } public GameEntity(int x, int y, Sprite staticSprite, boolean visible) { this.x = x; this.y = y; this.visible = visible; this.staticSprite = staticSprite; this.width = staticSprite.getWidth(); this.height = staticSprite.getHeight(); // Default params this.dx = 0; this.dy = 0; this.animations = new HashMap<String, Animation>(); this.keyTriggers = new ArrayList<KeyTrigger>(); this.animation = null; this.actAnimation = ""; } public GameEntity(int x, int y, Animation animation, boolean visible) { this.x = x; this.y = y; this.visible = visible; this.width = animation.getSprite().getWidth(); this.height = animation.getSprite().getHeight(); // Default params this.dx = 0; this.dy = 0; this.animations = new HashMap<String, Animation>(); this.keyTriggers = new ArrayList<KeyTrigger>(); this.animation = null; this.actAnimation = ""; this.staticSprite = null; // Setting the default animation addAnimation("default", animation); } public void update() { x += dx; y += dy; if (screenBound) { if (x < 0) x = 0; else if (x + width > Constants.WINDOW_WIDTH - 4) x = Constants.WINDOW_WIDTH - width - 4; if (y < 0) y = 0; else if (y + height > Constants.WINDOW_HEIGHT - 30) y = Constants.WINDOW_HEIGHT - height - 30; } if (!actAnimation.equals("")) animation.update(); } public void draw(Graphics g) { if (visible && (animation != null || staticSprite != null)) g.drawImage((staticSprite == null ? animation.getSprite() : staticSprite.getSprite()), x, y, null); } public void on(KeyTrigger trigger) { keyTriggers.add(trigger); } /** * Adds an animation into the GameObject's animations list. * * @param key * the identifier of the animation to add. * @param animation * the animation object to be added. */ public void addAnimation(String key, Animation animation) { if (!key.equals("")) { animations.put(key, animation); if (this.actAnimation.equals("")) { this.actAnimation = key; this.animation = animation; } } } /** * Set the active and playing animation to a new one. * * @param key * the identifier of the animation to be set. */ public void setAnimation(String key) { if (animations.containsKey(key)) { actAnimation = key; animation = animations.get(key); } else if (key.equals("")) { actAnimation = key; animation = null; } } /** * Removes an animation from the GameObject's animation list and returns the * removed animation object. * * @param key * the key identifier of the animation to be removed. * @return the removed animation object. */ public Animation removeAnimation(String key) { Animation animation = null; if (animations.containsKey(key)) { animation = animations.get(key); animations.remove(key); if (actAnimation.equals(key)) { this.animation = null; this.actAnimation = ""; } } return animation; } /** * Starts playing the active animation. */ public void startAnimation() { if (animation != null) animation.start(); } /** * Pauses the active animation. */ public void pauseAnimation() { if (animation != null) animation.pause(); } /** * Restarts the active animation. */ public void restartAnimation() { if (animation != null) animation.restart(); } /** * Resets the active animation. */ public void resetAnimation() { if (animation != null) animation.reset(); } public void resizeSprite(int width, int height) { this.width = width; this.height = height; staticSprite.resizeSprite(width, height); } // Controls Handling Methods public void keyPressed(KeyEvent e) { if (keyTriggers.size() > 0) keyTriggers.forEach(kt -> { kt.update(e, KeyTrigger.KEY_PRESSED); }); } public void keyReleased(KeyEvent e) { if (keyTriggers.size() > 0) keyTriggers.forEach(kt -> { kt.update(e, KeyTrigger.KEY_RELEASED); }); } public void keyTyped(KeyEvent e) { if (keyTriggers.size() > 0) keyTriggers.forEach(kt -> { kt.update(e, KeyTrigger.KEY_TYPED); }); } // Getters and Setters public String getAnimationKey() { return actAnimation; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public Sprite getStaticSprite() { return staticSprite; } public void setStaticSprite(Sprite staticSprite) { this.staticSprite = staticSprite; this.width = staticSprite.getWidth(); this.height = staticSprite.getHeight(); } public boolean hasKeyTriggers() { return keyTriggers.size() > 0; } public boolean isScreenBound() { return screenBound; } public void setScreenBound(boolean screenBound) { this.screenBound = screenBound; } public int getWidth() { return width; } public int getHeight() { return height; } public int getX() { return x; } public int getY() { return y; } }
package org.dspace.app.xmlui.aspect.eperson; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.SourceResolver; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.AuthenticationUtil; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Cell; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.app.xmlui.wing.element.Text; import org.xml.sax.SAXException; /** * Query the user for their authentication credentials. * * The parameter "return-url" may be passed to give a location where to redirect * the user to after successfully authenticating. * * @author Sid * @author Scott Phillips * @author Kevin Clarke */ public class PasswordLogin extends AbstractDSpaceTransformer implements CacheableProcessingComponent { /** language strings */ public static final Message T_title = message("xmlui.EPerson.PasswordLogin.title"); public static final Message T_dspace_home = message("xmlui.general.dspace_home"); public static final Message T_trail = message("xmlui.EPerson.PasswordLogin.trail"); public static final Message T_head1 = message("xmlui.EPerson.PasswordLogin.head1"); public static final Message T_reglogin_head = message("xmlui.EPerson.RegLogin.head"); public static final Message T_email_address = message("xmlui.EPerson.PasswordLogin.email_address"); public static final Message T_error_bad_login = message("xmlui.EPerson.PasswordLogin.error_bad_login"); public static final Message T_password = message("xmlui.EPerson.PasswordLogin.password"); public static final Message T_forgot_link = message("xmlui.EPerson.PasswordLogin.forgot_link"); public static final Message T_submit_register = message("xmlui.EPerson.PasswordLogin.submitReg"); public static final Message T_submit_login = message("xmlui.EPerson.PasswordLogin.submitLogin"); public static final Message T_head2 = message("xmlui.EPerson.PasswordLogin.head2"); public static final Message T_para1 = message("xmlui.EPerson.PasswordLogin.para1"); public static final Message T_register_link = message("xmlui.EPerson.PasswordLogin.register_link"); private static final Message T_email_address_help = message("xmlui.EPerson.StartRegistration.email_address_help"); /** The email address previously entered */ private String email; /** * Determine if the user failed on their last attempt to enter an email * address */ private java.util.List<String> errors; /** * Determine if the last failed attempt was because an account allready * existed for the given email address */ private boolean accountExists; public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, parameters); this.email = parameters.getParameter("email", ""); this.accountExists = parameters.getParameterAsBoolean("accountExists", false); String errors = parameters.getParameter("errors", ""); if (errors.length() > 0) this.errors = Arrays.asList(errors.split(",")); else this.errors = new ArrayList<String>(); } /** * Generate the unique caching key. This key must be unique inside the space * of this component. */ public Serializable getKey() { Request request = ObjectModelHelper.getRequest(objectModel); String previous_email = request.getParameter("login_email"); // Get any message parameters HttpSession session = request.getSession(); String header = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); String message = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); String characters = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); // If there is a message or previous email attempt then the page is not // cacheable if (header == null && message == null && characters == null && previous_email == null && accountExists == false && errors != null && errors.size() == 0) // cacheable return "1"; else // Uncacheable return "0"; } /** * Generate the cache validity object. */ public SourceValidity getValidity() { Request request = ObjectModelHelper.getRequest(objectModel); String previous_email = request.getParameter("login_email"); // Get any message parameters HttpSession session = request.getSession(); String header = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); String message = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); String characters = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); // If there is a message or previous email attempt then the page is not // cacheable if (header == null && message == null && characters == null && previous_email == null && errors != null && errors.size() == 0 && accountExists == false) // Always valid return NOPValidity.SHARED_INSTANCE; else // invalid return null; } /** * Set the page title and trail. */ public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } /** * Display the login form. */ public void addBody(Body body) throws SQLException, SAXException, WingException { // Check if the user has previously attempted to login. Request request = ObjectModelHelper.getRequest(objectModel); HttpSession session = request.getSession(); String previousEmail = request.getParameter("login_email"); boolean accountExists = parameters.getParameterAsBoolean( "accountExists", false); if (previousEmail != null) { email = previousEmail; } else { previousEmail = request.getParameter("email"); } // Get any message parameters String header = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); String message = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); String characters = (String) session .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); if (header != null || message != null || characters != null) { Division reason = body.addDivision("login-reason"); if (header != null) reason.setHead(message(header)); else // Always have a head. reason.setHead("Authentication Required"); if (message != null) reason.addPara(message(message)); if (characters != null) reason.addPara(characters); } Division register = body.addInteractiveDivision("register", contextPath + "/register", Division.METHOD_POST, "register-left"); register.addPara(T_reglogin_head); Table regTable = register.addTable("register", 2, 2); regTable.setHead(T_head1); Row regRow1 = regTable.addRow(); Cell regRow1Cell1 = regRow1.addCell(); Cell regRow1Cell2 = regRow1.addCell(); regRow1Cell1.addContent(T_email_address); Text regEmail = regRow1Cell2.addText("email"); regEmail.setRequired(); regEmail.setLabel(T_email_address); if (previousEmail != null) { regEmail.setValue(previousEmail); regEmail.addError(T_error_bad_login); } Row regRow2 = regTable.addRow(); Cell regRow2Cell1 = regRow2.addCell(); Cell regRow2Cell2 = regRow2.addCell(); Row regRow3 = regTable.addRow(); Cell regRow3Cell1 = regRow3.addCell(); Cell regRow3Cell2 = regRow3.addCell(); if (knot != null) { regRow3Cell1.addHidden("eperson-continue").setValue(knot.getId()); } regRow3Cell2.addButton("submit").setValue(T_submit_register); Division login = body.addInteractiveDivision("login", contextPath + "/password-login", Division.METHOD_POST, "login-right"); Table loginTable = login.addTable("login", 3, 2); loginTable.setHead(T_head2); Row loginRow1 = loginTable.addRow(); Cell loginRow1Cell1 = loginRow1.addCell(); Cell loginRow1Cell2 = loginRow1.addCell(); loginRow1Cell1.addContent(T_email_address); Text loginEmail = loginRow1Cell2.addText("login_email"); loginEmail.setRequired(); loginEmail.setLabel(T_email_address); if (previousEmail != null) { loginEmail.setValue(previousEmail); loginEmail.addError(T_error_bad_login); } Row loginRow2 = loginTable.addRow(); Cell loginRow2Cell1 = loginRow2.addCell(); Cell loginRow2Cell2 = loginRow2.addCell(); loginRow2Cell1.addContent(T_password); loginRow2Cell2.addPassword("login_password").setRequired(); Row loginRow3 = loginTable.addRow(); Cell loginRow3Cell1 = loginRow3.addCell(); Cell loginRow3Cell2 = loginRow3.addCell(); loginRow3Cell2.addButton("submit").setValue(T_submit_login); login.addPara().addXref("/forgot", T_forgot_link); } // HttpServletRequest httpRequest = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); /** * Recycle */ public void recycle() { this.email = null; this.errors = null; super.recycle(); } }
package com.preplay.android.i18next; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author stan */ public interface Operation { public interface PostOperation extends Operation { public abstract String postProcess(String source); } public interface PreOperation extends Operation { public abstract String preProcess(String key); public abstract String preProcessAfterNoValueFound(String key); } public static class MultiPostProcessing implements PostOperation, PreOperation { private Operation[] mOperations; public MultiPostProcessing(Operation... operations) { mOperations = operations; } @Override public String postProcess(String source) { if (mOperations != null) { for (Operation operation : mOperations) { if (operation instanceof PostOperation) { source = ((PostOperation) operation).postProcess(source); } } } return source; } @Override public String preProcess(String key) { if (mOperations != null) { for (Operation operation : mOperations) { if (operation instanceof PreOperation) { key = ((PreOperation) operation).preProcess(key); } } } return key; } @Override public String preProcessAfterNoValueFound(String key) { if (mOperations != null) { for (Operation operation : mOperations) { if (operation instanceof PreOperation) { String keyTemp = ((PreOperation) operation).preProcessAfterNoValueFound(key); if (keyTemp != null && !keyTemp.equals(key)) { return keyTemp; } } } } return null; } @Override public boolean equals(Object o) { if (o instanceof MultiPostProcessing) { Operation[] otherOperations = ((MultiPostProcessing) o).mOperations; int nbElement = (mOperations == null) ? 0 : mOperations.length; int nbElementOther = (otherOperations == null) ? 0 : otherOperations.length; if (nbElement == nbElementOther) { if (nbElement == 0) { return true; } else { for (int i = 0; i < nbElement; i++) { Operation operation1 = mOperations[i]; Operation operation2 = otherOperations[i]; if ((operation1 != null && !operation1.equals(operation2)) || (operation1 == null && operation2 == null)) { return false; } } return true; } } } return false; } } public static class Plural implements PreOperation, PostOperation { private int mCount; private Interpolation mInterpolation; public Plural(int count) { this("count", count); } public Plural(String key, int count) { mInterpolation = new Interpolation(key, Integer.toString(count)); mCount = count; } @Override public String preProcess(String key) { if (key != null) { int pluralExtension = Plurals.getInstance().get(I18Next.getInstance().getOptions().getLanguage(), mCount); if (pluralExtension != 1) { // plural key = key + I18Next.getInstance().getOptions().getPluralSuffix(); if (pluralExtension >= 0) { // specific plural key = key + "_" + pluralExtension; } } } return key; } @Override public String preProcessAfterNoValueFound(String key) { int index = key.lastIndexOf(I18Next.getInstance().getOptions().getPluralSuffix()); if (index > 0) { return key.substring(0, index); } else { return null; } } @Override public String postProcess(String source) { return mInterpolation.postProcess(source); } @Override public boolean equals(Object o) { if (o instanceof Plural) { Plural oPlural = (Plural) o; return oPlural.mCount == mCount && mInterpolation.equals(oPlural.mInterpolation); } return false; } } public static class Context implements PreOperation { private String mContextPrefix; public Context(String value) { mContextPrefix = I18Next.getInstance().getOptions().getContextPrefix() + value; } @Override public String preProcess(String key) { if (mContextPrefix != null && mContextPrefix.length() > 0 && key != null) { String keyWithContext = key + mContextPrefix; if (I18Next.getInstance().existValue(keyWithContext)) { key = keyWithContext; } } return key; } @Override public String preProcessAfterNoValueFound(String key) { return null; } @Override public boolean equals(Object o) { if (o instanceof Context) { return I18Next.equalsCharSequence(mContextPrefix, ((Context) o).mContextPrefix); } return false; } } public static class SPrintF implements PostOperation { private Object[] mArgs; public SPrintF(Object... args) { mArgs = args; } @Override public String postProcess(String source) { if (source != null && mArgs != null && mArgs.length > 0) { source = String.format(source, mArgs); } return source; } @Override public boolean equals(Object o) { if (o instanceof SPrintF) { Object[] otherArgs = ((SPrintF) o).mArgs; int nbElement = (mArgs == null) ? 0 : mArgs.length; int nbElementOther = (otherArgs == null) ? 0 : otherArgs.length; if (nbElement == nbElementOther) { if (nbElement == 0) { return true; } else { for (int i = 0; i < nbElement; i++) { Object arg1 = mArgs[i]; Object arg2 = otherArgs[i]; if ((arg1 != null && !arg1.equals(arg2)) || (arg1 == null && arg2 == null)) { return false; } } return true; } } } return false; } } public static class Interpolation implements PostOperation { private StringBuffer mStringBuffer = new StringBuffer(); private Map<String, Object> mReplacementMap; private static Map<String, Object> getReplacementMap(CharSequence target, CharSequence replacement) { Map<String, Object> map = new HashMap<String, Object>(); map.put(target.toString(), replacement); return map; } public Interpolation(CharSequence target, CharSequence replacement) { this(getReplacementMap(target, replacement)); } public Interpolation(Map<String, Object> replacementMap) { mReplacementMap = replacementMap; } @Override public String postProcess(String source) { if (source != null) { Options options = I18Next.getInstance().getOptions(); String prefix = options.getInterpolationPrefix(); int prefixLength = prefix.length(); String suffix = options.getInterpolationSuffix(); int lastIndexPrefix = -1; while (true) { int prefixIndex = source.indexOf(prefix, lastIndexPrefix); if (prefixIndex < 0) { break; } else { int suffixIndex = source.indexOf(suffix, prefixIndex + prefixLength); if (suffixIndex < 0) { break; } String target = source.substring(prefixIndex + prefixLength, suffixIndex); Object replacement = getObject(target); if (replacement == null) { lastIndexPrefix = suffixIndex + 1; // skip this replacement } else { mStringBuffer.setLength(0); mStringBuffer.append(prefix); mStringBuffer.append(target); mStringBuffer.append(suffix); source = source.replace(mStringBuffer.toString(), replacement == null ? "" : replacement.toString()); lastIndexPrefix = 0; } } } } return source; } @Override public boolean equals(Object o) { if (o instanceof Interpolation) { return mReplacementMap != null && mReplacementMap.equals(((Interpolation) o).mReplacementMap); } return false; } private Object getObject(String target) { if (target != null) { String[] targetParts = target.split("\\."); if (targetParts != null && targetParts.length > 0) { Object rootObject = mReplacementMap; for (int i = 0; i < targetParts.length; i++) { String part = targetParts[i]; if (rootObject instanceof Map<?, ?>) { rootObject = ((Map<?, ?>) rootObject).get(part); } else { I18Next.getInstance().log(I18Next.LogMode.WARNING, "Impossible to replace '%s': not found", target); return null; } } return rootObject; } } return null; } } public static class DefaultValue implements PostOperation { private String mValue; public DefaultValue(String value) { mValue = value; } @Override public String postProcess(String source) { if (source == null) { source = mValue; } return source; } @Override public boolean equals(Object o) { if (o instanceof DefaultValue) { return I18Next.equalsCharSequence(mValue, ((DefaultValue) o).mValue); } return false; } } }
package com.oracle.graal.hotspot.meta; import static com.oracle.graal.compiler.common.UnsafeAccess.*; import static com.oracle.graal.hotspot.HotSpotGraalRuntime.*; import java.lang.invoke.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.bytecode.*; import com.oracle.graal.compiler.common.*; import com.oracle.graal.hotspot.*; /** * Implementation of {@link ConstantPool} for HotSpot. */ public class HotSpotConstantPool extends CompilerObject implements ConstantPool { private static final long serialVersionUID = -5443206401485234850L; /** * Enum of all {@code JVM_CONSTANT} constants used in the VM. This includes the public and * internal ones. */ private enum JVM_CONSTANT { // @formatter:off Utf8(config().jvmConstantUtf8), Integer(config().jvmConstantInteger), Long(config().jvmConstantLong), Float(config().jvmConstantFloat), Double(config().jvmConstantDouble), Class(config().jvmConstantClass), UnresolvedClass(config().jvmConstantUnresolvedClass), UnresolvedClassInError(config().jvmConstantUnresolvedClassInError), String(config().jvmConstantString), Fieldref(config().jvmConstantFieldref), MethodRef(config().jvmConstantMethodref), InterfaceMethodref(config().jvmConstantInterfaceMethodref), NameAndType(config().jvmConstantNameAndType), MethodHandle(config().jvmConstantMethodHandle), MethodHandleInError(config().jvmConstantMethodHandleInError), MethodType(config().jvmConstantMethodType), MethodTypeInError(config().jvmConstantMethodTypeInError), InvokeDynamic(config().jvmConstantInvokeDynamic); // @formatter:on private final int tag; private static final int ExternalMax = config().jvmConstantExternalMax; private static final int InternalMin = config().jvmConstantInternalMin; private static final int InternalMax = config().jvmConstantInternalMax; private JVM_CONSTANT(int tag) { this.tag = tag; } private static HotSpotVMConfig config() { return runtime().getConfig(); } /** * Maps JVM_CONSTANT tags to {@link JVM_CONSTANT} values. Using a separate class for lazy * initialization. */ static class TagValueMap { private static final JVM_CONSTANT[] table = new JVM_CONSTANT[ExternalMax + 1 + (InternalMax - InternalMin) + 1]; static { assert InternalMin > ExternalMax; for (JVM_CONSTANT e : values()) { table[indexOf(e.tag)] = e; } } private static int indexOf(int tag) { if (tag >= InternalMin) { return tag - InternalMin + ExternalMax + 1; } else { assert tag <= ExternalMax; } return tag; } static JVM_CONSTANT get(int tag) { JVM_CONSTANT res = table[indexOf(tag)]; if (res != null) { return res; } throw GraalInternalError.shouldNotReachHere("unknown JVM_CONSTANT tag " + tag); } } public static JVM_CONSTANT getEnum(int tag) { return TagValueMap.get(tag); } } /** * Reference to the C++ ConstantPool object. */ private final long metaspaceConstantPool; public HotSpotConstantPool(long metaspaceConstantPool) { this.metaspaceConstantPool = metaspaceConstantPool; } /** * Gets the holder for this constant pool as {@link HotSpotResolvedObjectType}. * * @return holder for this constant pool */ private HotSpotResolvedObjectType getHolder() { final long metaspaceKlass = unsafe.getAddress(metaspaceConstantPool + runtime().getConfig().constantPoolHolderOffset); return (HotSpotResolvedObjectType) HotSpotResolvedObjectType.fromMetaspaceKlass(metaspaceKlass); } /** * Converts a raw index from the bytecodes to a constant pool index by adding a * {@link HotSpotVMConfig#constantPoolCpCacheIndexTag constant}. * * @param rawIndex index from the bytecode * @param opcode bytecode to convert the index for * @return constant pool index */ private static int toConstantPoolIndex(int rawIndex, int opcode) { int index; if (opcode == Bytecodes.INVOKEDYNAMIC) { index = rawIndex; // See: ConstantPool::is_invokedynamic_index assert index < 0 : "not an invokedynamic constant pool index " + index; } else { assert opcode == Bytecodes.GETFIELD || opcode == Bytecodes.PUTFIELD || opcode == Bytecodes.GETSTATIC || opcode == Bytecodes.PUTSTATIC || opcode == Bytecodes.INVOKEINTERFACE || opcode == Bytecodes.INVOKEVIRTUAL || opcode == Bytecodes.INVOKESPECIAL || opcode == Bytecodes.INVOKESTATIC : "unexpected invoke opcode " + Bytecodes.nameOf(opcode); index = rawIndex + runtime().getConfig().constantPoolCpCacheIndexTag; } return index; } /** * Decode a constant pool cache index to a constant pool index. * * See {@code ConstantPool::decode_cpcache_index}. * * @param index constant pool cache index * @return decoded index */ private static int decodeConstantPoolCacheIndex(int index) { if (isInvokedynamicIndex(index)) { return decodeInvokedynamicIndex(index); } else { return index - runtime().getConfig().constantPoolCpCacheIndexTag; } } /** * See {@code ConstantPool::is_invokedynamic_index}. */ private static boolean isInvokedynamicIndex(int index) { return index < 0; } /** * See {@code ConstantPool::decode_invokedynamic_index}. */ private static int decodeInvokedynamicIndex(int i) { assert isInvokedynamicIndex(i) : i; return ~i; } /** * Gets the constant pool tag at index {@code index}. * * @param index constant pool index * @return constant pool tag */ private JVM_CONSTANT getTagAt(int index) { assertBounds(index); HotSpotVMConfig config = runtime().getConfig(); final long metaspaceConstantPoolTags = unsafe.getAddress(metaspaceConstantPool + config.constantPoolTagsOffset); final int tag = unsafe.getByteVolatile(null, metaspaceConstantPoolTags + config.arrayU1DataOffset + index); if (tag == 0) { return null; } return JVM_CONSTANT.getEnum(tag); } /** * Gets the constant pool entry at index {@code index}. * * @param index constant pool index * @return constant pool entry */ private long getEntryAt(int index) { assertBounds(index); return unsafe.getAddress(metaspaceConstantPool + runtime().getConfig().constantPoolSize + index * runtime().getTarget().wordSize); } /** * Gets the integer constant pool entry at index {@code index}. * * @param index constant pool index * @return integer constant pool entry at index */ private int getIntAt(int index) { assertTag(index, JVM_CONSTANT.Integer); return unsafe.getInt(metaspaceConstantPool + runtime().getConfig().constantPoolSize + index * runtime().getTarget().wordSize); } /** * Gets the long constant pool entry at index {@code index}. * * @param index constant pool index * @return long constant pool entry */ private long getLongAt(int index) { assertTag(index, JVM_CONSTANT.Long); return unsafe.getLong(metaspaceConstantPool + runtime().getConfig().constantPoolSize + index * runtime().getTarget().wordSize); } /** * Gets the float constant pool entry at index {@code index}. * * @param index constant pool index * @return float constant pool entry */ private float getFloatAt(int index) { assertTag(index, JVM_CONSTANT.Float); return unsafe.getFloat(metaspaceConstantPool + runtime().getConfig().constantPoolSize + index * runtime().getTarget().wordSize); } /** * Gets the double constant pool entry at index {@code index}. * * @param index constant pool index * @return float constant pool entry */ private double getDoubleAt(int index) { assertTag(index, JVM_CONSTANT.Double); return unsafe.getDouble(metaspaceConstantPool + runtime().getConfig().constantPoolSize + index * runtime().getTarget().wordSize); } /** * Gets the {@code JVM_CONSTANT_NameAndType} constant pool entry at index {@code index}. * * @param index constant pool index * @return {@code JVM_CONSTANT_NameAndType} constant pool entry */ private int getNameAndTypeAt(int index) { assertTag(index, JVM_CONSTANT.NameAndType); return unsafe.getInt(metaspaceConstantPool + runtime().getConfig().constantPoolSize + index * runtime().getTarget().wordSize); } /** * Gets the {@code JVM_CONSTANT_NameAndType} reference index constant pool entry at index * {@code index}. * * @param index constant pool index * @return {@code JVM_CONSTANT_NameAndType} reference constant pool entry */ private int getNameAndTypeRefIndexAt(int index) { return runtime().getCompilerToVM().lookupNameAndTypeRefIndexInPool(metaspaceConstantPool, index); } /** * Gets the name of a {@code JVM_CONSTANT_NameAndType} constant pool entry at index * {@code index}. * * @param index constant pool index * @return name as {@link String} */ private String getNameRefAt(int index) { return runtime().getCompilerToVM().lookupNameRefInPool(metaspaceConstantPool, index); } /** * Gets the name reference index of a {@code JVM_CONSTANT_NameAndType} constant pool entry at * index {@code index}. * * @param index constant pool index * @return name reference index */ private int getNameRefIndexAt(int index) { final int refIndex = getNameAndTypeAt(index); // name ref index is in the low 16-bits. return refIndex & 0xFFFF; } /** * Gets the signature of a {@code JVM_CONSTANT_NameAndType} constant pool entry at index * {@code index}. * * @param index constant pool index * @return signature as {@link String} */ private String getSignatureRefAt(int index) { return runtime().getCompilerToVM().lookupSignatureRefInPool(metaspaceConstantPool, index); } /** * Gets the signature reference index of a {@code JVM_CONSTANT_NameAndType} constant pool entry * at index {@code index}. * * @param index constant pool index * @return signature reference index */ private int getSignatureRefIndexAt(int index) { final int refIndex = getNameAndTypeAt(index); // signature ref index is in the high 16-bits. return refIndex >>> 16; } /** * Gets the klass reference index constant pool entry at index {@code index}. * * @param index constant pool index * @return klass reference index */ private int getKlassRefIndexAt(int index) { return runtime().getCompilerToVM().lookupKlassRefIndexInPool(metaspaceConstantPool, index); } /** * Gets the uncached klass reference index constant pool entry at index {@code index}. See: * {@code ConstantPool::uncached_klass_ref_index_at}. * * @param index constant pool index * @return klass reference index */ private int getUncachedKlassRefIndexAt(int index) { assert getTagAt(index) == JVM_CONSTANT.Fieldref || getTagAt(index) == JVM_CONSTANT.MethodRef || getTagAt(index) == JVM_CONSTANT.InterfaceMethodref; final int refIndex = unsafe.getInt(metaspaceConstantPool + runtime().getConfig().constantPoolSize + index * runtime().getTarget().wordSize); // klass ref index is in the low 16-bits. return refIndex & 0xFFFF; } /** * Asserts that the constant pool index {@code index} is in the bounds of the constant pool. * * @param index constant pool index */ private void assertBounds(int index) { assert 0 <= index && index < length() : "index " + index + " not between 0 and " + length(); } /** * Asserts that the constant pool tag at index {@code index} is equal to {@code tag}. * * @param index constant pool index * @param tag expected tag */ private void assertTag(int index, JVM_CONSTANT tag) { assert getTagAt(index) == tag : "constant pool tag at index " + index + " is " + getTagAt(index) + " but expected " + tag; } @Override public int length() { return unsafe.getInt(metaspaceConstantPool + runtime().getConfig().constantPoolLengthOffset); } @Override public Object lookupConstant(int cpi) { assert cpi != 0; final JVM_CONSTANT tag = getTagAt(cpi); switch (tag) { case Integer: return Constant.forInt(getIntAt(cpi)); case Long: return Constant.forLong(getLongAt(cpi)); case Float: return Constant.forFloat(getFloatAt(cpi)); case Double: return Constant.forDouble(getDoubleAt(cpi)); case Class: case UnresolvedClass: case UnresolvedClassInError: final int opcode = -1; // opcode is not used return lookupType(cpi, opcode); case String: Object string = runtime().getCompilerToVM().resolvePossiblyCachedConstantInPool(metaspaceConstantPool, cpi); return HotSpotObjectConstant.forObject(string); case MethodHandle: case MethodHandleInError: case MethodType: case MethodTypeInError: Object obj = runtime().getCompilerToVM().resolveConstantInPool(metaspaceConstantPool, cpi); return HotSpotObjectConstant.forObject(obj); default: throw GraalInternalError.shouldNotReachHere("unknown constant pool tag " + tag); } } @Override public String lookupUtf8(int cpi) { assertTag(cpi, JVM_CONSTANT.Utf8); return runtime().getCompilerToVM().getSymbol(getEntryAt(cpi)); } @Override public Signature lookupSignature(int cpi) { return new HotSpotSignature(lookupUtf8(cpi)); } @Override public Constant lookupAppendix(int cpi, int opcode) { assert Bytecodes.isInvoke(opcode); final int index = toConstantPoolIndex(cpi, opcode); Object result = runtime().getCompilerToVM().lookupAppendixInPool(metaspaceConstantPool, index); if (result == null) { return null; } else { return HotSpotObjectConstant.forObject(result); } } /** * Gets a {@link JavaType} corresponding a given metaspace Klass or a metaspace Symbol depending * on the {@link HotSpotVMConfig#compilerToVMKlassTag tag}. * * @param metaspacePointer either a metaspace Klass or a metaspace Symbol */ private static JavaType getJavaType(final long metaspacePointer) { HotSpotGraalRuntime runtime = runtime(); HotSpotVMConfig config = runtime.getConfig(); if ((metaspacePointer & config.compilerToVMSymbolTag) != 0) { final long metaspaceSymbol = metaspacePointer & ~config.compilerToVMSymbolTag; String name = runtime.getCompilerToVM().getSymbol(metaspaceSymbol); return HotSpotUnresolvedJavaType.create("L" + name + ";"); } else { assert (metaspacePointer & config.compilerToVMKlassTag) == 0; return HotSpotResolvedObjectType.fromMetaspaceKlass(metaspacePointer); } } @Override public JavaMethod lookupMethod(int cpi, int opcode) { final int index = toConstantPoolIndex(cpi, opcode); final long metaspaceMethod = runtime().getCompilerToVM().lookupMethodInPool(metaspaceConstantPool, index, (byte) opcode); if (metaspaceMethod != 0L) { return HotSpotResolvedJavaMethod.fromMetaspace(metaspaceMethod); } else { // Get the method's name and signature. String name = getNameRefAt(index); String signature = getSignatureRefAt(index); if (opcode == Bytecodes.INVOKEDYNAMIC) { JavaType holder = HotSpotResolvedJavaType.fromClass(MethodHandle.class); return new HotSpotMethodUnresolved(name, signature, holder); } else { final int klassIndex = getKlassRefIndexAt(index); final long metaspacePointer = runtime().getCompilerToVM().lookupKlassInPool(metaspaceConstantPool, klassIndex); JavaType holder = getJavaType(metaspacePointer); return new HotSpotMethodUnresolved(name, signature, holder); } } } @Override public JavaType lookupType(int cpi, int opcode) { final long metaspacePointer = runtime().getCompilerToVM().lookupKlassInPool(metaspaceConstantPool, cpi); return getJavaType(metaspacePointer); } @Override public JavaField lookupField(int cpi, int opcode) { final int index = toConstantPoolIndex(cpi, opcode); final int nameAndTypeIndex = getNameAndTypeRefIndexAt(index); final int nameIndex = getNameRefIndexAt(nameAndTypeIndex); String name = lookupUtf8(nameIndex); final int typeIndex = getSignatureRefIndexAt(nameAndTypeIndex); String typeName = lookupUtf8(typeIndex); JavaType type = runtime().lookupType(typeName, getHolder(), false); final int holderIndex = getKlassRefIndexAt(index); JavaType holder = lookupType(holderIndex, opcode); if (holder instanceof HotSpotResolvedObjectType) { long[] info = new long[2]; long metaspaceKlass; try { metaspaceKlass = runtime().getCompilerToVM().resolveField(metaspaceConstantPool, index, (byte) opcode, info); } catch (Throwable t) { /* * If there was an exception resolving the field we give up and return an unresolved * field. */ return new HotSpotUnresolvedField(holder, name, type); } HotSpotResolvedObjectType resolvedHolder = (HotSpotResolvedObjectType) HotSpotResolvedObjectType.fromMetaspaceKlass(metaspaceKlass); final int flags = (int) info[0]; final long offset = info[1]; return resolvedHolder.createField(name, type, offset, flags); } else { return new HotSpotUnresolvedField(holder, name, type); } } @Override public void loadReferencedType(int cpi, int opcode) { int index; switch (opcode) { case Bytecodes.CHECKCAST: case Bytecodes.INSTANCEOF: case Bytecodes.NEW: case Bytecodes.ANEWARRAY: case Bytecodes.MULTIANEWARRAY: case Bytecodes.LDC: case Bytecodes.LDC_W: case Bytecodes.LDC2_W: index = cpi; break; case Bytecodes.INVOKEDYNAMIC: // invokedynamic instructions point to a constant pool cache entry. index = decodeConstantPoolCacheIndex(cpi) + runtime().getConfig().constantPoolCpCacheIndexTag; index = runtime().getCompilerToVM().constantPoolRemapInstructionOperandFromCache(metaspaceConstantPool, index); break; default: index = toConstantPoolIndex(cpi, opcode); index = runtime().getCompilerToVM().constantPoolRemapInstructionOperandFromCache(metaspaceConstantPool, index); } JVM_CONSTANT tag = getTagAt(index); if (tag == null) { assert getTagAt(index - 1) == JVM_CONSTANT.Double || getTagAt(index - 1) == JVM_CONSTANT.Long; return; } switch (tag) { case Fieldref: case MethodRef: case InterfaceMethodref: index = getUncachedKlassRefIndexAt(index); tag = getTagAt(index); assert tag == JVM_CONSTANT.Class || tag == JVM_CONSTANT.UnresolvedClass || tag == JVM_CONSTANT.UnresolvedClassInError : tag; // fall-through case Class: case UnresolvedClass: case UnresolvedClassInError: final long metaspaceKlass = runtime().getCompilerToVM().constantPoolKlassAt(metaspaceConstantPool, index); HotSpotResolvedObjectType type = (HotSpotResolvedObjectType) HotSpotResolvedObjectType.fromMetaspaceKlass(metaspaceKlass); Class<?> klass = type.mirror(); if (!klass.isPrimitive() && !klass.isArray()) { unsafe.ensureClassInitialized(klass); } break; case InvokeDynamic: if (isInvokedynamicIndex(cpi)) { runtime().getCompilerToVM().resolveInvokeDynamic(metaspaceConstantPool, cpi); } break; default: // nothing break; } } @Override public String toString() { HotSpotResolvedObjectType holder = getHolder(); return "HotSpotConstantPool<" + holder.toJavaName() + ">"; } }
package org.intermine.dwr; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.lucene.queryParser.ParseException; import org.apache.struts.Globals; import org.apache.struts.util.MessageResources; import org.directwebremoting.WebContext; import org.directwebremoting.WebContextFactory; import org.intermine.InterMineException; import org.intermine.api.InterMineAPI; import org.intermine.api.bag.BagManager; import org.intermine.api.bag.BagQueryConfig; import org.intermine.api.bag.TypeConverter; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.Profile; import org.intermine.api.profile.ProfileAlreadyExistsException; import org.intermine.api.profile.ProfileManager; import org.intermine.api.profile.SavedQuery; import org.intermine.api.profile.TagManager; import org.intermine.api.query.WebResultsExecutor; import org.intermine.api.results.WebTable; import org.intermine.api.search.Scope; import org.intermine.api.search.SearchFilterEngine; import org.intermine.api.search.SearchRepository; import org.intermine.api.search.WebSearchable; import org.intermine.api.tag.TagNames; import org.intermine.api.template.TemplateManager; import org.intermine.api.template.TemplateQuery; import org.intermine.api.template.TemplateSummariser; import org.intermine.api.util.NameUtil; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.ResultsRow; import org.intermine.pathquery.OrderDirection; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathException; import org.intermine.pathquery.PathQuery; import org.intermine.util.StringUtil; import org.intermine.util.TypeUtil; import org.intermine.web.autocompletion.AutoCompleter; import org.intermine.web.logic.Constants; import org.intermine.web.logic.PortalHelper; import org.intermine.web.logic.bag.BagConverter; import org.intermine.web.logic.config.Type; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.query.PageTableQueryMonitor; import org.intermine.web.logic.query.QueryMonitorTimeout; import org.intermine.web.logic.results.PagedTable; import org.intermine.web.logic.results.WebState; import org.intermine.web.logic.session.QueryCountQueryMonitor; import org.intermine.web.logic.session.SessionMethods; import org.intermine.web.logic.widget.EnrichmentWidget; import org.intermine.web.logic.widget.GraphWidget; import org.intermine.web.logic.widget.HTMLWidget; import org.intermine.web.logic.widget.TableWidget; import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig; import org.intermine.web.logic.widget.config.GraphWidgetConfig; import org.intermine.web.logic.widget.config.HTMLWidgetConfig; import org.intermine.web.logic.widget.config.TableWidgetConfig; import org.intermine.web.logic.widget.config.WidgetConfig; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; /** * This class contains the methods called through DWR Ajax * * @author Xavier Watkins * */ public class AjaxServices { protected static final Logger LOG = Logger.getLogger(AjaxServices.class); private static final Object ERROR_MSG = "Error happened during DWR ajax service."; private static final String INVALID_NAME_MSG = "Invalid name. Names may only contain letters, " + "numbers, spaces, and underscores."; /** * Creates a favourite Tag for the given templateName * * @param name the name of the template we want to set as a favourite * @param type type of tag (bag or template) * @param isFavourite whether or not this item is currently a favourite */ public void setFavourite(String name, String type, boolean isFavourite) { try { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); Profile profile = SessionMethods.getProfile(session); String nameCopy = name.replaceAll("#039;", "'"); TagManager tagManager = getTagManager(); // already a favourite. turning off. if (isFavourite) { tagManager.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername()); // not a favourite. turning on. } else { tagManager.addTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername()); } } catch (RuntimeException e) { processException(e); } } private static void processWidgetException(Exception e, String widgetId) { String msg = "Failed to render widget: " + widgetId; LOG.error(msg, e); } private static void processException(Exception e) { LOG.error(ERROR_MSG, e); if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } /** * Precomputes the given template query * @param templateName the template query name * @return a String to guarantee the service ran properly */ public String preCompute(String templateName) { try { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Profile profile = SessionMethods.getProfile(session); Map<String, TemplateQuery> templates = profile.getSavedTemplates(); TemplateQuery t = templates.get(templateName); WebResultsExecutor executor = im.getWebResultsExecutor(profile); try { session.setAttribute("precomputing_" + templateName, "true"); executor.precomputeTemplate(t); } catch (ObjectStoreException e) { LOG.error("Error while precomputing", e); } finally { session.removeAttribute("precomputing_" + templateName); } } catch (RuntimeException e) { processException(e); } return "precomputed"; } /** * Summarises the given template query. * * @param templateName the template query name * @return a String to guarantee the service ran properly */ public String summarise(String templateName) { try { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Profile profile = SessionMethods.getProfile(session); Map<String, TemplateQuery> templates = profile.getSavedTemplates(); TemplateQuery template = templates.get(templateName); TemplateSummariser summariser = im.getTemplateSummariser(); try { session.setAttribute("summarising_" + templateName, "true"); summariser.summarise(template); } catch (ObjectStoreException e) { LOG.error("Failed to summarise " + templateName, e); } catch (NullPointerException e) { NullPointerException e2 = new NullPointerException("No such template " + templateName); e2.initCause(e); throw e2; } finally { session.removeAttribute("summarising_" + templateName); } } catch (RuntimeException e) { processException(e); } return "summarised"; } /** * Rename a element such as history, name, bag * @param name the name of the element * @param type history, saved, bag * @param reName the new name for the element * @return the new name of the element as a String * @exception Exception if the application business logic throws * an exception */ public String rename(String name, String type, String reName) throws Exception { String newName; try { newName = reName.trim(); WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); Profile profile = SessionMethods.getProfile(session); SavedQuery sq; if (name.equals(newName) || StringUtils.isEmpty(newName)) { return name; } // TODO get error text from properties file if (!NameUtil.isValidName(newName)) { return INVALID_NAME_MSG; } if ("history".equals(type)) { if (profile.getHistory().get(name) == null) { return "<i>" + name + " does not exist</i>"; } if (profile.getHistory().get(newName) != null) { return "<i>" + newName + " already exists</i>"; } profile.renameHistory(name, newName); } else if ("saved".equals(type)) { if (profile.getSavedQueries().get(name) == null) { return "<i>" + name + " does not exist</i>"; } if (profile.getSavedQueries().get(newName) != null) { return "<i>" + newName + " already exists</i>"; } sq = profile.getSavedQueries().get(name); profile.deleteQuery(sq.getName()); sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery()); profile.saveQuery(sq.getName(), sq); } else if ("bag".equals(type)) { try { profile.renameBag(name, newName); } catch (IllegalArgumentException e) { return "<i>" + name + " does not exist</i>"; } catch (ProfileAlreadyExistsException e) { return "<i>" + newName + " already exists</i>"; } } else { return "Type unknown"; } return newName; } catch (RuntimeException e) { processException(e); return null; } } /** * For a given bag, set its description * @param bagName the bag * @param description the description as entered by the user * @return the description for display on the jsp page * @throws Exception an exception */ public String saveBagDescription(String bagName, String description) throws Exception { try { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); Profile profile = SessionMethods.getProfile(session); InterMineBag bag = profile.getSavedBags().get(bagName); if (bag == null) { throw new InterMineException("List \"" + bagName + "\" not found."); } bag.setDescription(description); profile.getSearchRepository().descriptionChanged(bag); return description; } catch (RuntimeException e) { processException(e); return null; } } /** * Set the description of a view path. * @param pathString the string representation of the path * @param description the new description * @return the description, or null if the description was empty */ public String changeViewPathDescription(String pathString, String description) { try { String descr = description; if (description.trim().length() == 0) { descr = null; } WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); PathQuery query = SessionMethods.getQuery(session); Path path = query.makePath(pathString); Path prefixPath = path.getPrefix(); if (descr == null) { // setting to null removes the description query.setDescription(prefixPath.getNoConstraintsString(), null); } else { query.setDescription(prefixPath.getNoConstraintsString(), descr); } if (descr == null) { return null; } return descr.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); } catch (RuntimeException e) { processException(e); return null; } catch (PathException e) { processException(e); return null; } } /* * Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null */ private static WebState getWebState() { HttpSession session = WebContextFactory.get().getSession(); return SessionMethods.getWebState(session); } /** * Get the summary for the given column * @param summaryPath the path for the column as a String * @param tableName name of column-owning table * @return a collection of rows * @throws Exception an exception */ public static List getColumnSummary(String tableName, String summaryPath) throws Exception { try { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Profile profile = SessionMethods.getProfile(session); WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile); WebTable webTable = (SessionMethods.getResultsTable(session, tableName)) .getWebTable(); PathQuery pathQuery = webTable.getPathQuery(); List<ResultsRow> results = (List) webResultsExecutor.summariseQuery(pathQuery, summaryPath); // Start the count of results Query countQuery = webResultsExecutor.makeSummaryQuery(pathQuery, summaryPath); QueryCountQueryMonitor clientState = new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery); MessageResources messages = (MessageResources) ctx.getHttpServletRequest() .getAttribute(Globals.MESSAGES_KEY); String qid = SessionMethods.startQueryCount(clientState, session, messages); List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>(); int rowCount = 0; for (ResultsRow row : results) { rowCount++; if (rowCount > 10) { break; } pageSizeResults.add(row); } return Arrays.asList(new Object[] {pageSizeResults, qid, new Integer(rowCount)}); } catch (RuntimeException e) { processException(e); return null; } } /** * Return the number of rows of results from the query with the given query id. If the size * isn't yet available, return null. The query must be started with * SessionMethods.startPagedTableCount(). * @param qid the id * @return the row count or null if not yet available */ public static Integer getResultsSize(String qid) { try { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); QueryMonitorTimeout controller = (QueryMonitorTimeout) SessionMethods.getRunningQueryController(qid, session); // this could happen if the user navigates away then back to the page if (controller == null) { return null; } // First tickle the controller to avoid timeout controller.tickle(); if (controller.isCancelledWithError()) { LOG.debug("query qid " + qid + " error"); return null; } else if (controller.isCancelled()) { LOG.debug("query qid " + qid + " cancelled"); return null; } else if (controller.isCompleted()) { LOG.debug("query qid " + qid + " complete"); if (controller instanceof PageTableQueryMonitor) { PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable(); return new Integer(pt.getExactSize()); } if (controller instanceof QueryCountQueryMonitor) { return new Integer(((QueryCountQueryMonitor) controller).getCount()); } LOG.debug("query qid " + qid + " - unknown controller type"); return null; } else { // query still running LOG.debug("query qid " + qid + " still running, making client wait"); return null; } } catch (RuntimeException e) { processException(e); return null; } } /** * Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in * a format useful in JavaScript. Each element of the returned List is a List containing a * WebSearchable name, a score (from Lucene) and a string with the matching parts of the * description highlighted. * @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE, * even though not all WebSearchables are templates) * @param type the type (from TagTypes) * @param tags the tags to filter on * @param filterText the text to pass to Lucene * @param filterAction toggles favourites filter off an on; will be blank or 'favourites' * @param callId unique id * @return a List of Lists */ public static List<String> filterWebSearchables(String scope, String type, List<String> tags, String filterText, String filterAction, String callId) { try { ServletContext servletContext = WebContextFactory.get().getServletContext(); HttpSession session = WebContextFactory.get().getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); ProfileManager pm = im.getProfileManager(); Profile profile = SessionMethods.getProfile(session); Map<String, WebSearchable> wsMap; Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>(); Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>(); if (filterText != null && filterText.length() > 1) { wsMap = new LinkedHashMap<String, WebSearchable>(); //Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>(); SearchRepository globalSearchRepository = SessionMethods.getGlobalSearchRepository(servletContext); try { long time = SearchRepository.runLeuceneSearch(filterText, scope, type, profile, globalSearchRepository, hitMap, null, highlightedDescMap); LOG.info("Lucene search took " + time + " milliseconds"); } catch (ParseException e) { LOG.error("couldn't run lucene filter", e); ArrayList<String> emptyList = new ArrayList<String>(); emptyList.add(callId); return emptyList; } catch (IOException e) { LOG.error("couldn't run lucene filter", e); ArrayList<String> emptyList = new ArrayList<String>(); emptyList.add(callId); return emptyList; } //long time = System.currentTimeMillis(); for (WebSearchable ws: hitMap.keySet()) { wsMap.put(ws.getName(), ws); } } else { if (scope.equals(Scope.USER)) { SearchRepository searchRepository = profile.getSearchRepository(); wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type); } else { SearchRepository globalRepository = SessionMethods .getGlobalSearchRepository(servletContext); if (scope.equals(Scope.GLOBAL)) { wsMap = (Map<String, WebSearchable>) globalRepository. getWebSearchableMap(type); } else { // must be "all" SearchRepository userSearchRepository = profile.getSearchRepository(); Map<String, ? extends WebSearchable> userWsMap = userSearchRepository.getWebSearchableMap(type); Map<String, ? extends WebSearchable> globalWsMap = globalRepository.getWebSearchableMap(type); wsMap = new HashMap<String, WebSearchable>(userWsMap); wsMap.putAll(globalWsMap); } } } Map<String, ? extends WebSearchable> filteredWsMap = new LinkedHashMap<String, WebSearchable>(); //Filter by aspects (defined in superuser account) List<String> aspectTags = new ArrayList<String>(); List<String> userTags = new ArrayList<String>(); for (String tag :tags) { if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) { aspectTags.add(tag); } else { userTags.add(tag); } } if (aspectTags.size() > 0) { wsMap = new SearchFilterEngine().filterByTags(wsMap, aspectTags, type, pm.getSuperuser(), getTagManager()); } if (profile.getUsername() != null && userTags.size() > 0) { filteredWsMap = new SearchFilterEngine().filterByTags(wsMap, userTags, type, profile.getUsername(), getTagManager()); } else { filteredWsMap = wsMap; } List returnList = new ArrayList<String>(); returnList.add(callId); // We need a modifiable map so we can filter out invalid templates LinkedHashMap<String, ? extends WebSearchable> modifiableWsMap = new LinkedHashMap(filteredWsMap); SearchRepository.filterOutInvalidTemplates(modifiableWsMap); for (WebSearchable ws: modifiableWsMap.values()) { List row = new ArrayList(); row.add(ws.getName()); if (filterText != null && filterText.length() > 1) { row.add(highlightedDescMap.get(ws)); row.add(hitMap.get(ws)); } else { row.add(ws.getDescription()); } returnList.add(row); } return returnList; } catch (RuntimeException e) { processException(e); return null; } } /** * For a given bag name and a type different from the bag type, give the number of * converted objects * * @param bagName the name of the bag * @param type the type to convert to * @return the number of converted objects */ public static int getConvertCountForBag(String bagName, String type) { try { HttpSession session = WebContextFactory.get().getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); String pckName = im.getModel().getPackageName(); Profile profile = SessionMethods.getProfile(session); BagManager bagManager = im.getBagManager(); TemplateManager templateManager = im.getTemplateManager(); WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile); InterMineBag imBag = null; int count = 0; try { imBag = bagManager.getUserOrGlobalBag(profile, bagName); List<TemplateQuery> conversionTemplates = templateManager.getConversionTemplates(); PathQuery pathQuery = TypeConverter.getConversionQuery(conversionTemplates, TypeUtil.instantiate(pckName + "." + imBag.getType()), TypeUtil.instantiate(pckName + "." + type), imBag); count = webResultsExecutor.count(pathQuery); } catch (Exception e) { throw new RuntimeException(e); } return count; } catch (RuntimeException e) { processException(e); return 0; } } /** * Saves information, that some element was toggled - displayed or hidden. * * @param elementId element id * @param opened new aspect state */ public static void saveToggleState(String elementId, boolean opened) { try { AjaxServices.getWebState().getToggledElements().put(elementId, Boolean.valueOf(opened)); } catch (RuntimeException e) { processException(e); } } /** * Set state that should be saved during the session. * @param name name of state * @param value value of state */ public static void setState(String name, String value) { try { AjaxServices.getWebState().setState(name, value); } catch (RuntimeException e) { processException(e); } } /** * validate bag upload * @param bagName name of new bag to be validated * @return error msg to display, if any */ public static String validateBagName(String bagName) { try { HttpSession session = WebContextFactory.get().getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Profile profile = SessionMethods.getProfile(session); BagManager bagManager = im.getBagManager(); bagName = bagName.trim(); // TODO get message text from the properties file if ("".equals(bagName)) { return "You cannot save a list with a blank name"; } if (!NameUtil.isValidName(bagName)) { return INVALID_NAME_MSG; } if (profile.getSavedBags().get(bagName) != null) { return "The list name you have chosen is already in use"; } if (bagManager.getGlobalBag(bagName) != null) { return "The list name you have chosen is already in use -" + " there is a public list called " + bagName; } return ""; } catch (RuntimeException e) { processException(e); return null; } } /** * validation that happens before new bag is saved * @param bagName name of new bag * @param selectedBags bags involved in operation * @param operation which operation is taking place - delete, union, intersect or subtract * @return error msg, if any */ public static String validateBagOperations(String bagName, String[] selectedBags, String operation) { try { ServletContext servletContext = WebContextFactory.get().getServletContext(); HttpSession session = WebContextFactory.get().getSession(); Profile profile = SessionMethods.getProfile(session); // TODO get error text from the properties file if (selectedBags.length == 0) { return "No lists are selected"; } if ("delete".equals(operation)) { for (int i = 0; i < selectedBags.length; i++) { Set<String> queries = new HashSet<String>(); queries.addAll(queriesThatMentionBag(profile.getSavedQueries(), selectedBags[i])); queries.addAll(queriesThatMentionBag(profile.getHistory(), selectedBags[i])); if (queries.size() > 0) { return "List " + selectedBags[i] + " cannot be deleted as it is referenced " + "by other queries " + queries; } } } else if (!"copy".equals(operation)) { Properties properties = SessionMethods.getWebProperties(servletContext); String defaultName = properties.getProperty("lists.input.example"); if (("".equals(bagName) || (bagName.equalsIgnoreCase(defaultName)))) { return "New list name is required"; } else if (!NameUtil.isValidName(bagName)) { return INVALID_NAME_MSG; } } return ""; } catch (RuntimeException e) { processException(e); return null; } } /** * Provide a list of queries that mention a named bag * @param savedQueries a saved queries map (name -&gt; query) * @param bagName the name of a bag * @return the list of queries */ private static List<String> queriesThatMentionBag(Map savedQueries, String bagName) { try { List<String> queries = new ArrayList<String>(); for (Iterator i = savedQueries.keySet().iterator(); i.hasNext();) { String queryName = (String) i.next(); SavedQuery query = (SavedQuery) savedQueries.get(queryName); if (query.getPathQuery().getBagNames().contains(bagName)) { queries.add(queryName); } } return queries; } catch (RuntimeException e) { processException(e); return null; } } /** * @param widgetId unique id for this widget * @param bagName name of list * @param selectedExtraAttribute extra attribute (like organism) * @return graph widget */ public static GraphWidget getProcessGraphWidget(String widgetId, String bagName, String selectedExtraAttribute) { try { ServletContext servletContext = WebContextFactory.get().getServletContext(); HttpSession session = WebContextFactory.get().getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); WebConfig webConfig = SessionMethods.getWebConfig(servletContext); ObjectStore os = im.getObjectStore(); Model model = os.getModel(); Profile profile = SessionMethods.getProfile(session); BagManager bagManager = im.getBagManager(); InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName); Type type = webConfig.getTypes().get(model.getPackageName() + "." + imBag.getType()); List<WidgetConfig> widgets = type.getWidgets(); for (WidgetConfig widget: widgets) { if (widget.getId().equals(widgetId)) { GraphWidgetConfig graphWidgetConf = (GraphWidgetConfig) widget; graphWidgetConf.setSession(session); GraphWidget graphWidget = new GraphWidget(graphWidgetConf, imBag, os, selectedExtraAttribute); return graphWidget; } } } catch (RuntimeException e) { processWidgetException(e, widgetId); } return null; } /** * @param widgetId unique id for this widget * @param bagName name of list * @return graph widget */ public static HTMLWidget getProcessHTMLWidget(String widgetId, String bagName) { try { ServletContext servletContext = WebContextFactory.get().getServletContext(); HttpSession session = WebContextFactory.get().getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); WebConfig webConfig = SessionMethods.getWebConfig(servletContext); Model model = im.getModel(); Profile profile = SessionMethods.getProfile(session); BagManager bagManager = im.getBagManager(); InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName); Type type = webConfig.getTypes().get(model.getPackageName() + "." + imBag.getType()); List<WidgetConfig> widgets = type.getWidgets(); for (WidgetConfig widget: widgets) { if (widget.getId().equals(widgetId)) { HTMLWidgetConfig htmlWidgetConf = (HTMLWidgetConfig) widget; HTMLWidget htmlWidget = new HTMLWidget(htmlWidgetConf); return htmlWidget; } } } catch (RuntimeException e) { processWidgetException(e, widgetId); } return null; } /** * * @param widgetId unique ID for this widget * @param bagName name of list * @return table widget */ public static TableWidget getProcessTableWidget(String widgetId, String bagName) { try { ServletContext servletContext = WebContextFactory.get().getServletContext(); HttpSession session = WebContextFactory.get().getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); WebConfig webConfig = SessionMethods.getWebConfig(servletContext); ObjectStore os = im.getObjectStore(); Model model = os.getModel(); Profile profile = SessionMethods.getProfile(session); BagManager bagManager = im.getBagManager(); InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName); Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys(); Type type = webConfig.getTypes().get(model.getPackageName() + "." + imBag.getType()); List<WidgetConfig> widgets = type.getWidgets(); for (WidgetConfig widgetConfig: widgets) { if (widgetConfig.getId().equals(widgetId)) { TableWidgetConfig tableWidgetConfig = (TableWidgetConfig) widgetConfig; tableWidgetConfig.setClassKeys(classKeys); tableWidgetConfig.setWebConfig(webConfig); TableWidget tableWidget = new TableWidget(tableWidgetConfig, imBag, os, null); return tableWidget; } } } catch (RuntimeException e) { processWidgetException(e, widgetId); } return null; } /** * * @param widgetId unique ID for each widget * @param bagName name of list * @param errorCorrection error correction method to use * @param max maximum value to display * @param filters list of strings used to filter widget results, ie Ontology * @param externalLink link to external datasource * @param externalLinkLabel name of external datasource. * @return enrichment widget */ public static EnrichmentWidget getProcessEnrichmentWidget(String widgetId, String bagName, String errorCorrection, String max, String filters, String externalLink, String externalLinkLabel) { try { ServletContext servletContext = WebContextFactory.get().getServletContext(); HttpSession session = WebContextFactory.get().getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); WebConfig webConfig = SessionMethods.getWebConfig(servletContext); ObjectStore os = im.getObjectStore(); Model model = os.getModel(); Profile profile = SessionMethods.getProfile(session); BagManager bagManager = im.getBagManager(); InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName); Type type = webConfig.getTypes().get(model.getPackageName() + "." + imBag.getType()); List<WidgetConfig> widgets = type.getWidgets(); for (WidgetConfig widgetConfig : widgets) { if (widgetConfig.getId().equals(widgetId)) { EnrichmentWidgetConfig enrichmentWidgetConfig = (EnrichmentWidgetConfig) widgetConfig; enrichmentWidgetConfig.setExternalLink(externalLink); enrichmentWidgetConfig.setExternalLinkLabel(externalLinkLabel); EnrichmentWidget enrichmentWidget = new EnrichmentWidget( enrichmentWidgetConfig, imBag, os, filters, max, errorCorrection); return enrichmentWidget; } } } catch (RuntimeException e) { processWidgetException(e, widgetId); } return null; } /** * Add an ID to the PagedTable selection * @param selectedId the id * @param tableId the identifier for the PagedTable * @param columnIndex the column of the selected id * @return the field values of the first selected objects */ public static List<String> selectId(String selectedId, String tableId, String columnIndex) { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); PagedTable pt = SessionMethods.getResultsTable(session, tableId); pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue()); Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys(); ObjectStore os = im.getObjectStore(); return pt.getFirstSelectedFields(os, classKeys); } /** * remove an Id from the PagedTable * @param deSelectId the ID to remove from the selection * @param tableId the PagedTable identifier * @return the field values of the first selected objects */ public static List<String> deSelectId(String deSelectId, String tableId) { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); PagedTable pt = SessionMethods.getResultsTable(session, tableId); pt.deSelectId(new Integer(deSelectId)); Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys(); ObjectStore os = im.getObjectStore(); return pt.getFirstSelectedFields(os, classKeys); } /** * Select all the elements in a PagedTable * @param index the index of the selected column * @param tableId the PagedTable identifier */ public static void selectAll(int index, String tableId) { HttpSession session = WebContextFactory.get().getSession(); PagedTable pt = SessionMethods.getResultsTable(session, tableId); pt.clearSelectIds(); pt.setAllSelectedColumn(index); } /** * AJAX request - reorder view. * @param newOrder the new order as a String * @param oldOrder the previous order as a String */ public void reorder(String newOrder, String oldOrder) { HttpSession session = WebContextFactory.get().getSession(); List<String> newOrderList = new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values()); List<String> oldOrderList = new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values()); List<String> view = SessionMethods.getEditingView(session); ArrayList<String> newView = new ArrayList<String>(); for (int i = 0; i < view.size(); i++) { String newi = newOrderList.get(i); int oldi = oldOrderList.indexOf(newi); newView.add(view.get(oldi)); } PathQuery query = SessionMethods.getQuery(session); query.clearView(); query.addViews(newView); } /** * AJAX request - reorder the constraints. * @param newOrder the new order as a String * @param oldOrder the previous order as a String */ public void reorderConstraints(String newOrder, String oldOrder) { HttpSession session = WebContextFactory.get().getSession(); List<String> newOrderList = new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values()); List<String> oldOrderList = new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values()); PathQuery query = SessionMethods.getQuery(session); if (query instanceof TemplateQuery) { TemplateQuery template = (TemplateQuery) query; for (int index = 0; index < newOrderList.size() - 1; index++) { String newi = newOrderList.get(index); int oldi = oldOrderList.indexOf(newi); if (index != oldi) { List<PathConstraint> editableConstraints = template.getModifiableEditableConstraints(); PathConstraint editableConstraint = editableConstraints.remove(oldi); editableConstraints.add(index, editableConstraint); template.setEditableConstraints(editableConstraints); break; } } } } /** * Add a Node from the sort order * @param path the Path as a String * @param direction the direction to sort by * @exception Exception if the application business logic throws */ public void addToSortOrder(String path, String direction) throws Exception { HttpSession session = WebContextFactory.get().getSession(); PathQuery query = SessionMethods.getQuery(session); OrderDirection orderDirection = OrderDirection.ASC; if ("DESC".equals(direction.toUpperCase())) { orderDirection = OrderDirection.DESC; } query.clearOrderBy(); query.addOrderBy(path, orderDirection); } /** * Work as a proxy for fetching remote file (RSS) * @param rssURL the url * @return String representation of a file */ public static String getNewsPreview(String rssURL) { try { URL url = new URL(rssURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; StringBuffer sb = new StringBuffer(); // append to string buffer while ((str = in.readLine()) != null) { sb.append(str); } in.close(); return sb.toString(); } catch (MalformedURLException e) { return ""; } catch (IOException e) { return ""; } } /** * Get the news * @param rssURI the URI of the rss feed * @return the news feed as html * * @deprecated use getNewsPreview() instead */ public static String getNewsRead(String rssURI) { try { URL feedUrl = new URL(rssURI); SyndFeedInput input = new SyndFeedInput(); XmlReader reader; try { reader = new XmlReader(feedUrl); } catch (Throwable e) { // xml document at this url doesn't exist or is invalid, so the news cannot be read return "<i>No news</i>"; } SyndFeed feed = input.build(reader); List<SyndEntry> entries = feed.getEntries(); StringBuffer html = new StringBuffer("<ol id=\"news\">"); int counter = 0; for (SyndEntry syndEntry : entries) { if (counter > 4) { break; } // NB: apparently, the only accepted formats for getPublishedDate are // Fri, 28 Jan 2008 11:02 GMT // Fri, 8 Jan 2008 11:02 GMT // Fri, 8 Jan 08 11:02 GMT // an annoying error appears if the format is not followed, and news tile hangs. // the following is used to display the date without timestamp. // this should always work since the retrieved date has a fixed format, // independent of the one used in the xml. // longDate = Wed Aug 19 14:44:19 BST 2009 String longDate = syndEntry.getPublishedDate().toString(); String dayMonth = longDate.substring(0, 10); String year = longDate.substring(24); DateFormat df = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); Date date = df.parse(longDate); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // month starts at zero int month = calendar.get(calendar.MONTH) + 1; String monthString = String.valueOf(month); if (monthString.length() == 1) { monthString = "0" + monthString; } // WebContext ctx = WebContextFactory.get(); // ServletContext servletContext = ctx.getServletContext(); // Properties properties = SessionMethods.getWebProperties(servletContext); String url = syndEntry.getLink(); // properties.getProperty("project.news") + "/" + year + "/" + monthString; html.append("<li>"); html.append("<strong>"); html.append("<a href=\"" + url + "\">"); html.append(syndEntry.getTitle()); html.append("</a>"); html.append("</strong>"); // html.append(" - <em>" + dayMonth + " " + year + "</em><br/>"); html.append("- <em>" + syndEntry.getPublishedDate().toString() + "</em><br/>"); html.append(syndEntry.getDescription().getValue()); html.append("</li>"); counter++; } html.append("</ol>"); return html.toString(); } catch (MalformedURLException e) { return "<i>No news at specified URL</i>"; } catch (IllegalArgumentException e) { return "<i>No news at specified URL</i>"; } catch (FeedException e) { return "<i>No news at specified URL</i>"; } catch (java.text.ParseException e) { return "<i>No news at specified URL</i>"; } } /** * Returns all objects names tagged with specified tag type and tag name. * @param type tag type * @param tag tag name * @return objects names */ public static Set<String> filterByTag(String type, String tag) { Profile profile = getProfile(getRequest()); SearchRepository searchRepository = profile.getSearchRepository(); Map<String, WebSearchable> map = (Map<String, WebSearchable>) searchRepository. getWebSearchableMap(type); if (map == null) { return null; } Map<String, WebSearchable> filteredMap = new TreeMap<String, WebSearchable>(); List<String> tagList = new ArrayList<String>(); tagList.add(tag); filteredMap.putAll(new SearchFilterEngine().filterByTags(map, tagList, type, profile.getUsername(), getTagManager())); return filteredMap.keySet(); } /** * Adds tag and assures that there is only one tag for this combination of tag name, tagged * Object and type. * @param tag tag name * @param taggedObject object id that is tagged by this tag * @param type tag type * @return 'ok' string if succeeded else error string */ public static String addTag(String tag, String taggedObject, String type) { String tagName = tag; LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:" + taggedObject + " type: " + type); try { HttpServletRequest request = getRequest(); Profile profile = getProfile(request); tagName = tagName.trim(); HttpSession session = request.getSession(); if (profile.getUsername() != null && !StringUtils.isEmpty(tagName) && !StringUtils.isEmpty(type) && !StringUtils.isEmpty(taggedObject)) { if (tagExists(tagName, taggedObject, type)) { return "Already tagged with this tag."; } if (!TagManager.isValidTagName(tagName)) { return INVALID_NAME_MSG; } if (tagName.startsWith(TagNames.IM_PREFIX) && !SessionMethods.isSuperUser(session)) { return "You cannot add a tag starting with " + TagNames.IM_PREFIX + ", " + "that is a reserved word."; } TagManager tagManager = getTagManager(); tagManager.addTag(tagName, taggedObject, type, profile.getUsername()); ServletContext servletContext = session.getServletContext(); if (SessionMethods.isSuperUser(session)) { SearchRepository tr = SessionMethods. getGlobalSearchRepository(servletContext); tr.webSearchableTagChange(type, tagName); } return "ok"; } return "Adding tag failed."; } catch (Throwable e) { LOG.error("Adding tag failed", e); return "Adding tag failed."; } } /** * Deletes tag. * @param tagName tag name * @param tagged id of tagged object * @param type tag type * @return 'ok' string if succeeded else error string */ public static String deleteTag(String tagName, String tagged, String type) { LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:" + tagged + " type: " + type); try { HttpServletRequest request = getRequest(); HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Profile profile = getProfile(request); TagManager manager = im.getTagManager(); manager.deleteTag(tagName, tagged, type, profile.getUsername()); ServletContext servletContext = session.getServletContext(); if (SessionMethods.isSuperUser(session)) { SearchRepository tr = SessionMethods.getGlobalSearchRepository(servletContext); tr.webSearchableTagChange(type, tagName); } return "ok"; } catch (Throwable e) { LOG.error("Deleting tag failed", e); return "Deleting tag failed."; } } /** * Returns all tags of specified tag type together with prefixes of these tags. * For instance: for tag 'bio:experiment' it automatically adds 'bio' tag. * @param type tag type * @return tags */ public static Set<String> getTags(String type) { HttpServletRequest request = getRequest(); final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession()); TagManager tagManager = im.getTagManager(); Profile profile = getProfile(request); if (profile.isLoggedIn()) { return tagManager.getUserTagNames(type, profile.getUsername()); } return new TreeSet<String>(); } /** * Returns all tags by which is specified object tagged. * @param type tag type * @param tagged id of tagged object * @return tags */ public static Set<String> getObjectTags(String type, String tagged) { HttpServletRequest request = getRequest(); final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession()); TagManager tagManager = im.getTagManager(); Profile profile = getProfile(request); if (profile.isLoggedIn()) { return tagManager.getObjectTagNames(tagged, type, profile.getUsername()); } return new TreeSet<String>(); } private static boolean tagExists(String tag, String taggedObject, String type) { HttpServletRequest request = getRequest(); final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession()); TagManager tagManager = im.getTagManager(); String userName = getProfile(request).getUsername(); return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag); } private static Profile getProfile(HttpServletRequest request) { return SessionMethods.getProfile(request.getSession()); } private static HttpServletRequest getRequest() { return WebContextFactory.get().getHttpServletRequest(); } private static TagManager getTagManager() { HttpServletRequest request = getRequest(); final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession()); return im.getTagManager(); } /** * Set the constraint logic on a query to be the given expression. * * @param expression the constraint logic for the query * @throws PathException if the query is invalid */ public static void setConstraintLogic(String expression) throws PathException { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); PathQuery query = SessionMethods.getQuery(session); query.setConstraintLogic(expression); List<String> messages = query.fixUpForJoinStyle(); for (String message : messages) { SessionMethods.recordMessage(message, session); } } /** * Get the grouped constraint logic * @return a list representing the grouped constraint logic */ public static String getConstraintLogic() { WebContext ctx = WebContextFactory.get(); HttpSession session = ctx.getSession(); PathQuery query = SessionMethods.getQuery(session); return (query.getConstraintLogic()); } /** * @param suffix string of input before request for more results * @param wholeList whether or not to show the entire list or a truncated version * @param field field name from the table for the lucene search * @param className class name (table in the database) for lucene search * @return an array of values for this classname.field */ public String[] getContent(String suffix, boolean wholeList, String field, String className) { ServletContext servletContext = WebContextFactory.get().getServletContext(); AutoCompleter ac = SessionMethods.getAutoCompleter(servletContext); ac.createRAMIndex(className + "." + field); if (!wholeList && suffix.length() > 0) { String[] shortList = ac.getFastList(suffix, field, 31); return shortList; } else if (suffix.length() > 2 && wholeList) { String[] longList = ac.getList(suffix, field); return longList; } String[] defaultList = {""}; return defaultList; } /** * Used on list analysis page to convert list contents to orthologues. then forwarded to * another intermine instance. * * @param bagType class of bag * @param bagName name of bag * @param param name of parameter value, eg. `orthologue` * @param selectedValue orthologue organism * @return converted list of orthologues * @throws UnsupportedEncodingException bad encoding */ public String convertObjects(String bagType, String bagName, String param, String selectedValue) throws UnsupportedEncodingException { ServletContext servletContext = WebContextFactory.get().getServletContext(); HttpServletRequest request = getRequest(); HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Profile profile = SessionMethods.getProfile(session); WebConfig webConfig = SessionMethods.getWebConfig(servletContext); BagQueryConfig bagQueryConfig = im.getBagQueryConfig(); // Use custom converters Map<String, String []> additionalConverters = bagQueryConfig.getAdditionalConverters(bagType); if (additionalConverters != null) { for (String converterClassName : additionalConverters.keySet()) { String addparameter = PortalHelper.getAdditionalParameter(param, additionalConverters.get(converterClassName)); if (StringUtils.isNotEmpty(addparameter)) { BagConverter bagConverter = PortalHelper.getBagConverter(im, webConfig, converterClassName); return bagConverter.getConvertedObjectFields(profile, bagType, bagName, selectedValue); } } } return null; } }
package com.trygveaa.gcmnotifier; import com.google.android.gcm.GCMRegistrar; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { private static final String TAG = "GCMNotifier"; private static final String SENDER_ID = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { GCMRegistrar.register(this, SENDER_ID); } else { Log.v(TAG, "Already registered with id: " + regId); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.oracle.graal.phases.common; import static com.oracle.graal.api.meta.DeoptimizationAction.*; import static com.oracle.graal.api.meta.DeoptimizationReason.*; import static com.oracle.graal.compiler.common.GraalOptions.*; import static com.oracle.graal.compiler.common.type.StampFactory.*; import java.util.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.code.Assumptions.Assumption; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.meta.JavaTypeProfile.ProfiledType; import com.oracle.graal.api.meta.ResolvedJavaType.Representation; import com.oracle.graal.compiler.common.*; import com.oracle.graal.compiler.common.calc.*; import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.Debug.Scope; import com.oracle.graal.graph.*; import com.oracle.graal.graph.Graph.DuplicationReplacement; import com.oracle.graal.graph.Node.Verbosity; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.java.MethodCallTargetNode.InvokeKind; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; import com.oracle.graal.nodes.util.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.common.InliningPhase.InliningData; import com.oracle.graal.phases.tiers.*; import com.oracle.graal.phases.util.*; public class InliningUtil { private static final DebugMetric metricInliningTailDuplication = Debug.metric("InliningTailDuplication"); private static final String inliningDecisionsScopeString = "InliningDecisions"; /** * Meters the size (in bytecodes) of all methods processed during compilation (i.e., top level * and all inlined methods), irrespective of how many bytecodes in each method are actually * parsed (which may be none for methods whose IR is retrieved from a cache). */ public static final DebugMetric InlinedBytecodes = Debug.metric("InlinedBytecodes"); public interface InliningPolicy { boolean continueInlining(StructuredGraph graph); boolean isWorthInlining(Replacements replacements, InlineInfo info, int inliningDepth, double probability, double relevance, boolean fullyProcessed); } public interface Inlineable { int getNodeCount(); Iterable<Invoke> getInvokes(); } public static class InlineableGraph implements Inlineable { private final StructuredGraph graph; public InlineableGraph(StructuredGraph graph) { this.graph = graph; } @Override public int getNodeCount() { return graph.getNodeCount(); } @Override public Iterable<Invoke> getInvokes() { return graph.getInvokes(); } public StructuredGraph getGraph() { return graph; } } public static class InlineableMacroNode implements Inlineable { private final Class<? extends FixedWithNextNode> macroNodeClass; public InlineableMacroNode(Class<? extends FixedWithNextNode> macroNodeClass) { this.macroNodeClass = macroNodeClass; } @Override public int getNodeCount() { return 1; } @Override public Iterable<Invoke> getInvokes() { return Collections.emptyList(); } public Class<? extends FixedWithNextNode> getMacroNodeClass() { return macroNodeClass; } } /** * Print a HotSpot-style inlining message to the console. */ private static void printInlining(final InlineInfo info, final int inliningDepth, final boolean success, final String msg, final Object... args) { printInlining(info.methodAt(0), info.invoke(), inliningDepth, success, msg, args); } /** * Print a HotSpot-style inlining message to the console. */ private static void printInlining(final ResolvedJavaMethod method, final Invoke invoke, final int inliningDepth, final boolean success, final String msg, final Object... args) { if (HotSpotPrintInlining.getValue()) { // 1234567 TTY.print(" "); // print timestamp // 1234 TTY.print(" "); // print compilation number // % s ! b n TTY.print("%c%c%c%c%c ", ' ', method.isSynchronized() ? 's' : ' ', ' ', ' ', method.isNative() ? 'n' : ' '); TTY.print(" "); // more indent TTY.print(" "); // initial inlining indent for (int i = 0; i < inliningDepth; i++) { TTY.print(" "); } TTY.println(String.format("@ %d %s %s%s", invoke.bci(), methodName(method, null), success ? "" : "not inlining ", String.format(msg, args))); } } public static boolean logInlinedMethod(InlineInfo info, int inliningDepth, boolean allowLogging, String msg, Object... args) { return logInliningDecision(info, inliningDepth, allowLogging, true, msg, args); } public static boolean logNotInlinedMethod(InlineInfo info, int inliningDepth, String msg, Object... args) { return logInliningDecision(info, inliningDepth, true, false, msg, args); } public static boolean logInliningDecision(InlineInfo info, int inliningDepth, boolean allowLogging, boolean success, String msg, final Object... args) { if (allowLogging) { printInlining(info, inliningDepth, success, msg, args); if (shouldLogInliningDecision()) { logInliningDecision(methodName(info), success, msg, args); } } return success; } public static void logInliningDecision(final String msg, final Object... args) { try (Scope s = Debug.scope(inliningDecisionsScopeString)) { // Can't use log here since we are varargs if (Debug.isLogEnabled()) { Debug.logv(msg, args); } } } private static boolean logNotInlinedMethod(Invoke invoke, String msg) { if (shouldLogInliningDecision()) { String methodString = invoke.toString() + (invoke.callTarget() == null ? " callTarget=null" : invoke.callTarget().targetName()); logInliningDecision(methodString, false, msg, new Object[0]); } return false; } private static InlineInfo logNotInlinedMethodAndReturnNull(Invoke invoke, int inliningDepth, ResolvedJavaMethod method, String msg) { return logNotInlinedMethodAndReturnNull(invoke, inliningDepth, method, msg, new Object[0]); } private static InlineInfo logNotInlinedMethodAndReturnNull(Invoke invoke, int inliningDepth, ResolvedJavaMethod method, String msg, Object... args) { printInlining(method, invoke, inliningDepth, false, msg, args); if (shouldLogInliningDecision()) { String methodString = methodName(method, invoke); logInliningDecision(methodString, false, msg, args); } return null; } private static boolean logNotInlinedMethodAndReturnFalse(Invoke invoke, int inliningDepth, ResolvedJavaMethod method, String msg) { printInlining(method, invoke, inliningDepth, false, msg, new Object[0]); if (shouldLogInliningDecision()) { String methodString = methodName(method, invoke); logInliningDecision(methodString, false, msg, new Object[0]); } return false; } private static void logInliningDecision(final String methodString, final boolean success, final String msg, final Object... args) { String inliningMsg = "inlining " + methodString + ": " + msg; if (!success) { inliningMsg = "not " + inliningMsg; } logInliningDecision(inliningMsg, args); } public static boolean shouldLogInliningDecision() { try (Scope s = Debug.scope(inliningDecisionsScopeString)) { return Debug.isLogEnabled(); } } private static String methodName(ResolvedJavaMethod method, Invoke invoke) { if (invoke != null && invoke.stateAfter() != null) { return methodName(invoke.stateAfter(), invoke.bci()) + ": " + MetaUtil.format("%H.%n(%p):%r", method) + " (" + method.getCodeSize() + " bytes)"; } else { return MetaUtil.format("%H.%n(%p):%r", method) + " (" + method.getCodeSize() + " bytes)"; } } private static String methodName(InlineInfo info) { if (info == null) { return "null"; } else if (info.invoke() != null && info.invoke().stateAfter() != null) { return methodName(info.invoke().stateAfter(), info.invoke().bci()) + ": " + info.toString(); } else { return info.toString(); } } private static String methodName(FrameState frameState, int bci) { StringBuilder sb = new StringBuilder(); if (frameState.outerFrameState() != null) { sb.append(methodName(frameState.outerFrameState(), frameState.outerFrameState().bci)); sb.append("->"); } sb.append(MetaUtil.format("%h.%n", frameState.method())); sb.append("@").append(bci); return sb.toString(); } /** * Represents an opportunity for inlining at a given invoke, with the given weight and level. * The weight is the amortized weight of the additional code - so smaller is better. The level * is the number of nested inlinings that lead to this invoke. */ public interface InlineInfo { /** * The graph containing the {@link #invoke() invocation} that may be inlined. */ StructuredGraph graph(); /** * The invocation that may be inlined. */ Invoke invoke(); /** * Returns the number of methods that may be inlined by the {@link #invoke() invocation}. * This may be more than one in the case of a invocation profile showing a number of "hot" * concrete methods dispatched to by the invocation. */ int numberOfMethods(); ResolvedJavaMethod methodAt(int index); Inlineable inlineableElementAt(int index); double probabilityAt(int index); double relevanceAt(int index); void setInlinableElement(int index, Inlineable inlineableElement); /** * Performs the inlining described by this object and returns the node that represents the * return value of the inlined method (or null for void methods and methods that have no * non-exceptional exit). */ void inline(Providers providers, Assumptions assumptions); /** * Try to make the call static bindable to avoid interface and virtual method calls. */ void tryToDevirtualizeInvoke(MetaAccessProvider metaAccess, Assumptions assumptions); boolean shouldInline(); } public abstract static class AbstractInlineInfo implements InlineInfo { protected final Invoke invoke; public AbstractInlineInfo(Invoke invoke) { this.invoke = invoke; } @Override public StructuredGraph graph() { return invoke.asNode().graph(); } @Override public Invoke invoke() { return invoke; } protected static void inline(Invoke invoke, ResolvedJavaMethod concrete, Inlineable inlineable, Assumptions assumptions, boolean receiverNullCheck) { if (inlineable instanceof InlineableGraph) { StructuredGraph calleeGraph = ((InlineableGraph) inlineable).getGraph(); InliningUtil.inline(invoke, calleeGraph, receiverNullCheck); } else { assert inlineable instanceof InlineableMacroNode; Class<? extends FixedWithNextNode> macroNodeClass = ((InlineableMacroNode) inlineable).getMacroNodeClass(); inlineMacroNode(invoke, concrete, macroNodeClass); } InlinedBytecodes.add(concrete.getCodeSize()); assumptions.recordMethodContents(concrete); } } public static void replaceInvokeCallTarget(Invoke invoke, StructuredGraph graph, InvokeKind invokeKind, ResolvedJavaMethod targetMethod) { MethodCallTargetNode oldCallTarget = (MethodCallTargetNode) invoke.callTarget(); MethodCallTargetNode newCallTarget = graph.add(new MethodCallTargetNode(invokeKind, targetMethod, oldCallTarget.arguments().toArray(new ValueNode[0]), oldCallTarget.returnType())); invoke.asNode().replaceFirstInput(oldCallTarget, newCallTarget); } /** * Represents an inlining opportunity where the compiler can statically determine a monomorphic * target method and therefore is able to determine the called method exactly. */ public static class ExactInlineInfo extends AbstractInlineInfo { protected final ResolvedJavaMethod concrete; private Inlineable inlineableElement; private boolean suppressNullCheck; public ExactInlineInfo(Invoke invoke, ResolvedJavaMethod concrete) { super(invoke); this.concrete = concrete; assert concrete != null; } public void suppressNullCheck() { suppressNullCheck = true; } @Override public void inline(Providers providers, Assumptions assumptions) { inline(invoke, concrete, inlineableElement, assumptions, !suppressNullCheck); } @Override public void tryToDevirtualizeInvoke(MetaAccessProvider metaAccess, Assumptions assumptions) { // nothing todo, can already be bound statically } @Override public int numberOfMethods() { return 1; } @Override public ResolvedJavaMethod methodAt(int index) { assert index == 0; return concrete; } @Override public double probabilityAt(int index) { assert index == 0; return 1.0; } @Override public double relevanceAt(int index) { assert index == 0; return 1.0; } @Override public String toString() { return "exact " + MetaUtil.format("%H.%n(%p):%r", concrete); } @Override public Inlineable inlineableElementAt(int index) { assert index == 0; return inlineableElement; } @Override public void setInlinableElement(int index, Inlineable inlineableElement) { assert index == 0; this.inlineableElement = inlineableElement; } public boolean shouldInline() { return concrete.shouldBeInlined(); } } /** * Represents an inlining opportunity for which profiling information suggests a monomorphic * receiver, but for which the receiver type cannot be proven. A type check guard will be * generated if this inlining is performed. */ private static class TypeGuardInlineInfo extends AbstractInlineInfo { private final ResolvedJavaMethod concrete; private final ResolvedJavaType type; private Inlineable inlineableElement; public TypeGuardInlineInfo(Invoke invoke, ResolvedJavaMethod concrete, ResolvedJavaType type) { super(invoke); this.concrete = concrete; this.type = type; assert type.isArray() || !type.isAbstract() : type; } @Override public int numberOfMethods() { return 1; } @Override public ResolvedJavaMethod methodAt(int index) { assert index == 0; return concrete; } @Override public Inlineable inlineableElementAt(int index) { assert index == 0; return inlineableElement; } @Override public double probabilityAt(int index) { assert index == 0; return 1.0; } @Override public double relevanceAt(int index) { assert index == 0; return 1.0; } @Override public void setInlinableElement(int index, Inlineable inlineableElement) { assert index == 0; this.inlineableElement = inlineableElement; } @Override public void inline(Providers providers, Assumptions assumptions) { createGuard(graph(), providers.getMetaAccess()); inline(invoke, concrete, inlineableElement, assumptions, false); } @Override public void tryToDevirtualizeInvoke(MetaAccessProvider metaAccess, Assumptions assumptions) { createGuard(graph(), metaAccess); replaceInvokeCallTarget(invoke, graph(), InvokeKind.Special, concrete); } private void createGuard(StructuredGraph graph, MetaAccessProvider metaAccess) { ValueNode nonNullReceiver = InliningUtil.nonNullReceiver(invoke); ConstantNode typeHub = ConstantNode.forConstant(type.getEncoding(Representation.ObjectHub), metaAccess, graph); LoadHubNode receiverHub = graph.unique(new LoadHubNode(nonNullReceiver, typeHub.getKind())); CompareNode typeCheck = CompareNode.createCompareNode(graph, Condition.EQ, receiverHub, typeHub); FixedGuardNode guard = graph.add(new FixedGuardNode(typeCheck, DeoptimizationReason.TypeCheckedInliningViolated, DeoptimizationAction.InvalidateReprofile)); assert invoke.predecessor() != null; ValueNode anchoredReceiver = createAnchoredReceiver(graph, guard, type, nonNullReceiver, true); invoke.callTarget().replaceFirstInput(nonNullReceiver, anchoredReceiver); graph.addBeforeFixed(invoke.asNode(), guard); } @Override public String toString() { return "type-checked with type " + type.getName() + " and method " + MetaUtil.format("%H.%n(%p):%r", concrete); } public boolean shouldInline() { return concrete.shouldBeInlined(); } } /** * Polymorphic inlining of m methods with n type checks (n &ge; m) in case that the profiling * information suggests a reasonable amount of different receiver types and different methods. * If an unknown type is encountered a deoptimization is triggered. */ private static class MultiTypeGuardInlineInfo extends AbstractInlineInfo { private final List<ResolvedJavaMethod> concretes; private final double[] methodProbabilities; private final double maximumMethodProbability; private final ArrayList<Integer> typesToConcretes; private final ArrayList<ProfiledType> ptypes; private final ArrayList<Double> concretesProbabilities; private final double notRecordedTypeProbability; private final Inlineable[] inlineableElements; public MultiTypeGuardInlineInfo(Invoke invoke, ArrayList<ResolvedJavaMethod> concretes, ArrayList<Double> concretesProbabilities, ArrayList<ProfiledType> ptypes, ArrayList<Integer> typesToConcretes, double notRecordedTypeProbability) { super(invoke); assert concretes.size() > 0 : "must have at least one method"; assert ptypes.size() == typesToConcretes.size() : "array lengths must match"; this.concretesProbabilities = concretesProbabilities; this.concretes = concretes; this.ptypes = ptypes; this.typesToConcretes = typesToConcretes; this.notRecordedTypeProbability = notRecordedTypeProbability; this.inlineableElements = new Inlineable[concretes.size()]; this.methodProbabilities = computeMethodProbabilities(); this.maximumMethodProbability = maximumMethodProbability(); assert maximumMethodProbability > 0; } private double[] computeMethodProbabilities() { double[] result = new double[concretes.size()]; for (int i = 0; i < typesToConcretes.size(); i++) { int concrete = typesToConcretes.get(i); double probability = ptypes.get(i).getProbability(); result[concrete] += probability; } return result; } private double maximumMethodProbability() { double max = 0; for (int i = 0; i < methodProbabilities.length; i++) { max = Math.max(max, methodProbabilities[i]); } return max; } @Override public int numberOfMethods() { return concretes.size(); } @Override public ResolvedJavaMethod methodAt(int index) { assert index >= 0 && index < concretes.size(); return concretes.get(index); } @Override public Inlineable inlineableElementAt(int index) { assert index >= 0 && index < concretes.size(); return inlineableElements[index]; } @Override public double probabilityAt(int index) { return methodProbabilities[index]; } @Override public double relevanceAt(int index) { return probabilityAt(index) / maximumMethodProbability; } @Override public void setInlinableElement(int index, Inlineable inlineableElement) { assert index >= 0 && index < concretes.size(); inlineableElements[index] = inlineableElement; } @Override public void inline(Providers providers, Assumptions assumptions) { if (hasSingleMethod()) { inlineSingleMethod(graph(), providers.getMetaAccess(), assumptions); } else { inlineMultipleMethods(graph(), providers, assumptions); } } public boolean shouldInline() { for (ResolvedJavaMethod method : concretes) { if (method.shouldBeInlined()) { return true; } } return false; } private boolean hasSingleMethod() { return concretes.size() == 1 && !shouldFallbackToInvoke(); } private boolean shouldFallbackToInvoke() { return notRecordedTypeProbability > 0; } private void inlineMultipleMethods(StructuredGraph graph, Providers providers, Assumptions assumptions) { int numberOfMethods = concretes.size(); FixedNode continuation = invoke.next(); ValueNode originalReceiver = ((MethodCallTargetNode) invoke.callTarget()).receiver(); // setup merge and phi nodes for results and exceptions MergeNode returnMerge = graph.add(new MergeNode()); returnMerge.setStateAfter(invoke.stateAfter()); PhiNode returnValuePhi = null; if (invoke.asNode().getKind() != Kind.Void) { returnValuePhi = graph.addWithoutUnique(new ValuePhiNode(invoke.asNode().stamp().unrestricted(), returnMerge)); } MergeNode exceptionMerge = null; PhiNode exceptionObjectPhi = null; if (invoke instanceof InvokeWithExceptionNode) { InvokeWithExceptionNode invokeWithException = (InvokeWithExceptionNode) invoke; ExceptionObjectNode exceptionEdge = (ExceptionObjectNode) invokeWithException.exceptionEdge(); exceptionMerge = graph.add(new MergeNode()); FixedNode exceptionSux = exceptionEdge.next(); graph.addBeforeFixed(exceptionSux, exceptionMerge); exceptionObjectPhi = graph.addWithoutUnique(new ValuePhiNode(StampFactory.forKind(Kind.Object), exceptionMerge)); exceptionMerge.setStateAfter(exceptionEdge.stateAfter().duplicateModified(invoke.stateAfter().bci, true, Kind.Object, exceptionObjectPhi)); } // create one separate block for each invoked method BeginNode[] successors = new BeginNode[numberOfMethods + 1]; for (int i = 0; i < numberOfMethods; i++) { successors[i] = createInvocationBlock(graph, invoke, returnMerge, returnValuePhi, exceptionMerge, exceptionObjectPhi, true); } // create the successor for an unknown type FixedNode unknownTypeSux; if (shouldFallbackToInvoke()) { unknownTypeSux = createInvocationBlock(graph, invoke, returnMerge, returnValuePhi, exceptionMerge, exceptionObjectPhi, false); } else { unknownTypeSux = graph.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.TypeCheckedInliningViolated)); } successors[successors.length - 1] = BeginNode.begin(unknownTypeSux); // replace the invoke exception edge if (invoke instanceof InvokeWithExceptionNode) { InvokeWithExceptionNode invokeWithExceptionNode = (InvokeWithExceptionNode) invoke; ExceptionObjectNode exceptionEdge = (ExceptionObjectNode) invokeWithExceptionNode.exceptionEdge(); exceptionEdge.replaceAtUsages(exceptionObjectPhi); exceptionEdge.setNext(null); GraphUtil.killCFG(invokeWithExceptionNode.exceptionEdge()); } assert invoke.asNode().isAlive(); // replace the invoke with a switch on the type of the actual receiver boolean methodDispatch = createDispatchOnTypeBeforeInvoke(graph, successors, false, providers.getMetaAccess()); assert invoke.next() == continuation; invoke.setNext(null); returnMerge.setNext(continuation); invoke.asNode().replaceAtUsages(returnValuePhi); invoke.asNode().replaceAndDelete(null); ArrayList<GuardedValueNode> replacementNodes = new ArrayList<>(); // do the actual inlining for every invoke for (int i = 0; i < numberOfMethods; i++) { BeginNode node = successors[i]; Invoke invokeForInlining = (Invoke) node.next(); ResolvedJavaType commonType; if (methodDispatch) { commonType = concretes.get(i).getDeclaringClass(); } else { commonType = getLeastCommonType(i); } ValueNode receiver = ((MethodCallTargetNode) invokeForInlining.callTarget()).receiver(); boolean exact = (getTypeCount(i) == 1 && !methodDispatch); GuardedValueNode anchoredReceiver = createAnchoredReceiver(graph, node, commonType, receiver, exact); invokeForInlining.callTarget().replaceFirstInput(receiver, anchoredReceiver); inline(invokeForInlining, methodAt(i), inlineableElementAt(i), assumptions, false); replacementNodes.add(anchoredReceiver); } if (shouldFallbackToInvoke()) { replacementNodes.add(null); } if (OptTailDuplication.getValue()) { /* * We might want to perform tail duplication at the merge after a type switch, if * there are invokes that would benefit from the improvement in type information. */ FixedNode current = returnMerge; int opportunities = 0; do { if (current instanceof InvokeNode && ((InvokeNode) current).callTarget() instanceof MethodCallTargetNode && ((MethodCallTargetNode) ((InvokeNode) current).callTarget()).receiver() == originalReceiver) { opportunities++; } else if (current.inputs().contains(originalReceiver)) { opportunities++; } current = ((FixedWithNextNode) current).next(); } while (current instanceof FixedWithNextNode); if (opportunities > 0) { metricInliningTailDuplication.increment(); Debug.log("MultiTypeGuardInlineInfo starting tail duplication (%d opportunities)", opportunities); PhaseContext phaseContext = new PhaseContext(providers, assumptions); CanonicalizerPhase canonicalizer = new CanonicalizerPhase(!ImmutableCode.getValue()); TailDuplicationPhase.tailDuplicate(returnMerge, TailDuplicationPhase.TRUE_DECISION, replacementNodes, phaseContext, canonicalizer); } } } private int getTypeCount(int concreteMethodIndex) { int count = 0; for (int i = 0; i < typesToConcretes.size(); i++) { if (typesToConcretes.get(i) == concreteMethodIndex) { count++; } } return count; } private ResolvedJavaType getLeastCommonType(int concreteMethodIndex) { ResolvedJavaType commonType = null; for (int i = 0; i < typesToConcretes.size(); i++) { if (typesToConcretes.get(i) == concreteMethodIndex) { if (commonType == null) { commonType = ptypes.get(i).getType(); } else { commonType = commonType.findLeastCommonAncestor(ptypes.get(i).getType()); } } } assert commonType != null; return commonType; } private ResolvedJavaType getLeastCommonType() { ResolvedJavaType result = getLeastCommonType(0); for (int i = 1; i < concretes.size(); i++) { result = result.findLeastCommonAncestor(getLeastCommonType(i)); } return result; } private void inlineSingleMethod(StructuredGraph graph, MetaAccessProvider metaAccess, Assumptions assumptions) { assert concretes.size() == 1 && inlineableElements.length == 1 && ptypes.size() > 1 && !shouldFallbackToInvoke() && notRecordedTypeProbability == 0; BeginNode calleeEntryNode = graph.add(new BeginNode()); BeginNode unknownTypeSux = createUnknownTypeSuccessor(graph); BeginNode[] successors = new BeginNode[]{calleeEntryNode, unknownTypeSux}; createDispatchOnTypeBeforeInvoke(graph, successors, false, metaAccess); calleeEntryNode.setNext(invoke.asNode()); inline(invoke, methodAt(0), inlineableElementAt(0), assumptions, false); } private boolean createDispatchOnTypeBeforeInvoke(StructuredGraph graph, BeginNode[] successors, boolean invokeIsOnlySuccessor, MetaAccessProvider metaAccess) { assert ptypes.size() >= 1; ValueNode nonNullReceiver = nonNullReceiver(invoke); Kind hubKind = ((MethodCallTargetNode) invoke.callTarget()).targetMethod().getDeclaringClass().getEncoding(Representation.ObjectHub).getKind(); LoadHubNode hub = graph.unique(new LoadHubNode(nonNullReceiver, hubKind)); if (!invokeIsOnlySuccessor && chooseMethodDispatch()) { assert successors.length == concretes.size() + 1; assert concretes.size() > 0; Debug.log("Method check cascade with %d methods", concretes.size()); ValueNode[] constantMethods = new ValueNode[concretes.size()]; double[] probability = new double[concretes.size()]; for (int i = 0; i < concretes.size(); ++i) { ResolvedJavaMethod firstMethod = concretes.get(i); Constant firstMethodConstant = firstMethod.getEncoding(); ValueNode firstMethodConstantNode = ConstantNode.forConstant(firstMethodConstant, metaAccess, graph); constantMethods[i] = firstMethodConstantNode; double concretesProbability = concretesProbabilities.get(i); assert concretesProbability >= 0.0; probability[i] = concretesProbability; if (i > 0) { double prevProbability = probability[i - 1]; if (prevProbability == 1.0) { probability[i] = 1.0; } else { probability[i] = Math.min(1.0, Math.max(0.0, probability[i] / (1.0 - prevProbability))); } } } FixedNode lastSucc = successors[concretes.size()]; for (int i = concretes.size() - 1; i >= 0; --i) { LoadMethodNode method = graph.add(new LoadMethodNode(concretes.get(i), hub, constantMethods[i].getKind())); CompareNode methodCheck = CompareNode.createCompareNode(graph, Condition.EQ, method, constantMethods[i]); IfNode ifNode = graph.add(new IfNode(methodCheck, successors[i], lastSucc, probability[i])); method.setNext(ifNode); lastSucc = method; } FixedWithNextNode pred = (FixedWithNextNode) invoke.asNode().predecessor(); pred.setNext(lastSucc); return true; } else { Debug.log("Type switch with %d types", concretes.size()); } ResolvedJavaType[] keys = new ResolvedJavaType[ptypes.size()]; double[] keyProbabilities = new double[ptypes.size() + 1]; int[] keySuccessors = new int[ptypes.size() + 1]; for (int i = 0; i < ptypes.size(); i++) { keys[i] = ptypes.get(i).getType(); keyProbabilities[i] = ptypes.get(i).getProbability(); keySuccessors[i] = invokeIsOnlySuccessor ? 0 : typesToConcretes.get(i); assert keySuccessors[i] < successors.length - 1 : "last successor is the unknownTypeSux"; } keyProbabilities[keyProbabilities.length - 1] = notRecordedTypeProbability; keySuccessors[keySuccessors.length - 1] = successors.length - 1; TypeSwitchNode typeSwitch = graph.add(new TypeSwitchNode(hub, successors, keys, keyProbabilities, keySuccessors)); FixedWithNextNode pred = (FixedWithNextNode) invoke.asNode().predecessor(); pred.setNext(typeSwitch); return false; } private boolean chooseMethodDispatch() { for (ResolvedJavaMethod concrete : concretes) { if (!concrete.isInVirtualMethodTable()) { return false; } } if (concretes.size() == 1 && this.notRecordedTypeProbability > 0) { // Always chose method dispatch if there is a single concrete method and the call // site is megamorphic. return true; } if (concretes.size() == ptypes.size()) { // Always prefer types over methods if the number of types is smaller than the // number of methods. return false; } return chooseMethodDispatchCostBased(); } private boolean chooseMethodDispatchCostBased() { double remainder = 1.0 - this.notRecordedTypeProbability; double costEstimateMethodDispatch = remainder; for (int i = 0; i < concretes.size(); ++i) { if (i != 0) { costEstimateMethodDispatch += remainder; } remainder -= concretesProbabilities.get(i); } double costEstimateTypeDispatch = 0.0; remainder = 1.0; for (int i = 0; i < ptypes.size(); ++i) { if (i != 0) { costEstimateTypeDispatch += remainder; } remainder -= ptypes.get(i).getProbability(); } costEstimateTypeDispatch += notRecordedTypeProbability; return costEstimateMethodDispatch < costEstimateTypeDispatch; } private static BeginNode createInvocationBlock(StructuredGraph graph, Invoke invoke, MergeNode returnMerge, PhiNode returnValuePhi, MergeNode exceptionMerge, PhiNode exceptionObjectPhi, boolean useForInlining) { Invoke duplicatedInvoke = duplicateInvokeForInlining(graph, invoke, exceptionMerge, exceptionObjectPhi, useForInlining); BeginNode calleeEntryNode = graph.add(new BeginNode()); calleeEntryNode.setNext(duplicatedInvoke.asNode()); AbstractEndNode endNode = graph.add(new EndNode()); duplicatedInvoke.setNext(endNode); returnMerge.addForwardEnd(endNode); if (returnValuePhi != null) { returnValuePhi.addInput(duplicatedInvoke.asNode()); } return calleeEntryNode; } private static Invoke duplicateInvokeForInlining(StructuredGraph graph, Invoke invoke, MergeNode exceptionMerge, PhiNode exceptionObjectPhi, boolean useForInlining) { Invoke result = (Invoke) invoke.asNode().copyWithInputs(); Node callTarget = result.callTarget().copyWithInputs(); result.asNode().replaceFirstInput(result.callTarget(), callTarget); result.setUseForInlining(useForInlining); Kind kind = invoke.asNode().getKind(); if (kind != Kind.Void) { FrameState stateAfter = invoke.stateAfter(); stateAfter = stateAfter.duplicate(stateAfter.bci); stateAfter.replaceFirstInput(invoke.asNode(), result.asNode()); result.setStateAfter(stateAfter); } if (invoke instanceof InvokeWithExceptionNode) { assert exceptionMerge != null && exceptionObjectPhi != null; InvokeWithExceptionNode invokeWithException = (InvokeWithExceptionNode) invoke; ExceptionObjectNode exceptionEdge = (ExceptionObjectNode) invokeWithException.exceptionEdge(); FrameState stateAfterException = exceptionEdge.stateAfter(); ExceptionObjectNode newExceptionEdge = (ExceptionObjectNode) exceptionEdge.copyWithInputs(); // set new state (pop old exception object, push new one) newExceptionEdge.setStateAfter(stateAfterException.duplicateModified(stateAfterException.bci, stateAfterException.rethrowException(), Kind.Object, newExceptionEdge)); AbstractEndNode endNode = graph.add(new EndNode()); newExceptionEdge.setNext(endNode); exceptionMerge.addForwardEnd(endNode); exceptionObjectPhi.addInput(newExceptionEdge); ((InvokeWithExceptionNode) result).setExceptionEdge(newExceptionEdge); } return result; } @Override public void tryToDevirtualizeInvoke(MetaAccessProvider metaAccess, Assumptions assumptions) { if (hasSingleMethod()) { devirtualizeWithTypeSwitch(graph(), InvokeKind.Special, concretes.get(0), metaAccess); } else { tryToDevirtualizeMultipleMethods(graph(), metaAccess); } } private void tryToDevirtualizeMultipleMethods(StructuredGraph graph, MetaAccessProvider metaAccess) { MethodCallTargetNode methodCallTarget = (MethodCallTargetNode) invoke.callTarget(); if (methodCallTarget.invokeKind() == InvokeKind.Interface) { ResolvedJavaMethod targetMethod = methodCallTarget.targetMethod(); ResolvedJavaType leastCommonType = getLeastCommonType(); // check if we have a common base type that implements the interface -> in that case // we have a vtable entry for the interface method and can use a less expensive // virtual call if (!leastCommonType.isInterface() && targetMethod.getDeclaringClass().isAssignableFrom(leastCommonType)) { ResolvedJavaMethod baseClassTargetMethod = leastCommonType.resolveMethod(targetMethod); if (baseClassTargetMethod != null) { devirtualizeWithTypeSwitch(graph, InvokeKind.Virtual, leastCommonType.resolveMethod(targetMethod), metaAccess); } } } } private void devirtualizeWithTypeSwitch(StructuredGraph graph, InvokeKind kind, ResolvedJavaMethod target, MetaAccessProvider metaAccess) { BeginNode invocationEntry = graph.add(new BeginNode()); BeginNode unknownTypeSux = createUnknownTypeSuccessor(graph); BeginNode[] successors = new BeginNode[]{invocationEntry, unknownTypeSux}; createDispatchOnTypeBeforeInvoke(graph, successors, true, metaAccess); invocationEntry.setNext(invoke.asNode()); ValueNode receiver = ((MethodCallTargetNode) invoke.callTarget()).receiver(); GuardedValueNode anchoredReceiver = createAnchoredReceiver(graph, invocationEntry, target.getDeclaringClass(), receiver, false); invoke.callTarget().replaceFirstInput(receiver, anchoredReceiver); replaceInvokeCallTarget(invoke, graph, kind, target); } private static BeginNode createUnknownTypeSuccessor(StructuredGraph graph) { return BeginNode.begin(graph.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.TypeCheckedInliningViolated))); } @Override public String toString() { StringBuilder builder = new StringBuilder(shouldFallbackToInvoke() ? "megamorphic" : "polymorphic"); builder.append(", "); builder.append(concretes.size()); builder.append(" methods [ "); for (int i = 0; i < concretes.size(); i++) { builder.append(MetaUtil.format(" %H.%n(%p):%r", concretes.get(i))); } builder.append(" ], "); builder.append(ptypes.size()); builder.append(" type checks [ "); for (int i = 0; i < ptypes.size(); i++) { builder.append(" "); builder.append(ptypes.get(i).getType().getName()); builder.append(ptypes.get(i).getProbability()); } builder.append(" ]"); return builder.toString(); } } /** * Represents an inlining opportunity where the current class hierarchy leads to a monomorphic * target method, but for which an assumption has to be registered because of non-final classes. */ private static class AssumptionInlineInfo extends ExactInlineInfo { private final Assumption takenAssumption; public AssumptionInlineInfo(Invoke invoke, ResolvedJavaMethod concrete, Assumption takenAssumption) { super(invoke, concrete); this.takenAssumption = takenAssumption; } @Override public void inline(Providers providers, Assumptions assumptions) { assumptions.record(takenAssumption); super.inline(providers, assumptions); } @Override public void tryToDevirtualizeInvoke(MetaAccessProvider metaAccess, Assumptions assumptions) { assumptions.record(takenAssumption); replaceInvokeCallTarget(invoke, graph(), InvokeKind.Special, concrete); } @Override public String toString() { return "assumption " + MetaUtil.format("%H.%n(%p):%r", concrete); } } /** * Determines if inlining is possible at the given invoke node. * * @param invoke the invoke that should be inlined * @return an instance of InlineInfo, or null if no inlining is possible at the given invoke */ public static InlineInfo getInlineInfo(InliningData data, Invoke invoke, int maxNumberOfMethods, Replacements replacements, Assumptions assumptions, OptimisticOptimizations optimisticOpts) { if (!checkInvokeConditions(invoke)) { return null; } MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); ResolvedJavaMethod targetMethod = callTarget.targetMethod(); if (callTarget.invokeKind() == InvokeKind.Special || targetMethod.canBeStaticallyBound()) { return getExactInlineInfo(data, invoke, replacements, optimisticOpts, targetMethod); } assert callTarget.invokeKind() == InvokeKind.Virtual || callTarget.invokeKind() == InvokeKind.Interface; ResolvedJavaType holder = targetMethod.getDeclaringClass(); if (!(callTarget.receiver().stamp() instanceof ObjectStamp)) { return null; } ObjectStamp receiverStamp = (ObjectStamp) callTarget.receiver().stamp(); if (receiverStamp.alwaysNull()) { // Don't inline if receiver is known to be null return null; } if (receiverStamp.type() != null) { // the invoke target might be more specific than the holder (happens after inlining: // parameters lose their declared type...) ResolvedJavaType receiverType = receiverStamp.type(); if (receiverType != null && holder.isAssignableFrom(receiverType)) { holder = receiverType; if (receiverStamp.isExactType()) { assert targetMethod.getDeclaringClass().isAssignableFrom(holder) : holder + " subtype of " + targetMethod.getDeclaringClass() + " for " + targetMethod; ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod); if (resolvedMethod != null) { return getExactInlineInfo(data, invoke, replacements, optimisticOpts, resolvedMethod); } } } } if (holder.isArray()) { // arrays can be treated as Objects ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod); if (resolvedMethod != null) { return getExactInlineInfo(data, invoke, replacements, optimisticOpts, resolvedMethod); } } if (assumptions.useOptimisticAssumptions()) { ResolvedJavaType uniqueSubtype = holder.findUniqueConcreteSubtype(); if (uniqueSubtype != null) { ResolvedJavaMethod resolvedMethod = uniqueSubtype.resolveMethod(targetMethod); if (resolvedMethod != null) { return getAssumptionInlineInfo(data, invoke, replacements, optimisticOpts, resolvedMethod, new Assumptions.ConcreteSubtype(holder, uniqueSubtype)); } } ResolvedJavaMethod concrete = holder.findUniqueConcreteMethod(targetMethod); if (concrete != null) { return getAssumptionInlineInfo(data, invoke, replacements, optimisticOpts, concrete, new Assumptions.ConcreteMethod(targetMethod, holder, concrete)); } } // type check based inlining return getTypeCheckedInlineInfo(data, invoke, maxNumberOfMethods, replacements, targetMethod, optimisticOpts); } private static InlineInfo getAssumptionInlineInfo(InliningData data, Invoke invoke, Replacements replacements, OptimisticOptimizations optimisticOpts, ResolvedJavaMethod concrete, Assumption takenAssumption) { assert !concrete.isAbstract(); if (!checkTargetConditions(data, replacements, invoke, concrete, optimisticOpts)) { return null; } return new AssumptionInlineInfo(invoke, concrete, takenAssumption); } private static InlineInfo getExactInlineInfo(InliningData data, Invoke invoke, Replacements replacements, OptimisticOptimizations optimisticOpts, ResolvedJavaMethod targetMethod) { assert !targetMethod.isAbstract(); if (!checkTargetConditions(data, replacements, invoke, targetMethod, optimisticOpts)) { return null; } return new ExactInlineInfo(invoke, targetMethod); } private static InlineInfo getTypeCheckedInlineInfo(InliningData data, Invoke invoke, int maxNumberOfMethods, Replacements replacements, ResolvedJavaMethod targetMethod, OptimisticOptimizations optimisticOpts) { JavaTypeProfile typeProfile; ValueNode receiver = invoke.callTarget().arguments().get(0); if (receiver instanceof TypeProfileProxyNode) { TypeProfileProxyNode typeProfileProxyNode = (TypeProfileProxyNode) receiver; typeProfile = typeProfileProxyNode.getProfile(); } else { return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "no type profile exists"); } ProfiledType[] ptypes = typeProfile.getTypes(); if (ptypes == null || ptypes.length <= 0) { return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "no types in profile"); } double notRecordedTypeProbability = typeProfile.getNotRecordedProbability(); if (ptypes.length == 1 && notRecordedTypeProbability == 0) { if (!optimisticOpts.inlineMonomorphicCalls()) { return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "inlining monomorphic calls is disabled"); } ResolvedJavaType type = ptypes[0].getType(); assert type.isArray() || !type.isAbstract(); ResolvedJavaMethod concrete = type.resolveMethod(targetMethod); if (!checkTargetConditions(data, replacements, invoke, concrete, optimisticOpts)) { return null; } return new TypeGuardInlineInfo(invoke, concrete, type); } else { invoke.setPolymorphic(true); if (!optimisticOpts.inlinePolymorphicCalls() && notRecordedTypeProbability == 0) { return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "inlining polymorphic calls is disabled (%d types)", ptypes.length); } if (!optimisticOpts.inlineMegamorphicCalls() && notRecordedTypeProbability > 0) { // due to filtering impossible types, notRecordedTypeProbability can be > 0 although // the number of types is lower than what can be recorded in a type profile return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "inlining megamorphic calls is disabled (%d types, %f %% not recorded types)", ptypes.length, notRecordedTypeProbability * 100); } // Find unique methods and their probabilities. ArrayList<ResolvedJavaMethod> concreteMethods = new ArrayList<>(); ArrayList<Double> concreteMethodsProbabilities = new ArrayList<>(); for (int i = 0; i < ptypes.length; i++) { ResolvedJavaMethod concrete = ptypes[i].getType().resolveMethod(targetMethod); if (concrete == null) { return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "could not resolve method"); } int index = concreteMethods.indexOf(concrete); double curProbability = ptypes[i].getProbability(); if (index < 0) { index = concreteMethods.size(); concreteMethods.add(concrete); concreteMethodsProbabilities.add(curProbability); } else { concreteMethodsProbabilities.set(index, concreteMethodsProbabilities.get(index) + curProbability); } } if (concreteMethods.size() > maxNumberOfMethods) { return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "polymorphic call with more than %d target methods", maxNumberOfMethods); } // Clear methods that fall below the threshold. if (notRecordedTypeProbability > 0) { ArrayList<ResolvedJavaMethod> newConcreteMethods = new ArrayList<>(); ArrayList<Double> newConcreteMethodsProbabilities = new ArrayList<>(); for (int i = 0; i < concreteMethods.size(); ++i) { if (concreteMethodsProbabilities.get(i) >= MegamorphicInliningMinMethodProbability.getValue()) { newConcreteMethods.add(concreteMethods.get(i)); newConcreteMethodsProbabilities.add(concreteMethodsProbabilities.get(i)); } } if (newConcreteMethods.size() == 0) { // No method left that is worth inlining. return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "no methods remaining after filtering less frequent methods (%d methods previously)", concreteMethods.size()); } concreteMethods = newConcreteMethods; concreteMethodsProbabilities = newConcreteMethodsProbabilities; } // Clean out types whose methods are no longer available. ArrayList<ProfiledType> usedTypes = new ArrayList<>(); ArrayList<Integer> typesToConcretes = new ArrayList<>(); for (ProfiledType type : ptypes) { ResolvedJavaMethod concrete = type.getType().resolveMethod(targetMethod); int index = concreteMethods.indexOf(concrete); if (index == -1) { notRecordedTypeProbability += type.getProbability(); } else { assert type.getType().isArray() || !type.getType().isAbstract() : type + " " + concrete; usedTypes.add(type); typesToConcretes.add(index); } } if (usedTypes.size() == 0) { // No type left that is worth checking for. return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "no types remaining after filtering less frequent types (%d types previously)", ptypes.length); } for (ResolvedJavaMethod concrete : concreteMethods) { if (!checkTargetConditions(data, replacements, invoke, concrete, optimisticOpts)) { return logNotInlinedMethodAndReturnNull(invoke, data.inliningDepth(), targetMethod, "it is a polymorphic method call and at least one invoked method cannot be inlined"); } } return new MultiTypeGuardInlineInfo(invoke, concreteMethods, concreteMethodsProbabilities, usedTypes, typesToConcretes, notRecordedTypeProbability); } } private static GuardedValueNode createAnchoredReceiver(StructuredGraph graph, GuardingNode anchor, ResolvedJavaType commonType, ValueNode receiver, boolean exact) { return createAnchoredReceiver(graph, anchor, receiver, exact ? StampFactory.exactNonNull(commonType) : StampFactory.declaredNonNull(commonType)); } private static GuardedValueNode createAnchoredReceiver(StructuredGraph graph, GuardingNode anchor, ValueNode receiver, Stamp stamp) { // to avoid that floating reads on receiver fields float above the type check return graph.unique(new GuardedValueNode(receiver, anchor, stamp)); } // TODO (chaeubl): cleanup this method private static boolean checkInvokeConditions(Invoke invoke) { if (invoke.predecessor() == null || !invoke.asNode().isAlive()) { return logNotInlinedMethod(invoke, "the invoke is dead code"); } else if (!(invoke.callTarget() instanceof MethodCallTargetNode)) { return logNotInlinedMethod(invoke, "the invoke has already been lowered, or has been created as a low-level node"); } else if (((MethodCallTargetNode) invoke.callTarget()).targetMethod() == null) { return logNotInlinedMethod(invoke, "target method is null"); } else if (invoke.stateAfter() == null) { // TODO (chaeubl): why should an invoke not have a state after? return logNotInlinedMethod(invoke, "the invoke has no after state"); } else if (!invoke.useForInlining()) { return logNotInlinedMethod(invoke, "the invoke is marked to be not used for inlining"); } else if (((MethodCallTargetNode) invoke.callTarget()).receiver() != null && ((MethodCallTargetNode) invoke.callTarget()).receiver().isConstant() && ((MethodCallTargetNode) invoke.callTarget()).receiver().asConstant().isNull()) { return logNotInlinedMethod(invoke, "receiver is null"); } else { return true; } } private static boolean checkTargetConditions(InliningData data, Replacements replacements, Invoke invoke, ResolvedJavaMethod method, OptimisticOptimizations optimisticOpts) { if (method == null) { return logNotInlinedMethodAndReturnFalse(invoke, data.inliningDepth(), method, "the method is not resolved"); } else if (method.isNative() && (!Intrinsify.getValue() || !InliningUtil.canIntrinsify(replacements, method))) { return logNotInlinedMethodAndReturnFalse(invoke, data.inliningDepth(), method, "it is a non-intrinsic native method"); } else if (method.isAbstract()) { return logNotInlinedMethodAndReturnFalse(invoke, data.inliningDepth(), method, "it is an abstract method"); } else if (!method.getDeclaringClass().isInitialized()) { return logNotInlinedMethodAndReturnFalse(invoke, data.inliningDepth(), method, "the method's class is not initialized"); } else if (!method.canBeInlined()) { return logNotInlinedMethodAndReturnFalse(invoke, data.inliningDepth(), method, "it is marked non-inlinable"); } else if (data.countRecursiveInlining(method) > MaximumRecursiveInlining.getValue()) { return logNotInlinedMethodAndReturnFalse(invoke, data.inliningDepth(), method, "it exceeds the maximum recursive inlining depth"); } else if (new OptimisticOptimizations(method.getProfilingInfo()).lessOptimisticThan(optimisticOpts)) { return logNotInlinedMethodAndReturnFalse(invoke, data.inliningDepth(), method, "the callee uses less optimistic optimizations than caller"); } else { return true; } } static MonitorExitNode findPrecedingMonitorExit(UnwindNode unwind) { Node pred = unwind.predecessor(); while (pred != null) { if (pred instanceof MonitorExitNode) { return (MonitorExitNode) pred; } pred = pred.predecessor(); } return null; } /** * Performs an actual inlining, thereby replacing the given invoke with the given inlineGraph. * * @param invoke the invoke that will be replaced * @param inlineGraph the graph that the invoke will be replaced with * @param receiverNullCheck true if a null check needs to be generated for non-static inlinings, * false if no such check is required */ public static Map<Node, Node> inline(Invoke invoke, StructuredGraph inlineGraph, boolean receiverNullCheck) { final NodeInputList<ValueNode> parameters = invoke.callTarget().arguments(); FixedNode invokeNode = invoke.asNode(); StructuredGraph graph = invokeNode.graph(); assert inlineGraph.getGuardsStage().ordinal() >= graph.getGuardsStage().ordinal(); assert !invokeNode.graph().isAfterFloatingReadPhase() : "inline isn't handled correctly after floating reads phase"; FrameState stateAfter = invoke.stateAfter(); assert stateAfter == null || stateAfter.isAlive(); if (receiverNullCheck && !((MethodCallTargetNode) invoke.callTarget()).isStatic()) { nonNullReceiver(invoke); } ArrayList<Node> nodes = new ArrayList<>(inlineGraph.getNodes().count()); ArrayList<ReturnNode> returnNodes = new ArrayList<>(4); UnwindNode unwindNode = null; final StartNode entryPointNode = inlineGraph.start(); FixedNode firstCFGNode = entryPointNode.next(); if (firstCFGNode == null) { throw new IllegalStateException("Inlined graph is in invalid state"); } for (Node node : inlineGraph.getNodes()) { if (node == entryPointNode || node == entryPointNode.stateAfter() || node instanceof ParameterNode) { // Do nothing. } else { nodes.add(node); if (node instanceof ReturnNode) { returnNodes.add((ReturnNode) node); } else if (node instanceof UnwindNode) { assert unwindNode == null; unwindNode = (UnwindNode) node; } } } final BeginNode prevBegin = BeginNode.prevBegin(invokeNode); DuplicationReplacement localReplacement = new DuplicationReplacement() { public Node replacement(Node node) { if (node instanceof ParameterNode) { return parameters.get(((ParameterNode) node).index()); } else if (node == entryPointNode) { return prevBegin; } return node; } }; assert invokeNode.successors().first() != null : invoke; assert invokeNode.predecessor() != null; Map<Node, Node> duplicates = graph.addDuplicates(nodes, inlineGraph, inlineGraph.getNodeCount(), localReplacement); FixedNode firstCFGNodeDuplicate = (FixedNode) duplicates.get(firstCFGNode); invokeNode.replaceAtPredecessor(firstCFGNodeDuplicate); FrameState stateAtExceptionEdge = null; if (invoke instanceof InvokeWithExceptionNode) { InvokeWithExceptionNode invokeWithException = ((InvokeWithExceptionNode) invoke); if (unwindNode != null) { assert unwindNode.predecessor() != null; assert invokeWithException.exceptionEdge().successors().count() == 1; ExceptionObjectNode obj = (ExceptionObjectNode) invokeWithException.exceptionEdge(); stateAtExceptionEdge = obj.stateAfter(); UnwindNode unwindDuplicate = (UnwindNode) duplicates.get(unwindNode); obj.replaceAtUsages(unwindDuplicate.exception()); unwindDuplicate.clearInputs(); Node n = obj.next(); obj.setNext(null); unwindDuplicate.replaceAndDelete(n); } else { invokeWithException.killExceptionEdge(); } // get rid of memory kill BeginNode begin = invokeWithException.next(); if (begin instanceof KillingBeginNode) { BeginNode newBegin = new BeginNode(); graph.addAfterFixed(begin, graph.add(newBegin)); begin.replaceAtUsages(newBegin); graph.removeFixed(begin); } } else { if (unwindNode != null) { UnwindNode unwindDuplicate = (UnwindNode) duplicates.get(unwindNode); DeoptimizeNode deoptimizeNode = graph.add(new DeoptimizeNode(DeoptimizationAction.InvalidateRecompile, DeoptimizationReason.NotCompiledExceptionHandler)); unwindDuplicate.replaceAndDelete(deoptimizeNode); } } if (stateAfter != null) { processFrameStates(invoke, inlineGraph, duplicates, stateAtExceptionEdge); int callerLockDepth = stateAfter.nestedLockDepth(); if (callerLockDepth != 0) { for (MonitorIdNode original : inlineGraph.getNodes(MonitorIdNode.class)) { MonitorIdNode monitor = (MonitorIdNode) duplicates.get(original); monitor.setLockDepth(monitor.getLockDepth() + callerLockDepth); } } } else { assert checkContainsOnlyInvalidOrAfterFrameState(duplicates); } if (!returnNodes.isEmpty()) { FixedNode n = invoke.next(); invoke.setNext(null); if (returnNodes.size() == 1) { ReturnNode returnNode = (ReturnNode) duplicates.get(returnNodes.get(0)); Node returnValue = returnNode.result(); invokeNode.replaceAtUsages(returnValue); returnNode.clearInputs(); returnNode.replaceAndDelete(n); } else { ArrayList<ReturnNode> returnDuplicates = new ArrayList<>(returnNodes.size()); for (ReturnNode returnNode : returnNodes) { returnDuplicates.add((ReturnNode) duplicates.get(returnNode)); } MergeNode merge = graph.add(new MergeNode()); merge.setStateAfter(stateAfter); ValueNode returnValue = mergeReturns(merge, returnDuplicates); invokeNode.replaceAtUsages(returnValue); merge.setNext(n); } } invokeNode.replaceAtUsages(null); GraphUtil.killCFG(invokeNode); return duplicates; } protected static void processFrameStates(Invoke invoke, StructuredGraph inlineGraph, Map<Node, Node> duplicates, FrameState stateAtExceptionEdge) { FrameState stateAfter = invoke.stateAfter(); FrameState outerFrameState = null; Kind invokeReturnKind = invoke.asNode().getKind(); for (FrameState original : inlineGraph.getNodes(FrameState.class)) { FrameState frameState = (FrameState) duplicates.get(original); if (frameState != null && frameState.isAlive()) { assert frameState.bci != BytecodeFrame.BEFORE_BCI : frameState; if (frameState.bci == BytecodeFrame.AFTER_BCI) { /* * pop return kind from invoke's stateAfter and replace with this frameState's * return value (top of stack) */ Node otherFrameState = stateAfter; if (invokeReturnKind != Kind.Void && frameState.stackSize() > 0) { otherFrameState = stateAfter.duplicateModified(invokeReturnKind, frameState.stackAt(0)); } frameState.replaceAndDelete(otherFrameState); } else if (frameState.bci == BytecodeFrame.AFTER_EXCEPTION_BCI || (frameState.bci == BytecodeFrame.UNWIND_BCI && !frameState.method().isSynchronized())) { if (stateAtExceptionEdge != null) { /* * pop exception object from invoke's stateAfter and replace with this * frameState's exception object (top of stack) */ Node newFrameState = stateAtExceptionEdge; if (frameState.stackSize() > 0 && stateAtExceptionEdge.stackAt(0) != frameState.stackAt(0)) { newFrameState = stateAtExceptionEdge.duplicateModified(Kind.Object, frameState.stackAt(0)); } frameState.replaceAndDelete(newFrameState); } else { handleMissingAfterExceptionFrameState(frameState); } } else if (frameState.bci == BytecodeFrame.UNWIND_BCI) { handleMissingAfterExceptionFrameState(frameState); } else { // only handle the outermost frame states if (frameState.outerFrameState() == null) { assert frameState.bci == BytecodeFrame.INVALID_FRAMESTATE_BCI || frameState.method().equals(inlineGraph.method()); assert frameState.bci != BytecodeFrame.AFTER_EXCEPTION_BCI && frameState.bci != BytecodeFrame.BEFORE_BCI && frameState.bci != BytecodeFrame.AFTER_EXCEPTION_BCI && frameState.bci != BytecodeFrame.UNWIND_BCI : frameState.bci; if (outerFrameState == null) { outerFrameState = stateAfter.duplicateModified(invoke.bci(), stateAfter.rethrowException(), invoke.asNode().getKind()); outerFrameState.setDuringCall(true); } frameState.setOuterFrameState(outerFrameState); } } } } } protected static void handleMissingAfterExceptionFrameState(FrameState nonReplacableFrameState) { Graph graph = nonReplacableFrameState.graph(); NodeWorkList workList = graph.createNodeWorkList(); workList.add(nonReplacableFrameState); for (Node node : workList) { FrameState fs = (FrameState) node; for (Node usage : fs.usages().snapshot()) { if (!usage.isAlive()) { continue; } if (usage instanceof FrameState) { workList.add(usage); } else { StateSplit stateSplit = (StateSplit) usage; FixedNode fixedStateSplit = stateSplit.asNode(); if (fixedStateSplit instanceof MergeNode) { MergeNode merge = (MergeNode) fixedStateSplit; while (merge.isAlive()) { AbstractEndNode end = merge.forwardEnds().first(); DeoptimizeNode deoptimizeNode = graph.add(new DeoptimizeNode(DeoptimizationAction.InvalidateRecompile, DeoptimizationReason.NotCompiledExceptionHandler)); end.replaceAtPredecessor(deoptimizeNode); GraphUtil.killCFG(end); } } else { FixedNode deoptimizeNode = graph.add(new DeoptimizeNode(DeoptimizationAction.InvalidateRecompile, DeoptimizationReason.NotCompiledExceptionHandler)); if (fixedStateSplit instanceof BeginNode) { deoptimizeNode = BeginNode.begin(deoptimizeNode); } fixedStateSplit.replaceAtPredecessor(deoptimizeNode); GraphUtil.killCFG(fixedStateSplit); } } } } } public static ValueNode mergeReturns(MergeNode merge, List<? extends ReturnNode> returnNodes) { PhiNode returnValuePhi = null; for (ReturnNode returnNode : returnNodes) { // create and wire up a new EndNode EndNode endNode = merge.graph().add(new EndNode()); merge.addForwardEnd(endNode); if (returnNode.result() != null) { if (returnValuePhi == null) { returnValuePhi = merge.graph().addWithoutUnique(new ValuePhiNode(returnNode.result().stamp().unrestricted(), merge)); } returnValuePhi.addInput(returnNode.result()); } returnNode.clearInputs(); returnNode.replaceAndDelete(endNode); } return returnValuePhi; } private static boolean checkContainsOnlyInvalidOrAfterFrameState(Map<Node, Node> duplicates) { for (Node node : duplicates.values()) { if (node instanceof FrameState) { FrameState frameState = (FrameState) node; assert frameState.bci == BytecodeFrame.AFTER_BCI || frameState.bci == BytecodeFrame.INVALID_FRAMESTATE_BCI : node.toString(Verbosity.Debugger); } } return true; } /** * Gets the receiver for an invoke, adding a guard if necessary to ensure it is non-null. */ public static ValueNode nonNullReceiver(Invoke invoke) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); assert !callTarget.isStatic() : callTarget.targetMethod(); StructuredGraph graph = callTarget.graph(); ValueNode firstParam = callTarget.arguments().get(0); if (firstParam.getKind() == Kind.Object && !StampTool.isObjectNonNull(firstParam)) { IsNullNode condition = graph.unique(new IsNullNode(firstParam)); Stamp stamp = firstParam.stamp().join(objectNonNull()); GuardingPiNode nonNullReceiver = graph.add(new GuardingPiNode(firstParam, condition, true, NullCheckException, InvalidateReprofile, stamp)); graph.addBeforeFixed(invoke.asNode(), nonNullReceiver); callTarget.replaceFirstInput(firstParam, nonNullReceiver); return nonNullReceiver; } return firstParam; } public static boolean canIntrinsify(Replacements replacements, ResolvedJavaMethod target) { return getIntrinsicGraph(replacements, target) != null || getMacroNodeClass(replacements, target) != null; } public static StructuredGraph getIntrinsicGraph(Replacements replacements, ResolvedJavaMethod target) { return replacements.getMethodSubstitution(target); } public static Class<? extends FixedWithNextNode> getMacroNodeClass(Replacements replacements, ResolvedJavaMethod target) { return replacements.getMacroSubstitution(target); } public static FixedWithNextNode inlineMacroNode(Invoke invoke, ResolvedJavaMethod concrete, Class<? extends FixedWithNextNode> macroNodeClass) throws GraalInternalError { StructuredGraph graph = invoke.asNode().graph(); if (!concrete.equals(((MethodCallTargetNode) invoke.callTarget()).targetMethod())) { assert ((MethodCallTargetNode) invoke.callTarget()).invokeKind() != InvokeKind.Static; InliningUtil.replaceInvokeCallTarget(invoke, graph, InvokeKind.Special, concrete); } FixedWithNextNode macroNode = createMacroNodeInstance(macroNodeClass, invoke); CallTargetNode callTarget = invoke.callTarget(); if (invoke instanceof InvokeNode) { graph.replaceFixedWithFixed((InvokeNode) invoke, graph.add(macroNode)); } else { InvokeWithExceptionNode invokeWithException = (InvokeWithExceptionNode) invoke; invokeWithException.killExceptionEdge(); graph.replaceSplitWithFixed(invokeWithException, graph.add(macroNode), invokeWithException.next()); } GraphUtil.killWithUnusedFloatingInputs(callTarget); return macroNode; } private static FixedWithNextNode createMacroNodeInstance(Class<? extends FixedWithNextNode> macroNodeClass, Invoke invoke) throws GraalInternalError { try { return macroNodeClass.getConstructor(Invoke.class).newInstance(invoke); } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException e) { throw new GraalGraphInternalError(e).addContext(invoke.asNode()).addContext("macroSubstitution", macroNodeClass); } } }
package com.valkryst.VTerminal; import com.valkryst.VRadio.Radio; import com.valkryst.VTerminal.misc.ColoredImageCache; import lombok.Getter; import lombok.Setter; import javax.swing.Timer; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.util.Objects; public class AsciiCharacter { /** The character. */ @Getter @Setter private char character; /** Whether or not the foreground should be drawn using the background color. */ @Getter @Setter private boolean isHidden = false; /** The background color. Defaults to black. */ @Getter private Color backgroundColor = Color.BLACK; /** The foreground color. Defaults to white. */ @Getter private Color foregroundColor = Color.WHITE; /** The bounding box of the character's area. */ @Getter private final Rectangle boundingBox = new Rectangle(); /** Whether or not to draw the character as underlined. */ @Getter @Setter private boolean isUnderlined = false; /** The thickness of the underline to draw beneath the character. */ @Getter private int underlineThickness = 2; /** Whether or not the character should be flipped horizontally when drawn. */ @Getter @Setter private boolean isFlippedHorizontally = false; /** Whether or not the character should be flipped vertically when drawn. */ @Getter @Setter private boolean isFlippedVertically = false; private Timer blinkTimer; /** The amount of time, in milliseconds, before the blink effect can occur. */ @Getter private short millsBetweenBlinks = 1000; /** * Constructs a new AsciiCharacter. * * @param character * The character. */ public AsciiCharacter(final char character) { this.character = character; } @Override public String toString() { return "Character:\n" + "\tCharacter: '" + character + "'\n" + "\tBackground Color: " + backgroundColor + "\n" + "\tForeground Color: " + foregroundColor + "\n" + "\tIs Hidden: " + isHidden + "\n" + "\tBounding Box: " + boundingBox + "\n" + "\tIs Underlined: " + isUnderlined + "\n" + "\tUnderline Thickness: " + underlineThickness + "\n" + "\tIs Flipped Horizontally: " + isFlippedHorizontally + "\n" + "\tIs Flipped Vertically: " + isFlippedVertically + "\n" + "\tBlink Timer: " + blinkTimer + "\n" + "\tMilliseconds Between Blinks: " + millsBetweenBlinks + "\n"; } @Override public boolean equals(final Object object) { if (object instanceof AsciiCharacter == false) { return false; } if (object == this) { return true; } final AsciiCharacter otherCharacter = (AsciiCharacter) object; if (character != otherCharacter.character) { return false; } if (backgroundColor.equals(otherCharacter.backgroundColor) == false) { return false; } if (foregroundColor.equals(otherCharacter.foregroundColor) == false) { return false; } return true; } @Override public int hashCode() { return Objects.hash(character, isHidden, backgroundColor, foregroundColor, boundingBox, isUnderlined, underlineThickness, isFlippedHorizontally, isFlippedVertically, blinkTimer, millsBetweenBlinks); } /** * Draws the character onto the specified context. * * @param gc * The graphics context to draw with. * * @param imageCache * The image cache to retrieve character images from. * * @param columnIndex * The x-axis (column) coordinate where the character is to be drawn. * * @param rowIndex * The y-axis (row) coordinate where the character is to be drawn. */ public void draw(final Graphics2D gc, final ColoredImageCache imageCache, int columnIndex, int rowIndex) { BufferedImage image = imageCache.retrieveFromCache(this); // Handle Horizontal/Vertical Flipping: if (isFlippedHorizontally || isFlippedVertically) { AffineTransform tx; if (isFlippedHorizontally && isFlippedVertically) { tx = AffineTransform.getScaleInstance(-1, -1); tx.translate(-image.getWidth(), -image.getHeight()); } else if (isFlippedHorizontally) { tx = AffineTransform.getScaleInstance(-1, 1); tx.translate(-image.getWidth(), 0); } else { tx = AffineTransform.getScaleInstance(1, -1); tx.translate(0, -image.getHeight()); } final BufferedImageOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC); image = op.filter(image, null); } // Draw character: final int fontWidth = imageCache.getFont().getWidth(); final int fontHeight = imageCache.getFont().getHeight(); columnIndex *= fontWidth; rowIndex *= fontHeight; gc.drawImage(image, columnIndex, rowIndex,null); boundingBox.setLocation(columnIndex, rowIndex); boundingBox.setSize(fontWidth, fontHeight); // Draw underline: if (isUnderlined) { gc.setColor(foregroundColor); final int y = rowIndex + fontHeight - underlineThickness; gc.fillRect(columnIndex, y, fontWidth, underlineThickness); } } /** * Enables the blink effect. * * @param millsBetweenBlinks * The amount of time, in milliseconds, before the blink effect can occur. * * @param radio * The Radio to transmit a DRAW event to whenever a blink occurs. */ public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) { if (radio == null) { throw new NullPointerException("You must specify a Radio when enabling a blink effect."); } if (millsBetweenBlinks <= 0) { this.millsBetweenBlinks = 1000; } else { this.millsBetweenBlinks = millsBetweenBlinks; } blinkTimer = new Timer(this.millsBetweenBlinks, e -> { isHidden = !isHidden; radio.transmit("DRAW"); }); blinkTimer.setInitialDelay(this.millsBetweenBlinks); blinkTimer.setRepeats(true); blinkTimer.start(); } /** Resumes the blink effect. */ public void resumeBlinkEffect() { if (blinkTimer != null) { if (blinkTimer.isRunning() == false) { blinkTimer.start(); } } } /** Pauses the blink effect. */ public void pauseBlinkEffect() { if (blinkTimer != null) { if (blinkTimer.isRunning()) { isHidden = false; blinkTimer.stop(); } } } /** Disables the blink effect. */ public void disableBlinkEffect() { if (blinkTimer != null) { blinkTimer.stop(); blinkTimer = null; } } /** Swaps the background and foreground colors. */ public void invertColors() { final Color temp = backgroundColor; setBackgroundColor(foregroundColor); setForegroundColor(temp); } /** * Sets the new background color. * * Does nothing if the specified color is null. * * @param color * The new background color. */ public void setBackgroundColor(final Color color) { boolean canProceed = color != null; canProceed &= backgroundColor.equals(color) == false; if (canProceed) { this.backgroundColor = color; } } /** * Sets the new foreground color. * * Does nothing if the specified color is null. * * @param color * The new foreground color. */ public void setForegroundColor(final Color color) { boolean canProceed = color != null; canProceed &= foregroundColor.equals(color) == false; if (canProceed) { this.foregroundColor = color; } } /** * Sets the new underline thickness. * * If the specified thickness is negative, then the thickness is set to 1. * If the specified thickness is greater than the font height, then the thickness is set to the font height. * If the font height is greater than Byte.MAX_VALUE, then the thickness is set to Byte.MAX_VALUE. * * @param underlineThickness * The new underline thickness. */ public void setUnderlineThickness(final int underlineThickness) { if (underlineThickness > boundingBox.getHeight()) { this.underlineThickness = (int) boundingBox.getHeight(); } else if (underlineThickness <= 0) { this.underlineThickness = 1; } else { this.underlineThickness = underlineThickness; } } }
package org.drools.guvnor.server; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import org.drools.guvnor.client.rpc.PackageConfigData; import org.drools.repository.PackageItem; import org.drools.repository.RulesRepository; import org.junit.Test; import org.mockito.Mockito; public class RepositoryPackageOperationsTest { @Test public void testPackageNameSorting() { PackageConfigData c1 = new PackageConfigData( "org.foo" ); PackageConfigData c2 = new PackageConfigData( "org.foo.bar" ); List<PackageConfigData> ls = new ArrayList<PackageConfigData>(); ls.add( c2 ); ls.add( c1 ); RepositoryPackageOperations repositoryPackageOperations = new RepositoryPackageOperations(); repositoryPackageOperations.sortPackages( ls ); assertEquals( c1, ls.get( 0 ) ); assertEquals( c2, ls.get( 1 ) ); } @Test public void testLoadGlobalPackageAndDependenciesAreNotFetched(){ RulesRepository rulesRepository = mock( RulesRepository.class ); RepositoryPackageOperations packageOperations = new RepositoryPackageOperations(); packageOperations.setRulesRepository( rulesRepository ); PackageItem packageItem = mock(PackageItem.class); when( rulesRepository.loadGlobalArea() ).thenReturn( packageItem ); when( packageItem.getLastModified()).thenReturn( GregorianCalendar.getInstance() ); when( packageItem.getCreatedDate()).thenReturn( GregorianCalendar.getInstance() ); when(packageItem.getDependencies()).thenReturn( new String[]{"dependency"} ); assertNull(packageOperations.loadGlobalPackage().dependencies); } @Test public void testLoadGlobalPackageAndIsSnapshot(){ RulesRepository rulesRepository = mock( RulesRepository.class ); RepositoryPackageOperations packageOperations = new RepositoryPackageOperations(); packageOperations.setRulesRepository( rulesRepository ); PackageItem packageItem = mock(PackageItem.class); when( rulesRepository.loadGlobalArea() ).thenReturn( packageItem ); when( packageItem.getLastModified()).thenReturn( GregorianCalendar.getInstance() ); when( packageItem.getCreatedDate()).thenReturn( GregorianCalendar.getInstance() ); when(packageItem.isSnapshot()).thenReturn( true ); when(packageItem.getSnapshotName()).thenReturn( "snapshotName123" ); assertTrue(packageOperations.loadGlobalPackage().isSnapshot); assertEquals(packageOperations.loadGlobalPackage().snapshotName,"snapshotName123" ); } @Test public void testLoadGlobalPackageAndIsNotSnapshot(){ RulesRepository rulesRepository = mock( RulesRepository.class ); RepositoryPackageOperations packageOperations = new RepositoryPackageOperations(); packageOperations.setRulesRepository( rulesRepository ); PackageItem packageItem = mock(PackageItem.class); when( rulesRepository.loadGlobalArea() ).thenReturn( packageItem ); when( packageItem.getLastModified()).thenReturn( GregorianCalendar.getInstance() ); when( packageItem.getCreatedDate()).thenReturn( GregorianCalendar.getInstance() ); when(packageItem.isSnapshot()).thenReturn( false ); when(packageItem.getSnapshotName()).thenReturn( "snapshotName123" ); assertFalse(packageOperations.loadGlobalPackage().isSnapshot); assertNull(packageOperations.loadGlobalPackage().snapshotName); } }
package com.wakatime.intellij.plugin; import com.intellij.AppTopics; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PlatformUtils; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import org.apache.log4j.Level; public class WakaTime implements ApplicationComponent { public static final BigDecimal FREQUENCY = new BigDecimal(2 * 60); // max secs between heartbeats for continuous coding public static final Logger log = Logger.getInstance("WakaTime"); public static String VERSION; public static String IDE_NAME; public static String IDE_VERSION; public static MessageBusConnection connection; public static Boolean DEBUG = false; public static Boolean READY = false; public static String lastFile = null; public static BigDecimal lastTime = new BigDecimal(0); private final int queueTimeoutSeconds = 30; private static ConcurrentLinkedQueue<Heartbeat> heartbeatsQueue = new ConcurrentLinkedQueue<Heartbeat>(); private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private static ScheduledFuture<?> scheduledFixture; public WakaTime() { } public void initComponent() { try { // support older IDE versions with deprecated PluginManager VERSION = PluginManager.getPlugin(PluginId.getId("com.wakatime.intellij.plugin")).getVersion(); } catch (Exception e) { // use PluginManagerCore if PluginManager deprecated VERSION = PluginManagerCore.getPlugin(PluginId.getId("com.wakatime.intellij.plugin")).getVersion(); } log.info("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)"); // Set runtime constants IDE_NAME = PlatformUtils.getPlatformPrefix(); IDE_VERSION = ApplicationInfo.getInstance().getFullVersion(); setupDebugging(); setLoggingLevel(); Dependencies.configureProxy(); checkApiKey(); checkCli(); setupEventListeners(); setupQueueProcessor(); checkDebug(); log.info("Finished initializing WakaTime plugin"); } private void checkCli() { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { if (!Dependencies.isCLIInstalled()) { log.info("Downloading and installing wakatime-cli ..."); Dependencies.installCLI(); WakaTime.READY = true; log.info("Finished downloading and installing wakatime-cli."); } else if (Dependencies.isCLIOld()) { log.info("Upgrading wakatime-cli ..."); Dependencies.installCLI(); WakaTime.READY = true; log.info("Finished upgrading wakatime-cli."); } else { WakaTime.READY = true; log.info("wakatime-cli is up to date."); } log.debug("CLI location: " + Dependencies.getCLILocation()); } }); } private void checkApiKey() { ApplicationManager.getApplication().invokeLater(new Runnable(){ public void run() { // prompt for apiKey if it does not already exist Project project = null; try { project = ProjectManager.getInstance().getDefaultProject(); } catch (Exception e) { } ApiKey apiKey = new ApiKey(project); if (apiKey.getApiKey().equals("")) { apiKey.promptForApiKey(); } log.debug("Api Key: " + obfuscateKey(ApiKey.getApiKey())); } }); } private void setupEventListeners() { ApplicationManager.getApplication().invokeLater(new Runnable(){ public void run() { // save file MessageBus bus = ApplicationManager.getApplication().getMessageBus(); connection = bus.connect(); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new CustomSaveListener()); // edit document EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new CustomDocumentListener()); // mouse press EditorFactory.getInstance().getEventMulticaster().addEditorMouseListener(new CustomEditorMouseListener()); // scroll document EditorFactory.getInstance().getEventMulticaster().addVisibleAreaListener(new CustomVisibleAreaListener()); } }); } private void setupQueueProcessor() { final Runnable handler = new Runnable() { public void run() { processHeartbeatQueue(); } }; long delay = queueTimeoutSeconds; scheduledFixture = scheduler.scheduleAtFixedRate(handler, delay, delay, java.util.concurrent.TimeUnit.SECONDS); } private void checkDebug() { if (WakaTime.DEBUG) { try { Messages.showWarningDialog("Running WakaTime in DEBUG mode. Your IDE may be slow when saving or editing files.", "Debug"); } catch (Exception e) { } } } public void disposeComponent() { try { connection.disconnect(); } catch(Exception e) { } try { scheduledFixture.cancel(true); } catch (Exception e) { } // make sure to send all heartbeats before exiting processHeartbeatQueue(); } public static BigDecimal getCurrentTimestamp() { return new BigDecimal(String.valueOf(System.currentTimeMillis() / 1000.0)).setScale(4, BigDecimal.ROUND_HALF_UP); } public static void appendHeartbeat(final VirtualFile file, Project project, final boolean isWrite) { if (!shouldLogFile(file)) return; final String projectName = project != null ? project.getName() : null; final BigDecimal time = WakaTime.getCurrentTimestamp(); if (!isWrite && file.getPath().equals(WakaTime.lastFile) && !enoughTimePassed(time)) { return; } WakaTime.lastFile = file.getPath(); WakaTime.lastTime = time; final String language = WakaTime.getLanguage(file); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { Heartbeat h = new Heartbeat(); h.entity = file.getPath(); h.timestamp = time; h.isWrite = isWrite; h.project = projectName; h.language = language; heartbeatsQueue.add(h); } }); } private static void processHeartbeatQueue() { if (WakaTime.READY) { // get single heartbeat from queue Heartbeat heartbeat = heartbeatsQueue.poll(); if (heartbeat == null) return; // get all extra heartbeats from queue ArrayList<Heartbeat> extraHeartbeats = new ArrayList<Heartbeat>(); while (true) { Heartbeat h = heartbeatsQueue.poll(); if (h == null) break; extraHeartbeats.add(h); } sendHeartbeat(heartbeat, extraHeartbeats); } } private static void sendHeartbeat(final Heartbeat heartbeat, final ArrayList<Heartbeat> extraHeartbeats) { final String[] cmds = buildCliCommand(heartbeat, extraHeartbeats); log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds))); try { Process proc = Runtime.getRuntime().exec(cmds); if (extraHeartbeats.size() > 0) { String json = toJSON(extraHeartbeats); log.debug(json); try { BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); stdin.write(json); stdin.write("\n"); try { stdin.flush(); stdin.close(); } catch (IOException e) { /* ignored because wakatime-cli closes pipe after receiving \n */ } } catch (IOException e) { log.warn(e); } } if (WakaTime.DEBUG) { BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); proc.waitFor(); String s; while ((s = stdout.readLine()) != null) { log.debug(s); } while ((s = stderr.readLine()) != null) { log.debug(s); } log.debug("Command finished with return value: " + proc.exitValue()); } } catch (Exception e) { log.warn(e); } } private static String toJSON(ArrayList<Heartbeat> extraHeartbeats) { StringBuffer json = new StringBuffer(); json.append("["); boolean first = true; for (Heartbeat heartbeat : extraHeartbeats) { StringBuffer h = new StringBuffer(); h.append("{\"entity\":\""); h.append(jsonEscape(heartbeat.entity)); h.append("\",\"timestamp\":"); h.append(heartbeat.timestamp.toPlainString()); h.append(",\"is_write\":"); h.append(heartbeat.isWrite.toString()); if (heartbeat.project != null) { h.append(",\"project\":\""); h.append(jsonEscape(heartbeat.project)); h.append("\""); } if (heartbeat.language != null) { h.append(",\"language\":\""); h.append(jsonEscape(heartbeat.language)); h.append("\""); } h.append("}"); if (!first) json.append(","); json.append(h.toString()); first = false; } json.append("]"); return json.toString(); } private static String jsonEscape(String s) { if (s == null) return null; StringBuffer escaped = new StringBuffer(); final int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); switch(c) { case '\\': escaped.append("\\\\"); break; case '"': escaped.append("\\\""); break; case '\b': escaped.append("\\b"); break; case '\f': escaped.append("\\f"); break; case '\n': escaped.append("\\n"); break; case '\r': escaped.append("\\r"); break; case '\t': escaped.append("\\t"); break; default: boolean isUnicode = (c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F') || (c >= '\u2000' && c <= '\u20FF'); if (isUnicode){ escaped.append("\\u"); String hex = Integer.toHexString(c); for (int k = 0; k < 4 - hex.length(); k++) { escaped.append('0'); } escaped.append(hex.toUpperCase()); } else { escaped.append(c); } } } return escaped.toString(); } private static String[] buildCliCommand(Heartbeat heartbeat, ArrayList<Heartbeat> extraHeartbeats) { ArrayList<String> cmds = new ArrayList<String>(); cmds.add(Dependencies.getCLILocation()); cmds.add("--entity"); cmds.add(heartbeat.entity); cmds.add("--time"); cmds.add(heartbeat.timestamp.toPlainString()); cmds.add("--key"); cmds.add(ApiKey.getApiKey()); if (heartbeat.project != null) { cmds.add("--project"); cmds.add(heartbeat.project); } if (heartbeat.language != null) { cmds.add("--language"); cmds.add(heartbeat.language); } cmds.add("--plugin"); cmds.add(IDE_NAME+"/"+IDE_VERSION+" "+IDE_NAME+"-wakatime/"+VERSION); if (heartbeat.isWrite) cmds.add("--write"); if (extraHeartbeats.size() > 0) cmds.add("--extra-heartbeats"); return cmds.toArray(new String[cmds.size()]); } private static String getLanguage(final VirtualFile file) { FileType type = file.getFileType(); if (type != null) return type.getName(); return null; } public static boolean enoughTimePassed(BigDecimal currentTime) { return WakaTime.lastTime.add(FREQUENCY).compareTo(currentTime) < 0; } public static boolean shouldLogFile(VirtualFile file) { if (file == null || file.getUrl().startsWith("mock: return false; } String filePath = file.getPath(); if (filePath.equals("atlassian-ide-plugin.xml") || filePath.contains("/.idea/workspace.xml")) { return false; } return true; } public static void setupDebugging() { String debug = ConfigFile.get("settings", "debug"); WakaTime.DEBUG = debug != null && debug.trim().equals("true"); } public static void setLoggingLevel() { if (WakaTime.DEBUG) { log.setLevel(Level.DEBUG); log.debug("Logging level set to DEBUG"); } else { log.setLevel(Level.INFO); } } public static Project getProject(Document document) { Editor[] editors = EditorFactory.getInstance().getEditors(document); if (editors.length > 0) { return editors[0].getProject(); } return null; } private static String obfuscateKey(String key) { String newKey = null; if (key != null) { newKey = key; if (key.length() > 4) newKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX" + key.substring(key.length() - 4); } return newKey; } private static String[] obfuscateKey(String[] cmds) { ArrayList<String> newCmds = new ArrayList<String>(); String lastCmd = ""; for (String cmd : cmds) { if (lastCmd == "--key") newCmds.add(obfuscateKey(cmd)); else newCmds.add(cmd); lastCmd = cmd; } return newCmds.toArray(new String[newCmds.size()]); } @NotNull public String getComponentName() { return "WakaTime"; } }
package com.wakatime.intellij.plugin; import com.intellij.AppTopics; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.Messages; import com.intellij.util.PlatformUtils; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import org.apache.log4j.Level; public class WakaTime implements ApplicationComponent { public static final String VERSION = "7.0.8"; public static final String CONFIG = ".wakatime.cfg"; public static final BigDecimal FREQUENCY = new BigDecimal(2 * 60); // max secs between heartbeats for continuous coding public static final Logger log = Logger.getInstance("WakaTime"); public static String IDE_NAME; public static String IDE_VERSION; public static MessageBusConnection connection; public static Boolean DEBUG = false; public static Boolean READY = false; public static String lastFile = null; public static BigDecimal lastTime = new BigDecimal(0); private static String lastProject = null; private final int queueTimeoutSeconds = 10; private static ConcurrentLinkedQueue<Heartbeat> heartbeatsQueue = new ConcurrentLinkedQueue<Heartbeat>(); private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private static ScheduledFuture<?> scheduledFixture; public WakaTime() { } public void initComponent() { log.info("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)"); // Set runtime constants IDE_NAME = PlatformUtils.getPlatformPrefix(); IDE_VERSION = ApplicationInfo.getInstance().getFullVersion(); setupDebugging(); setLoggingLevel(); Dependencies.configureProxy(); checkApiKey(); setupMenuItem(); if (Dependencies.isPythonInstalled()) { checkCore(); setupEventListeners(); setupQueueProcessor(); checkDebug(); log.info("Finished initializing WakaTime plugin"); } else { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { log.info("Python not found, downloading python..."); // download and install python Dependencies.installPython(); if (Dependencies.isPythonInstalled()) { log.info("Finished installing python..."); checkCore(); setupEventListeners(); setupQueueProcessor(); checkDebug(); log.info("Finished initializing WakaTime plugin"); } else { ApplicationManager.getApplication().invokeLater(new Runnable(){ public void run(){ Messages.showErrorDialog("WakaTime requires Python to be installed.\nYou can install it from https: } }); } } }); } } private void checkCore() { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { if (!Dependencies.isCLIInstalled()) { log.info("Downloading and installing wakatime-cli ..."); Dependencies.installCLI(); WakaTime.READY = true; log.info("Finished downloading and installing wakatime-cli."); } else if (Dependencies.isCLIOld()) { log.info("Upgrading wakatime-cli ..."); Dependencies.upgradeCLI(); WakaTime.READY = true; log.info("Finished upgrading wakatime-cli."); } else { WakaTime.READY = true; log.info("wakatime-cli is up to date."); } log.debug("CLI location: " + Dependencies.getCLILocation()); } }); } private void checkApiKey() { ApplicationManager.getApplication().invokeLater(new Runnable(){ public void run() { // prompt for apiKey if it does not already exist Project project = null; try { project = ProjectManager.getInstance().getDefaultProject(); } catch (NullPointerException e) { } ApiKey apiKey = new ApiKey(project); if (apiKey.getApiKey().equals("")) { apiKey.promptForApiKey(); } log.debug("Api Key: " + obfuscateKey(ApiKey.getApiKey())); } }); } private void setupEventListeners() { ApplicationManager.getApplication().invokeLater(new Runnable(){ public void run() { // save file MessageBus bus = ApplicationManager.getApplication().getMessageBus(); connection = bus.connect(); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new CustomSaveListener()); // edit document EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new CustomDocumentListener()); // mouse press EditorFactory.getInstance().getEventMulticaster().addEditorMouseListener(new CustomEditorMouseListener()); // scroll document EditorFactory.getInstance().getEventMulticaster().addVisibleAreaListener(new CustomVisibleAreaListener()); } }); } private void setupQueueProcessor() { final Runnable handler = new Runnable() { public void run() { processHeartbeatQueue(); } }; long delay = queueTimeoutSeconds; scheduledFixture = scheduler.scheduleAtFixedRate(handler, delay, delay, java.util.concurrent.TimeUnit.SECONDS); } private void setupMenuItem() { ApplicationManager.getApplication().invokeLater(new Runnable(){ public void run() { ActionManager am = ActionManager.getInstance(); PluginMenu action = new PluginMenu(); am.registerAction("WakaTimeApiKey", action); DefaultActionGroup menu = (DefaultActionGroup) am.getAction("ToolsMenu"); menu.addSeparator(); menu.add(action); } }); } private void checkDebug() { if (WakaTime.DEBUG) { try { Messages.showWarningDialog("Running WakaTime in DEBUG mode. Your IDE may be slow when saving or editing files.", "Debug"); } catch (NullPointerException e) { } } } public void disposeComponent() { try { connection.disconnect(); } catch(Exception e) { } try { scheduledFixture.cancel(true); } catch (Exception e) { } // make sure to send all heartbeats before exiting processHeartbeatQueue(); } public static BigDecimal getCurrentTimestamp() { return new BigDecimal(String.valueOf(System.currentTimeMillis() / 1000.0)).setScale(4, BigDecimal.ROUND_HALF_UP); } public static void appendHeartbeat(final BigDecimal time, final String file, final boolean isWrite) { WakaTime.lastFile = file; WakaTime.lastTime = time; final String project = WakaTime.getProjectName(); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { Heartbeat h = new Heartbeat(); h.entity = file; h.timestamp = time; h.isWrite = isWrite; h.project = project; heartbeatsQueue.add(h); } }); } private static void processHeartbeatQueue() { if (WakaTime.READY) { // get single heartbeat from queue Heartbeat heartbeat = heartbeatsQueue.poll(); if (heartbeat == null) return; // get all extra heartbeats from queue ArrayList<Heartbeat> extraHeartbeats = new ArrayList<Heartbeat>(); while (true) { Heartbeat h = heartbeatsQueue.poll(); if (h == null) break; extraHeartbeats.add(h); } sendHeartbeat(heartbeat, extraHeartbeats); } } private static void sendHeartbeat(final Heartbeat heartbeat, final ArrayList<Heartbeat> extraHeartbeats) { final String[] cmds = buildCliCommand(heartbeat, extraHeartbeats); log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds))); try { Process proc = Runtime.getRuntime().exec(cmds); if (extraHeartbeats.size() > 0) { String json = toJSON(extraHeartbeats); log.debug(json); try { BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); stdin.write(json); stdin.write("\n"); try { stdin.flush(); stdin.close(); } catch (IOException e) { /* ignored because wakatime-cli closes pipe after receiving \n */ } } catch (IOException e) { log.warn(e); } } if (WakaTime.DEBUG) { BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); proc.waitFor(); String s; while ((s = stdout.readLine()) != null) { log.debug(s); } while ((s = stderr.readLine()) != null) { log.debug(s); } log.debug("Command finished with return value: " + proc.exitValue()); } } catch (Exception e) { log.warn(e); } } private static String toJSON(ArrayList<Heartbeat> extraHeartbeats) { StringBuffer json = new StringBuffer(); json.append("["); boolean first = true; for (Heartbeat heartbeat : extraHeartbeats) { StringBuffer h = new StringBuffer(); h.append("{\"entity\":\""); h.append(jsonEscape(heartbeat.entity)); h.append("\",\"timestamp\":"); h.append(heartbeat.timestamp.toPlainString()); h.append(",\"is_write\":"); h.append(heartbeat.isWrite.toString()); if (heartbeat.project != null) { h.append(",\"project\":\""); h.append(jsonEscape(heartbeat.project)); h.append("\""); } h.append("}"); if (!first) json.append(","); json.append(h.toString()); first = false; } json.append("]"); return json.toString(); } private static String jsonEscape(String s) { if (s == null) return null; StringBuffer escaped = new StringBuffer(); final int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); switch(c) { case '\\': escaped.append("\\\\"); break; case '"': escaped.append("\\\""); break; case '\b': escaped.append("\\b"); break; case '\f': escaped.append("\\f"); break; case '\n': escaped.append("\\n"); break; case '\r': escaped.append("\\r"); break; case '\t': escaped.append("\\t"); break; default: boolean isUnicode = (c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F') || (c >= '\u2000' && c <= '\u20FF'); if (isUnicode){ escaped.append("\\u"); String hex = Integer.toHexString(c); for (int k = 0; k < 4 - hex.length(); k++) { escaped.append('0'); } escaped.append(hex.toUpperCase()); } else { escaped.append(c); } } } return escaped.toString(); } private static String[] buildCliCommand(Heartbeat heartbeat, ArrayList<Heartbeat> extraHeartbeats) { ArrayList<String> cmds = new ArrayList<String>(); cmds.add(Dependencies.getPythonLocation()); cmds.add(Dependencies.getCLILocation()); cmds.add("--entity"); cmds.add(heartbeat.entity); cmds.add("--time"); cmds.add(heartbeat.timestamp.toPlainString()); cmds.add("--key"); cmds.add(ApiKey.getApiKey()); if (heartbeat.project != null) { cmds.add("--project"); cmds.add(heartbeat.project); } cmds.add("--plugin"); cmds.add(IDE_NAME+"/"+IDE_VERSION+" "+IDE_NAME+"-wakatime/"+VERSION); if (heartbeat.isWrite) cmds.add("--write"); if (extraHeartbeats.size() > 0) cmds.add("--extra-heartbeats"); return cmds.toArray(new String[cmds.size()]); } private static String getProjectName() { DataContext dataContext = DataManager.getInstance().getDataContext(); if (dataContext != null) { Project project = null; try { project = PlatformDataKeys.PROJECT.getData(dataContext); } catch (NoClassDefFoundError e) { try { project = DataKeys.PROJECT.getData(dataContext); } catch (NoClassDefFoundError ex) { } } if (project != null) { lastProject = project.getName(); return lastProject; } } if (lastProject != null) { return lastProject; } else { return null; } } public static boolean enoughTimePassed(BigDecimal currentTime) { return WakaTime.lastTime.add(FREQUENCY).compareTo(currentTime) < 0; } public static boolean shouldLogFile(String file) { if (file.equals("atlassian-ide-plugin.xml") || file.contains("/.idea/workspace.xml")) { return false; } return true; } public static void setupDebugging() { String debug = ConfigFile.get("settings", "debug"); WakaTime.DEBUG = debug != null && debug.trim().equals("true"); } public static void setLoggingLevel() { if (WakaTime.DEBUG) { log.setLevel(Level.DEBUG); log.debug("Logging level set to DEBUG"); } else { log.setLevel(Level.INFO); } } private static String obfuscateKey(String key) { String newKey = null; if (key != null) { newKey = key; if (key.length() > 4) newKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX" + key.substring(key.length() - 4); } return newKey; } private static String[] obfuscateKey(String[] cmds) { ArrayList<String> newCmds = new ArrayList<String>(); String lastCmd = ""; for (String cmd : cmds) { if (lastCmd == "--key") newCmds.add(obfuscateKey(cmd)); else newCmds.add(cmd); lastCmd = cmd; } return newCmds.toArray(new String[newCmds.size()]); } @NotNull public String getComponentName() { return "WakaTime"; } }
package org.mariadb.jdbc.internal.com.send.authentication; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; import org.mariadb.jdbc.internal.com.read.Buffer; import org.mariadb.jdbc.internal.com.send.authentication.gssapi.GssUtility; import org.mariadb.jdbc.internal.com.send.authentication.gssapi.GssapiAuth; import org.mariadb.jdbc.internal.com.send.authentication.gssapi.StandardGssapiAuthentication; import org.mariadb.jdbc.internal.io.input.PacketInputStream; import org.mariadb.jdbc.internal.io.output.PacketOutputStream; public class SendGssApiAuthPacket implements AuthenticationPlugin { private static final GssapiAuth gssapiAuth; private byte[] authData; private String optionServicePrincipalName; static { GssapiAuth init; try { init = GssUtility.getAuthenticationMethod(); } catch (Throwable t) { init = new StandardGssapiAuthentication(); } gssapiAuth = init; } public SendGssApiAuthPacket(byte[] authData, String servicePrincipalName) { this.authData = authData; this.optionServicePrincipalName = servicePrincipalName; } public Buffer process(PacketOutputStream out, PacketInputStream in, AtomicInteger sequence) throws IOException, SQLException { Buffer buffer = new Buffer(authData); final String serverSpn = buffer.readStringNullEnd(StandardCharsets.UTF_8); //using provided connection string SPN if set, or if not, using to server information final String servicePrincipalName = (optionServicePrincipalName != null && !optionServicePrincipalName.isEmpty()) ? optionServicePrincipalName : serverSpn; String mechanisms = buffer.readStringNullEnd(StandardCharsets.UTF_8); if (mechanisms.isEmpty()) { mechanisms = "Kerberos"; } gssapiAuth.authenticate(out, in, sequence, servicePrincipalName, mechanisms); buffer = in.getPacket(true); sequence.set(in.getLastPacketSeq()); return buffer; } }
package pl.tomaszdziurko.jvm_bloggers.newsletter_issues.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Singular; import lombok.ToString; import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPost; import pl.tomaszdziurko.jvm_bloggers.blogs.domain.Blog; import java.time.LocalDate; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import static lombok.AccessLevel.PRIVATE; @Entity @Table(name = "newsletter_issue") @NoArgsConstructor(access = PRIVATE) @AllArgsConstructor(access = PRIVATE) @Builder @Getter @ToString(exclude = {"blogPosts", "newBlogs"}) public class NewsletterIssue { @Id @GeneratedValue(generator = "NEWSLETTER_ISSUE_SEQ", strategy = GenerationType.SEQUENCE) @SequenceGenerator(name = "NEWSLETTER_ISSUE_SEQ", sequenceName = "NEWSLETTER_ISSUE_SEQ", allocationSize = 1) @Column(name = "ID") private Long id; @NonNull @Column(name = "ISSUE_NUMBER", nullable = false, updatable = false) private Long issueNumber; @Column(name = "PUBLISHED_DATE", updatable = false) private LocalDate publishedDate; @Column(name = "HEADING", length = 4000, updatable = false) private String heading; @Singular @NonNull @OneToMany(fetch = FetchType.EAGER) @JoinTable(name = "blog_posts_in_newsletter_issue", joinColumns = {@JoinColumn(name = "newsletter_issue_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "blog_post_id", referencedColumnName = "id")} ) private List<BlogPost> blogPosts; @Singular @NonNull @OneToMany(fetch = FetchType.EAGER) @JoinTable(name = "new_blogs_in_newsletter_issue", joinColumns = {@JoinColumn(name = "newsletter_issue_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "new_blog_id", referencedColumnName = "id")} ) private List<Blog> newBlogs; @Column(name = "VARIA", length = 4000, updatable = false) private String varia; }
package problems; public class FirstMissingPositive { public int firstMissingPositive(int[] A) { if (A == null || A.length == 0) return 1; for (int i = 0; i < A.length; ) { if (A[i] > 0 && A[i] <= A.length && A[A[i] - 1] != A[i]) swap(A, i, A[i] - 1); else i++; } for (int i = 0; i < A.length; i++) { if (A[i] != i + 1) return i + 1; } return A.length + 1; } void swap(int[] A, int i, int j) { int t = A[i]; A[i] = A[j]; A[j] = t; } public static void main(String[] args) { FirstMissingPositive fm = new FirstMissingPositive(); int[] a = { 3, 4, -1, 1 }; System.out.println(fm.firstMissingPositive(a)); } }
package uk.ac.ebi.phenotype.stats.categorical; import java.io.IOException; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.WordUtils; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import uk.ac.ebi.phenotype.dao.CategoricalStatisticsDAO; import uk.ac.ebi.phenotype.dao.PhenotypePipelineDAO; import uk.ac.ebi.phenotype.pojo.BiologicalModel; import uk.ac.ebi.phenotype.pojo.CategoricalResult; import uk.ac.ebi.phenotype.pojo.Parameter; import uk.ac.ebi.phenotype.pojo.ParameterOption; import uk.ac.ebi.phenotype.pojo.SexType; import uk.ac.ebi.phenotype.pojo.StatisticalResult; import uk.ac.ebi.phenotype.pojo.ZygosityType; import uk.ac.ebi.phenotype.stats.ChartData; import uk.ac.ebi.phenotype.stats.ExperimentDTO; import uk.ac.ebi.phenotype.stats.ExperimentService; import uk.ac.ebi.phenotype.stats.ObservationDTO; import uk.ac.ebi.phenotype.stats.TableObject; import uk.ac.ebi.phenotype.stats.graphs.ChartColors; @Service public class CategoricalChartAndTableProvider { private static final Logger logger = Logger.getLogger(CategoricalChartAndTableProvider.class); @Autowired PhenotypePipelineDAO ppDAO; /** * return a list of categorical result and chart objects - one for each ExperimentDTO * @param experiment * @param parameter * @param acc * @param gender * @param parameterId * @param charts * @return * @throws SQLException * @throws IOException * @throws URISyntaxException */ public CategoricalResultAndCharts doCategoricalData( ExperimentDTO experiment, Parameter parameter, String acc, String numberString, BiologicalModel expBiologicalModel) throws SQLException, IOException, URISyntaxException { List<String> categories = this.getCategories(parameter);//loop through all the parameters no just ones with >0 result so use parameter rather than experiment logger.debug("running categorical data"); CategoricalResultAndCharts categoricalResultAndCharts = new CategoricalResultAndCharts(); categoricalResultAndCharts.setExperiment(experiment); List<? extends StatisticalResult> statsResults = (List<? extends StatisticalResult>) experiment .getResults(); // should get one for each sex here if there is a result for each // experimental sex CategoricalChartDataObject chartData = new CategoricalChartDataObject();// make a chart object one for both sexes for (SexType sexType : experiment.getSexes()) { categoricalResultAndCharts.setStatsResults(statsResults); //chartData.setSexType(sexType); // do control first as requires no zygocity CategoricalSet controlSet = new CategoricalSet(); controlSet.setName(WordUtils.capitalize(sexType.name())+" Control"); controlSet.setSexType(sexType); for (String category :categories) { if (category.equals("imageOnly")) continue;// ignore image categories as no numbers! CategoricalDataObject controlCatData = new CategoricalDataObject(); controlCatData.setName(WordUtils.capitalize(sexType.name())+" Control"); controlCatData.setCategory(ppDAO.getCategoryDescription(parameter.getId(), category)); long controlCount = 0; for (ObservationDTO control : experiment.getControls()) { // get the attributes of this data point SexType docSexType = SexType.valueOf(control .getSex()); String categoString =control.getCategory(); //System.out.println("category string="+categoString); if (categoString.equals( category) && docSexType.equals(sexType)) { controlCount++; } } controlCatData.setCount(controlCount); logger.debug("control=" + sexType.name() + " count=" + controlCount + " category=" + ppDAO.getCategoryDescription(parameter.getId(), category)); controlSet.add(controlCatData); } chartData.add(controlSet); // now do experimental i.e. zygocities for (ZygosityType zType : experiment.getZygosities()) { CategoricalSet zTypeSet = new CategoricalSet();// hold the data for each bar on graph hom, normal, abnormal zTypeSet.setName(WordUtils.capitalize(sexType.name())+" "+WordUtils.capitalize(zType.name())); for (String category : categories) { if (category.equals("imageOnly")) continue; Long mutantCount = new Long(0);// .countMutant(sexType, zType, parameter, category, popId); // loop over all the experimental docs and get // all that apply to current loop parameters Set<ObservationDTO> expObservationsSet = Collections.emptySet(); expObservationsSet=experiment.getMutants(sexType, zType); for (ObservationDTO expDto : expObservationsSet) { // get the attributes of this data point SexType docSexType = SexType.valueOf(expDto .getSex()); String categoString = expDto.getCategory(); // get docs that match the criteria and add // 1 for each that does if (categoString.equals(category) && docSexType.equals(sexType)) { mutantCount++; } } CategoricalDataObject expCatData = new CategoricalDataObject(); expCatData.setName(zType.name()); expCatData.setCategory(ppDAO.getCategoryDescription(parameter.getId(), category)); expCatData.setCount(mutantCount); CategoricalResult tempStatsResult=null; for(StatisticalResult result: statsResults) { if(result.getZygosityType().equals(zType) && result.getSexType().equals(sexType)) { expCatData.setResult((CategoricalResult)result); result.setSexType(sexType); result.setZygosityType(zType); tempStatsResult=(CategoricalResult)result; //result.setControlBiologicalModel(controlBiologicalModel); } } // //TODO get multiple p values when necessary // System.err.println("ERROR WE NEED to change the code to handle multiple p values and max effect!!!!!!!!"); if(tempStatsResult!=null) { expCatData.setpValue(tempStatsResult.getpValue()); if(tempStatsResult.getEffectSize()!=null) { expCatData.setMaxEffect(tempStatsResult.getEffectSize()); } } // logger.warn("pValue="+pValue+" maxEffect="+maxEffect); zTypeSet.add(expCatData); } chartData.add(zTypeSet); } categoricalResultAndCharts.setOrganisation(experiment.getOrganisation());//add it here before check so we can see the organisation even if no graph data }// end of gender String chartNew = this .createCategoricalHighChartUsingObjects(numberString, chartData, parameter, experiment.getOrganisation(), experiment.getMetadataGroup()); chartData.setChart(chartNew); categoricalResultAndCharts.add(chartData); categoricalResultAndCharts .setStatsResults(experiment.getResults()); return categoricalResultAndCharts; } public List<ChartData> doCategoricalDataOverview(CategoricalSet controlSet, CategoricalSet mutantSet, Model model, Parameter parameter) throws SQLException{ // do the charts ChartData chartData = new ChartData(); List<ChartData> categoricalResultAndCharts = new ArrayList<ChartData>(); if (mutantSet.getCount() > 0 && controlSet.getCount() > 0) {// if size is greater than one i.e. we have more than the control data then draw charts and tables String chartNew = this.createCategoricalHighChartUsingObjects2( controlSet, mutantSet, model, parameter, chartData); chartData.setChart(chartNew); categoricalResultAndCharts.add(chartData); } return categoricalResultAndCharts; } private String createCategoricalHighChartUsingObjects2(CategoricalSet controlSet, CategoricalSet mutantSet, Model model, Parameter parameter, ChartData chartData) throws SQLException { // to not 0 index as using loop count in jsp JSONArray seriesArray = new JSONArray(); JSONArray xAxisCategoriesArray = new JSONArray(); String title = parameter.getName(); String subtitle = parameter.getStableId(); // get a list of unique categories HashMap<String, List<Long>> categories = new LinkedHashMap<String, List<Long>>();// keep the order so we have normal first! for (CategoricalDataObject catObject : controlSet.getCatObjects()) { String category = catObject.getCategory(); categories.put(category, new ArrayList<Long>()); } for (CategoricalDataObject catObject : mutantSet.getCatObjects()) { String category = catObject.getCategory(); if (!categories.containsKey(category) && !category.equalsIgnoreCase("no data")){ categories.put(category, new ArrayList<Long>()); } } for(String categoryLabel : categories.keySet()){ if (controlSet.getCategoryByLabel(categoryLabel) != null){ categories.get(categoryLabel).add(controlSet.getCategoryByLabel(categoryLabel).getCount()); } else categories.get(categoryLabel).add((long)0); if (mutantSet.getCategoryByLabel(categoryLabel) != null){ categories.get(categoryLabel).add(mutantSet.getCategoryByLabel(categoryLabel).getCount()); } else categories.get(categoryLabel).add((long)0); } xAxisCategoriesArray.put(controlSet.getName()); xAxisCategoriesArray.put(mutantSet.getName()); try { int i = 0; Iterator it = categories.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); List<Long> data = (List<Long>) pairs.getValue(); JSONObject dataset1 = new JSONObject();// e.g. normal dataset1.put("name", pairs.getKey()); JSONArray dataset = new JSONArray(); for (Long singleValue : data) { dataset.put(singleValue); } dataset1.put("data", dataset); seriesArray.put(dataset1); i++; } } catch (JSONException e) { e.printStackTrace(); } String chartId = "single-chart-div";//replace space in MRC Harwell with underscore so valid javascritp variable String toolTipFunction = " { formatter: function() { return \''+ this.series.name +': '+ this.y +' ('+ (this.y*100/this.total).toFixed(1) +'%)'; } }"; List<String> colors=ChartColors.getFemaleMaleColorsRgba(ChartColors.alphaBox); JSONArray colorArray = new JSONArray(colors); String javascript = "$(document).ready(function() { chart = new Highcharts.Chart({ " +" colors:"+colorArray +", chart: { renderTo: '" + chartId + "', type: 'column' }, title: { text: '" + WordUtils.capitalize(title) + "' }, subtitle: { text:'" + subtitle + "'}, credits: { enabled: false }, " + "xAxis: { categories: " + xAxisCategoriesArray + "}, yAxis: { min: 0, title: { text: 'Percent Occurrance' } , labels: { formatter: function() { return this.value +'%'; } }}, plotOptions: { column: { stacking: 'percent' } }, series: " + seriesArray + " }); });"; chartData.setChart(javascript); chartData.setId(chartId); return javascript; } private String createCategoricalHighChartUsingObjects(String chartId, CategoricalChartDataObject chartData, Parameter parameter, String organisation, String metadataGroup) throws SQLException { //System.out.println(chartData); // int size=categoricalBarCharts.size()+1;//to know which div to render // to not 0 index as using loop count in jsp JSONArray seriesArray = new JSONArray(); JSONArray xAxisCategoriesArray = new JSONArray(); String title = parameter.getName(); // try { // logger.debug("call to highchart" + " sex=" + sex + " title=" // + title + " xAxisCategories=" + xAxisCategories // + " categoricalDataTypesTitles=" // + categoricalDataTypesTitles // + " seriesDataForCategoricalType=" // + seriesDataForCategoricalType); // "{ chart: { renderTo: 'female', type: 'column' }, title: { text: '' }, xAxis: { categories: [] }, yAxis: { min: 0, title: { text: '' } }, plotOptions: { column: { stacking: 'percent' } }, series: [ { name: 'Abnormal Femur', color: '#AA4643', data: [2, 2, 3] },{ name: 'Normal', color: '#4572A7', data: [5, 3, 4] }] }" String colorNormal = "#4572A7"; String colorAbnormal = "#AA4643"; String color = ""; List<CategoricalSet> catSets = chartData.getCategoricalSets(); // get a list of unique categories HashMap<String, List<Long>> categories = new LinkedHashMap<String, List<Long>>();// keep the order so we have normal first! // for(CategoricalSet catSet: catSets){ CategoricalSet catSet1 = catSets.get(0);// assume each cat set has the same number of categories for (CategoricalDataObject catObject : catSet1.getCatObjects()) { String category = catObject.getCategory(); // if(!category.equals("")){ categories.put(category, new ArrayList<Long>()); } for (CategoricalSet catSet : catSets) {// loop through control, then hom, then het etc xAxisCategoriesArray.put(catSet.getName()); for (CategoricalDataObject catObject : catSet.getCatObjects()) {// each cat object represents List<Long> catData = categories.get(catObject.getCategory()); catData.add(catObject.getCount()); } } try { int i = 0; Iterator it = categories.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); List<Long> data = (List<Long>) pairs.getValue(); JSONObject dataset1 = new JSONObject();// e.g. normal dataset1.put("name", pairs.getKey()); //System.out.println("paris key="+pairs.getKey()); // dataset1.put("color", color); JSONArray dataset = new JSONArray(); for (Long singleValue : data) { // if (i == 0) { // sex = SexType.female; // } else { // sex=SexType.male; // //System.out.println("single value="+singleValue); dataset.put(singleValue); //dataset1.put("color", ChartColors.getRgbaString(sex, i, ChartColors.alphaScatter)); i++; } dataset1.put("data", dataset); //System.out.println("XAxisCat="+xAxisCategoriesArray.get(i)); seriesArray.put(dataset1); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //replace space in MRC Harwell with underscore so valid javascript variable //String chartId = bm.getId() + sex.name()+organisation.replace(" ", "_")+"_"+metadataGroup; List<String> colors=ChartColors.getFemaleMaleColorsRgba(ChartColors.alphaBox); JSONArray colorArray = new JSONArray(colors); String toolTipFunction = " { formatter: function() { return \''+ this.series.name +': '+ this.y +' ('+ (this.y*100/this.total).toFixed(1) +'%)'; } }"; String javascript = "$(function () { var chart_" + chartId + "; $(document).ready(function() { chart_" + chartId + " = new Highcharts.Chart({ tooltip : " + toolTipFunction +", colors:"+colorArray + ", chart: { renderTo: 'chart" + chartId + "', type: 'column' }, title: { text: '" + WordUtils.capitalize(title) + "' }, credits: { enabled: false }, subtitle: { text: '" + parameter.getStableId() + "', x: -20 }, xAxis: { categories: " + xAxisCategoriesArray + "}, yAxis: { min: 0, title: { text: 'Percent Occurrance' } , labels: { formatter: function() { return this.value +'%'; } }}, plotOptions: { column: { stacking: 'percent' } }, series: " + seriesArray + " }); });});"; // logger.debug(javascript); // categoricalBarCharts.add(javascript); chartData.setChart(javascript); chartData.setChartIdentifier(chartId); //System.out.println("\n\n" + javascript); return javascript; } private void removeColumnsWithZeroData(List<String> xAxisCategories, List<List<Long>> seriesDataForCategoricalType) { Set<Integer> removeColumns = new HashSet<Integer>(); for (int i = 0; i < seriesDataForCategoricalType.get(0).size(); i++) { int count = 0; for (int j = 0; j < seriesDataForCategoricalType.size(); j++) { // logger.debug("checking cell with data="+seriesDataForCategoricalType.get(j).get(i)); count += seriesDataForCategoricalType.get(j).get(i); } if (count == 0) { // remove the column as there is no data removeColumns.add(i); } logger.debug("end of checking column"); } if (!removeColumns.isEmpty()) { for (Integer column : removeColumns) { for (List<Long> ll : seriesDataForCategoricalType) { ll.remove(column.intValue()); // logger.debug("removedcell="+column.intValue()); } String removedCat = xAxisCategories.remove(column.intValue()); // logger.debug("removedCat="+removedCat); } } } public List<String> getCategories(Parameter parameter) { // List<ParameterOption> options = parameter.getOptions(); // List<String> categories = new ArrayList<String>(); // for (ParameterOption option : options) { // categories.add(option.getName()); // //exclude - "no data", "not defined" etc // List<String>okCategoriesList=CategoriesExclude.getInterfaceFreindlyCategories(categories); // return okCategoriesList; return parameter.getCategoriesUserInterfaceFreindly(); } }
package jade.content.schema; import jade.content.onto.*; import jade.content.abs.*; import java.util.Hashtable; import java.util.Vector; import java.util.Enumeration; import jade.content.schema.facets.*; import jade.core.CaseInsensitiveString; import jade.util.leap.Serializable; /** * @author Giovanni Caire - TILAB */ class ObjectSchemaImpl extends ObjectSchema { private class SlotDescriptor implements Serializable { private String name = null; private ObjectSchema schema = null; private int optionality = 0; /** Construct a SlotDescriptor */ private SlotDescriptor(String name, ObjectSchema schema, int optionality) { this.name = name; this.schema = schema; this.optionality = optionality; } } private String typeName = null; private Hashtable slots; private Vector slotNames; private Vector superSchemas; private Hashtable facets; static { baseSchema = new ObjectSchemaImpl(); } /** * Construct a schema that vinculates an entity to be a generic * object (i.e. no constraints at all) */ private ObjectSchemaImpl() { this(BASE_NAME); } /** * Creates an <code>ObjectSchema</code> with a given type-name. * @param typeName The name of this <code>ObjectSchema</code>. */ protected ObjectSchemaImpl(String typeName) { this.typeName = typeName; } /** * Add a slot to the schema. * @param name The name of the slot. * @param slotSchema The schema defining the type of the slot. * @param optionality The optionality, i.e., <code>OPTIONAL</code> * or <code>MANDATORY</code> */ protected void add(String name, ObjectSchema slotSchema, int optionality) { CaseInsensitiveString ciName = new CaseInsensitiveString(name); if (slots == null) { slots = new Hashtable(); slotNames = new Vector(); } if (slots.put(ciName, new SlotDescriptor(name, slotSchema, optionality)) == null) { slotNames.addElement(ciName); } } /** * Add a mandatory slot to the schema. * @param name name of the slot. * @param slotSchema schema of the slot. */ protected void add(String name, ObjectSchema slotSchema) { add(name, slotSchema, MANDATORY); } /** * Add a slot with cardinality between <code>cardMin</code> * and <code>cardMax</code> to this schema. * Adding such a slot corresponds to add a slot * of type Aggregate and then to add proper facets (constraints) * to check that the type of the elements in the aggregate are * compatible with <code>elementsSchema</code> and that the * aggregate contains at least <code>cardMin</code> elements and * at most <code>cardMax</code> elements. By default the Aggregate * is of type <code>BasicOntology.SEQUENCE</code>. * @param name The name of the slot. * @param elementsSchema The schema for the elements of this slot. * @param cardMin This slot must get at least <code>cardMin</code> * values * @param cardMax This slot can get at most <code>cardMax</code> * values */ protected void add(String name, ObjectSchema elementsSchema, int cardMin, int cardMax) { add(name, elementsSchema, cardMin, cardMax, BasicOntology.SEQUENCE); } /** * Add a slot with cardinality between <code>cardMin</code> * and <code>cardMax</code> to this schema and allow specifying the type * of Aggregate to be used for this slot. * @param name The name of the slot. * @param elementsSchema The schema for the elements of this slot. * @param cardMin This slot must get at least <code>cardMin</code> * values * @param cardMax This slot can get at most <code>cardMax</code> * values * @param aggType The type of Aggregate to be used * @see #add(String, ObjectSchema, int, int) */ protected void add(String name, ObjectSchema elementsSchema, int cardMin, int cardMax, String aggType) { int optionality = (cardMin == 0 ? OPTIONAL : MANDATORY); try { add(name, BasicOntology.getInstance().getSchema(aggType), optionality); // Add proper facets addFacet(name, new TypedAggregateFacet(elementsSchema)); addFacet(name, new CardinalityFacet(cardMin, cardMax)); } catch (OntologyException oe) { // Should never happen oe.printStackTrace(); } } /** * Add a super schema tho this schema, i.e. this schema will * inherit all characteristics from the super schema * @param superSchema the super schema. */ protected void addSuperSchema(ObjectSchema superSchema) { if (superSchemas == null) { superSchemas = new Vector(); } superSchemas.addElement(superSchema); } /** Add a <code>Facet</code> on a slot of this schema @param slotName the name of the slot the <code>Facet</code> must be added to. @param f the <code>Facet</code> to be added. @throws OntologyException if slotName does not identify a valid slot in this schema */ protected void addFacet(String slotName, Facet f) throws OntologyException { if (containsSlot(slotName)) { CaseInsensitiveString ciName = new CaseInsensitiveString(slotName); if (facets == null) { facets = new Hashtable(); } Vector v = (Vector) facets.get(ciName); if (v == null) { v = new Vector(); facets.put(ciName, v); //DEBUG //System.out.println("Added facet "+f+" to slot "+slotName); } v.addElement(f); } else { throw new OntologyException(slotName+" is not a valid slot in this schema"); } } /** * Retrieves the name of the type of this schema. * @return the name of the type of this schema. */ public String getTypeName() { return typeName; } /** * Returns the names of all the slots in this <code>Schema</code> * (including slots defined in super schemas). * * @return the names of all slots. */ public String[] getNames() { Vector allSlotNames = new Vector(); fillAllSlotNames(allSlotNames); String[] names = new String[allSlotNames.size()]; int counter = 0; for (Enumeration e = allSlotNames.elements(); e.hasMoreElements(); ) { names[counter++] = ((CaseInsensitiveString) e.nextElement()).toString(); } return names; } /** * Retrieves the schema of a slot of this <code>Schema</code>. * * @param name The name of the slot. * @return the <code>Schema</code> of slot <code>name</code> * @throws OntologyException If no slot with this name is present * in this schema. */ public ObjectSchema getSchema(String name) throws OntologyException { SlotDescriptor slot = getSlot(new CaseInsensitiveString(name)); if (slot == null) { throw new OntologyException("No slot named: " + name); } return slot.schema; /*CaseInsensitiveString ciName = new CaseInsensitiveString(name); SlotDescriptor slot = getOwnSlot(ciName); if (slot == null) { if (superSchemas != null) { for (Enumeration e = superSchemas.elements(); e.hasMoreElements(); ) { try { ObjectSchema superSchema = (ObjectSchema) e.nextElement(); return superSchema.getSchema(name); } catch (OntologyException oe) { // Do nothing. Maybe the slot is defined in another super-schema } } } throw new OntologyException("No slot named: " + name); } return slot.schema; */ } /** * Indicate whether a given <code>String</code> is the name of a * slot defined in this <code>Schema</code> * * @param name The <code>String</code> to test. * @return <code>true</code> if <code>name</code> is the name of a * slot defined in this <code>Schema</code>. */ public boolean containsSlot(String name) { SlotDescriptor slot = getSlot(new CaseInsensitiveString(name)); return (slot != null); } /** * Indicate whether a slot of this schema is mandatory * * @param name The name of the slot. * @return <code>true</code> if the slot is mandatory. * @throws OntologyException If no slot with this name is present * in this schema. */ public boolean isMandatory(String name) throws OntologyException { SlotDescriptor slot = getSlot(new CaseInsensitiveString(name)); if (slot == null) { throw new OntologyException("No slot named: " + name); } return slot.optionality == MANDATORY; } /** * Creates an Abstract descriptor to hold an object compliant to * this <code>Schema</code>. */ public AbsObject newInstance() throws OntologyException { throw new OntologyException("AbsObject cannot be instantiated"); } private final void fillAllSlotNames(Vector v) { // Get slot names of super schemas (if any) first if (superSchemas != null) { for (Enumeration e = superSchemas.elements(); e.hasMoreElements(); ) { ObjectSchemaImpl superSchema = (ObjectSchemaImpl) e.nextElement(); superSchema.fillAllSlotNames(v); } } // Then add slot names of this schema if (slotNames != null) { for (Enumeration e = slotNames.elements(); e.hasMoreElements(); ) { v.addElement(e.nextElement()); } } } /** Check whether a given abstract descriptor complies with this schema. @param abs The abstract descriptor to be checked @throws OntologyException If the abstract descriptor does not complies with this schema */ public void validate(AbsObject abs, Ontology onto) throws OntologyException { validateSlots(abs, onto); } /** For each slot - get the corresponding attribute value from the abstract descriptor abs - Check that it is not null if the slot is mandatory - Check that its schema is compatible with the schema of the slot - Check that it is a correct abstract descriptor by validating it against its schema. */ protected void validateSlots(AbsObject abs, Ontology onto) throws OntologyException { // Validate all the attributes in the abstract descriptor String[] slotNames = getNames(); for (int i = 0; i < slotNames.length; ++i) { AbsObject slotValue = abs.getAbsObject(slotNames[i]); CaseInsensitiveString ciName = new CaseInsensitiveString(slotNames[i]); validate(ciName, slotValue, onto); } } /** Validate a given abstract descriptor as a value for a slot defined in this schema @param slotName The name of the slot @param value The abstract descriptor to be validated @throws OntologyException If the abstract descriptor is not a valid value @return true if the slot is defined in this schema (or in one of its super schemas). false otherwise */ private boolean validate(CaseInsensitiveString slotName, AbsObject value, Ontology onto) throws OntologyException { // DEBUG //System.out.println("Validating "+value+" as a value for slot "+slotName); // NOTE: for performance reasons we don't want to scan the schema // to check if slotValue is a valid slot and THEN to scan again // the schema to validate value. This is the reason for the // boolean return value of this method boolean slotFound = false; // If the slot is defined in this schema --> check the value // against the schema of the slot. Otherwise let the super-schema // where the slot is defined validate the value SlotDescriptor dsc = getOwnSlot(slotName); if (dsc != null) { // DEBUG //System.out.println("Slot "+slotName+" is defined in schema "+this); if (value == null) { // Check optionality if (dsc.optionality == MANDATORY) { throw new OntologyException("Missing value for mandatory slot "+slotName+". Schema is "+this); } // Don't need to check facets on a null value for an optional slot return true; } else { // - Get from the ontology the schema s that defines the type // of the abstract descriptor value. // - Check if this schema is compatible with the schema for // slot slotName // - Finally check value against s ObjectSchema s = onto.getSchema(value.getTypeName()); //DEBUG //System.out.println("Actual schema for "+value+" is "+s); if (s == null) { throw new OntologyException("No schema found for type "+value.getTypeName()); } if (!s.isCompatibleWith(dsc.schema)) { throw new OntologyException("Schema "+s+" for element "+value+" is not compatible with schema "+dsc.schema+" for slot "+slotName); } //DEBUG //System.out.println("Schema "+s+" for type "+value+" is compatible with schema "+dsc.schema+" for slot "+slotName); s.validate(value, onto); } slotFound = true; } else { if (superSchemas != null) { Enumeration e = superSchemas.elements(); while (e.hasMoreElements()) { ObjectSchemaImpl s = (ObjectSchemaImpl) e.nextElement(); if (s.validate(slotName, value, onto)) { slotFound = true; // Don't need to check other super-schemas break; } } } } if (slotFound && facets != null) { // Check value against the facets (if any) defined for the // slot in this schema Vector ff = (Vector) facets.get(slotName); if (ff != null) { Enumeration e = ff.elements(); while (e.hasMoreElements()) { Facet f = (Facet) e.nextElement(); //DEBUG //System.out.println("Checking facet "+f+" defined on slot "+slotName); f.validate(value, onto); } } else { //DEBUG //System.out.println("No facets for slot "+slotName); } } return slotFound; } /** Check if this schema is compatible with a given schema s. This is the case if 1) This schema is equals to s 2) s is one of the super-schemas of this schema 3) This schema descends from s i.e. - s is the base schema for the XXXSchema class this schema is an instance of (e.g. s is ConceptSchema.getBaseSchema() and this schema is an instance of ConceptSchema) - s is the base schema for a super-class of the XXXSchema class this schema is an instance of (e.g. s is TermSchema.getBaseSchema() and this schema is an instance of ConceptSchema) */ public boolean isCompatibleWith(ObjectSchema s) { if (equals(s)) { return true; } if (isSubSchemaOf(s)) { return true; } if (descendsFrom(s)) { return true; } return false; } /** Return true if - s is the base schema for the XXXSchema class this schema is an instance of (e.g. s is ConceptSchema.getBaseSchema() and this schema is an instance of ConceptSchema) - s is the base schema for a super-class of the XXXSchema class this schema is an instance of (e.g. s is TermSchema.getBaseSchema() and this schema is an instance of ConceptSchema) */ protected boolean descendsFrom(ObjectSchema s) { // The base schema for the ObjectSchema class descends only // from itself if (s!= null) { return s.equals(getBaseSchema()); } else { return false; } } /** Return true if s is a super-schema (directly or indirectly) of this schema */ private boolean isSubSchemaOf(ObjectSchema s) { if (superSchemas != null) { Enumeration e = superSchemas.elements(); while (e.hasMoreElements()) { ObjectSchemaImpl s1 = (ObjectSchemaImpl) e.nextElement(); if (s1.equals(s)) { return true; } if (s1.isSubSchemaOf(s)) { return true; } } } return false; } public String toString() { return getClass().getName()+"-"+getTypeName(); } public boolean equals(Object o) { if (o != null) { return toString().equals(o.toString()); } else { return false; } } /** * Get the facets defined upon a slot of the objectschema. * Return null if there aren't facets on the specified slot. */ public Facet[] getFacets(String slotName) { Facet[] temp = null; CaseInsensitiveString caseInsensitiveSlotName = new CaseInsensitiveString(slotName); if (getOwnSlot(caseInsensitiveSlotName)!=null) { if (facets != null) { Vector v = (Vector)facets.get(caseInsensitiveSlotName); if (v!=null) { temp = new Facet[v.size()]; for (int i=0; i<v.size()-1; i++) temp[i] = (Facet)v.elementAt(i); } } } else { if (superSchemas!=null) { for (int i = 0; i < superSchemas.size() && temp==null; i++) { temp = ((ObjectSchema)superSchemas.get(i)).getFacets(slotName); } } } return temp; } private final SlotDescriptor getOwnSlot(CaseInsensitiveString ciName) { return (slots != null ? (SlotDescriptor) slots.get(ciName) : null); } private final SlotDescriptor getSlot(CaseInsensitiveString ciName) { SlotDescriptor dsc = getOwnSlot(ciName); if (dsc == null) { if (superSchemas != null) { for (int i = 0; i < superSchemas.size(); ++i) { ObjectSchemaImpl sc = (ObjectSchemaImpl) superSchemas.elementAt(i); dsc = sc.getSlot(ciName); if (dsc != null) { break; } } } } return dsc; } }
package de.epiceric.shopchest.utils; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang.WordUtils; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import java.util.Map; public class ItemNames { private static final Map<String, String> map = ImmutableMap.<String, String>builder() .put("1", "Stone") .put("1:1", "Granite") .put("1:2", "Polished Granite") .put("1:3", "Diorite") .put("1:4", "Polished Diorite") .put("1:5", "Andesite") .put("1:6", "Polished Andesite") .put("2", "Grass Block") .put("3", "Dirt") .put("3:1", "Coarse Dirt") .put("3:2", "Podzol") .put("4", "Cobblestone") .put("5", "Oak Wood Planks") .put("5:1", "Spruce Wood Planks") .put("5:2", "Birch Wood Planks") .put("5:3", "Jungle Wood Planks") .put("5:4", "Acacia Wood Planks") .put("5:5", "Dark Oak Wood Planks") .put("6", "Oak Sapling") .put("6:1", "Spruce Sapling") .put("6:2", "Birch Sapling") .put("6:3", "Jungle Sapling") .put("6:4", "Acacia Sapling") .put("6:5", "Dark Oak Sapling") .put("7", "Bedrock") .put("8", "Water (No Spread)") .put("9", "Water") .put("10", "Lava (No Spread)") .put("11", "Lava") .put("12", "Sand") .put("12:1", "Red Sand") .put("13", "Gravel") .put("14", "Gold Ore") .put("15", "Iron Ore") .put("16", "Coal Ore") .put("17", "Oak Wood") .put("17:1", "Spruce Wood") .put("17:2", "Birch Wood") .put("17:3", "Jungle Wood") .put("18", "Oak Leaves") .put("18:1", "Spruce Leaves") .put("18:2", "Birch Leaves") .put("18:3", "Jungle Leaves") .put("19", "Sponge") .put("19:1", "Wet Sponge") .put("20", "Glass") .put("21", "Lapis Lazuli Ore") .put("22", "Lapis Lazuli Block") .put("23", "Dispenser") .put("24", "Sandstone") .put("24:1", "Chiseled Sandstone") .put("24:2", "Smooth Sandstone") .put("25", "Note Block") .put("26", "Bed") .put("27", "Powered Rail") .put("28", "Detector Rail") .put("29", "Sticky Piston") .put("30", "Web") .put("31", "Shrub") .put("31:1", "Grass") .put("31:2", "Fern") .put("32", "Dead Bush") .put("33", "Piston") .put("34", "Piston (Head)") .put("35", "Wool") .put("35:1", "Orange Wool") .put("35:2", "Magenta Wool") .put("35:3", "Light Blue Wool") .put("35:4", "Yellow Wool") .put("35:5", "Lime Wool") .put("35:6", "Pink Wool") .put("35:7", "Gray Wool") .put("35:8", "Light Gray Wool") .put("35:9", "Cyan Wool") .put("35:10", "Purple Wool") .put("35:11", "Blue Wool") .put("35:12", "Brown Wool") .put("35:13", "Green Wool") .put("35:14", "Red Wool") .put("35:15", "Black Wool") .put("37", "Dandelion") .put("38", "Rose") .put("38:1", "Blue Orchid") .put("38:2", "Allium") .put("38:3", "Azure Bluet") .put("38:4", "Red Tulip") .put("38:5", "Orange Tulip") .put("38:6", "White Tulip") .put("38:7", "Pink Tulip") .put("38:8", "Oxeye Daisy") .put("39", "Brown Mushroom") .put("40", "Red Mushroom") .put("41", "Gold Block") .put("42", "Iron Block") .put("43", "Stone Slab (Double)") .put("43:1", "Sandstone Slab (Double)") .put("43:2", "Wooden Slab (Double)") .put("43:3", "Cobblestone Slab (Double)") .put("43:4", "Brick Slab (Double)") .put("43:5", "Stone Brick Slab (Double)") .put("43:6", "Nether Brick Slab (Double)") .put("43:7", "Quartz Slab (Double)") .put("43:8", "Smooth Stone Slab (Double)") .put("43:9", "Smooth Sandstone Slab (Double)") .put("44", "Stone Slab") .put("44:1", "Sandstone Slab") .put("44:2", "Wooden Slab") .put("44:3", "Cobblestone Slab") .put("44:4", "Brick Slab") .put("44:5", "Stone Brick Slab") .put("44:6", "Nether Brick Slab") .put("44:7", "Quartz Slab") .put("45", "Brick") .put("46", "TNT") .put("47", "Bookcase") .put("48", "Moss Stone") .put("49", "Obsidian") .put("50", "Torch") .put("51", "Fire") .put("52", "Mob Spawner") .put("53", "Oak Wood Stairs") .put("54", "Chest") .put("55", "Redstone Wire") .put("56", "Diamond Ore") .put("57", "Diamond Block") .put("58", "Crafting Table") .put("59", "Wheat (Crop)") .put("60", "Farmland") .put("61", "Furnace") .put("62", "Furnace (Smelting)") .put("63", "Sign (Block)") .put("64", "Wood Door (Block)") .put("65", "Ladder") .put("66", "Rails") .put("67", "Stone Stairs") .put("68", "Sign (Wall Block)") .put("69", "Lever") .put("70", "Pressure Plate") .put("71", "Iron Door (Block)") .put("72", "Pressure Plate") .put("73", "Redstone Ore") .put("74", "Redstone Ore (Glowing)") .put("75", "Redstone Torch (Off)") .put("76", "Redstone Torch") .put("77", "Button") .put("78", "Snow") .put("79", "Ice") .put("80", "Snow Block") .put("81", "Cactus") .put("82", "Clay Block") .put("83", "Sugar Cane (Block)") .put("84", "Jukebox") .put("85", "Fence") .put("86", "Pumpkin") .put("87", "Netherrack") .put("88", "Soul Sand") .put("89", "Glowstone") .put("90", "Portal") .put("91", "Jack-O-Lantern") .put("92", "Cake (Block)") .put("93", "Redstone Repeater (Block Off)") .put("94", "Redstone Repeater (Block On)") .put("95", "Stained Glass") .put("96", "Wooden Trapdoor") .put("97", "Stone Monster Egg") .put("97:1", "Cobblestone Monster Egg") .put("97:2", "Stone Brick Monster Egg") .put("97:3", "Mossy Stone Brick Monster Egg") .put("97:4", "Cracked Stone Brick Monster Egg") .put("97:5", "Chiseled Stone Brick Monster Egg") .put("98", "Stone Bricks") .put("98:1", "Mossy Stone Bricks") .put("98:2", "Cracked Stone Bricks") .put("98:3", "Chiseled Stone Bricks") .put("99", "Brown Mushroom (Block)") .put("100", "Red Mushroom (Block)") .put("101", "Iron Bars") .put("102", "Glass Pane") .put("103", "Melon (Block)") .put("104", "Pumpkin Vine") .put("105", "Melon Vine") .put("106", "Vines") .put("107", "Fence Gate") .put("108", "Brick Stairs") .put("109", "Stone Brick Stairs") .put("110", "Mycelium") .put("111", "Lily Pad") .put("112", "Nether Brick") .put("113", "Nether Brick Fence") .put("114", "Nether Brick Stairs") .put("115", "Nether Wart") .put("116", "Enchantment Table") .put("117", "Brewing Stand (Block)") .put("118", "Cauldron (Block)") .put("119", "End Portal") .put("120", "End Portal Frame") .put("121", "End Stone") .put("122", "Dragon Egg") .put("123", "Redstone Lamp (Inactive)") .put("124", "Redstone Lamp (Active)") .put("125", "Double Wood Slab") .put("126", "Oak Wood Slab") .put("126:1", "Spruce Wood Slab") .put("126:2", "Birch Slab") .put("126:3", "Jungle Slab") .put("126:4", "Acacia Wood Slab") .put("126:5", "Dark Oak Wood Slab") .put("127", "Cocoa Plant") .put("128", "Sandstone Stairs") .put("129", "Emerald Ore") .put("130", "Ender Chest") .put("131", "Tripwire Hook") .put("132", "Tripwire") .put("133", "Emerald Block") .put("134", "Spruce Wood Stairs") .put("135", "Birch Wood Stairs") .put("136", "Jungle Wood Stairs") .put("137", "Command Block") .put("138", "Beacon Block") .put("139", "Cobblestone Wall") .put("139:1", "Mossy Cobblestone Wall") .put("140", "Flower Pot") .put("141", "Carrots") .put("142", "Potatoes") .put("143", "Button") .put("144", "Head") .put("145", "Anvil") .put("146", "Trapped Chest") .put("147", "Weighted Pressure Plate (Light)") .put("148", "Weighted Pressure Plate (Heavy)") .put("149", "Redstone Comparator (inactive)") .put("150", "Redstone Comparator (active)") .put("151", "Daylight Sensor") .put("152", "Redstone Block") .put("153", "Nether Quartz Ore") .put("154", "Hopper") .put("155", "Quartz Block") .put("155:1", "Chiseled Quartz Block") .put("155:2", "Pillar Quartz Block") .put("156", "Quartz Stairs") .put("157", "Activator Rail") .put("158", "Dropper") .put("159", "Stained Clay") .put("160", "Stained Glass Pane") .put("161", "Acacia Leaves") .put("161:1", "Dark Oak Leaves") .put("162", "Acacia Wood") .put("162:1", "Dark Oak Wood") .put("163", "Acacia Wood Stairs") .put("164", "Dark Oak Wood Stairs") .put("165", "Slime Block") .put("166", "Barrier") .put("167", "Iron Trapdoor") .put("168", "Prismarine") .put("168:1", "Prismarine Bricks") .put("168:2", "Dark Prismarine") .put("169", "Sea Lantern") .put("170", "Hay Block") .put("171", "Carpet") .put("172", "Hardened Clay") .put("173", "Block of Coal") .put("174", "Packed Ice") .put("175", "Sunflower") .put("175:1", "Lilac") .put("175:2", "Double Tallgrass") .put("175:3", "Large Fern") .put("175:4", "Rose Bush") .put("175:5", "Peony") .put("178", "Daylight Sensor (Inverted)") .put("179", "Red Sandstone") .put("179:1", "Chiseled Red Sandstone") .put("179:2", "Smooth Red Sandstone") .put("180", "Red Sandstone Stairs") .put("182", "Red Sandstone Slab") .put("183", "Spruce Fence Gate") .put("184", "Birch Fence Gate") .put("185", "Jungle Fence Gate") .put("186", "Dark Oak Fence Gate") .put("187", "Acacia Fence Gate") .put("188", "Spruce Fence") .put("189", "Birch Fence") .put("190", "Jungle Fence") .put("191", "Dark Oak Fence") .put("192", "Acacia Fence") .put("198", "End Rod") .put("199", "Chorus Plant") .put("200", "Chorus Flower") .put("201", "Purpur Block") .put("202", "Purpur Pillar") .put("203", "Purpur Stairs") .put("204", "Purpur Slab (Double)") .put("205", "Purpur Slab") .put("206", "End Stone Bricks") .put("208", "Grass Path") .put("209", "End Gateway") .put("210", "Repeating Command Block") .put("211", "Chain Command Block") .put("212", "Frosted Ice") .put("213", "Magma Block") .put("214", "Nether Wart Block") .put("215", "Red Nether Brick") .put("216", "Bone Block") .put("217", "Structure Void") .put("255", "Structure Block") .put("256", "Iron Shovel") .put("257", "Iron Pickaxe") .put("258", "Iron Axe") .put("259", "Flint and Steel") .put("260", "Apple") .put("261", "Bow") .put("262", "Arrow") .put("263", "Coal") .put("263:1", "Charcoal") .put("264", "Diamond") .put("265", "Iron Ingot") .put("266", "Gold Ingot") .put("267", "Iron Sword") .put("268", "Wooden Sword") .put("269", "Wooden Shovel") .put("270", "Wooden Pickaxe") .put("271", "Wooden Axe") .put("272", "Stone Sword") .put("273", "Stone Shovel") .put("274", "Stone Pickaxe") .put("275", "Stone Axe") .put("276", "Diamond Sword") .put("277", "Diamond Shovel") .put("278", "Diamond Pickaxe") .put("279", "Diamond Axe") .put("280", "Stick") .put("281", "Bowl") .put("282", "Mushroom Stew") .put("283", "Gold Sword") .put("284", "Gold Shovel") .put("285", "Gold Pickaxe") .put("286", "Gold Axe") .put("287", "String") .put("288", "Feather") .put("289", "Gunpowder") .put("290", "Wooden Hoe") .put("291", "Stone Hoe") .put("292", "Iron Hoe") .put("293", "Diamond Hoe") .put("294", "Gold Hoe") .put("295", "Seeds") .put("296", "Wheat") .put("297", "Bread") .put("298", "Leather Helmet") .put("299", "Leather Chestplate") .put("300", "Leather Leggings") .put("301", "Leather Boots") .put("302", "Chainmail Helmet") .put("303", "Chainmail Chestplate") .put("304", "Chainmail Leggings") .put("305", "Chainmail Boots") .put("306", "Iron Helmet") .put("307", "Iron Chestplate") .put("308", "Iron Leggings") .put("309", "Iron Boots") .put("310", "Diamond Helmet") .put("311", "Diamond Chestplate") .put("312", "Diamond Leggings") .put("313", "Diamond Boots") .put("314", "Gold Helmet") .put("315", "Gold Chestplate") .put("316", "Gold Leggings") .put("317", "Gold Boots") .put("318", "Flint") .put("319", "Raw Porkchop") .put("320", "Cooked Porkchop") .put("321", "Painting") .put("322", "Gold Apple") .put("322:1", "Gold Apple (Enchanted)") .put("323", "Sign") .put("324", "Wooden Door") .put("325", "Bucket") .put("326", "Water Bucket") .put("327", "Lava Bucket") .put("328", "Minecart") .put("329", "Saddle") .put("330", "Iron Door") .put("331", "Redstone") .put("332", "Snowball") .put("333", "Boat") .put("334", "Leather") .put("335", "Milk Bucket") .put("336", "Brick") .put("337", "Clay") .put("338", "Sugar Cane") .put("339", "Paper") .put("340", "Book") .put("341", "Slime Ball") .put("342", "Storage Minecart") .put("343", "Powered Minecart") .put("344", "Egg") .put("345", "Compass") .put("346", "Fishing Rod") .put("347", "Watch") .put("348", "Glowstone Dust") .put("349", "Raw Fish") .put("349:1", "Raw Salmon") .put("349:2", "Clownfish") .put("349:3", "Pufferfish") .put("350", "Cooked Fish") .put("350:1", "Cooked Salmon") .put("351", "Ink Sac") .put("351:1", "Rose Red") .put("351:2", "Cactus Green") .put("351:3", "Cocoa Bean") .put("351:4", "Lapis Lazuli") .put("351:5", "Purple Dye") .put("351:6", "Cyan Dye") .put("351:7", "Light Gray Dye") .put("351:8", "Gray Dye") .put("351:9", "Pink Dye") .put("351:10", "Lime Dye") .put("351:11", "Dandelion Yellow") .put("351:12", "Light Blue Dye") .put("351:13", "Magenta Dye") .put("351:14", "Orange Dye") .put("351:15", "Bone Meal") .put("352", "Bone") .put("353", "Sugar") .put("354", "Cake") .put("355", "Bed") .put("356", "Redstone Repeater") .put("357", "Cookie") .put("358", "Map") .put("359", "Shears") .put("360", "Melon") .put("361", "Pumpkin Seeds") .put("362", "Melon Seeds") .put("363", "Raw Beef") .put("364", "Steak") .put("365", "Raw Chicken") .put("366", "Roast Chicken") .put("367", "Rotten Flesh") .put("368", "Ender Pearl") .put("369", "Blaze Rod") .put("370", "Ghast Tear") .put("371", "Gold Nugget") .put("372", "Nether Wart") .put("373", "Water Bottle") .put("373:16", "Awkward Potion") .put("373:32", "Thick Potion") .put("373:64", "Mundane Potion") .put("373:8193", "Regeneration Potion (0:45)") .put("373:8194", "Swiftness Potion (3:00)") .put("373:8195", "Fire Resistance Potion (3:00)") .put("373:8196", "Poison Potion (0:45)") .put("373:8197", "Healing Potion") .put("373:8200", "Weakness Potion (1:30)") .put("373:8201", "Strength Potion (3:00)") .put("373:8202", "Slowness Potion (1:30)") .put("373:8203", "Potion of Leaping (3:00)") .put("373:8204", "Harming Potion") .put("373:8225", "Regeneration Potion II (0:22)") .put("373:8226", "Swiftness Potion II (1:30)") .put("373:8228", "Poison Potion II (0:22)") .put("373:8229", "Healing Potion II") .put("373:8230", "Night Vision Potion (3:00)") .put("373:8233", "Strength Potion II (1:30)") .put("373:8235", "Potion of Leaping (1:30)") .put("373:8236", "Harming Potion II") .put("373:8237", "Water Breathing Potion (3:00)") .put("373:8238", "Invisibility Potion (3:00)") .put("373:8257", "Regeneration Potion (2:00)") .put("373:8258", "Swiftness Potion (8:00)") .put("373:8259", "Fire Resistance Potion (8:00)") .put("373:8260", "Poison Potion (2:00)") .put("373:8262", "Night Vision Potion (8:00)") .put("373:8264", "Weakness Potion (4:00)") .put("373:8265", "Strength Potion (8:00)") .put("373:8266", "Slowness Potion (4:00)") .put("373:8269", "Water Breathing Potion (8:00)") .put("373:8270", "Invisibility Potion (8:00)") .put("373:16378", "Fire Resistance Splash (2:15)") .put("373:16385", "Regeneration Splash (0:33)") .put("373:16386", "Swiftness Splash (2:15)") .put("373:16388", "Poison Splash (0:33)") .put("373:16389", "Healing Splash") .put("373:16392", "Weakness Splash (1:07)") .put("373:16393", "Strength Splash (2:15)") .put("373:16394", "Slowness Splash (1:07)") .put("373:16396", "Harming Splash") .put("373:16418", "Swiftness Splash II (1:07)") .put("373:16420", "Poison Splash II (0:16)") .put("373:16421", "Healing Splash II") .put("373:16422", "Night Vision Splash (2:15)") .put("373:16425", "Strength Splash II (1:07)") .put("373:16428", "Harming Splash II") .put("373:16429", "Water Breathing Splash (2:15)") .put("373:16430", "Invisibility Splash (2:15)") .put("373:16449", "Regeneration Splash (1:30)") .put("373:16450", "Swiftness Splash (6:00)") .put("373:16451", "Fire Resistance Splash (6:00)") .put("373:16452", "Poison Splash (1:30)") .put("373:16454", "Night Vision Splash (6:00)") .put("373:16456", "Weakness Splash (3:00)") .put("373:16457", "Strength Splash (6:00)") .put("373:16458", "Slowness Splash (3:00)") .put("373:16461", "Water Breathing Splash (6:00)") .put("373:16462", "Invisibility Splash (6:00)") .put("373:16471", "Regeneration Splash II (0:16)") .put("374", "Glass Bottle") .put("375", "Spider Eye") .put("376", "Fermented Spider Eye") .put("377", "Blaze Powder") .put("378", "Magma Cream") .put("379", "Brewing Stand") .put("380", "Cauldron") .put("381", "Eye of Ender") .put("382", "Glistering Melon") .put("383", "Spawn Egg") .put("383:50", "Spawn Creeper") .put("383:51", "Spawn Skeleton") .put("383:52", "Spawn Spider") .put("383:54", "Spawn Zombie") .put("383:55", "Spawn Slime") .put("383:56", "Spawn Ghast") .put("383:57", "Spawn Pigman") .put("383:58", "Spawn Enderman") .put("383:59", "Spawn Cave Spider") .put("383:60", "Spawn Silverfish") .put("383:61", "Spawn Blaze") .put("383:62", "Spawn Magma Cube") .put("383:65", "Spawn Bat") .put("383:66", "Spawn Witch") .put("383:67", "Spawn Endermite") .put("383:68", "Spawn Guardian") .put("383:90", "Spawn Pig") .put("383:91", "Spawn Sheep") .put("383:92", "Spawn Cow") .put("383:93", "Spawn Chicken") .put("383:94", "Spawn Squid") .put("383:95", "Spawn Wolf") .put("383:96", "Spawn Mooshroom") .put("383:98", "Spawn Ocelot") .put("383:100", "Spawn Horse") .put("383:101", "Spawn Rabbit") .put("383:120", "Spawn Villager") .put("384", "Bottle o' Enchanting") .put("385", "Fire Charge") .put("386", "Book and Quill") .put("387", "Written Book") .put("388", "Emerald") .put("389", "Item Frame") .put("390", "Flower Pot") .put("391", "Carrot") .put("392", "Potato") .put("393", "Baked Potato") .put("394", "Poisonous Potato") .put("395", "Empty Map") .put("396", "Golden Carrot") .put("397", "Skull Item") .put("397:0", "Skeleton Skull") .put("397:1", "Wither Skeleton Skull") .put("397:2", "Zombie Head") .put("373:3", "Head") .put("373:4", "Creeper Head") .put("398", "Carrot on a Stick") .put("399", "Nether Star") .put("400", "Pumpkin Pie") .put("401", "Firework Rocket") .put("402", "Firework Star") .put("403", "Enchanted Book") .put("404", "Redstone Comparator") .put("405", "Nether Brick") .put("406", "Nether Quartz") .put("407", "Minecart with TNT") .put("408", "Minecart with Hopper") .put("409", "Prismarine Shard") .put("410", "Prismarine Crystals") .put("411", "Raw Rabbit") .put("412", "Cooked Rabbit") .put("413", "Rabbit Stew") .put("414", "Rabbit Foot") .put("415", "Rabbit Hide") .put("417", "Iron Horse Armor") .put("418", "Gold Horse Armor") .put("419", "Diamond Horse Armor") .put("420", "Lead") .put("421", "Name Tag") .put("422", "Minecart with Command Block") .put("423", "Raw Mutton") .put("424", "Cooked Mutton") .put("425", "Banner") .put("426", "End Crystal") .put("427", "Spruce Door") .put("428", "Birch Door") .put("429", "Jungle Door") .put("430", "Acacia Door") .put("431", "Dark Oak Door") .put("432", "Chorus Fruit") .put("433", "Popped Chorus Fruit") .put("434", "Beetroot") .put("435", "Beetroot Seeds") .put("436", "Beetroot Soup") .put("437", "Dragon Breath") .put("438", "Splash Potion") .put("439", "Spectral Arrow") .put("440", "Tipped Arrow") .put("441", "Lingering Potion") .put("442", "Shield") .put("443", "Elytra") .put("444", "Spruce Boat") .put("445", "Birch Boat") .put("446", "Jungle Boat") .put("447", "Acacia Boat") .put("448", "Dark Oak Boat") .put("2256", "Music Disk (13)") .put("2257", "Music Disk (Cat)") .put("2258", "Music Disk (Blocks)") .put("2259", "Music Disk (Chirp)") .put("2260", "Music Disk (Far)") .put("2261", "Music Disk (Mall)") .put("2262", "Music Disk (Mellohi)") .put("2263", "Music Disk (Stal)") .put("2264", "Music Disk (Strad)") .put("2265", "Music Disk (Ward)") .put("2266", "Music Disk (11)") .put("2267", "Music Disk (wait)") .build(); public static String lookup(ItemStack stack) { if (stack.hasItemMeta()) { ItemMeta meta = stack.getItemMeta(); if (meta.getDisplayName() != null) { return meta.getDisplayName(); } else if (meta instanceof BookMeta) { return ((BookMeta) meta).getTitle(); } } String result; String key = Integer.toString(stack.getTypeId()); Material mat = stack.getType(); if ((mat == Material.WOOL || mat == Material.CARPET) && stack.getDurability() == 0) { // special case: white wool/carpet is just called "Wool" or "Carpet" result = map.get(key); } else if (mat == Material.WOOL || mat == Material.CARPET || mat == Material.STAINED_CLAY || mat == Material.STAINED_GLASS || mat == Material.STAINED_GLASS_PANE) { DyeColor dc = DyeColor.getByWoolData((byte) stack.getDurability()); result = dc == null ? map.get(key) : WordUtils.capitalizeFully(dc.toString().replace("_", " ")) + " " + map.get(key); } else if (mat == Material.LEATHER_HELMET || mat == Material.LEATHER_CHESTPLATE || mat == Material.LEATHER_LEGGINGS || mat == Material.LEATHER_BOOTS) { LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) stack.getItemMeta(); DyeColor dc = DyeColor.getByColor(leatherArmorMeta.getColor()); result = dc == null ? map.get(key) : WordUtils.capitalizeFully(dc.toString()).replace("_", " ") + " " + map.get(key); } else if (stack.getDurability() != 0) { result = map.get(key + ":" + stack.getDurability()); if (result == null) { result = map.get(key); } } else { result = map.containsKey(key) ? map.get(key) : stack.getType().toString(); } return result; } }
import net.dlogic.kryonet.client.event.callback.IRoomEventCallback; import net.dlogic.kryonet.common.entity.Room; import net.dlogic.kryonet.common.entity.User; import com.esotericsoftware.minlog.Log; public class RoomEventCallback implements IRoomEventCallback { @Override public void onJoinRoomFailure(String errorMessage) { Log.info(errorMessage); } @Override public void onJoinRoomSuccess(User joinedUser, Room joinedRoom) { Log.info(joinedUser.username + "=>" + joinedRoom.name); } @Override public void onGetRooms(Room[] rooms) { for (Room room : rooms) { Log.info(room.name); } } @Override public void onLeaveRoom(User userLeft, Room roomLeft) { // TODO Auto-generated method stub } }
package de.j4velin.pedometer; import java.util.Locale; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.Preference.OnPreferenceClickListener; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.NumberPicker; import android.widget.RadioGroup; import android.widget.TextView; public class SettingsFragment extends PreferenceFragment implements OnPreferenceClickListener { final static int DEFAULT_GOAL = 10000; final static float DEFAULT_STEP_SIZE = Locale.getDefault() == Locale.US ? 2.5f : 75f; final static String DEFAULT_STEP_UNIT = Locale.getDefault() == Locale.US ? "ft" : "cm"; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); findPreference("about").setOnPreferenceClickListener(this); Preference account = findPreference("account"); account.setOnPreferenceClickListener(this); if (((MainActivity) getActivity()).getGC().isConnected()) { account.setSummary(getString(R.string.signed_in, ((MainActivity) getActivity()).getGC().getCurrentPlayer() .getDisplayName())); } final SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); Preference goal = findPreference("goal"); goal.setOnPreferenceClickListener(this); goal.setSummary(getString(R.string.goal_summary, prefs.getInt("goal", DEFAULT_GOAL))); Preference stepsize = findPreference("stepsize"); stepsize.setOnPreferenceClickListener(this); stepsize.setSummary(getString(R.string.step_size_summary, prefs.getFloat("stepsize_value", DEFAULT_STEP_SIZE), prefs.getString("stepsize_unit", DEFAULT_STEP_UNIT))); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); getActivity().getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.main, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.action_settings).setVisible(false); } @Override public boolean onOptionsItemSelected(final MenuItem item) { return ((MainActivity) getActivity()).optionsItemSelected(item); } @Override public boolean onPreferenceClick(final Preference preference) { AlertDialog.Builder builder; View v; final SharedPreferences prefs; switch (preference.getTitleRes()) { case R.string.goal: builder = new AlertDialog.Builder(getActivity()); final NumberPicker np = new NumberPicker(getActivity()); prefs = getPreferenceManager().getSharedPreferences(); np.setMinValue(1); np.setMaxValue(100000); np.setValue(prefs.getInt("goal", 10000)); builder.setView(np); builder.setTitle("Set goal"); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { np.clearFocus(); prefs.edit().putInt("goal", np.getValue()).apply(); preference.setSummary(getString(R.string.goal_summary, np.getValue())); dialog.dismiss(); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = builder.create(); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); break; case R.string.step_size: builder = new AlertDialog.Builder(getActivity()); prefs = getPreferenceManager().getSharedPreferences(); v = getActivity().getLayoutInflater().inflate(R.layout.stepsize, null); final RadioGroup unit = (RadioGroup) v.findViewById(R.id.unit); final EditText value = (EditText) v.findViewById(R.id.value); unit.check(prefs.getString("stepsize_unit", DEFAULT_STEP_UNIT).equals("cm") ? R.id.cm : R.id.ft); value.setText(String.valueOf(prefs.getFloat("stepsize_value", DEFAULT_STEP_SIZE))); builder.setView(v); builder.setTitle("Set step size"); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { prefs.edit().putFloat("stepsize_value", Float.valueOf(value.getText().toString())) .putString("stepsize_unit", unit.getCheckedRadioButtonId() == R.id.cm ? "cm" : "ft").apply(); preference.setSummary(getString(R.string.step_size_summary, Float.valueOf(value.getText().toString()), unit.getCheckedRadioButtonId() == R.id.cm ? "cm" : "ft")); dialog.dismiss(); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); break; case R.string.about: builder = new AlertDialog.Builder(getActivity()); builder.setTitle("About"); builder.setMessage("This app was created by Thomas Hoffmann (www.j4velin-development.de) and uses the 'HoloGraphLibrary' by Daniel Nadeau"); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); break; case R.string.account: builder = new AlertDialog.Builder(getActivity()); v = getActivity().getLayoutInflater().inflate(R.layout.signin, null); builder.setView(v); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (((MainActivity) getActivity()).getGC().isConnected()) { ((TextView) v.findViewById(R.id.signedin)).append(((MainActivity) getActivity()).getGC().getCurrentPlayer() .getDisplayName()); v.findViewById(R.id.sign_in_button).setVisibility(View.GONE); builder.setPositiveButton("Sign out", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ((MainActivity) getActivity()).getGC().signOut(); preference.setSummary(getString(R.string.sign_in)); dialog.dismiss(); } }); } final Dialog d = builder.create(); if (!((MainActivity) getActivity()).getGC().isConnected()) { v.findViewById(R.id.signedin).setVisibility(View.GONE); v.findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { // start the asynchronous sign in flow ((MainActivity) getActivity()).beginSignIn(); d.dismiss(); } }); } d.show(); break; } return false; } }
package me.dilek.cezmi.plugin; import com.omertron.thetvdbapi.TheTVDBApi; import com.omertron.thetvdbapi.model.Episode; import com.omertron.thetvdbapi.model.Series; import org.apache.commons.lang3.math.NumberUtils; import org.pojava.datetime.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamj.api.common.http.CommonHttpClient; import java.util.List; import javax.inject.Inject; import me.dilek.cezmi.domain.TvShow; import me.dilek.cezmi.util.StringTools; /** * @author Hakan Dilek on 15.04.2015. */ public class TheTvDBPlugin { private static final Logger LOG = LoggerFactory.getLogger(TheTvDBPlugin.class); private static final String DEFAULT_LANG = "en"; final TheTVDBApi tvDb; @Inject public TheTvDBPlugin(String apiKey, CommonHttpClient httpClient) { this.tvDb = new TheTVDBApi(apiKey, httpClient); } public TvShow load(String name, String year) { TvShow result = null; String id = findId(name, year); if (StringTools.isNotEmpty(id)) { Series series = tvDb.getSeries(id, DEFAULT_LANG); if (series != null) { result = new TvShow(); result.setTitle(series.getSeriesName()); result.setPoster(series.getPoster()); result.setFanArt(series.getBanner()); List<Episode> episodes = tvDb.getAllEpisodes(id, DEFAULT_LANG); for (Episode ep : episodes) { result.addEpisode(ep.getSeasonNumber(), ep.getEpisodeNumber(), ep.getEpisodeName(), ep.getFirstAired()); } } } return result; } private String findId(String title, String year) { String result = null; List<Series> seriesList = tvDb.searchSeries(title, DEFAULT_LANG); if(seriesList != null) { Series series = null; for (Series s : seriesList) { if (StringTools.isNotEmpty(s.getFirstAired())) { if (StringTools.isNotEmpty(year)) { DateTime firstAired = DateTime.parse(s.getFirstAired()); if (NumberUtils.toInt(firstAired.toString("yyyy")) == NumberUtils.toInt(year)) { series = s; break; } } else { series = s; break; } } } // If we can't find an exact match, select the first one if (series == null) { series = seriesList.get(0); LOG.debug("No exact match for {} found", title); } result = String.valueOf(series.getId()); } return result; } }
package net.sf.jabref.plugin; import java.io.File; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jabref.Globals; import net.sf.jabref.plugin.util.Util; import org.java.plugin.ObjectFactory; import org.java.plugin.PluginManager; import org.java.plugin.PluginManager.PluginLocation; import org.java.plugin.boot.DefaultPluginsCollector; import org.java.plugin.registry.PluginDescriptor; import org.java.plugin.standard.StandardPluginLocation; import org.java.plugin.util.ExtendedProperties; /** * Helper class for the plug-in system. Helps to retrieve the singleton instance * of the PluginManager, which then can be used to access all the plug-ins * registered. * * For an example how this is done see * {@link net.sf.jabref.export.layout.LayoutEntry#getLayoutFormatterFromPlugins(String)} * * The PluginCore relies on the generated class * {@link net.sf.jabref.plugin.core.JabRefPlugin} in the sub-package "core" for * finding the plugins and their extension. * * @author Christopher Oezbek */ public class PluginCore { static PluginManager singleton; static File userPluginDir = new File(System.getProperty("user.home")+"/.jabref/plugins"); static PluginLocation getLocationInsideJar(String context, String manifest) { URL jar = PluginCore.class .getResource(Util.joinPath(context, manifest)); if (jar == null) { return null; } String protocol = jar.getProtocol().toLowerCase(); try { if (protocol.startsWith("jar")) { return new StandardPluginLocation(new URL(jar.toExternalForm() .replaceFirst("!(.*?)$", Util.joinPath("!", context))), jar); } else if (protocol.startsWith("file")) { File f = new File(jar.toURI()); return new StandardPluginLocation(f.getParentFile(), manifest); } } catch (URISyntaxException e) { return null; } catch (MalformedURLException e) { return null; } return null; } static PluginManager initialize() { // We do not want info messages from JPF. Logger.getLogger("org.java.plugin").setLevel(Level.WARNING); Logger log = Logger.getLogger(PluginCore.class.getName()); ObjectFactory objectFactory = ObjectFactory.newInstance(); PluginManager result = objectFactory.createManager(); /* * Now find plug-ins! Check directories and jar. */ try { DefaultPluginsCollector collector = new DefaultPluginsCollector(); ExtendedProperties ep = new ExtendedProperties(); List<File> directoriesToSearch = new LinkedList<File>(); directoriesToSearch.add(new File("./src/resources/plugins")); directoriesToSearch.add(new File("./plugins")); directoriesToSearch.add(userPluginDir); try { File parent = new File(PluginCore.class.getProtectionDomain() .getCodeSource().getLocation().toURI()).getParentFile(); if (!parent.getCanonicalFile().equals( new File(".").getCanonicalFile())) { directoriesToSearch.add(new File(parent, "/src/resources/plugins")); directoriesToSearch.add(new File(parent, "/plugins")); } } catch (Exception e) { // no problem, we just use paths relative to current dir. } StringBuilder sb = new StringBuilder(); for (File directory : directoriesToSearch) { // We don't want warnings if the default plug-in paths don't // exist, we do that below if (directory.exists()) { if (sb.length() > 0) sb.append(','); sb.append(directory.getPath()); } } ep.setProperty("org.java.plugin.boot.pluginsRepositories", sb .toString()); collector.configure(ep); Collection<PluginLocation> plugins = collector .collectPluginLocations(); /** * I know the following is really, really ugly, but I have found no * way to automatically discover multiple plugin.xmls in JARs */ String[] jarLocationsToSearch = new String[] { "/plugins/net.sf.jabref.core/", "/plugins/net.sf.jabref.export.misq/"}; // Collection locations for (String jarLocation : jarLocationsToSearch) { PluginLocation location = getLocationInsideJar(jarLocation, "plugin.xml"); if (location != null) plugins.add(location); } if (plugins.size() <= 0) { log .warning( Globals.lang("No plugins were found in the following folders:") + "\n " + Util.join(directoriesToSearch .toArray(new String[directoriesToSearch.size()]), "\n ", 0, directoriesToSearch.size()) + "\n" + Globals.lang("and inside the JabRef-jar:") + "\n " + Util.join(jarLocationsToSearch, "\n ", 0, jarLocationsToSearch.length) + "\n" + Globals.lang("At least the plug-in 'net.sf.jabref.core' should be there.")); } else { result.publishPlugins(plugins.toArray(new PluginLocation[plugins.size()])); Collection<PluginDescriptor> descs = result.getRegistry() .getPluginDescriptors(); sb = new StringBuilder(); sb.append(Globals.lang("Found %0 plugin(s)", String .valueOf(descs.size()))).append(":\n"); for (PluginDescriptor p : result.getRegistry() .getPluginDescriptors()) { sb.append(" - ").append(p.getId()).append(" (").append( p.getLocation()).append(")\n"); } log.info(sb.toString()); } } catch (Exception e) { log .severe(Globals.lang("Error in starting plug-in system. Starting without, but some functionality may be missing.") + "\n" + e.getLocalizedMessage()); } return result; } public static PluginManager getManager() { if (singleton == null) { singleton = PluginCore.initialize(); } return singleton; } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import javax.swing.Timer; import org.jdesktop.swingx.painter.BusyPainter; import org.jdesktop.swingx.painter.PainterIcon; /** * <p>A simple circular animation, useful for denoting an action is taking * place that may take an unknown length of time to complete. Similar to an * indeterminant JProgressBar, but with a different look.</p> * * <p>For example: * <pre><code> * JXFrame frame = new JXFrame("test", true); * JXBusyLabel label = new JXBusyLabel(); * frame.add(label); * //... * label.setBusy(true); * </code></pre></p> * * @author rbair * @author joshy */ public class JXBusyLabel extends JLabel { private BusyPainter busyPainter; private Timer busy; private boolean running; /** Creates a new instance of JXBusyLabel */ public JXBusyLabel() { busyPainter = new BusyPainter(); busyPainter.setBaseColor(Color.LIGHT_GRAY); busyPainter.setHighlightColor(getForeground()); Dimension dim = new Dimension(26,26); PainterIcon icon = new PainterIcon(dim); icon.setPainter(busyPainter); this.setIcon(icon); } /** * <p>Gets whether this <code>JXBusyLabel</code> is busy. If busy, then * the <code>JXBusyLabel</code> instance will indicate that it is busy, * generally by animating some state.</p> * * @return true if this instance is busy */ public boolean isBusy() { return busy != null; } /** * <p>Sets whether this <code>JXBusyLabel</code> instance should consider * itself busy. A busy component may indicate that it is busy via animation, * or some other means.</p> * * @param busy whether this <code>JXBusyLabel</code> instance should * consider itself busy */ public void setBusy(boolean busy) { boolean old = isBusy(); if (!old && busy) { running = true; startAnimation(); firePropertyChange("busy", old, isBusy()); } else if (old && !busy) { running = false; stopAnimation(); firePropertyChange("busy", old, isBusy()); } } private void startAnimation() { if (!running || getParent() == null) { return; } if(busy != null) { stopAnimation(); } busy = new Timer(100, new ActionListener() { int frame = 8; public void actionPerformed(ActionEvent e) { frame = (frame+1)%8; busyPainter.setFrame(frame); repaint(); } }); busy.start(); } private void stopAnimation() { if (busy != null) { busy.stop(); busyPainter.setFrame(-1); repaint(); busy = null; } } @Override public void removeNotify() { // fix for #626 stopAnimation(); super.removeNotify(); } @Override public void addNotify() { super.addNotify(); // fix for #626 startAnimation(); } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Cursor; import java.awt.Dialog; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.LayoutManager; import java.awt.Robot; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.awt.event.WindowListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.View; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.auth.DefaultUserNameStore; import org.jdesktop.swingx.auth.LoginAdapter; import org.jdesktop.swingx.auth.LoginEvent; import org.jdesktop.swingx.auth.LoginListener; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.PasswordStore; import org.jdesktop.swingx.auth.UserNameStore; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.plaf.LoginPaneAddon; import org.jdesktop.swingx.plaf.LoginPaneUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPane is a specialized JPanel that implements a Login dialog with * support for saving passwords supplied for future use in a secure * manner. <strong>LoginService</strong> is invoked to perform authentication * and optional <strong>PasswordStore</strong> can be provided to store the user * login information.</p> * * <p> In order to perform the authentication, <strong>JXLoginPane</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPane</strong> calls the put method of the * <strong>PasswordStore</strong> object that is supplied. If * the <strong>PasswordStore</strong> is <code>null</code>, then the password * is not saved. Similarly, if a <strong>PasswordStore</strong> is * supplied and the password is null, then the <strong>PasswordStore</strong> * will be queried for the password using the <code>get</code> method. * * Example: * <code><pre> * final JXLoginPane panel = new JXLoginPane(new LoginService() { * public boolean authenticate(String name, char[] password, * String server) throws Exception { * // perform authentication and return true on success. * return false; * }}); * final JFrame frame = JXLoginPane.showLoginFrame(panel); * </pre></code> * * @author Bino George * @author Shai Almog * @author rbair * @author Karl Schaefer * @author rah003 */ public class JXLoginPane extends JXPanel { private static class LoginPaneLayout extends VerticalLayout implements LayoutManager { public Dimension preferredLayoutSize(Container parent) { Insets insets = parent.getInsets(); Dimension pref = new Dimension(0, 0); int gap = getGap(); for (int i = 0, c = parent.getComponentCount(); i < c; i++) { Component m = parent.getComponent(i); if (m.isVisible()) { Dimension componentPreferredSize = m.getPreferredSize(); // swingx-917 - don't let jlabel to force width due to long text if (m instanceof JLabel) { View view = (View) ((JLabel)m).getClientProperty(BasicHTML.propertyKey); if (view != null) { view.setSize(pref.width, m.getHeight()); // get fresh preferred size since we have forced new size on label componentPreferredSize = m.getPreferredSize(); } } else { pref.width = Math.max(pref.width, componentPreferredSize.width); } pref.height += componentPreferredSize.height + gap; } } pref.width += insets.left + insets.right; pref.height += insets.top + insets.bottom; return pref; } } /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPane.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPaneUI"; /** * Action key for an Action in the ActionMap that initiates the Login * procedure */ public static final String LOGIN_ACTION_COMMAND = "login"; /** * Action key for an Action in the ActionMap that cancels the Login * procedure */ public static final String CANCEL_LOGIN_ACTION_COMMAND = "cancel-login"; /** * The JXLoginPane can attempt to save certain user information such as * the username, password, or both to their respective stores. * This type specifies what type of save should be performed. */ public static enum SaveMode {NONE, USER_NAME, PASSWORD, BOTH} /** * Returns the status of the login process */ public enum Status {NOT_STARTED, IN_PROGRESS, FAILED, CANCELLED, SUCCEEDED} /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME = JXLoginPane.class.getSimpleName(); /** * The current login status for this panel */ private Status status = Status.NOT_STARTED; /** * An optional banner at the top of the panel */ private JXImagePanel banner; /** * Text that should appear on the banner */ private String bannerText; /** * Custom label allowing the developer to display some message to the user */ private JLabel messageLabel; /** * Shows an error message such as "user name or password incorrect" or * "could not contact server" or something like that if something * goes wrong */ private JXLabel errorMessageLabel; /** * A Panel containing all of the input fields, check boxes, etc necessary * for the user to do their job. The items on this panel change whenever * the SaveMode changes, so this panel must be recreated at runtime if the * SaveMode changes. Thus, I must maintain this reference so I can remove * this panel from the content panel at runtime. */ private JXPanel loginPanel; /** * The panel on which the input fields, messageLabel, and errorMessageLabel * are placed. While the login thread is running, this panel is removed * from the dialog and replaced by the progressPanel */ private JXPanel contentPanel; /** * This is the area in which the name field is placed. That way it can toggle on the fly * between text field and a combo box depending on the situation, and have a simple * way to get the user name */ private NameComponent namePanel; /** * The password field presented allowing the user to enter their password */ private JPasswordField passwordField; /** * A combo box presenting the user with a list of servers to which they * may log in. This is an optional feature, which is only enabled if * the List of servers supplied to the JXLoginPane has a length greater * than 1. */ private JComboBox serverCombo; /** * Check box presented if a PasswordStore is used, allowing the user to decide whether to * save their password */ private JCheckBox saveCB; /** * Label displayed whenever caps lock is on. */ private JLabel capsOn; /** * A special panel that displays a progress bar and cancel button, and * which notify the user of the login process, and allow them to cancel * that process. */ private JXPanel progressPanel; /** * A JLabel on the progressPanel that is used for informing the user * of the status of the login procedure (logging in..., canceling login...) */ private JLabel progressMessageLabel; /** * The LoginService to use. This must be specified for the login dialog to operate. * If no LoginService is defined, a default login service is used that simply * allows all users access. This is useful for demos or prototypes where a proper login * server is not available. */ private LoginService loginService; /** * Optional: a PasswordStore to use for storing and retrieving passwords for a specific * user. */ private PasswordStore passwordStore; /** * Optional: a UserNameStore to use for storing user names and retrieving them */ private UserNameStore userNameStore; /** * A list of servers where each server is represented by a String. If the * list of Servers is greater than 1, then a combo box will be presented to * the user to choose from. If any servers are specified, the selected one * (or the only one if servers.size() == 1) will be passed to the LoginService */ private List<String> servers; /** * Whether to save password or username or both. */ private SaveMode saveMode; /** * Tracks the cursor at the time that authentication was started, and restores to that * cursor after authentication ends, or is canceled; */ private Cursor oldCursor; private boolean namePanelEnabled = true; /** * The default login listener used by this panel. */ private LoginListener defaultLoginListener; private final CapsOnTest capsOnTest; private boolean caps; private boolean isTestingCaps; private final KeyEventDispatcher capsOnListener; /** * Caps lock detection support */ private boolean capsLockSupport = true; /** * Login/cancel control pane; */ private JXBtnPanel buttonPanel; /** * Window event listener responsible for triggering caps lock test on vindow activation and * focus changes. */ private final CapsOnWinListener capsOnWinListener; /** * Card pane holding user/pwd fields view and the progress view. */ private JPanel contentCardPane; private boolean isErrorMessageSet; /** * Creates a default JXLoginPane instance */ static { LookAndFeelAddons.contribute(new LoginPaneAddon()); } /** * Populates UIDefaults with the localizable Strings we will use * in the Login panel. */ private void reinitLocales(Locale l) { // PENDING: JW - use the locale given as parameter // as this probably (?) should be called before super.setLocale setBannerText(UIManagerExt.getString(CLASS_NAME + ".bannerString", getLocale())); banner.setImage(createLoginBanner()); if (!isErrorMessageSet) { errorMessageLabel.setText(UIManager.getString(CLASS_NAME + ".errorMessage", getLocale())); } progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); recreateLoginPanel(); Window w = SwingUtilities.getWindowAncestor(this); if (w instanceof JXLoginFrame) { JXLoginFrame f = (JXLoginFrame) w; f.setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); if (buttonPanel != null) { buttonPanel.getOk().setText(UIManagerExt.getString(CLASS_NAME + ".loginString", getLocale())); buttonPanel.getCancel().setText(UIManagerExt.getString(CLASS_NAME + ".cancelString", getLocale())); } } JLabel lbl = (JLabel) passwordField.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); } lbl = (JLabel) namePanel.getComponent().getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); } if (serverCombo != null) { lbl = (JLabel) serverCombo.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); } } saveCB.setText(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); // by default, caps is initialized in off state - i.e. without warning. Setting to // whitespace preserves formatting of the panel. capsOn.setText(isCapsLockOn() ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); getActionMap().get(LOGIN_ACTION_COMMAND).putValue(Action.NAME, UIManagerExt.getString(CLASS_NAME + ".loginString", getLocale())); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).putValue(Action.NAME, UIManagerExt.getString(CLASS_NAME + ".cancelString", getLocale())); } /** * Create a {@code JXLoginPane} that always accepts the user, never stores * passwords or user ids, and has no target servers. * <p> * This constructor should <i>NOT</i> be used in a real application. It is * provided for compliance to the bean specification and for use with visual * editors. */ public JXLoginPane() { this(null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService} * that does not store user ids or passwords and has no target servers. * * @param service * the {@code LoginService} to use for logging in */ public JXLoginPane(LoginService service) { this(service, null, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, and {@code UserNameStore}, but without a server * list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, {@code UserNameStore}, and server list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * <p> * Setting the server list to {@code null} will unset all of the servers. * The server list is guaranteed to be non-{@code null}. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information * @param servers * a list of servers to authenticate against */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore, List<String> servers) { //init capslock detection support if (Boolean.parseBoolean(System.getProperty("swingx.enableCapslockTesting"))) { capsOnTest = new CapsOnTest(); capsOnListener = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { return false; } if (e.getKeyCode() == 20) { setCapsLock(!isCapsLockOn()); } return false; }}; capsOnWinListener = new CapsOnWinListener(capsOnTest); } else { capsOnTest = null; capsOnListener = null; capsOnWinListener = null; capsLockSupport = false; } setLoginService(service); setPasswordStore(passwordStore); setUserNameStore(userStore); setServers(servers); //create the login and cancel actions, and add them to the action map getActionMap().put(LOGIN_ACTION_COMMAND, createLoginAction()); getActionMap().put(CANCEL_LOGIN_ACTION_COMMAND, createCancelAction()); //initialize the save mode if (passwordStore != null && userStore != null) { saveMode = SaveMode.BOTH; } else if (passwordStore != null) { saveMode = SaveMode.PASSWORD; } else if (userStore != null) { saveMode = SaveMode.USER_NAME; } else { saveMode = SaveMode.NONE; } // #732 set all internal components opacity to false in order to allow top level (frame's content pane) background painter to have any effect. setOpaque(false); initComponents(); } /** * Sets current state of the caps lock key as detected by the component. * @param b True when caps lock is turned on, false otherwise. */ private void setCapsLock(boolean b) { caps = b; capsOn.setText(caps ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); } /** * Gets current state of the caps lock as seen by the login panel. The state seen by the login * panel and therefore returned by this method can be delayed in comparison to the real caps * lock state and displayed by the keyboard light. This is usually the case when component or * its text fields are not focused. * * @return True when caps lock is on, false otherwise. Returns always false when * <code>isCapsLockDetectionSupported()</code> returns false. */ public boolean isCapsLockOn() { return caps; } /** * Check current state of the caps lock state detection. Note that the value can change after * component have been made visible. Due to current problems in locking key state detection by * core java detection of the changes in caps lock can be always reliably determined. When * component can't guarantee reliable detection it will switch it off. This is usually the case * for unsigned applets and webstart invoked application. Since your users are going to pass * their password in the component you should always sign it when distributing application over * the network. * @return True if changes in caps lock state can be monitored by the component, false otherwise. */ public boolean isCapsLockDetectionSupported() { return capsLockSupport; } /** * {@inheritDoc} */ public LoginPaneUI getUI() { return (LoginPaneUI) super.getUI(); } /** * Sets the look and feel (L&F) object that renders this component. * * @param ui the LoginPaneUI L&F object * @see javax.swing.UIDefaults#getUI */ public void setUI(LoginPaneUI ui) { // initialized here due to implicit updateUI call from JPanel if (banner == null) { banner = new JXImagePanel(); } if (errorMessageLabel == null) { errorMessageLabel = new JXLabel(UIManagerExt.getString(CLASS_NAME + ".errorMessage", getLocale())); } super.setUI(ui); banner.setImage(createLoginBanner()); } /** * Notification from the <code>UIManager</code> that the L&F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see javax.swing.JComponent#updateUI */ public void updateUI() { setUI((LoginPaneUI) LookAndFeelAddons.getUI(this, LoginPaneUI.class)); } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Recreates the login panel, and replaces the current one with the new one */ protected void recreateLoginPanel() { JXPanel old = loginPanel; loginPanel = createLoginPanel(); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.remove(old); contentPanel.add(loginPanel, 1); } /** * Creates and returns a new LoginPanel, based on the SaveMode state of * the login panel. Whenever the SaveMode changes, the panel is recreated. * I do this rather than hiding/showing components, due to a cleaner * implementation (no invisible components, components are not sharing * locations in the LayoutManager, etc). */ private JXPanel createLoginPanel() { JXPanel loginPanel = new JXPanel(); JPasswordField oldPwd = passwordField; //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); passwordLabel.setLabelFor(passwordField); if (oldPwd != null) { passwordField.setText(new String(oldPwd.getPassword())); } NameComponent oldPanel = namePanel; //create the NameComponent if (saveMode == SaveMode.NONE) { namePanel = new SimpleNamePanel(passwordStore, passwordField); } else { namePanel = new ComboNamePanel(userNameStore, passwordStore, passwordField); } if (oldPanel != null) { // need to reset here otherwise value will get lost during LAF change as panel gets recreated. namePanel.setUserName(oldPanel.getUserName()); namePanel.setEnabled(oldPanel.isEnabled()); namePanel.setEditable(oldPanel.isEditable()); } else { namePanel.setEnabled(namePanelEnabled); namePanel.setEditable(namePanelEnabled); } JLabel nameLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); nameLabel.setLabelFor(namePanel.getComponent()); //create the server combo box if necessary JLabel serverLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); if (servers.size() > 1) { serverCombo = new JComboBox(servers.toArray()); serverLabel.setLabelFor(serverCombo); } else { serverCombo = null; } //create the save check box. By default, it is not selected saveCB = new JCheckBox(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); saveCB.setIconTextGap(10); //TODO should get this from preferences!!! And, it should be based on the user saveCB.setSelected(false); //determine whether to show/hide the save check box based on the SaveMode saveCB.setVisible(saveMode == SaveMode.PASSWORD || saveMode == SaveMode.BOTH); saveCB.setOpaque(false); capsOn = new JLabel(" "); // don't show by default. We perform test when login panel gets focus. int lShift = 3;// lShift is used to align all other components with the checkbox GridLayout grid = new GridLayout(2,1); grid.setVgap(5); JPanel fields = new JPanel(grid); fields.setOpaque(false); fields.add(namePanel.getComponent()); fields.add(passwordField); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(4, lShift, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 1; gridBagConstraints.gridheight = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(fields, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(5, lShift, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, lShift, 5, 11); loginPanel.add(serverLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(serverCombo, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } else { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } loginPanel.setOpaque(false); return loginPanel; } /** * This method adds functionality to support bidi languages within this * component */ public void setComponentOrientation(ComponentOrientation orient) { // this if is used to avoid needless creations of the image if(orient != super.getComponentOrientation()) { super.setComponentOrientation(orient); banner.setImage(createLoginBanner()); progressPanel.applyComponentOrientation(orient); } } /** * Create all of the UI components for the login panel */ private void initComponents() { //create the default banner banner.setImage(createLoginBanner()); //create the default label messageLabel = new JLabel(" "); messageLabel.setOpaque(false); messageLabel.setFont(messageLabel.getFont().deriveFont(Font.BOLD)); //create the main components loginPanel = createLoginPanel(); //create the message and hyperlink and hide them errorMessageLabel.setIcon(UIManager.getIcon(CLASS_NAME + ".errorIcon", getLocale())); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setLineWrap(true); errorMessageLabel.setPaintBorderInsets(false); errorMessageLabel.setBackgroundPainter(new MattePainter(UIManager.getColor(CLASS_NAME + ".errorBackground", getLocale()), true)); errorMessageLabel.setMaxLineSpan(320); errorMessageLabel.setVisible(false); //aggregate the optional message label, content, and error label into //the contentPanel contentPanel = new JXPanel(new LoginPaneLayout()); contentPanel.setOpaque(false); messageLabel.setBorder(BorderFactory.createEmptyBorder(12, 12, 7, 11)); contentPanel.add(messageLabel); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel); errorMessageLabel.setBorder(UIManager.getBorder(CLASS_NAME + ".errorBorder", getLocale())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressPanel.setOpaque(false); progressMessageLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); progressMessageLabel.setFont(UIManager.getFont(CLASS_NAME +".pleaseWaitFont", getLocale())); JProgressBar pb = new JProgressBar(); pb.setIndeterminate(true); JButton cancelButton = new JButton(getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND)); progressPanel.add(progressMessageLabel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 11, 11), 0, 0)); progressPanel.add(pb, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 11, 7), 0, 0)); progressPanel.add(cancelButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 11, 11), 0, 0)); //layout the panel setLayout(new BorderLayout()); add(banner, BorderLayout.NORTH); contentCardPane = new JPanel(new CardLayout()); contentCardPane.setOpaque(false); contentCardPane.add(contentPanel, "0"); contentCardPane.add(progressPanel, "1"); add(contentCardPane, BorderLayout.CENTER); } /** * Create and return an image to use for the Banner. This may be overridden * to return any image you like */ protected Image createLoginBanner() { return getUI() == null ? null : getUI().getBanner(); } /** * Create and return an Action for logging in */ protected Action createLoginAction() { return new LoginAction(this); } /** * Create and return an Action for canceling login */ protected Action createCancelAction() { return new CancelAction(this); } //REMEMBER: when adding new methods, they need to fire property change events!!! /** * @return Returns the saveMode. */ public SaveMode getSaveMode() { return saveMode; } /** * The save mode indicates whether the "save" password is checked by default. This method * makes no difference if the passwordStore is null. * * @param saveMode The saveMode to set either SAVE_NONE, SAVE_PASSWORD or SAVE_USERNAME */ public void setSaveMode(SaveMode saveMode) { if (this.saveMode != saveMode) { SaveMode oldMode = getSaveMode(); this.saveMode = saveMode; recreateLoginPanel(); firePropertyChange("saveMode", oldMode, getSaveMode()); } } public boolean isRememberPassword() { return saveCB.isSelected(); } /** * @return the List of servers */ public List<String> getServers() { return Collections.unmodifiableList(servers); } /** * Sets the list of servers. See the servers field javadoc for more info. */ public void setServers(List<String> servers) { //only at startup if (this.servers == null) { this.servers = servers == null ? new ArrayList<String>() : servers; } else if (this.servers != servers) { List<String> old = getServers(); this.servers = servers == null ? new ArrayList<String>() : servers; recreateLoginPanel(); firePropertyChange("servers", old, getServers()); } } private LoginListener getDefaultLoginListener() { if (defaultLoginListener == null) { defaultLoginListener = new LoginListenerImpl(); } return defaultLoginListener; } /** * Sets the {@code LoginService} for this panel. Setting the login service * to {@code null} will actually set the service to use * {@code NullLoginService}. * * @param service * the service to set. If {@code service == null}, then a * {@code NullLoginService} is used. */ public void setLoginService(LoginService service) { LoginService oldService = getLoginService(); LoginService newService = service == null ? new NullLoginService() : service; //newService is guaranteed to be nonnull if (!newService.equals(oldService)) { if (oldService != null) { oldService.removeLoginListener(getDefaultLoginListener()); } loginService = newService; this.loginService.addLoginListener(getDefaultLoginListener()); firePropertyChange("loginService", oldService, getLoginService()); } } /** * Gets the <strong>LoginService</strong> for this panel. * * @return service service */ public LoginService getLoginService() { return loginService; } /** * Sets the <strong>PasswordStore</strong> for this panel. * * @param store PasswordStore */ public void setPasswordStore(PasswordStore store) { PasswordStore oldStore = getPasswordStore(); PasswordStore newStore = store == null ? new NullPasswordStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { passwordStore = newStore; firePropertyChange("passwordStore", oldStore, getPasswordStore()); } } /** * Gets the {@code UserNameStore} for this panel. * * @return the {@code UserNameStore} */ public UserNameStore getUserNameStore() { return userNameStore; } /** * Sets the user name store for this panel. * @param store */ public void setUserNameStore(UserNameStore store) { UserNameStore oldStore = getUserNameStore(); UserNameStore newStore = store == null ? new DefaultUserNameStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { userNameStore = newStore; firePropertyChange("userNameStore", oldStore, getUserNameStore()); } } /** * Gets the <strong>PasswordStore</strong> for this panel. * * @return store PasswordStore */ public PasswordStore getPasswordStore() { return passwordStore; } /** * Sets the <strong>User name</strong> for this panel. * * @param username User name */ public void setUserName(String username) { if (namePanel != null) { String old = getUserName(); namePanel.setUserName(username); firePropertyChange("userName", old, getUserName()); } } /** * Enables or disables <strong>User name</strong> for this panel. * * @param enabled */ public void setUserNameEnabled(boolean enabled) { boolean old = isUserNameEnabled(); this.namePanelEnabled = enabled; if (namePanel != null) { namePanel.setEnabled(enabled); namePanel.setEditable(enabled); } firePropertyChange("userNameEnabled", old, isUserNameEnabled()); } /** * Gets current state of the user name field. Field can be either disabled (false) for editing or enabled (true). * @return True when user name field is enabled and editable, false otherwise. */ public boolean isUserNameEnabled() { return this.namePanelEnabled; } /** * Gets the <strong>User name</strong> for this panel. * @return the user name */ public String getUserName() { return namePanel == null ? null : namePanel.getUserName(); } /** * Sets the <strong>Password</strong> for this panel. * * @param password Password */ public void setPassword(char[] password) { passwordField.setText(new String(password)); } /** * Gets the <strong>Password</strong> for this panel. * * @return password Password */ public char[] getPassword() { return passwordField.getPassword(); } /** * Return the image used as the banner */ public Image getBanner() { return banner.getImage(); } /** * Set the image to use for the banner. If the {@code img} is {@code null}, * then no image will be displayed. * * @param img * the image to display */ public void setBanner(Image img) { // we do not expose the ImagePanel, so we will produce property change // events here Image oldImage = getBanner(); if (oldImage != img) { banner.setImage(img); firePropertyChange("banner", oldImage, getBanner()); } } /** * Set the text to use when creating the banner. If a custom banner image is * specified, then this is ignored. If {@code text} is {@code null}, then * no text is displayed. * * @param text * the text to display */ public void setBannerText(String text) { if (text == null) { text = ""; } if (!text.equals(this.bannerText)) { String oldText = this.bannerText; this.bannerText = text; //fix the login banner this.banner.setImage(createLoginBanner()); firePropertyChange("bannerText", oldText, text); } } /** * Returns text used when creating the banner */ public String getBannerText() { return bannerText; } /** * Returns the custom message for this login panel */ public String getMessage() { return messageLabel.getText(); } /** * Sets a custom message for this login panel */ public void setMessage(String message) { String old = messageLabel.getText(); messageLabel.setText(message); firePropertyChange("message", old, messageLabel.getText()); } /** * Returns the error message for this login panel */ public String getErrorMessage() { return errorMessageLabel.getText(); } /** * Sets the error message for this login panel */ public void setErrorMessage(String errorMessage) { isErrorMessageSet = true; String old = errorMessageLabel.getText(); errorMessageLabel.setText(errorMessage); firePropertyChange("errorMessage", old, errorMessageLabel.getText()); } /** * Returns the panel's status */ public Status getStatus() { return status; } /** * Change the status */ protected void setStatus(Status newStatus) { if (status != newStatus) { Status oldStatus = status; status = newStatus; firePropertyChange("status", oldStatus, newStatus); } } public void setLocale(Locale l) { super.setLocale(l); reinitLocales(l); } /** * Initiates the login procedure. This method is called internally by * the LoginAction. This method handles cursor management, and actually * calling the LoginService's startAuthentication method. Method will return * immediately if asynchronous login is enabled or will block until * authentication finishes if <code>getSynchronous()</code> returns true. */ protected void startLogin() { oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); String name = getUserName(); char[] password = getPassword(); String server = servers.size() == 1 ? servers.get(0) : serverCombo == null ? null : (String)serverCombo.getSelectedItem(); loginService.startAuthentication(name, password, server); } catch(Exception ex) { //The status is set via the loginService listener, so no need to set //the status here. Just log the error. LOG.log(Level.WARNING, "Authentication exception while logging in", ex); } finally { setCursor(oldCursor); } } /** * Cancels the login procedure. Handles cursor management and interfacing * with the LoginService's cancelAuthentication method. Calling this method * has an effect only when authentication is still in progress (i.e. after * previous call to <code>startAuthentications()</code> and only when * authentication is performed asynchronously (<code>getSynchronous()</code> * returns false). */ protected void cancelLogin() { progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".cancelWait", getLocale())); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * Puts the password into the password store. If password store is not set, method will do * nothing. */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } public void removeNotify() { try { // TODO: keep it here until all ui stuff is moved to uidelegate. if (capsLockSupport) KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(capsOnListener); Container c = getTLA(); if (c instanceof Window) { Window w = (Window) c; w.removeWindowFocusListener(capsOnWinListener ); w.removeWindowListener(capsOnWinListener ); } } catch (Exception e) { // bail out; probably running unsigned app distributed over web } super.removeNotify(); } private Window getTLA() { Container c = JXLoginPane.this; // #810 bail out on first window found up the hierarchy (modal dialogs) while (!(c.getParent() == null || c instanceof Window)) { c = c.getParent(); } return (Window) c; } public void addNotify() { try { KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( capsOnListener); Container c = getTLA(); if (c instanceof Window) { Window w = (Window) c; w.addWindowFocusListener(capsOnWinListener ); w.addWindowListener(capsOnWinListener); } } catch (Exception e) { // probably unsigned app over web, disable capslock support and bail out capsLockSupport = false; } super.addNotify(); } /* For Login (initiated in LoginAction): 0) set the status 1) Immediately disable the login action 2) Immediately disable the close action (part of enclosing window) 3) initialize the progress pane a) enable the cancel login action b) set the message text 4) hide the content pane, show the progress pane When cancelling (initiated in CancelAction): 0) set the status 1) Disable the cancel login action 2) Change the message text on the progress pane When cancel finishes (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action When login fails (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action 4) Show the error message 5) resize the window (part of enclosing window) When login succeeds (handled in LoginListener): 0) set the status 1) close the dialog/frame (part of enclosing window) */ /** * Listener class to track state in the LoginService */ protected class LoginListenerImpl extends LoginAdapter { public void loginSucceeded(LoginEvent source) { //save the user names and passwords String userName = namePanel.getUserName(); savePassword(); if ((getSaveMode() == SaveMode.USER_NAME || getSaveMode() == SaveMode.BOTH) && userName != null && !userName.trim().equals("")) { userNameStore.addUserName(userName); userNameStore.saveUserNames(); } setStatus(Status.SUCCEEDED); } public void loginStarted(LoginEvent source) { assert EventQueue.isDispatchThread(); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(false); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(true); // remove(contentPanel); // add(progressPanel, BorderLayout.CENTER); ((CardLayout) contentCardPane.getLayout()).last(contentCardPane); revalidate(); repaint(); setStatus(Status.IN_PROGRESS); } public void loginFailed(LoginEvent source) { assert EventQueue.isDispatchThread(); // remove(progressPanel); // add(contentPanel, BorderLayout.CENTER); ((CardLayout) contentCardPane.getLayout()).first(contentCardPane); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(true); revalidate(); repaint(); setStatus(Status.FAILED); } public void loginCanceled(LoginEvent source) { assert EventQueue.isDispatchThread(); // remove(progressPanel); // add(contentPanel, BorderLayout.CENTER); ((CardLayout) contentCardPane.getLayout()).first(contentCardPane); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(false); revalidate(); repaint(); setStatus(Status.CANCELLED); } } /** * Action that initiates a login procedure. Delegates to JXLoginPane.startLogin */ private static final class LoginAction extends AbstractActionExt { private static final long serialVersionUID = 7256761187925982485L; private JXLoginPane panel; public LoginAction(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".loginString", p.getLocale()), LOGIN_ACTION_COMMAND); this.panel = p; } public void actionPerformed(ActionEvent e) { panel.startLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Action that cancels the login procedure. */ private static final class CancelAction extends AbstractActionExt { private static final long serialVersionUID = 4040029973355439229L; private JXLoginPane panel; public CancelAction(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".cancelLogin", p.getLocale()), CANCEL_LOGIN_ACTION_COMMAND); this.panel = p; this.setEnabled(false); } public void actionPerformed(ActionEvent e) { panel.cancelLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Simple login service that allows everybody to login. This is useful in demos and allows * us to avoid having to check for LoginService being null */ private static final class NullLoginService extends LoginService { public boolean authenticate(String name, char[] password, String server) throws Exception { return true; } public boolean equals(Object obj) { return obj instanceof NullLoginService; } public int hashCode() { return 7; } } /** * Simple PasswordStore that does not remember passwords */ private static final class NullPasswordStore extends PasswordStore { private static final char[] EMPTY = new char[0]; public boolean set(String username, String server, char[] password) { //null op return false; } public char[] get(String username, String server) { return EMPTY; } public boolean equals(Object obj) { return obj instanceof NullPasswordStore; } public int hashCode() { return 7; } } public static interface NameComponent { public String getUserName(); public boolean isEnabled(); public boolean isEditable(); public void setEditable(boolean enabled); public void setEnabled(boolean enabled); public void setUserName(String userName); public JComponent getComponent(); } /** * If a UserNameStore is not used, then this text field is presented allowing the user * to simply enter their user name */ public static final class SimpleNamePanel extends JTextField implements NameComponent { private static final long serialVersionUID = 6513437813612641002L; public SimpleNamePanel() { this(null, null); } public SimpleNamePanel(final PasswordStore passwordStore, final JPasswordField passwordField) { super("", 15); // listen to text input, and offer password suggestion based on current // text if (passwordStore != null && passwordField!=null) { addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { updatePassword(getText(), passwordStore, passwordField); } }); } } public String getUserName() { return getText(); } public void setUserName(String userName) { setText(userName); } public JComponent getComponent() { return this; } private void updatePassword(final String username, final PasswordStore passwordStore, final JPasswordField passwordField) { String password = ""; if (username != null) { char[] pw = passwordStore.get(username, null); password = pw == null ? "" : new String(pw); } passwordField.setText(password); } } /** * If a UserNameStore is used, then this combo box is presented allowing the user * to select a previous login name, or type in a new login name */ public static final class ComboNamePanel extends JComboBox implements NameComponent { private static final long serialVersionUID = 2511649075486103959L; private UserNameStore userNameStore; public ComboNamePanel(final UserNameStore userNameStore) { this(userNameStore, null,null); } public ComboNamePanel(final UserNameStore userNameStore, final PasswordStore passwordStore, final JPasswordField passwordField) { super(); this.userNameStore = userNameStore; setModel(new NameComboBoxModel()); setEditable(true); // listen to selection or text input, and offer password suggestion based on current // text if (passwordStore != null && passwordField!=null) { final JTextField textfield = (JTextField) getEditor().getEditorComponent(); textfield.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { updatePassword(textfield.getText(), passwordStore, passwordField); } }); super.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { updatePassword((String)getSelectedItem(), passwordStore, passwordField); } }); } } private void updatePassword(final String username, final PasswordStore passwordStore, final JPasswordField passwordField) { String password = ""; if (username != null) { char[] pw = passwordStore.get(username, null); password = pw == null ? "" : new String(pw); } passwordField.setText(password); } public String getUserName() { Object item = getModel().getSelectedItem(); return item == null ? null : item.toString(); } public void setUserName(String userName) { getModel().setSelectedItem(userName); } public void setUserNames(String[] names) { setModel(new DefaultComboBoxModel(names)); } public JComponent getComponent() { return this; } private final class NameComboBoxModel extends AbstractListModel implements ComboBoxModel { private static final long serialVersionUID = 7097674687536018633L; private Object selectedItem; public void setSelectedItem(Object anItem) { selectedItem = anItem; fireContentsChanged(this, -1, -1); } public Object getSelectedItem() { return selectedItem; } public Object getElementAt(int index) { return userNameStore.getUserNames()[index]; } public int getSize() { return userNameStore.getUserNames().length; } } } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc) { return showLoginDialog(parent, svc, null, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginDialog(parent, svc, ps, us, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginDialog(parent, panel); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, JXLoginPane panel) { Window w = WindowUtils.findWindow(parent); JXLoginDialog dlg = null; if (w == null) { dlg = new JXLoginDialog((Frame)null, panel); } else if (w instanceof Dialog) { dlg = new JXLoginDialog((Dialog)w, panel); } else if (w instanceof Frame) { dlg = new JXLoginDialog((Frame)w, panel); } else { throw new AssertionError("Shouldn't be able to happen"); } dlg.setVisible(true); return dlg.getStatus(); } /** * Shows a login frame. A JFrame is not modal, and thus does not block */ public static JXLoginFrame showLoginFrame(LoginService svc) { return showLoginFrame(svc, null, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginFrame(svc, ps, us, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPane panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private static final long serialVersionUID = -3185639594267828103L; private JXLoginPane panel; public JXLoginDialog(Frame parent, JXLoginPane p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPane p) { super(parent, true); init(p); } protected void init(JXLoginPane p) { setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); this.panel = p; initWindow(this, panel); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JXFrame { private static final long serialVersionUID = -9016407314342050807L; private JXLoginPane panel; public JXLoginFrame(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".titleString", p.getLocale())); JXPanel cp = new JXPanel(); cp.setOpaque(true); setContentPane(cp); this.panel = p; initWindow(this, panel); } public JXPanel getContentPane() { return (JXPanel) super.getContentPane(); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } public JXLoginPane getPanel() { return panel; } } /** * Utility method for initializing a Window for displaying a LoginDialog. * This is particularly useful because the differences between JFrame and * JDialog are so minor. * * Note: This method is package private for use by JXLoginDialog (proper, * not JXLoginPane.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPane panel) { w.setLayout(new BorderLayout()); w.add(panel, BorderLayout.CENTER); JButton okButton = new JButton(panel.getActionMap().get(LOGIN_ACTION_COMMAND)); final JButton cancelButton = new JButton( UIManagerExt.getString(CLASS_NAME + ".cancelString", panel.getLocale())); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to canceled! panel.status = JXLoginPane.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPane.Status status = (JXLoginPane.Status)evt.getNewValue(); switch (status) { case NOT_STARTED: break; case IN_PROGRESS: cancelButton.setEnabled(false); break; case CANCELLED: cancelButton.setEnabled(true); w.pack(); break; case FAILED: cancelButton.setEnabled(true); w.pack(); break; case SUCCEEDED: w.setVisible(false); w.dispose(); } for (PropertyChangeListener l : w.getPropertyChangeListeners("status")) { PropertyChangeEvent pce = new PropertyChangeEvent(w, "status", evt.getOldValue(), evt.getNewValue()); l.propertyChange(pce); } } }); // FIX for #663 - commented out two lines below. Not sure why they were here in a first place. // cancelButton.setText(UIManager.getString(CLASS_NAME + ".cancelString")); // okButton.setText(UIManager.getString(CLASS_NAME + ".loginString")); JXBtnPanel buttonPanel = new JXBtnPanel(okButton, cancelButton); buttonPanel.setOpaque(false); panel.setButtonPanel(buttonPanel); JXPanel controls = new JXPanel(new FlowLayout(FlowLayout.RIGHT)); controls.setOpaque(false); new BoxLayout(controls, BoxLayout.X_AXIS); controls.add(Box.createHorizontalGlue()); controls.add(buttonPanel); w.add(controls, BorderLayout.SOUTH); w.addWindowListener(new WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { panel.cancelLogin(); } }); if (w instanceof JFrame) { final JFrame f = (JFrame)w; f.getRootPane().setDefaultButton(okButton); f.setResizable(false); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { f.setVisible(false); f.dispose(); } }; f.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } else if (w instanceof JDialog) { final JDialog d = (JDialog)w; d.getRootPane().setDefaultButton(okButton); d.setResizable(false); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }; d.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } w.pack(); w.setLocation(WindowUtils.getPointForCentering(w)); } private void setButtonPanel(JXBtnPanel buttonPanel) { this.buttonPanel = buttonPanel; } private static class JXBtnPanel extends JXPanel { private static final long serialVersionUID = 4136611099721189372L; private JButton cancel; private JButton ok; public JXBtnPanel(JButton okButton, JButton cancelButton) { GridLayout layout = new GridLayout(1,2); layout.setHgap(5); setLayout(layout); this.ok = okButton; this.cancel = cancelButton; add(okButton); add(cancelButton); setBorder(new EmptyBorder(0,0,7,11)); } /** * @return the cancel button. */ public JButton getCancel() { return cancel; } /** * @return the ok button. */ public JButton getOk() { return ok; } } private class CapsOnTest { RemovableKeyEventDispatcher ked; public void runTest() { boolean success = false; // TODO: check the progress from time to time //try { // java.awt.Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); //} catch (Exception ex) { //ex.printStackTrace(); //success = false; if (!success) { try { KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager(); // #swingx-697 // In some cases panel is not focused after the creation leaving bogus dispatcher in place. If found remove it. if (ked != null) { kfm.removeKeyEventDispatcher(ked); } // Temporarily installed listener with auto-uninstall after // test is finished. ked = new RemovableKeyEventDispatcher(this); kfm.addKeyEventDispatcher(ked); Robot r = new Robot(); isTestingCaps = true; r.keyPress(65); r.keyRelease(65); r.keyPress(KeyEvent.VK_BACK_SPACE); r.keyRelease(KeyEvent.VK_BACK_SPACE); } catch (Exception e1) { // this can happen for example due to security reasons in unsigned applets // when we can't test caps lock state programatically bail out silently // no matter what's the cause - uninstall ked.uninstall(); } } } public void clean() { if (ked != null) { ked.cleanOnBogusFocus(); } } } /** * Window event listener to invoke capslock test when login panel get * activated. */ public static class CapsOnWinListener extends WindowAdapter implements WindowFocusListener, WindowListener { private CapsOnTest cot; private long stamp; public CapsOnWinListener(CapsOnTest cot) { this.cot = cot; } public void windowActivated(WindowEvent e) { cot.runTest(); stamp = System.currentTimeMillis(); } public void windowGainedFocus(WindowEvent e) { // repeat test only if more then 20ms passed between activation test // and now. if (stamp + 20 < System.currentTimeMillis()) { cot.runTest(); } } @Override public void windowOpened(WindowEvent arg0) { cot.clean(); } } public class RemovableKeyEventDispatcher implements KeyEventDispatcher { private CapsOnTest cot; private boolean tested = false; private int retry = 0; public RemovableKeyEventDispatcher(CapsOnTest capsOnTest) { this.cot = capsOnTest; } public boolean dispatchKeyEvent(KeyEvent e) { tested = true; if (e.getID() != KeyEvent.KEY_PRESSED) { return true; } if (isTestingCaps && e.getKeyCode() > 64 && e.getKeyCode() < 91) { setCapsLock(!e.isShiftDown() && Character.isUpperCase(e.getKeyChar())); } if (isTestingCaps && (e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) { // uninstall uninstall(); retry = 0; } return true; } void uninstall() { isTestingCaps = false; KeyboardFocusManager.getCurrentKeyboardFocusManager() .removeKeyEventDispatcher(this); if (cot.ked == this) { cot.ked = null; } } void cleanOnBogusFocus() { // #799 happens on windows when focus is lost during initialization of program since focusLost() even is not issued by jvm in this case (WinXP-WinVista only) SwingUtilities.invokeLater(new Runnable() { public void run() { if (!tested) { uninstall(); if (retry < 3) { // try 3 times to regain the focus Window w = JXLoginPane.this.getTLA(); if (w != null) { w.toFront(); } cot.runTest(); retry++; } } } }); } } }
package com.atlassian.jira.plugins.bitbucket.bitbucket; import com.atlassian.jira.plugins.bitbucket.Synchronizer; import com.atlassian.jira.plugins.bitbucket.api.Changeset; import com.atlassian.jira.plugins.bitbucket.api.SourceControlRepository; import com.atlassian.jira.plugins.bitbucket.api.impl.DefaultSourceControlRepository; import com.atlassian.jira.plugins.bitbucket.spi.Communicator; import com.atlassian.jira.plugins.bitbucket.spi.RepositoryManager; import com.atlassian.jira.plugins.bitbucket.spi.RepositoryUri; import com.atlassian.jira.plugins.bitbucket.spi.bitbucket.impl.BitbucketRepositoryManager; import com.atlassian.jira.plugins.bitbucket.spi.github.MinimalInfoChangeset; import com.atlassian.jira.plugins.bitbucket.webwork.BitbucketPostCommit; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.io.IOException; import java.util.Arrays; import java.util.List; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Unit test for {@link BitbucketPostCommit} */ @SuppressWarnings("deprecation") public class TestBitbucketPostCommit { @Mock Synchronizer synchronizer; @Mock RepositoryManager repositoryManager; @Mock RepositoryUri repositoryUri; @Mock Communicator communicator; @Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); } private String resource(String name) throws IOException { return IOUtils.toString(getClass().getClassLoader().getResourceAsStream(name)); } @Test public void testPostCommit() throws Exception { String projectKey = "PRJ"; String repositoryUrl = "https://bitbucket.org/mjensen/test"; String payload = resource("TestBitbucketPostCommit-payload.json"); SourceControlRepository repo = new DefaultSourceControlRepository(0, "bitbucket", repositoryUri, projectKey, null, null, null, null, null); when(repositoryManager.getRepositories(projectKey)).thenReturn(Arrays.asList(repo)); when(repositoryUri.getRepositoryUrl()).thenReturn(repositoryUrl); BitbucketPostCommit bitbucketPostCommit = new BitbucketPostCommit(repositoryManager, synchronizer); bitbucketPostCommit.setProjectKey(projectKey); bitbucketPostCommit.setPayload(payload); bitbucketPostCommit.execute(); verify(repositoryManager).parsePayload(repo, payload); } @Test public void testParsePayload() throws Exception { final String projectKey = "PRJ"; final String payload = resource("TestBitbucketPostCommit-payload.json"); final String node = "f2851c9f1db8"; final DefaultSourceControlRepository repo = new DefaultSourceControlRepository(0, "bitbucket", repositoryUri, projectKey, null, null, null, null, null); BitbucketRepositoryManager brm = new BitbucketRepositoryManager(null, communicator, null, null, null, null); when(communicator.getChangeset(eq(repo), anyString())).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return new MinimalInfoChangeset(0, (String) invocation.getArguments()[1], null); } }); List<Changeset> changesets = brm.parsePayload(repo, payload); ArgumentMatcher<List<Changeset>> matcher = new ArgumentMatcher<List<Changeset>>() { @Override public boolean matches(Object o) { //noinspection unchecked @SuppressWarnings("unchecked") List<Changeset> list = (List<Changeset>) o; Changeset changeset = list.get(0); return list.size() == 1 && changeset.getNode().equals(node); } }; Assert.assertTrue(matcher.matches(changesets)); verify(communicator).getChangeset(repo, node); } }
package com.continuuity.data.operation.executor.omid; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Before; import org.junit.Test; import com.continuuity.common.conf.CConfiguration; import com.continuuity.data.SyncReadTimeoutException; import com.continuuity.data.operation.CompareAndSwap; import com.continuuity.data.operation.Increment; import com.continuuity.data.operation.Read; import com.continuuity.data.operation.Write; import com.continuuity.data.operation.ttqueue.DequeueResult; import com.continuuity.data.operation.ttqueue.QueueAck; import com.continuuity.data.operation.ttqueue.QueueConfig; import com.continuuity.data.operation.ttqueue.QueueConsumer; import com.continuuity.data.operation.ttqueue.QueueDequeue; import com.continuuity.data.operation.ttqueue.QueueEnqueue; import com.continuuity.data.operation.ttqueue.QueuePartitioner; import com.continuuity.data.operation.ttqueue.TTQueueTable; import com.continuuity.data.operation.type.WriteOperation; import com.continuuity.data.runtime.DataFabricInMemoryModule; import com.continuuity.data.table.OVCTableHandle; import com.google.inject.Guice; import com.google.inject.Injector; public class TestOmidExecutorLikeAFlow { @SuppressWarnings("unused") private TimestampOracle timeOracle; @SuppressWarnings("unused") private TransactionOracle oracle; @SuppressWarnings("unused") private Configuration conf = new CConfiguration(); private OmidTransactionalOperationExecutor executor; private OVCTableHandle handle; private static List<WriteOperation> batch(WriteOperation ... ops) { return Arrays.asList(ops); } @Before public void initialize() { Injector injector = Guice.createInjector(new DataFabricInMemoryModule()); timeOracle = injector.getInstance(TimestampOracle.class); executor = injector.getInstance(OmidTransactionalOperationExecutor.class); oracle = executor.getOracle(); handle = executor.getTableHandle(); } @Test public void testStandaloneSimpleDequeue() throws Exception { byte [] queueName = Bytes.toBytes("standaloneDequeue"); QueueConsumer consumer = new QueueConsumer(0, 0, 1); QueueConfig config = new QueueConfig( new QueuePartitioner.RandomPartitioner(), true); // Queue should be empty QueueDequeue dequeue = new QueueDequeue(queueName, consumer, config); DequeueResult result = this.executor.execute(dequeue); assertTrue(result.isEmpty()); // Write to the queue assertTrue(this.executor.execute(Arrays.asList(new WriteOperation [] { new QueueEnqueue(queueName, Bytes.toBytes(1L)) })).isSuccess()); // Dequeue entry just written dequeue = new QueueDequeue(queueName, consumer, config); result = this.executor.execute(dequeue); assertTrue(result.isSuccess()); assertTrue(Bytes.equals(result.getValue(), Bytes.toBytes(1L))); // Dequeue again should give same entry back dequeue = new QueueDequeue(queueName, consumer, config); result = this.executor.execute(dequeue); assertTrue(result.isSuccess()); assertTrue(Bytes.equals(result.getValue(), Bytes.toBytes(1L))); // Ack it assertTrue(this.executor.execute(Arrays.asList(new WriteOperation [] { new QueueAck(queueName, result.getEntryPointer(), consumer) })).isSuccess()); // Queue should be empty again dequeue = new QueueDequeue(queueName, consumer, config); result = this.executor.execute(dequeue); assertTrue(result.isEmpty()); } @Test public void testUserReadOwnWritesAndWritesStableSorted() throws Exception { byte [] key = Bytes.toBytes("testUWSSkey"); // Write value = 1 this.executor.execute(batch(new Write(key, Bytes.toBytes(1L)))); // Verify value = 1 assertTrue(Bytes.equals(Bytes.toBytes(1L), this.executor.execute(new Read(key)))); // Create batch with increment and compareAndSwap // first try (CAS(1->3),Increment(3->4)) // (will fail if operations are reordered) assertTrue(this.executor.execute(batch( new CompareAndSwap(key, Bytes.toBytes(1L), Bytes.toBytes(3L)), new Increment(key, 1L))).isSuccess()); // verify value = 4 // (value = 2 if no ReadOwnWrites) byte [] value = this.executor.execute(new Read(key)); assertEquals(4L, Bytes.toLong(value)); // Create another batch with increment and compareAndSwap, change order // second try (Increment(4->5),CAS(5->1)) // (will fail if operations are reordered or if no ReadOwnWrites) assertTrue(this.executor.execute(batch(new Increment(key, 1L), new CompareAndSwap(key, Bytes.toBytes(5L), Bytes.toBytes(1L)))). isSuccess()); // verify value = 1 value = this.executor.execute(new Read(key)); assertEquals(1L, Bytes.toLong(value)); } @Test public void testWriteBatchJustAck() throws Exception { byte [] queueName = Bytes.toBytes("testWriteBatchJustAck"); QueueConsumer consumer = new QueueConsumer(0, 0, 1); QueueConfig config = new QueueConfig( new QueuePartitioner.RandomPartitioner(), true); // Queue should be empty QueueDequeue dequeue = new QueueDequeue(queueName, consumer, config); DequeueResult result = this.executor.execute(dequeue); assertTrue(result.isEmpty()); // Write to the queue assertTrue(this.executor.execute(batch(new QueueEnqueue(queueName, Bytes.toBytes(1L)))).isSuccess()); // Dequeue entry just written dequeue = new QueueDequeue(queueName, consumer, config); result = this.executor.execute(dequeue); assertTrue(result.isSuccess()); assertTrue(Bytes.equals(result.getValue(), Bytes.toBytes(1L))); // Ack it assertTrue(this.executor.execute(batch(new QueueAck(queueName, result.getEntryPointer(), consumer))).isSuccess()); // Can't ack it again assertFalse(this.executor.execute(batch(new QueueAck(queueName, result.getEntryPointer(), consumer))).isSuccess()); // Queue should be empty again dequeue = new QueueDequeue(queueName, consumer, config); result = this.executor.execute(dequeue); assertTrue(result.isEmpty()); } @Test public void testWriteBatchWithMultiWritesMultiEnqueuesPlusSuccessfulAck() throws Exception { // Verify operations are re-ordered // Verify user write operations are stable sorted QueueConsumer consumer = new QueueConsumer(0, 0, 1); QueueConfig config = new QueueConfig( new QueuePartitioner.RandomPartitioner(), true); // One source queue byte [] srcQueueName = Bytes.toBytes("testAckRollback_srcQueue1"); // Source queue entry byte [] srcQueueValue = Bytes.toBytes("srcQueueValue"); // Two dest queues byte [] destQueueOne = Bytes.toBytes("testAckRollback_destQueue1"); byte [] destQueueTwo = Bytes.toBytes("testAckRollback_destQueue2"); // Dest queue values byte [] destQueueOneVal = Bytes.toBytes("destValue1"); byte [] destQueueTwoVal = Bytes.toBytes("destValue2"); // Data key byte [] dataKey = Bytes.toBytes("datakey"); long expectedVal = 0L; // Add an entry to source queue assertTrue(this.executor.execute(batch( new QueueEnqueue(srcQueueName, srcQueueValue))).isSuccess()); // Dequeue one entry from source queue DequeueResult srcDequeueResult = this.executor.execute( new QueueDequeue(srcQueueName, consumer, config)); assertTrue(srcDequeueResult.isSuccess()); assertTrue(Bytes.equals(srcQueueValue, srcDequeueResult.getValue())); // Create batch of writes List<WriteOperation> writes = new ArrayList<WriteOperation>(); // Add increment operation writes.add(new Increment(dataKey, 1)); expectedVal = 1L; // Add an ack of entry one in source queue writes.add(new QueueAck(srcQueueName, srcDequeueResult.getEntryPointer(), consumer)); // Add a push to dest queue one writes.add(new QueueEnqueue(destQueueOne, destQueueOneVal)); // Add a compare-and-swap writes.add(new CompareAndSwap(dataKey, Bytes.toBytes(1L), Bytes.toBytes(10L))); expectedVal = 10L; // Add a push to dest queue two writes.add(new QueueEnqueue(destQueueTwo, destQueueTwoVal)); // Add another user increment operation writes.add(new Increment(dataKey, 3)); expectedVal = 13L; // Commit batch successfully assertTrue(this.executor.execute(writes).isSuccess()); // Verify value from operations was done in order assertEquals(expectedVal, Bytes.toLong(this.executor.execute(new Read(dataKey)))); // Dequeue from both dest queues, verify, ack DequeueResult destDequeueResult = this.executor.execute( new QueueDequeue(destQueueOne, consumer, config)); assertTrue(destDequeueResult.isSuccess()); assertTrue(Bytes.equals(destQueueOneVal, destDequeueResult.getValue())); assertTrue(this.executor.execute(batch( new QueueAck(destQueueOne, destDequeueResult.getEntryPointer(), consumer))).isSuccess()); destDequeueResult = this.executor.execute( new QueueDequeue(destQueueTwo, consumer, config)); assertTrue(destDequeueResult.isSuccess()); assertTrue(Bytes.equals(destQueueTwoVal, destDequeueResult.getValue())); assertTrue(this.executor.execute(batch( new QueueAck(destQueueTwo, destDequeueResult.getEntryPointer(), consumer))).isSuccess()); // Dest queues should be empty destDequeueResult = this.executor.execute( new QueueDequeue(destQueueOne, consumer, config)); assertTrue(destDequeueResult.isEmpty()); destDequeueResult = this.executor.execute( new QueueDequeue(destQueueTwo, consumer, config)); assertTrue(destDequeueResult.isEmpty()); } @Test public void testWriteBatchWithMultiWritesMultiEnqueuesPlusUnsuccessfulAckRollback() throws Exception { QueueConsumer consumer = new QueueConsumer(0, 0, 1); QueueConfig config = new QueueConfig( new QueuePartitioner.RandomPartitioner(), true); // One source queue byte [] srcQueueName = Bytes.toBytes("testAckRollback_srcQueue1"); // Source queue entry byte [] srcQueueValue = Bytes.toBytes("srcQueueValue"); // Two dest queues byte [] destQueueOne = Bytes.toBytes("testAckRollback_destQueue1"); byte [] destQueueTwo = Bytes.toBytes("testAckRollback_destQueue2"); // Dest queue values byte [] destQueueOneVal = Bytes.toBytes("destValue1"); byte [] destQueueTwoVal = Bytes.toBytes("destValue2"); // Three keys we will increment byte [][] dataKeys = new byte [][] { Bytes.toBytes(1), Bytes.toBytes(2), Bytes.toBytes(3) }; long [] expectedVals = new long [] { 0L, 0L, 0L }; // Add an entry to source queue assertTrue(this.executor.execute(batch( new QueueEnqueue(srcQueueName, srcQueueValue))).isSuccess()); // Dequeue one entry from source queue DequeueResult srcDequeueResult = this.executor.execute( new QueueDequeue(srcQueueName, consumer, config)); assertTrue(srcDequeueResult.isSuccess()); assertTrue(Bytes.equals(srcQueueValue, srcDequeueResult.getValue())); // Create batch of writes List<WriteOperation> writes = new ArrayList<WriteOperation>(); // Add two user increment operations writes.add(new Increment(dataKeys[0], 1)); writes.add(new Increment(dataKeys[1], 2)); // Update expected vals (this batch will be successful) expectedVals[0] = 1L; expectedVals[1] = 2L; // Add an ack of entry one in source queue writes.add(new QueueAck(srcQueueName, srcDequeueResult.getEntryPointer(), consumer)); // Add two pushes to two dest queues writes.add(new QueueEnqueue(destQueueOne, destQueueOneVal)); writes.add(new QueueEnqueue(destQueueTwo, destQueueTwoVal)); // Add another user increment operation writes.add(new Increment(dataKeys[2], 3)); expectedVals[2] = 3L; // Commit batch successfully assertTrue(this.executor.execute(writes).isSuccess()); // Verify three values from increment operations for (int i=0; i<3; i++) { assertEquals(expectedVals[i], Bytes.toLong(this.executor.execute(new Read(dataKeys[i])))); } // Dequeue from both dest queues, verify, ack DequeueResult destDequeueResult = this.executor.execute( new QueueDequeue(destQueueOne, consumer, config)); assertTrue(destDequeueResult.isSuccess()); assertTrue(Bytes.equals(destQueueOneVal, destDequeueResult.getValue())); assertTrue(this.executor.execute(batch( new QueueAck(destQueueOne, destDequeueResult.getEntryPointer(), consumer))).isSuccess()); destDequeueResult = this.executor.execute( new QueueDequeue(destQueueTwo, consumer, config)); assertTrue(destDequeueResult.isSuccess()); assertTrue(Bytes.equals(destQueueTwoVal, destDequeueResult.getValue())); assertTrue(this.executor.execute(batch( new QueueAck(destQueueTwo, destDequeueResult.getEntryPointer(), consumer))).isSuccess()); // Dest queues should be empty destDequeueResult = this.executor.execute( new QueueDequeue(destQueueOne, consumer, config)); assertTrue(destDequeueResult.isEmpty()); destDequeueResult = this.executor.execute( new QueueDequeue(destQueueTwo, consumer, config)); assertTrue(destDequeueResult.isEmpty()); // Create another batch of writes writes = new ArrayList<WriteOperation>(); // Add one user increment operation writes.add(new Increment(dataKeys[0], 1)); // Don't change expected, this will fail // Add an ack of entry one in source queue (we already ackd, should fail) writes.add(new QueueAck(srcQueueName, srcDequeueResult.getEntryPointer(), consumer)); // Add two pushes to two dest queues writes.add(new QueueEnqueue(destQueueOne, destQueueOneVal)); writes.add(new QueueEnqueue(destQueueTwo, destQueueTwoVal)); // Add another user increment operation writes.add(new Increment(dataKeys[2], 3)); // Commit batch, should fail assertFalse(this.executor.execute(writes).isSuccess()); // All values from increments should be the same as before for (int i=0; i<3; i++) { assertEquals(expectedVals[i], Bytes.toLong(this.executor.execute(new Read(dataKeys[i])))); } // Dest queues should still be empty destDequeueResult = this.executor.execute( new QueueDequeue(destQueueOne, consumer, config)); assertTrue(destDequeueResult.isEmpty()); destDequeueResult = this.executor.execute( new QueueDequeue(destQueueTwo, consumer, config)); assertTrue(destDequeueResult.isEmpty()); } final byte [] threadedQueueName = Bytes.toBytes("threadedQueue"); @Test public void testThreadedProducersAndThreadedConsumers() throws Exception { long MAX_TIMEOUT = 30000; OmidTransactionalOperationExecutor.MAX_DEQUEUE_RETRIES = 100; OmidTransactionalOperationExecutor.DEQUEUE_RETRY_SLEEP = 1; ConcurrentSkipListMap<byte[], byte[]> enqueuedMap = new ConcurrentSkipListMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); ConcurrentSkipListMap<byte[], byte[]> dequeuedMapOne = new ConcurrentSkipListMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); ConcurrentSkipListMap<byte[], byte[]> dequeuedMapTwo = new ConcurrentSkipListMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); AtomicBoolean producersDone = new AtomicBoolean(false); long startTime = System.currentTimeMillis(); // Create P producer threads, each inserts N queue entries int p = 5; int n = 2000; Producer [] producers = new Producer[p]; for (int i=0;i<p;i++) { producers[i] = new Producer(i, n, enqueuedMap); } // Create (P*2) consumer threads, two groups of (P) // Use synchronous execution first Consumer [] consumerGroupOne = new Consumer[p]; Consumer [] consumerGroupTwo = new Consumer[p]; for (int i=0;i<p;i++) { consumerGroupOne[i] = new Consumer(new QueueConsumer(i, 0, p), new QueueConfig(new QueuePartitioner.RandomPartitioner(), true), dequeuedMapOne, producersDone); } for (int i=0;i<p;i++) { consumerGroupTwo[i] = new Consumer(new QueueConsumer(i, 1, p), new QueueConfig(new QueuePartitioner.RandomPartitioner(), true), dequeuedMapTwo, producersDone); } // Let the producing begin! System.out.println("Starting producers"); for (int i=0; i<p; i++) producers[i].start(); long expectedDequeues = p * n; long startConsumers = System.currentTimeMillis(); // Start consumers! System.out.println("Starting consumers"); for (int i=0; i<p; i++) consumerGroupOne[i].start(); for (int i=0; i<p; i++) consumerGroupTwo[i].start(); // Wait for producers to finish System.out.println("Waiting for producers to finish"); long start = System.currentTimeMillis(); for (int i=0; i<p; i++) producers[i].join(MAX_TIMEOUT); long stop = System.currentTimeMillis(); System.out.println("Producers done"); if (stop - start >= MAX_TIMEOUT) fail("Timed out waiting for producers"); producersDone.set(true); // Verify producers produced correct number assertEquals(p * n , enqueuedMap.size()); System.out.println("Producers correctly enqueued " + enqueuedMap.size() + " entries"); long producerTime = System.currentTimeMillis(); System.out.println("" + p + " producers generated " + (n*p) + " total " + "queue entries in " + (producerTime - startTime) + " millis (" + ((producerTime-startTime)/((float)(n*p))) + " ms/enqueue)"); // Wait for consumers to finish System.out.println("Waiting for consumers to finish"); start = System.currentTimeMillis(); for (int i=0; i<p; i++) consumerGroupOne[i].join(MAX_TIMEOUT); for (int i=0; i<p; i++) consumerGroupTwo[i].join(MAX_TIMEOUT); stop = System.currentTimeMillis(); System.out.println("Consumers done!"); if (stop - start >= MAX_TIMEOUT) fail("Timed out waiting for consumers"); long stopTime = System.currentTimeMillis(); System.out.println("" + (p*2) + " consumers dequeued " + (expectedDequeues*2) + " total queue entries in " + (stopTime - startConsumers) + " millis (" + ((stopTime-startConsumers)/((float)(expectedDequeues*2))) + " ms/dequeue)"); // Each group should total <expectedDequeues> long groupOneTotal = 0; long groupTwoTotal = 0; for (int i=0; i<p; i++) { groupOneTotal += consumerGroupOne[i].dequeued; groupTwoTotal += consumerGroupTwo[i].dequeued; } if (expectedDequeues != groupOneTotal) { System.out.println("Group One: totalDequeues=" + groupOneTotal + ", DequeuedMap.size=" + dequeuedMapOne.size()); for (byte [] dequeuedValue : dequeuedMapOne.values()) { enqueuedMap.remove(dequeuedValue); } System.out.println("After removing dequeued entries, there are " + enqueuedMap.size() + " remaining entries produced"); for (byte [] enqueuedValue : enqueuedMap.values()) { System.out.println("EnqueuedNotDequeued: instanceid=" + Bytes.toInt(enqueuedValue) + ", entrynum=" + Bytes.toInt(enqueuedValue, 4)); } printQueueInfo(threadedQueueName, 0); } assertEquals(expectedDequeues, groupOneTotal); if (expectedDequeues != groupTwoTotal) { System.out.println("Group Two: totalDequeues=" + groupTwoTotal + ", DequeuedMap.size=" + dequeuedMapTwo.size()); for (byte [] dequeuedValue : dequeuedMapTwo.values()) { enqueuedMap.remove(dequeuedValue); } System.out.println("After removing dequeued entries, there are " + enqueuedMap.size() + " remaining entries produced"); for (byte [] enqueuedValue : enqueuedMap.values()) { System.out.println("EnqueuedNotDequeued: instanceid=" + Bytes.toInt(enqueuedValue) + ", entrynum=" + Bytes.toInt(enqueuedValue, 4)); } printQueueInfo(threadedQueueName, 1); } assertEquals(expectedDequeues, groupTwoTotal); } private void printQueueInfo(byte[] queueName, int groupId) { TTQueueTable table = this.handle.getQueueTable(Bytes.toBytes("queues")); System.out.println(table.getInfo(queueName, groupId)); } class Producer extends Thread { int instanceid; int numentries; ConcurrentSkipListMap<byte[], byte[]> enqueuedMap; Producer(int instanceid, int numentries, ConcurrentSkipListMap<byte[], byte[]> enqueuedMap) { this.instanceid = instanceid; this.numentries = numentries; this.enqueuedMap = enqueuedMap; System.out.println("Producer " + instanceid + " will enqueue " + numentries + " entries"); } @Override public void run() { System.out.println("Producer " + this.instanceid + " running"); for (int i=0; i<this.numentries; i++) { try { byte [] entry = Bytes.add(Bytes.toBytes(this.instanceid), Bytes.toBytes(i)); assertTrue(TestOmidExecutorLikeAFlow.this.executor.execute( Arrays.asList(new WriteOperation [] { new QueueEnqueue(TestOmidExecutorLikeAFlow.this.threadedQueueName, entry)})).isSuccess()); this.enqueuedMap.put(entry, entry); } catch (OmidTransactionException e) { e.printStackTrace(); throw new RuntimeException(e); } } System.out.println("Producer " + this.instanceid + " done"); } } class Consumer extends Thread { QueueConsumer consumer; QueueConfig config; long dequeued = 0; ConcurrentSkipListMap<byte[], byte[]> dequeuedMap; AtomicBoolean producersDone; Consumer(QueueConsumer consumer, QueueConfig config, ConcurrentSkipListMap<byte[], byte[]> dequeuedMap, AtomicBoolean producersDone) { this.consumer = consumer; this.config = config; this.dequeuedMap = dequeuedMap; this.producersDone = producersDone; } @Override public void run() { boolean gotEmptyAndDone = false; while (true) { boolean localProducersDone = producersDone.get(); QueueDequeue dequeue = new QueueDequeue(TestOmidExecutorLikeAFlow.this.threadedQueueName, this.consumer, this.config); try { DequeueResult result = TestOmidExecutorLikeAFlow.this.executor.execute(dequeue); if (result.isSuccess() && this.config.isSingleEntry()) { assertTrue(TestOmidExecutorLikeAFlow.this.executor.execute( Arrays.asList(new WriteOperation [] { new QueueAck(TestOmidExecutorLikeAFlow.this.threadedQueueName, result.getEntryPointer(), this.consumer)})).isSuccess()); } if (result.isSuccess()) { this.dequeued++; this.dequeuedMap.put(result.getValue(), result.getValue()); if (gotEmptyAndDone) { System.out.println("Got empty+done then got another dequeue after sleep!"); gotEmptyAndDone = false; } } else if (result.isFailure()) { fail("Dequeue failed " + result); } else if (result.isEmpty() && localProducersDone) { if (gotEmptyAndDone) { System.out.println("Empty and done looped, result empty again"); return; } else { System.out.println(this.consumer.toString() + " finished after " + this.dequeued + " dequeues, sleeping and retrying dequeue"); Thread.sleep(10); gotEmptyAndDone = true; } } else if (result.isEmpty() && !localProducersDone) { System.out.println(this.consumer.toString() + " empty but waiting"); Thread.sleep(1); } else { fail("What is this?"); } } catch (SyncReadTimeoutException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (OmidTransactionException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } } } } }
package dr.app.beauti.traitspanel; import dr.app.beauti.BeautiFrame; import dr.app.beauti.BeautiPanel; import dr.app.beauti.ComboBoxRenderer; import dr.app.beauti.datapanel.DataPanel; import dr.app.beauti.options.BeautiOptions; import dr.app.beauti.options.TraitData; import dr.app.beauti.options.TraitGuesser; import dr.app.beauti.util.PanelUtils; import dr.app.gui.table.TableEditorStopper; import dr.app.gui.table.TableSorter; import dr.evolution.util.Taxa; import dr.evolution.util.Taxon; import jam.framework.Exportable; import jam.panels.ActionPanel; import jam.table.TableRenderer; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.BorderUIResource; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; /** * @author Andrew Rambaut * @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $ */ public class TraitsPanel extends BeautiPanel implements Exportable { private static final long serialVersionUID = 5283922195494563924L; private static final int MINIMUM_TABLE_WIDTH = 140; private static final String ADD_TRAITS_TOOLTIP = "<html>Define a new trait for the current taxa</html>"; private static final String IMPORT_TRAITS_TOOLTIP = "<html>Import one or more traits for these taxa from a tab-delimited<br>" + "file. Taxa should be in the first column and the trait names<br>" + "in the first row</html>"; private static final String GUESS_TRAIT_VALUES_TOOLTIP = "<html>This attempts to extract values for this trait that are<br>" + "encoded in the names of the selected taxa.</html>"; private static final String SET_TRAIT_VALUES_TOOLTIP = "<html>This sets values for this trait for all<br>" + "the selected taxa.</html>"; private static final String CLEAR_TRAIT_VALUES_TOOLTIP = "<html>This clears all the values currently assigned to taxa for<br>" + "this trait.</html>"; private static final String CREATE_TRAIT_PARTITIONS_TOOLTIP = "<html>Create a data partition for the selected traits.</html>"; public final JTable traitsTable; private final TraitsTableModel traitsTableModel; private final JTable dataTable; private final DataTableModel dataTableModel; private final BeautiFrame frame; private final DataPanel dataPanel; private BeautiOptions options = null; private TraitData currentTrait = null; // current trait private CreateTraitDialog createTraitDialog = null; private GuessTraitDialog guessTraitDialog = null; private TraitValueDialog traitValueDialog = null; AddTraitAction addTraitAction = new AddTraitAction(); Action importTraitsAction; CreateTraitPartitionAction createTraitPartitionAction = new CreateTraitPartitionAction(); GuessTraitsAction guessTraitsAction = new GuessTraitsAction(); SetValueAction setValueAction = new SetValueAction(); public TraitsPanel(BeautiFrame parent, DataPanel dataPanel, Action importTraitsAction) { this.frame = parent; this.dataPanel = dataPanel; traitsTableModel = new TraitsTableModel(); // TableSorter sorter = new TableSorter(traitsTableModel); // traitsTable = new JTable(sorter); // sorter.setTableHeader(traitsTable.getTableHeader()); traitsTable = new JTable(traitsTableModel); traitsTable.getTableHeader().setReorderingAllowed(false); traitsTable.getTableHeader().setResizingAllowed(false); // traitsTable.getTableHeader().setDefaultRenderer( // new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); TableColumn col = traitsTable.getColumnModel().getColumn(1); ComboBoxRenderer comboBoxRenderer = new ComboBoxRenderer(TraitData.TraitType.values()); comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); col.setCellRenderer(comboBoxRenderer); TableEditorStopper.ensureEditingStopWhenTableLosesFocus(traitsTable); traitsTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); traitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { traitSelectionChanged(); // dataTableModel.fireTableDataChanged(); } }); JScrollPane scrollPane1 = new JScrollPane(traitsTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane1.setOpaque(false); dataTableModel = new DataTableModel(); TableSorter sorter = new TableSorter(dataTableModel); dataTable = new JTable(sorter); sorter.setTableHeader(dataTable.getTableHeader()); dataTable.getTableHeader().setReorderingAllowed(false); // dataTable.getTableHeader().setDefaultRenderer( // new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(0).setCellRenderer( new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(0).setPreferredWidth(80); col = dataTable.getColumnModel().getColumn(1); comboBoxRenderer = new ComboBoxRenderer(); comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); col.setCellRenderer(comboBoxRenderer); TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable); // dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { // public void valueChanged(ListSelectionEvent evt) { // traitSelectionChanged(); JScrollPane scrollPane2 = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane2.setOpaque(false); JToolBar toolBar1 = new JToolBar(); toolBar1.setFloatable(false); toolBar1.setOpaque(false); toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); JButton button; button = new JButton(addTraitAction); PanelUtils.setupComponent(button); button.setToolTipText(ADD_TRAITS_TOOLTIP); toolBar1.add(button); this.importTraitsAction = importTraitsAction; button = new JButton(importTraitsAction); PanelUtils.setupComponent(button); button.setToolTipText(IMPORT_TRAITS_TOOLTIP); toolBar1.add(button); toolBar1.add(new JToolBar.Separator(new Dimension(12, 12))); button = new JButton(guessTraitsAction); PanelUtils.setupComponent(button); button.setToolTipText(GUESS_TRAIT_VALUES_TOOLTIP); toolBar1.add(button); button = new JButton(setValueAction); PanelUtils.setupComponent(button); button.setToolTipText(SET_TRAIT_VALUES_TOOLTIP); toolBar1.add(button); // Don't see the need for a clear values button // button = new JButton(new ClearTraitAction()); // PanelUtils.setupComponent(button); // button.setToolTipText(CLEAR_TRAIT_VALUES_TOOLTIP); // toolBar1.add(button); button = new JButton(createTraitPartitionAction); PanelUtils.setupComponent(button); button.setToolTipText(CREATE_TRAIT_PARTITIONS_TOOLTIP); toolBar1.add(button); ActionPanel actionPanel1 = new ActionPanel(false); actionPanel1.setAddAction(addTraitAction); actionPanel1.setRemoveAction(removeTraitAction); // actionPanel1.getAddActionButton().setTooltipText(ADD_TRAITS_TOOLTIP); removeTraitAction.setEnabled(false); JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT)); controlPanel1.setOpaque(false); controlPanel1.add(actionPanel1); JPanel panel1 = new JPanel(new BorderLayout(0, 0)); panel1.setOpaque(false); panel1.add(scrollPane1, BorderLayout.CENTER); panel1.add(controlPanel1, BorderLayout.SOUTH); panel1.setMinimumSize(new Dimension(MINIMUM_TABLE_WIDTH, 0)); JPanel panel2 = new JPanel(new BorderLayout(0, 0)); panel2.setOpaque(false); panel2.add(toolBar1, BorderLayout.NORTH); panel2.add(scrollPane2, BorderLayout.CENTER); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2); splitPane.setDividerLocation(MINIMUM_TABLE_WIDTH); splitPane.setContinuousLayout(true); splitPane.setBorder(BorderFactory.createEmptyBorder()); splitPane.setOpaque(false); setOpaque(false); setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12))); setLayout(new BorderLayout(0, 0)); add(splitPane, BorderLayout.CENTER); add(toolBar1, BorderLayout.NORTH); } public void setOptions(BeautiOptions options) { this.options = options; updateButtons(); // int selRow = traitsTable.getSelectedRow(); // traitsTableModel.fireTableDataChanged(); // if (selRow < 0) { // selRow = 0; // traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow); // if (selectedTrait == null) { // traitsTable.getSelectionModel().setSelectionInterval(0, 0); traitsTableModel.fireTableDataChanged(); dataTableModel.fireTableDataChanged(); validate(); repaint(); } public void getOptions(BeautiOptions options) { // int selRow = traitsTable.getSelectedRow(); // if (selRow >= 0 && options.traitsOptions.selecetedTraits.size() > 0) { // selectedTrait = options.traitsOptions.selecetedTraits.get(selRow); // options.datesUnits = unitsCombo.getSelectedIndex(); // options.datesDirection = directionCombo.getSelectedIndex(); } public JComponent getExportableComponent() { return dataTable; } public void fireTraitsChanged() { if (currentTrait != null) { // if (currentTrait.getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())) { // frame.setupStarBEAST(); // } else if (currentTrait != null && currentTrait.getTraitType() == TraitData.TraitType.DISCRETE) { frame.updateDiscreteTraitAnalysis(); } // if (selRow > 0) { // traitsTable.getSelectionModel().setSelectionInterval(selRow-1, selRow-1); // } else if (selRow == 0 && options.traitsOptions.traits.size() > 0) { // options.traitsOptions.traits.size() after remove // traitsTable.getSelectionModel().setSelectionInterval(0, 0); traitsTableModel.fireTableDataChanged(); options.updatePartitionAllLinks(); frame.setDirty(); } } private void traitSelectionChanged() { int selRow = traitsTable.getSelectedRow(); if (selRow >= 0) { currentTrait = options.traits.get(selRow); // traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow); removeTraitAction.setEnabled(true); // } else { // currentTrait = null; // removeTraitAction.setEnabled(false); } if (options.traits.size() <= 0) { currentTrait = null; removeTraitAction.setEnabled(false); } dataTableModel.fireTableDataChanged(); // traitsTableModel.fireTableDataChanged(); } private void updateButtons() { //TODO: better to merge updateButtons() fireTraitsChanged() traitSelectionChanged() into one boolean hasData = options.hasData(); addTraitAction.setEnabled(hasData); importTraitsAction.setEnabled(hasData); createTraitPartitionAction.setEnabled(hasData && options.traits.size() > 0); guessTraitsAction.setEnabled(hasData && options.traits.size() > 0); setValueAction.setEnabled(hasData && options.traits.size() > 0); } public void clearTraitValues(String traitName) { options.clearTraitValues(traitName); dataTableModel.fireTableDataChanged(); } public void guessTrait() { if (options.taxonList == null) { // validation of check empty taxonList return; } if (currentTrait == null) { if (!addTrait()) { return; // if addTrait() cancel then false } } int result; do { TraitGuesser currentTraitGuesser = new TraitGuesser(currentTrait); if (guessTraitDialog == null) { guessTraitDialog = new GuessTraitDialog(frame); } guessTraitDialog.setDescription("Extract values for trait '" + currentTrait + "' from taxa labels"); result = guessTraitDialog.showDialog(); if (result == -1 || result == JOptionPane.CANCEL_OPTION) { return; } guessTraitDialog.setupGuesserFromDialog(currentTraitGuesser); try { int[] selRows = dataTable.getSelectedRows(); if (selRows.length > 0) { Taxa selectedTaxa = new Taxa(); for (int row : selRows) { Taxon taxon = (Taxon) dataTable.getValueAt(row, 0); selectedTaxa.addTaxon(taxon); } currentTraitGuesser.guessTrait(selectedTaxa); } else { currentTraitGuesser.guessTrait(options.taxonList); } } catch (IllegalArgumentException iae) { JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE); result = -1; } dataTableModel.fireTableDataChanged(); } while (result < 0); } public void setTraitValue() { if (options.taxonList == null) { // validation of check empty taxonList return; } int result; do { if (traitValueDialog == null) { traitValueDialog = new TraitValueDialog(frame); } int[] selRows = dataTable.getSelectedRows(); if (selRows.length > 0) { traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for selected taxa"); } else { traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for all taxa"); } result = traitValueDialog.showDialog(); if (result == -1 || result == JOptionPane.CANCEL_OPTION) { return; } // currentTrait.guessTrait = true; // ?? no use? String value = traitValueDialog.getTraitValue(); try { if (selRows.length > 0) { for (int row : selRows) { Taxon taxon = (Taxon) dataTable.getValueAt(row, 0); taxon.setAttribute(currentTrait.getName(), value); } } else { for (Taxon taxon : options.taxonList) { taxon.setAttribute(currentTrait.getName(), value); } } } catch (IllegalArgumentException iae) { JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE); result = -1; } dataTableModel.fireTableDataChanged(); } while (result < 0); } public boolean addTrait() { return addTrait("Untitled"); // The 'species' trait doesn't need to be a reserved keyword since the StarBEAST button was added // if (options.traitExists(TraitData.TRAIT_SPECIES)) { // JOptionPane.showMessageDialog(frame, "Keyword \"species\" has been reserved for *BEAST !" + // options.removeTrait(TraitData.TRAIT_SPECIES); //// options.useStarBEAST = false; // traitsTableModel.fireTableDataChanged(); // dataTableModel.fireTableDataChanged(); // return false; // return isAdd; } public boolean addTrait(String traitName) { return addTrait(null, traitName, false); } public boolean addTrait(String message, String traitName, boolean isSpeciesTrait) { if (createTraitDialog == null) { createTraitDialog = new CreateTraitDialog(frame); } createTraitDialog.setSpeciesTrait(isSpeciesTrait); createTraitDialog.setTraitName(traitName); createTraitDialog.setMessage(message); int result = createTraitDialog.showDialog(); if (result == JOptionPane.OK_OPTION) { frame.tabbedPane.setSelectedComponent(this); String name = createTraitDialog.getName(); TraitData.TraitType type = createTraitDialog.getType(); TraitData newTrait = new TraitData(options, name, "", type); currentTrait = newTrait; // The createTraitDialog will have already checked if the // user is overwriting an existing trait addTrait(newTrait); if (createTraitDialog.createTraitPartition()) { options.createPartitionForTraits(name, newTrait); } fireTraitsChanged(); updateButtons(); // traitsTableModel.fireTableDataChanged(); // dataTableModel.fireTableDataChanged(); // traitSelectionChanged(); // AR we don't want to guess traits automatically - the user may // be planning on typing them in. Also this method may have been // called by guessTraits() anyway. // guessTrait(); } else if (result == CreateTraitDialog.OK_IMPORT) { boolean done = frame.doImportTraits(); if (done) { if (isSpeciesTrait) { // check that we did indeed import a 'species' trait if (!options.traitExists(TraitData.TRAIT_SPECIES)) { JOptionPane.showMessageDialog(this, "The imported trait file didn't contain a trait\n" + "called '" + TraitData.TRAIT_SPECIES + "', required for *BEAST.\n" + "Please edit it or select a different file.", "Reserved trait name", JOptionPane.WARNING_MESSAGE); return false; } } updateButtons(); } return done; } else if (result == JOptionPane.CANCEL_OPTION) { return false; } return true; } public void addTrait(TraitData newTrait) { int selRow = options.addTrait(newTrait); traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow); } private void removeTrait() { int selRow = traitsTable.getSelectedRow(); removeTrait(traitsTable.getValueAt(selRow, 0).toString()); } public void removeTrait(String traitName) { if (options.useStarBEAST && traitName.equalsIgnoreCase(TraitData.TRAIT_SPECIES)) { JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used by *BEAST.\nTurn *BEAST off before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE); return; } TraitData traitData = options.getTrait(traitName); if (options.getAllPartitionData(traitData).size() > 0) { JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used in a partition.\nRemove the partition before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE); return; } options.removeTrait(traitName); updateButtons(); fireTraitsChanged(); traitSelectionChanged(); } public class ClearTraitAction extends AbstractAction { private static final long serialVersionUID = -7281309694753868635L; public ClearTraitAction() { super("Clear trait values"); setToolTipText("Use this tool to remove trait values from each taxon"); } public void actionPerformed(ActionEvent ae) { if (currentTrait != null) clearTraitValues(currentTrait.getName()); // Clear trait values } } public class GuessTraitsAction extends AbstractAction { private static final long serialVersionUID = 8514706149822252033L; public GuessTraitsAction() { super("Guess trait values"); setToolTipText("Use this tool to guess the trait values from the taxon labels"); } public void actionPerformed(ActionEvent ae) { guessTrait(); } } public class AddTraitAction extends AbstractAction { public AddTraitAction() { super("Add trait"); setToolTipText("Use this button to add a new trait"); } public void actionPerformed(ActionEvent ae) { addTrait(); } } AbstractAction removeTraitAction = new AbstractAction() { public void actionPerformed(ActionEvent ae) { removeTrait(); } }; public class SetValueAction extends AbstractAction { public SetValueAction() { super("Set trait values"); setToolTipText("Use this button to set the trait values of selected taxa"); } public void actionPerformed(ActionEvent ae) { setTraitValue(); } } class TraitsTableModel extends AbstractTableModel { private static final long serialVersionUID = -6707994233020715574L; String[] columnNames = {"Trait", "Type"}; public TraitsTableModel() { } public int getColumnCount() { return columnNames.length; } public int getRowCount() { if (options == null) return 0; return options.traits.size(); } public Object getValueAt(int row, int col) { switch (col) { case 0: return options.traits.get(row).getName(); case 1: return options.traits.get(row).getTraitType(); } return null; } public void setValueAt(Object aValue, int row, int col) { switch (col) { case 0: String oldName = options.traits.get(row).getName(); options.traits.get(row).setName(aValue.toString()); Object value; for (Taxon t : options.taxonList) { value = t.getAttribute(oldName); t.setAttribute(aValue.toString(), value); // cannot remvoe attribute in Attributable inteface } fireTraitsChanged(); break; case 1: options.traits.get(row).setTraitType((TraitData.TraitType) aValue); break; } } public boolean isCellEditable(int row, int col) { return !options.useStarBEAST || !options.traits.get(row).getName().equalsIgnoreCase(TraitData.TRAIT_SPECIES.toString()); } public String getColumnName(int column) { return columnNames[column]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getColumnName(0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getColumnName(j)); } buffer.append("\n"); for (int i = 0; i < getRowCount(); i++) { buffer.append(getValueAt(i, 0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getValueAt(i, j)); } buffer.append("\n"); } return buffer.toString(); } } class DataTableModel extends AbstractTableModel { private static final long serialVersionUID = -6707994233020715574L; String[] columnNames = {"Taxon", "Value"}; public DataTableModel() { } public int getColumnCount() { return columnNames.length; } public int getRowCount() { if (options == null) return 0; if (options.taxonList == null) return 0; if (currentTrait == null) return 0; return options.taxonList.getTaxonCount(); } public Object getValueAt(int row, int col) { switch (col) { case 0: return options.taxonList.getTaxon(row); case 1: Object value = null; if (currentTrait != null) { value = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName()); } if (value != null) { return value; } else { return ""; } } return null; } public void setValueAt(Object aValue, int row, int col) { if (col == 1) { // Location location = options.taxonList.getTaxon(row).getLocation(); // if (location != null) { // options.taxonList.getTaxon(row).setLocation(location); if (currentTrait != null) { options.taxonList.getTaxon(row).setAttribute(currentTrait.getName(), aValue); } } } public boolean isCellEditable(int row, int col) { if (col == 1) { // Object t = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName()); // return (t != null); return true; } else { return false; } } public String getColumnName(int column) { return columnNames[column]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getColumnName(0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getColumnName(j)); } buffer.append("\n"); for (int i = 0; i < getRowCount(); i++) { buffer.append(getValueAt(i, 0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getValueAt(i, j)); } buffer.append("\n"); } return buffer.toString(); } } public class CreateTraitPartitionAction extends AbstractAction { public CreateTraitPartitionAction() { super("Create partition from trait ..."); setToolTipText("Create a data partition from a trait. Traits can be defined in the Traits panel."); } public void actionPerformed(ActionEvent ae) { int[] selRows = traitsTable.getSelectedRows(); java.util.List<TraitData> traits = new ArrayList<TraitData>(); for (int row : selRows) { TraitData trait = options.traits.get(row); traits.add(trait); } dataPanel.createFromTraits(traits); } } }
package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.activity.Activity; import com.epam.ta.reportportal.entity.activity.ActivityDetails; import com.epam.ta.reportportal.entity.activity.HistoryField; import com.epam.ta.reportportal.ws.model.ActivityResource; import org.junit.Test; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Collections; import java.util.Date; import static org.junit.Assert.assertEquals; /** * @author <a href="mailto:ihar_kahadouski@epam.com">Ihar Kahadouski</a> */ public class ActivityConverterTest { @Test(expected = NullPointerException.class) public void testNull() { ActivityConverter.TO_RESOURCE.apply(null); } @Test public void testConvert() { Activity activity = new Activity(); activity.setId(1L); activity.setAction("LAUNCH_STARTED"); activity.setCreatedAt(LocalDateTime.now()); final ActivityDetails details = new ActivityDetails(); details.setObjectName("objectName"); details.setHistory(Collections.singletonList(HistoryField.of("filed", "old", "new"))); activity.setDetails(details); activity.setUsername("username"); activity.setActivityEntityType(Activity.ActivityEntityType.LAUNCH); activity.setProjectId(2L); activity.setUserId(3L); validate(activity, ActivityConverter.TO_RESOURCE.apply(activity)); } private void validate(Activity db, ActivityResource resource) { assertEquals(Date.from(db.getCreatedAt().atZone(ZoneId.of("UTC")).toInstant()), resource.getLastModified()); assertEquals(db.getId(), resource.getId()); assertEquals(db.getActivityEntityType(), Activity.ActivityEntityType.fromString(resource.getObjectType()).get()); assertEquals(String.valueOf(db.getUserId()), resource.getUser()); assertEquals(db.getProjectId(), resource.getProjectId()); assertEquals(db.getAction(), resource.getActionType()); } }
package dr.app.beauti.traitspanel; import dr.app.beauti.BeautiFrame; import dr.app.beauti.BeautiPanel; import dr.app.beauti.ComboBoxRenderer; import dr.app.beauti.datapanel.DataPanel; import dr.app.beauti.options.BeautiOptions; import dr.app.beauti.options.TraitData; import dr.app.beauti.options.TraitGuesser; import dr.app.beauti.util.PanelUtils; import dr.app.gui.table.TableEditorStopper; import dr.app.gui.table.TableSorter; import dr.evolution.util.Taxa; import dr.evolution.util.Taxon; import jam.framework.Exportable; import jam.panels.ActionPanel; import jam.table.TableRenderer; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.BorderUIResource; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.ActionEvent; import java.util.ArrayList; /** * @author Andrew Rambaut * @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $ */ public class TraitsPanel extends BeautiPanel implements Exportable { private static final long serialVersionUID = 5283922195494563924L; private static final int MINIMUM_TABLE_WIDTH = 140; private static final String ADD_TRAITS_TOOLTIP = "<html>Define a new trait for the current taxa</html>"; private static final String IMPORT_TRAITS_TOOLTIP = "<html>Import one or more traits for these taxa from a tab-delimited<br>" + "file. Taxa should be in the first column and the trait names<br>" + "in the first row</html>"; private static final String GUESS_TRAIT_VALUES_TOOLTIP = "<html>This attempts to extract values for this trait that are<br>" + "encoded in the names of the selected taxa.</html>"; private static final String SET_TRAIT_VALUES_TOOLTIP = "<html>This sets values for this trait for all<br>" + "the selected taxa.</html>"; private static final String CLEAR_TRAIT_VALUES_TOOLTIP = "<html>This clears all the values currently assigned to taxa for<br>" + "this trait.</html>"; private static final String CREATE_TRAIT_PARTITIONS_TOOLTIP = "<html>Create a data partition for the selected traits.</html>"; public final JTable traitsTable; private final TraitsTableModel traitsTableModel; private final JTable dataTable; private final DataTableModel dataTableModel; private final BeautiFrame frame; private final DataPanel dataPanel; private BeautiOptions options = null; private TraitData currentTrait = null; // current trait private CreateTraitDialog createTraitDialog = null; private GuessTraitDialog guessTraitDialog = null; private TraitValueDialog traitValueDialog = null; AddTraitAction addTraitAction = new AddTraitAction(); Action importTraitsAction; CreateTraitPartitionAction createTraitPartitionAction = new CreateTraitPartitionAction(); GuessTraitsAction guessTraitsAction = new GuessTraitsAction(); SetValueAction setValueAction = new SetValueAction(); public TraitsPanel(BeautiFrame parent, DataPanel dataPanel, Action importTraitsAction) { this.frame = parent; this.dataPanel = dataPanel; traitsTableModel = new TraitsTableModel(); // TableSorter sorter = new TableSorter(traitsTableModel); // traitsTable = new JTable(sorter); // sorter.setTableHeader(traitsTable.getTableHeader()); traitsTable = new JTable(traitsTableModel); traitsTable.getTableHeader().setReorderingAllowed(false); traitsTable.getTableHeader().setResizingAllowed(false); // traitsTable.getTableHeader().setDefaultRenderer( // new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); TableColumn col = traitsTable.getColumnModel().getColumn(1); ComboBoxRenderer comboBoxRenderer = new ComboBoxRenderer(TraitData.TraitType.values()); comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); col.setCellRenderer(comboBoxRenderer); TableEditorStopper.ensureEditingStopWhenTableLosesFocus(traitsTable); traitsTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); traitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { traitSelectionChanged(); // dataTableModel.fireTableDataChanged(); } }); JScrollPane scrollPane1 = new JScrollPane(traitsTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane1.setOpaque(false); dataTableModel = new DataTableModel(); TableSorter sorter = new TableSorter(dataTableModel); dataTable = new JTable(sorter); sorter.setTableHeader(dataTable.getTableHeader()); dataTable.getTableHeader().setReorderingAllowed(false); // dataTable.getTableHeader().setDefaultRenderer( // new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(0).setCellRenderer( new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(0).setPreferredWidth(80); col = dataTable.getColumnModel().getColumn(1); comboBoxRenderer = new ComboBoxRenderer(); comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); col.setCellRenderer(comboBoxRenderer); TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable); // dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { // public void valueChanged(ListSelectionEvent evt) { // traitSelectionChanged(); JScrollPane scrollPane2 = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane2.setOpaque(false); JToolBar toolBar1 = new JToolBar(); toolBar1.setFloatable(false); toolBar1.setOpaque(false); toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); JButton button; button = new JButton(addTraitAction); PanelUtils.setupComponent(button); button.setToolTipText(ADD_TRAITS_TOOLTIP); toolBar1.add(button); this.importTraitsAction = importTraitsAction; button = new JButton(importTraitsAction); PanelUtils.setupComponent(button); button.setToolTipText(IMPORT_TRAITS_TOOLTIP); toolBar1.add(button); toolBar1.add(new JToolBar.Separator(new Dimension(12, 12))); button = new JButton(guessTraitsAction); PanelUtils.setupComponent(button); button.setToolTipText(GUESS_TRAIT_VALUES_TOOLTIP); toolBar1.add(button); button = new JButton(setValueAction); PanelUtils.setupComponent(button); button.setToolTipText(SET_TRAIT_VALUES_TOOLTIP); toolBar1.add(button); // Don't see the need for a clear values button // button = new JButton(new ClearTraitAction()); // PanelUtils.setupComponent(button); // button.setToolTipText(CLEAR_TRAIT_VALUES_TOOLTIP); // toolBar1.add(button); button = new JButton(createTraitPartitionAction); PanelUtils.setupComponent(button); button.setToolTipText(CREATE_TRAIT_PARTITIONS_TOOLTIP); toolBar1.add(button); ActionPanel actionPanel1 = new ActionPanel(false); actionPanel1.setAddAction(addTraitAction); actionPanel1.setRemoveAction(removeTraitAction); actionPanel1.setAddToolTipText(ADD_TRAITS_TOOLTIP); removeTraitAction.setEnabled(false); JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT)); controlPanel1.setOpaque(false); controlPanel1.add(actionPanel1); JPanel panel1 = new JPanel(new BorderLayout(0, 0)); panel1.setOpaque(false); panel1.add(scrollPane1, BorderLayout.CENTER); panel1.add(controlPanel1, BorderLayout.SOUTH); panel1.setMinimumSize(new Dimension(MINIMUM_TABLE_WIDTH, 0)); JPanel panel2 = new JPanel(new BorderLayout(0, 0)); panel2.setOpaque(false); panel2.add(toolBar1, BorderLayout.NORTH); panel2.add(scrollPane2, BorderLayout.CENTER); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2); splitPane.setDividerLocation(MINIMUM_TABLE_WIDTH); splitPane.setContinuousLayout(true); splitPane.setBorder(BorderFactory.createEmptyBorder()); splitPane.setOpaque(false); setOpaque(false); setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12))); setLayout(new BorderLayout(0, 0)); add(splitPane, BorderLayout.CENTER); add(toolBar1, BorderLayout.NORTH); } public void setOptions(BeautiOptions options) { this.options = options; updateButtons(); // int selRow = traitsTable.getSelectedRow(); // traitsTableModel.fireTableDataChanged(); // if (selRow < 0) { // selRow = 0; // traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow); // if (selectedTrait == null) { // traitsTable.getSelectionModel().setSelectionInterval(0, 0); traitsTableModel.fireTableDataChanged(); dataTableModel.fireTableDataChanged(); validate(); repaint(); } public void getOptions(BeautiOptions options) { // int selRow = traitsTable.getSelectedRow(); // if (selRow >= 0 && options.traitsOptions.selecetedTraits.size() > 0) { // selectedTrait = options.traitsOptions.selecetedTraits.get(selRow); // options.datesUnits = unitsCombo.getSelectedIndex(); // options.datesDirection = directionCombo.getSelectedIndex(); } public JComponent getExportableComponent() { return dataTable; } public void fireTraitsChanged() { if (currentTrait != null) { // if (currentTrait.getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())) { // frame.setupStarBEAST(); // } else if (currentTrait != null && currentTrait.getTraitType() == TraitData.TraitType.DISCRETE) { frame.updateDiscreteTraitAnalysis(); } // if (selRow > 0) { // traitsTable.getSelectionModel().setSelectionInterval(selRow-1, selRow-1); // } else if (selRow == 0 && options.traitsOptions.traits.size() > 0) { // options.traitsOptions.traits.size() after remove // traitsTable.getSelectionModel().setSelectionInterval(0, 0); traitsTableModel.fireTableDataChanged(); options.updatePartitionAllLinks(); frame.setDirty(); } } private void traitSelectionChanged() { int selRow = traitsTable.getSelectedRow(); if (selRow >= 0) { currentTrait = options.traits.get(selRow); // traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow); removeTraitAction.setEnabled(true); // } else { // currentTrait = null; // removeTraitAction.setEnabled(false); } if (options.traits.size() <= 0) { currentTrait = null; removeTraitAction.setEnabled(false); } dataTableModel.fireTableDataChanged(); // traitsTableModel.fireTableDataChanged(); } private void updateButtons() { //TODO: better to merge updateButtons() fireTraitsChanged() traitSelectionChanged() into one boolean hasData = options.hasData(); addTraitAction.setEnabled(hasData); importTraitsAction.setEnabled(hasData); createTraitPartitionAction.setEnabled(hasData && options.traits.size() > 0); guessTraitsAction.setEnabled(hasData && options.traits.size() > 0); setValueAction.setEnabled(hasData && options.traits.size() > 0); } public void clearTraitValues(String traitName) { options.clearTraitValues(traitName); dataTableModel.fireTableDataChanged(); } public void guessTrait() { if (options.taxonList == null) { // validation of check empty taxonList return; } if (currentTrait == null) { if (!addTrait()) { return; // if addTrait() cancel then false } } int result; do { TraitGuesser currentTraitGuesser = new TraitGuesser(currentTrait); if (guessTraitDialog == null) { guessTraitDialog = new GuessTraitDialog(frame); } guessTraitDialog.setDescription("Extract values for trait '" + currentTrait + "' from taxa labels"); result = guessTraitDialog.showDialog(); if (result == -1 || result == JOptionPane.CANCEL_OPTION) { return; } guessTraitDialog.setupGuesserFromDialog(currentTraitGuesser); try { int[] selRows = dataTable.getSelectedRows(); if (selRows.length > 0) { Taxa selectedTaxa = new Taxa(); for (int row : selRows) { Taxon taxon = (Taxon) dataTable.getValueAt(row, 0); selectedTaxa.addTaxon(taxon); } currentTraitGuesser.guessTrait(selectedTaxa); } else { currentTraitGuesser.guessTrait(options.taxonList); } } catch (IllegalArgumentException iae) { JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE); result = -1; } dataTableModel.fireTableDataChanged(); } while (result < 0); } public void setTraitValue() { if (options.taxonList == null) { // validation of check empty taxonList return; } int result; do { if (traitValueDialog == null) { traitValueDialog = new TraitValueDialog(frame); } int[] selRows = dataTable.getSelectedRows(); if (selRows.length > 0) { traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for selected taxa"); } else { traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for all taxa"); } result = traitValueDialog.showDialog(); if (result == -1 || result == JOptionPane.CANCEL_OPTION) { return; } // currentTrait.guessTrait = true; // ?? no use? String value = traitValueDialog.getTraitValue(); try { if (selRows.length > 0) { for (int row : selRows) { Taxon taxon = (Taxon) dataTable.getValueAt(row, 0); taxon.setAttribute(currentTrait.getName(), value); } } else { for (Taxon taxon : options.taxonList) { taxon.setAttribute(currentTrait.getName(), value); } } } catch (IllegalArgumentException iae) { JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE); result = -1; } dataTableModel.fireTableDataChanged(); } while (result < 0); } public boolean addTrait() { return addTrait("Untitled"); } public boolean addTrait(String traitName) { return addTrait(null, traitName, false); } public boolean addTrait(String message, String traitName, boolean isSpeciesTrait) { if (createTraitDialog == null) { createTraitDialog = new CreateTraitDialog(frame); } createTraitDialog.setSpeciesTrait(isSpeciesTrait); createTraitDialog.setTraitName(traitName); createTraitDialog.setMessage(message); int result = createTraitDialog.showDialog(); if (result == JOptionPane.OK_OPTION) { frame.tabbedPane.setSelectedComponent(this); String name = createTraitDialog.getName(); TraitData.TraitType type = createTraitDialog.getType(); TraitData newTrait = new TraitData(options, name, "", type); currentTrait = newTrait; // The createTraitDialog will have already checked if the // user is overwriting an existing trait addTrait(newTrait); if (createTraitDialog.createTraitPartition()) { options.createPartitionForTraits(name, newTrait); } fireTraitsChanged(); updateButtons(); } else if (result == CreateTraitDialog.OK_IMPORT) { boolean done = frame.doImportTraits(); if (done) { if (isSpeciesTrait) { // check that we did indeed import a 'species' trait if (!options.traitExists(TraitData.TRAIT_SPECIES)) { JOptionPane.showMessageDialog(this, "The imported trait file didn't contain a trait\n" + "called '" + TraitData.TRAIT_SPECIES + "', required for *BEAST.\n" + "Please edit it or select a different file.", "Reserved trait name", JOptionPane.WARNING_MESSAGE); return false; } } updateButtons(); } return done; } else if (result == JOptionPane.CANCEL_OPTION) { return false; } return true; } public void createTraitPartition() { int[] selRows = traitsTable.getSelectedRows(); java.util.List<TraitData> traits = new ArrayList<TraitData>(); int discreteCount = 0; int continuousCount = 0; for (int row : selRows) { TraitData trait = options.traits.get(row); traits.add(trait); if (trait.getTraitType() == TraitData.TraitType.DISCRETE) { discreteCount ++; } if (trait.getTraitType() == TraitData.TraitType.CONTINUOUS) { continuousCount ++; } } boolean success = false; if (discreteCount > 0) { if (continuousCount > 0) { JOptionPane.showMessageDialog(TraitsPanel.this, "Don't mix discrete and continuous traits when creating partition(s).", "Mixed Trait Types", JOptionPane.ERROR_MESSAGE); return; } // with discrete traits, create a separate partition for each for (TraitData trait : traits) { java.util.List<TraitData> singleTrait = new ArrayList<TraitData>(); singleTrait.add(trait); if (dataPanel.createFromTraits(singleTrait)) { success = true; } } } else { // with success = dataPanel.createFromTraits(traits); } if (success) { frame.switchToPanel(BeautiFrame.DATA_PARTITIONS); } } public void addTrait(TraitData newTrait) { int selRow = options.addTrait(newTrait); traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow); } private void removeTrait() { int selRow = traitsTable.getSelectedRow(); removeTrait(traitsTable.getValueAt(selRow, 0).toString()); } public void removeTrait(String traitName) { if (options.useStarBEAST && traitName.equalsIgnoreCase(TraitData.TRAIT_SPECIES)) { JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used by *BEAST.\nTurn *BEAST off before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE); return; } TraitData traitData = options.getTrait(traitName); if (options.getTraitPartitions(traitData).size() > 0) { JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used in a partition.\nRemove the partition before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE); return; } options.removeTrait(traitName); updateButtons(); fireTraitsChanged(); traitSelectionChanged(); } public class ClearTraitAction extends AbstractAction { private static final long serialVersionUID = -7281309694753868635L; public ClearTraitAction() { super("Clear trait values"); } public void actionPerformed(ActionEvent ae) { if (currentTrait != null) clearTraitValues(currentTrait.getName()); // Clear trait values } } public class GuessTraitsAction extends AbstractAction { private static final long serialVersionUID = 8514706149822252033L; public GuessTraitsAction() { super("Guess trait values"); } public void actionPerformed(ActionEvent ae) { guessTrait(); } } public class AddTraitAction extends AbstractAction { public AddTraitAction() { super("Add trait"); } public void actionPerformed(ActionEvent ae) { addTrait(); } } AbstractAction removeTraitAction = new AbstractAction() { public void actionPerformed(ActionEvent ae) { removeTrait(); } }; public class SetValueAction extends AbstractAction { public SetValueAction() { super("Set trait values"); setToolTipText("Use this button to set the trait values of selected taxa"); } public void actionPerformed(ActionEvent ae) { setTraitValue(); } } public class CreateTraitPartitionAction extends AbstractAction { public CreateTraitPartitionAction() { super("Create partition from trait ..."); } public void actionPerformed(ActionEvent ae) { createTraitPartition(); } } class TraitsTableModel extends AbstractTableModel { private static final long serialVersionUID = -6707994233020715574L; String[] columnNames = {"Trait", "Type"}; public TraitsTableModel() { } public int getColumnCount() { return columnNames.length; } public int getRowCount() { if (options == null) return 0; return options.traits.size(); } public Object getValueAt(int row, int col) { switch (col) { case 0: return options.traits.get(row).getName(); case 1: return options.traits.get(row).getTraitType(); } return null; } public void setValueAt(Object aValue, int row, int col) { switch (col) { case 0: String oldName = options.traits.get(row).getName(); options.traits.get(row).setName(aValue.toString()); Object value; for (Taxon t : options.taxonList) { value = t.getAttribute(oldName); t.setAttribute(aValue.toString(), value); // cannot remvoe attribute in Attributable inteface } fireTraitsChanged(); break; case 1: options.traits.get(row).setTraitType((TraitData.TraitType) aValue); break; } } public boolean isCellEditable(int row, int col) { return !options.useStarBEAST || !options.traits.get(row).getName().equalsIgnoreCase(TraitData.TRAIT_SPECIES.toString()); } public String getColumnName(int column) { return columnNames[column]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getColumnName(0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getColumnName(j)); } buffer.append("\n"); for (int i = 0; i < getRowCount(); i++) { buffer.append(getValueAt(i, 0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getValueAt(i, j)); } buffer.append("\n"); } return buffer.toString(); } } class DataTableModel extends AbstractTableModel { private static final long serialVersionUID = -6707994233020715574L; String[] columnNames = {"Taxon", "Value"}; public DataTableModel() { } public int getColumnCount() { return columnNames.length; } public int getRowCount() { if (options == null) return 0; if (options.taxonList == null) return 0; if (currentTrait == null) return 0; return options.taxonList.getTaxonCount(); } public Object getValueAt(int row, int col) { switch (col) { case 0: return options.taxonList.getTaxon(row); case 1: Object value = null; if (currentTrait != null) { value = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName()); } if (value != null) { return value; } else { return ""; } } return null; } public void setValueAt(Object aValue, int row, int col) { if (col == 1) { // Location location = options.taxonList.getTaxon(row).getLocation(); // if (location != null) { // options.taxonList.getTaxon(row).setLocation(location); if (currentTrait != null) { options.taxonList.getTaxon(row).setAttribute(currentTrait.getName(), aValue); } } } public boolean isCellEditable(int row, int col) { if (col == 1) { // Object t = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName()); // return (t != null); return true; } else { return false; } } public String getColumnName(int column) { return columnNames[column]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getColumnName(0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getColumnName(j)); } buffer.append("\n"); for (int i = 0; i < getRowCount(); i++) { buffer.append(getValueAt(i, 0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getValueAt(i, j)); } buffer.append("\n"); } return buffer.toString(); } } }
package dr.math; import dr.math.distributions.GammaDistribution; import dr.stats.DiscreteStatistics; /** * @author Marc A. Suchard * @author Vladimir Minin * @author Philippe Lemey */ public class EmpiricalBayesPoissonSmoother { /** * Provides an empirical Bayes estimate of counts under a Poisson sampling density with a Gamma prior * on the unknown intensity. The marginal distribution of the data is then a Negative-Binomial. * * @param in vector of Poisson counts * @return smoothed count estimates */ public static double[] smooth(double[] in) { final int length = in.length; double[] out = new double[length]; double[] gammaStats = getNegBin(in); double alpha = gammaStats[0]; double beta = gammaStats[1]; // As defined on wiki page (scale) double mean = gammaStats[2]; if (beta == 0) { for (int i = 0; i < length; i++) { out[i] = mean; } } else { for (int i = 0; i < length; i++) { out[i] = (in[i] + alpha) / (1 + 1 / beta); } } return out; } public static double[] smoothWithSample(double[] in) { final int length = in.length; double[] out = new double[length]; double[] gammaStats = getNegBin(in); double alpha = gammaStats[0]; double beta = gammaStats[1]; // As defined on wiki page (scale) double mean = gammaStats[2]; if (beta == 0) { for (int i = 0; i < length; i++) { out[i] = mean; } } else { for (int i = 0; i < length; i++) { // out[i] = (in[i] + alpha) / (1 + 1 / beta); double shape = in[i] + alpha; double scale = 1 / (1 + 1 / beta); out[i] = GammaDistribution.nextGamma(shape, scale); } } return out; } public static double[] smoothOld(double[] in) { final int length = in.length; double[] out = new double[length]; double[] gammaStats = getNegBin(in); for (int i = 0; i < length; i++) { out[i] = (in[i] + gammaStats[0]) / (1 + 1 / gammaStats[1]); } return out; } // Method of moments estimators following Martiz 1969 private static double[] getNegBin(double[] array) { double mean = DiscreteStatistics.mean(array); double variance = DiscreteStatistics.variance(array, mean); double returnArray0 = (1 - (mean / variance)); double returnArray1 = (mean * ((1 - returnArray0) / returnArray0)); double shape = returnArray1; double scale = (returnArray0 / (1 - returnArray0)); if (variance <= mean) { shape = 0.0; scale = 0.0; } // // Check against Martiz 1969 (beta = shape, alpha = rate in the 1969 paper) // double matrizBeta = mean * mean / (variance - mean); // double matrizAlphaInv = mean / matrizBeta; // scale // System.err.println("mb = " + matrizBeta + " shape = " + shape); // System.err.println("ma = " + matrizAlphaInv + " scale = " + scale); return new double[]{shape, scale, mean}; } }
package org.usergrid.management.cassandra; import static java.lang.Boolean.parseBoolean; import static org.apache.commons.codec.binary.Base64.decodeBase64; import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString; import static org.apache.commons.codec.digest.DigestUtils.sha; import static org.apache.commons.lang.StringUtils.isBlank; import static org.usergrid.persistence.CredentialsInfo.checkPassword; import static org.usergrid.persistence.CredentialsInfo.getCredentialsSecret; import static org.usergrid.persistence.CredentialsInfo.mongoPasswordCredentials; import static org.usergrid.persistence.CredentialsInfo.passwordCredentials; import static org.usergrid.persistence.CredentialsInfo.plainTextCredentials; import static org.usergrid.persistence.Schema.DICTIONARY_CREDENTIALS; import static org.usergrid.persistence.Schema.PROPERTY_NAME; import static org.usergrid.persistence.Schema.PROPERTY_PATH; import static org.usergrid.persistence.Schema.PROPERTY_SECRET; import static org.usergrid.persistence.Schema.PROPERTY_UUID; import static org.usergrid.persistence.cassandra.CassandraService.MANAGEMENT_APPLICATION_ID; import static org.usergrid.security.AuthPrincipalType.ADMIN_USER; import static org.usergrid.security.AuthPrincipalType.APPLICATION_USER; import static org.usergrid.security.AuthPrincipalType.BASE64_PREFIX_LENGTH; import static org.usergrid.security.AuthPrincipalType.ORGANIZATION; import static org.usergrid.security.oauth.ClientCredentialsInfo.getTypeFromClientId; import static org.usergrid.security.oauth.ClientCredentialsInfo.getUUIDFromClientId; import static org.usergrid.services.ServiceParameter.parameters; import static org.usergrid.services.ServicePayload.payload; import static org.usergrid.utils.ConversionUtils.uuid; import static org.usergrid.utils.ListUtils.anyNull; import static org.usergrid.utils.MailUtils.sendHtmlMail; import static org.usergrid.utils.MapUtils.hashMap; import static org.usergrid.utils.StringUtils.stringOrSubstringAfterLast; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.UUID; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.text.StrSubstitutor; import org.apache.shiro.UnavailableSecurityManagerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.usergrid.locking.LockManager; import org.usergrid.management.ApplicationInfo; import org.usergrid.management.ManagementService; import org.usergrid.management.OrganizationInfo; import org.usergrid.management.OrganizationOwnerInfo; import org.usergrid.management.UserInfo; import org.usergrid.management.exceptions.BadAccessTokenException; import org.usergrid.management.exceptions.DisabledAdminUserException; import org.usergrid.management.exceptions.ExpiredAccessTokenException; import org.usergrid.management.exceptions.IncorrectPasswordException; import org.usergrid.management.exceptions.InvalidAccessTokenException; import org.usergrid.management.exceptions.UnactivatedAdminUserException; import org.usergrid.persistence.CredentialsInfo; import org.usergrid.persistence.Entity; import org.usergrid.persistence.EntityManager; import org.usergrid.persistence.EntityManagerFactory; import org.usergrid.persistence.EntityRef; import org.usergrid.persistence.Identifier; import org.usergrid.persistence.Results; import org.usergrid.persistence.Results.Level; import org.usergrid.persistence.SimpleEntityRef; import org.usergrid.persistence.entities.Application; import org.usergrid.persistence.entities.Group; import org.usergrid.persistence.entities.User; import org.usergrid.persistence.exceptions.DuplicateUniquePropertyExistsException; import org.usergrid.security.AuthPrincipalInfo; import org.usergrid.security.AuthPrincipalType; import org.usergrid.security.oauth.AccessInfo; import org.usergrid.security.oauth.ClientCredentialsInfo; import org.usergrid.security.shiro.PrincipalCredentialsToken; import org.usergrid.security.shiro.credentials.ApplicationClientCredentials; import org.usergrid.security.shiro.credentials.OrganizationClientCredentials; import org.usergrid.security.shiro.principals.ApplicationPrincipal; import org.usergrid.security.shiro.principals.OrganizationPrincipal; import org.usergrid.security.shiro.utils.SubjectUtils; import org.usergrid.services.ServiceAction; import org.usergrid.services.ServiceManager; import org.usergrid.services.ServiceManagerFactory; import org.usergrid.services.ServiceRequest; import org.usergrid.services.ServiceResults; import org.usergrid.utils.ConversionUtils; import org.usergrid.utils.JsonUtils; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; public class ManagementServiceImpl implements ManagementService { public static final String MANAGEMENT_APPLICATION = "management"; public static final String APPLICATION_INFO = "application_info"; private static final Logger logger = LoggerFactory .getLogger(ManagementServiceImpl.class); public static final String OAUTH_SECRET_SALT = "super secret oauth value"; public static final String TOKEN_SECRET_SALT = "super secret session value"; // Token is good for 24 hours public static final long MAX_TOKEN_AGE = 24 * 60 * 60 * 1000; String sessionSecretSalt = TOKEN_SECRET_SALT; public static String EMAIL_MAILER = "usergrid.management.mailer"; public static String EMAIL_ADMIN_PASSWORD_RESET = "usergrid.management.email.admin-password-reset"; public static String EMAIL_SYSADMIN_ORGANIZATION_ACTIVATION = "usergrid.management.email.sysadmin-organization-activation"; public static String EMAIL_ORGANIZATION_ACTIVATION = "usergrid.management.email.organization-activation"; public static String EMAIL_ORGANIZATION_ACTIVATED = "usergrid.management.email.organization-activated"; public static String EMAIL_SYSADMIN_ADMIN_ACTIVATION = "usergrid.management.email.sysadmin-admin-activation"; public static String EMAIL_ADMIN_ACTIVATION = "usergrid.management.email.admin-activation"; public static String EMAIL_ADMIN_ACTIVATED = "usergrid.management.email.admin-activated"; public static String EMAIL_ADMIN_USER_ACTIVATION = "usergrid.management.email.admin-user-activation"; public static String EMAIL_USER_ACTIVATION = "usergrid.management.email.user-activation"; public static String EMAIL_USER_ACTIVATED = "usergrid.management.email.user-activated"; public static String EMAIL_USER_PASSWORD_RESET = "usergrid.management.email.user-password-reset"; public static String EMAIL_USER_PIN_REQUEST = "usergrid.management.email.user-pin"; protected ServiceManagerFactory smf; protected EntityManagerFactory emf; protected Properties properties; protected LockManager lockManager; /** * Must be constructed with a CassandraClientPool. * * @param cassandraClientPool * the cassandra client pool */ public ManagementServiceImpl() { } @Autowired public void setEntityManagerFactory(EntityManagerFactory emf) { logger.info("ManagementServiceImpl.setEntityManagerFactory"); this.emf = emf; } @Autowired public void setProperties(Properties properties) { this.properties = properties; } @Autowired public void setServiceManagerFactory(ServiceManagerFactory smf) { this.smf = smf; } public LockManager getLockManager() { return lockManager; } @Autowired public void setLockManager(LockManager lockManager) { this.lockManager = lockManager; } public void setAccessTokenSecretSalt(String sessionSecretSalt) { if (sessionSecretSalt != null) { this.sessionSecretSalt = sessionSecretSalt; } } private String getPropertyValue(String propertyName) { String propertyValue = properties.getProperty(propertyName); if (isBlank(propertyValue)) { logger.warn("Missing value for " + propertyName); return null; } return propertyValue; } @Override public void setup() throws Exception { if (parseBoolean(properties.getProperty("usergrid.setup-test-account"))) { String test_app_name = getPropertyValue("usergrid.test-account.app"); String test_organization_name = getPropertyValue("usergrid.test-account.organization"); String test_admin_username = getPropertyValue("usergrid.test-account.admin-user.username"); String test_admin_name = getPropertyValue("usergrid.test-account.admin-user.name"); String test_admin_email = getPropertyValue("usergrid.test-account.admin-user.email"); String test_admin_password = getPropertyValue("usergrid.test-account.admin-user.password"); if (anyNull(test_app_name, test_organization_name, test_admin_username, test_admin_name, test_admin_email, test_admin_password)) { logger.warn("Missing values for test app, check properties. Skipping test app setup..."); return; } UserInfo user = createAdminUser(test_admin_username, test_admin_name, test_admin_email, test_admin_password, true, false, false); OrganizationInfo organization = createOrganization( test_organization_name, user); UUID appId = createApplication(organization.getUuid(), test_app_name); postOrganizationActivity(organization.getUuid(), user, "create", new SimpleEntityRef(APPLICATION_INFO, appId), "Application", test_app_name, "<a mailto=\"" + user.getEmail() + "\">" + user.getName() + " (" + user.getEmail() + ")</a> created a new application named " + test_app_name, null); boolean superuser_enabled = parseBoolean(properties .getProperty("usergrid.sysadmin.login.allowed")); String superuser_username = getPropertyValue("usergrid.sysadmin.login.name"); String superuser_email = getPropertyValue("usergrid.sysadmin.login.email"); String superuser_password = getPropertyValue("usergrid.sysadmin.login.password"); if (!anyNull(superuser_username, superuser_email, superuser_password)) { user = createAdminUser(superuser_username, "Super User", superuser_email, superuser_password, superuser_enabled, !superuser_enabled, false); } else { logger.warn("Missing values for superuser account, check properties. Skipping superuser account setup..."); } } else { logger.warn("Test app creation disabled"); } } public String generateOAuthSecretKey(AuthPrincipalType type) { long timestamp = System.currentTimeMillis(); ByteBuffer bytes = ByteBuffer.allocate(20); bytes.put(sha(timestamp + OAUTH_SECRET_SALT + UUID.randomUUID())); String secret = type.getBase64Prefix() + encodeBase64URLSafeString(bytes.array()); return secret; } @SuppressWarnings("serial") @Override public void postOrganizationActivity(UUID organizationId, final UserInfo user, String verb, final EntityRef object, final String objectType, final String objectName, String title, String content) throws Exception { ServiceManager sm = smf.getServiceManager(MANAGEMENT_APPLICATION_ID); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("verb", verb); properties.put("category", "admin"); if (content != null) { properties.put("content", content); } if (title != null) { properties.put("title", title); } properties.put("actor", new HashMap<String, Object>() { { put("displayName", user.getName()); put("objectType", "person"); put("entityType", "user"); put("uuid", user.getUuid()); } }); properties.put("object", new HashMap<String, Object>() { { put("displayName", objectName); put("objectType", objectType); put("entityType", object.getType()); put("uuid", object.getUuid()); } }); sm.newRequest(ServiceAction.POST, parameters("groups", organizationId, "activities"), payload(properties)).execute().getEntity(); } @Override public ServiceResults getOrganizationActivity(OrganizationInfo organization) throws Exception { ServiceManager sm = smf.getServiceManager(MANAGEMENT_APPLICATION_ID); return sm.newRequest(ServiceAction.GET, parameters("groups", organization.getUuid(), "feed")).execute(); } @Override public ServiceResults getOrganizationActivityForAdminUser( OrganizationInfo organization, UserInfo user) throws Exception { ServiceManager sm = smf.getServiceManager(MANAGEMENT_APPLICATION_ID); return sm.newRequest( ServiceAction.GET, parameters("groups", organization.getUuid(), "users", user.getUuid(), "feed")).execute(); } @Override public ServiceResults getAdminUserActivity(UserInfo user) throws Exception { ServiceManager sm = smf.getServiceManager(MANAGEMENT_APPLICATION_ID); return sm.newRequest(ServiceAction.GET, parameters("users", user.getUuid(), "feed")).execute(); } @Override public OrganizationOwnerInfo createOwnerAndOrganization( String organizationName, String username, String name, String email, String password, boolean activated, boolean disabled, boolean sendEmail) throws Exception { lockManager.lockProperty(MANAGEMENT_APPLICATION_ID, "groups", "path"); lockManager.lockProperty(MANAGEMENT_APPLICATION_ID, "users", "username", "email"); EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); UserInfo user = null; OrganizationInfo organization = null; try { if (!em.isPropertyValueUniqueForEntity("user", "username", username)) { throw new DuplicateUniquePropertyExistsException("user", "username", username); } if (!em.isPropertyValueUniqueForEntity("user", "email", email)) { throw new DuplicateUniquePropertyExistsException("user", "username", username); } if (!em.isPropertyValueUniqueForEntity("group", "path", organizationName)) { throw new DuplicateUniquePropertyExistsException("group", "path", organizationName); } user = createAdminUser(username, name, email, password, false, false, false); organization = createOrganization(organizationName, user); } finally { lockManager.unlockProperty(MANAGEMENT_APPLICATION_ID, "groups", "path"); lockManager.unlockProperty(MANAGEMENT_APPLICATION_ID, "users", "username", "email"); } return new OrganizationOwnerInfo(user, organization); } @Override public OrganizationInfo createOrganization(String organizationName, UserInfo user) throws Exception { if ((organizationName == null) || (user == null)) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Group organizationEntity = new Group(); organizationEntity.setPath(organizationName); organizationEntity = em.create(organizationEntity); em.addToCollection(organizationEntity, "users", new SimpleEntityRef( User.ENTITY_TYPE, user.getUuid())); Map<String, CredentialsInfo> credentials = new HashMap<String, CredentialsInfo>(); credentials .put("secret", plainTextCredentials(generateOAuthSecretKey(AuthPrincipalType.ORGANIZATION))); em.addMapToDictionary(organizationEntity, DICTIONARY_CREDENTIALS, credentials); OrganizationInfo organization = new OrganizationInfo( organizationEntity.getUuid(), organizationName); postOrganizationActivity(organization.getUuid(), user, "create", organizationEntity, "Organization", organization.getName(), "<a mailto=\"" + user.getEmail() + "\">" + user.getName() + " (" + user.getEmail() + ")</a> created a new organization account named " + organizationName, null); return organization; } @Override public OrganizationInfo importOrganization(UUID organizationId, OrganizationInfo organizationInfo, Map<String, Object> properties) throws Exception { if (properties == null) { properties = new HashMap<String, Object>(); } String organizationName = null; if (organizationInfo != null) { organizationName = organizationInfo.getName(); } if (organizationName == null) { organizationName = (String) properties.get(PROPERTY_PATH); } if (organizationName == null) { organizationName = (String) properties.get(PROPERTY_NAME); } if (organizationName == null) { return null; } if (organizationId == null) { if (organizationInfo != null) { organizationId = organizationInfo.getUuid(); } } if (organizationId == null) { organizationId = uuid(properties.get(PROPERTY_UUID)); } if (organizationId == null) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); properties.put(PROPERTY_PATH, organizationName); properties.put(PROPERTY_SECRET, generateOAuthSecretKey(AuthPrincipalType.ORGANIZATION)); Entity organization = em.create(organizationId, Group.ENTITY_TYPE, properties); // em.addToCollection(organization, "users", new SimpleEntityRef( // User.ENTITY_TYPE, userId)); return new OrganizationInfo(organization.getUuid(), organizationName); } @Override public UUID importApplication(UUID organizationId, Application application) throws Exception { UUID applicationId = emf.importApplication(application.getUuid(), application.getName(), application.getProperties()); EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); properties.put("name", application.getName()); Entity app = em.create(applicationId, APPLICATION_INFO, null); Map<String, CredentialsInfo> credentials = new HashMap<String, CredentialsInfo>(); credentials .put("secret", CredentialsInfo .plainTextCredentials(generateOAuthSecretKey(AuthPrincipalType.APPLICATION))); em.addMapToDictionary(app, DICTIONARY_CREDENTIALS, credentials); addApplicationToOrganization(organizationId, applicationId); return applicationId; } @Override public BiMap<UUID, String> getOrganizations() throws Exception { BiMap<UUID, String> organizations = HashBiMap.create(); EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Results results = em.getCollection(em.getApplicationRef(), "groups", null, 10000, Level.ALL_PROPERTIES, false); for (Entity entity : results.getEntities()) { organizations.put(entity.getUuid(), (String) entity.getProperty("path")); } return organizations; } @Override public OrganizationInfo getOrganizationInfoFromAccessToken(String token) throws Exception { if (!AuthPrincipalType.ORGANIZATION.equals(AuthPrincipalType .getFromAccessToken(token))) { return null; } Entity entity = geEntityFromAccessToken(MANAGEMENT_APPLICATION_ID, token); return new OrganizationInfo(entity.getProperties()); } @Override public Entity getOrganizationEntityByName(String organizationName) throws Exception { if (organizationName == null) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); EntityRef ref = em.getAlias("group", organizationName); if (ref == null) { return null; } return getOrganizationEntityByUuid(ref.getUuid()); } @Override public OrganizationInfo getOrganizationByName(String organizationName) throws Exception { if (organizationName == null) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); EntityRef ref = em.getAlias("group", organizationName); if (ref == null) { return null; } return getOrganizationByUuid(ref.getUuid()); } @Override public Entity getOrganizationEntityByUuid(UUID id) throws Exception { if (id == null) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Entity entity = em.get(new SimpleEntityRef(Group.ENTITY_TYPE, id)); return entity; } @Override public OrganizationInfo getOrganizationByUuid(UUID id) throws Exception { Entity entity = getOrganizationEntityByUuid(id); if (entity == null) { return null; } return new OrganizationInfo(entity.getProperties()); } @Override public Entity getOrganizationEntityByIdentifier(Identifier id) throws Exception { if (id.isUUID()) { return getOrganizationEntityByUuid(id.getUUID()); } if (id.isName()) { return getOrganizationEntityByName(id.getName()); } return null; } @Override public OrganizationInfo getOrganizationByIdentifier(Identifier id) throws Exception { if (id.isUUID()) { return getOrganizationByUuid(id.getUUID()); } if (id.isName()) { return getOrganizationByName(id.getName()); } return null; } public void postUserActivity(UserInfo user, String verb, EntityRef object, String objectType, String objectName, String title, String content) throws Exception { ServiceManager sm = smf.getServiceManager(MANAGEMENT_APPLICATION_ID); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("verb", verb); properties.put("category", "admin"); if (content != null) { properties.put("content", content); } if (title != null) { properties.put("title", title); } properties.put("actor", user.getUuid()); properties.put("actorName", user.getName()); properties.put("object", object.getUuid()); properties.put("objectEntityType", object.getType()); properties.put("objectType", objectType); properties.put("objectName", objectName); sm.newRequest(ServiceAction.POST, parameters("users", user.getUuid(), "activities"), payload(properties)).execute().getEntity(); } @Override public ServiceResults getAdminUserActivities(UserInfo user) throws Exception { ServiceManager sm = smf.getServiceManager(MANAGEMENT_APPLICATION_ID); ServiceRequest request = sm.newRequest(ServiceAction.GET, parameters("users", user.getUuid(), "feed")); ServiceResults results = request.execute(); return results; } @Override public UserInfo createAdminUser(String username, String name, String email, String password, boolean activated, boolean disabled, boolean sendEmail) throws Exception { if ((username == null) || (name == null) || (email == null) || (password == null)) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); User user = new User(); user.setUsername(username); user.setName(name); user.setEmail(email); user.setActivated(activated); user.setDisabled(disabled); user = em.create(user); Map<String, CredentialsInfo> credentials = new HashMap<String, CredentialsInfo>(); credentials.put("password", passwordCredentials(password)); credentials.put("mongo_pwd", mongoPasswordCredentials(username, password)); credentials .put("secret", plainTextCredentials(generateOAuthSecretKey(AuthPrincipalType.ADMIN_USER))); em.addMapToDictionary(user, DICTIONARY_CREDENTIALS, credentials); UserInfo userInfo = new UserInfo(MANAGEMENT_APPLICATION_ID, user.getUuid(), username, name, email, activated, disabled); if (sendEmail && !activated) { sendAdminUserActivationEmail(userInfo); } return userInfo; } public UserInfo getUserInfo(UUID applicationId, Entity entity) { if (entity == null) { return null; } return new UserInfo(applicationId, entity.getUuid(), (String) entity.getProperty("username"), entity.getName(), (String) entity.getProperty("email"), ConversionUtils.getBoolean(entity.getProperty("activated")), ConversionUtils.getBoolean(entity.getProperty("disabled"))); } public UserInfo getUserInfo(UUID applicationId, Map<String, Object> properties) { if (properties == null) { return null; } return new UserInfo(applicationId, properties); } @Override public List<UserInfo> getAdminUsersForOrganization(UUID organizationId) throws Exception { if (organizationId == null) { return null; } List<UserInfo> users = new ArrayList<UserInfo>(); EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Results results = em.getCollection(new SimpleEntityRef( Group.ENTITY_TYPE, organizationId), "users", null, 10000, Level.ALL_PROPERTIES, false); for (Entity entity : results.getEntities()) { users.add(getUserInfo(MANAGEMENT_APPLICATION_ID, entity)); } return users; } @Override public UserInfo updateAdminUser(UserInfo user, String username, String name, String email) throws Exception { lockManager.lockProperty(MANAGEMENT_APPLICATION_ID, "users", "username", "email"); try { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); if (!isBlank(username)) { em.setProperty( new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid()), "username", username); } if (!isBlank(name)) { em.setProperty( new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid()), "name", name); } if (!isBlank(email)) { em.setProperty( new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid()), "email", email); } user = getAdminUserByUuid(user.getUuid()); } finally { lockManager.unlockProperty(MANAGEMENT_APPLICATION_ID, "users", "username", "email"); } return user; } public User getAdminUserEntityByEmail(String email) throws Exception { if (email == null) { return null; } return getUserEntityByIdentifier(MANAGEMENT_APPLICATION_ID, Identifier.fromEmail(email)); } @Override public UserInfo getAdminUserByEmail(String email) throws Exception { if (email == null) { return null; } return getUserInfo( MANAGEMENT_APPLICATION_ID, getUserEntityByIdentifier(MANAGEMENT_APPLICATION_ID, Identifier.fromEmail(email))); } public User getUserEntityByIdentifier(UUID applicationId, Identifier indentifier) throws Exception { EntityManager em = emf.getEntityManager(applicationId); return em.get(em.getUserByIdentifier(indentifier), User.class); } @Override public UserInfo getAdminUserByUsername(String username) throws Exception { if (username == null) { return null; } return getUserInfo( MANAGEMENT_APPLICATION_ID, getUserEntityByIdentifier(MANAGEMENT_APPLICATION_ID, Identifier.fromName(username))); } @Override public User getAdminUserEntityByUuid(UUID id) throws Exception { if (id == null) { return null; } return getUserEntityByIdentifier(MANAGEMENT_APPLICATION_ID, Identifier.fromUUID(id)); } @Override public UserInfo getAdminUserByUuid(UUID id) throws Exception { return getUserInfo( MANAGEMENT_APPLICATION_ID, getUserEntityByIdentifier(MANAGEMENT_APPLICATION_ID, Identifier.fromUUID(id))); } @Override public User getAdminUserEntityByIdentifier(Identifier id) throws Exception { return getUserEntityByIdentifier(MANAGEMENT_APPLICATION_ID, id); } @Override public UserInfo getAdminUserByIdentifier(Identifier id) throws Exception { if (id.isUUID()) { return getAdminUserByUuid(id.getUUID()); } if (id.isName()) { return getAdminUserByUsername(id.getName()); } if (id.isEmail()) { return getAdminUserByEmail(id.getEmail()); } return null; } public User findUserEntity(UUID applicationId, String identifier) { User user = null; try { Entity entity = getUserEntityByIdentifier(applicationId, Identifier.fromUUID(UUID.fromString(identifier))); if (entity != null) { user = (User) entity.toTypedEntity(); logger.info("Found user " + identifier + " as a UUID"); } } catch (Exception e) { logger.error("Unable to get user " + identifier + " as a UUID, trying username..."); } if (user != null) { return user; } try { Entity entity = getUserEntityByIdentifier(applicationId, Identifier.fromName(identifier)); if (entity != null) { user = (User) entity.toTypedEntity(); logger.info("Found user " + identifier + " as a username"); } } catch (Exception e) { logger.error("Unable to get user " + identifier + " as a username, trying email"); } if (user != null) { return user; } try { Entity entity = getUserEntityByIdentifier(applicationId, Identifier.fromEmail(identifier)); if (entity != null) { user = (User) entity.toTypedEntity(); logger.info("Found user " + identifier + " as an email address"); } } catch (Exception e) { logger.error("Unable to get user " + identifier + " as an email address, failed..."); } if (user != null) { return user; } return null; } @Override public UserInfo findAdminUser(String identifier) { return getUserInfo(MANAGEMENT_APPLICATION_ID, findUserEntity(MANAGEMENT_APPLICATION_ID, identifier)); } @Override public void setAdminUserPassword(UUID userId, String oldPassword, String newPassword) throws Exception { if ((userId == null) || (oldPassword == null) || (newPassword == null)) { return; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Entity user = em.get(userId); if (!checkPassword(oldPassword, (CredentialsInfo) em.getDictionaryElementValue(user, DICTIONARY_CREDENTIALS, "password"))) { logger.info("Old password doesn't match"); throw new IncorrectPasswordException(); } em.addToDictionary(user, DICTIONARY_CREDENTIALS, "password", passwordCredentials(newPassword)); } @Override public void setAdminUserPassword(UUID userId, String newPassword) throws Exception { if ((userId == null) || (newPassword == null)) { return; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.addToDictionary(new SimpleEntityRef(User.ENTITY_TYPE, userId), DICTIONARY_CREDENTIALS, "password", passwordCredentials(newPassword)); } @Override public boolean verifyAdminUserPassword(UUID userId, String password) throws Exception { if ((userId == null) || (password == null)) { return false; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Entity user = em.get(userId); if (checkPassword(password, (CredentialsInfo) em.getDictionaryElementValue(user, DICTIONARY_CREDENTIALS, "password"))) { return true; } return false; } @Override public UserInfo verifyAdminUserPasswordCredentials(String name, String password) throws Exception { UserInfo userInfo = null; Entity user = findUserEntity(MANAGEMENT_APPLICATION_ID, name); if (user == null) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); if (checkPassword(password, (CredentialsInfo) em.getDictionaryElementValue(user, DICTIONARY_CREDENTIALS, "password"))) { userInfo = getUserInfo(MANAGEMENT_APPLICATION_ID, user); if (!userInfo.isActivated()) { throw new UnactivatedAdminUserException(); } if (userInfo.isDisabled()) { throw new DisabledAdminUserException(); } return userInfo; } return null; } @Override public UserInfo verifyMongoCredentials(String name, String nonce, String key) throws Exception { UserInfo userInfo = null; Entity user = findUserEntity(MANAGEMENT_APPLICATION_ID, name); if (user == null) { return null; } String mongo_pwd = (String) user.getProperty("mongo_pwd"); if (mongo_pwd == null) { userInfo = new UserInfo(MANAGEMENT_APPLICATION_ID, user.getProperties()); } if (userInfo == null) { String expected_key = DigestUtils.md5Hex(nonce + user.getProperty("username") + mongo_pwd); if (expected_key.equalsIgnoreCase(key)) { userInfo = new UserInfo(MANAGEMENT_APPLICATION_ID, user.getProperties()); } } if (userInfo != null) { if (!userInfo.isActivated()) { throw new UnactivatedAdminUserException(); } if (userInfo.isDisabled()) { throw new DisabledAdminUserException(); } } return userInfo; } public String getTokenForPrincipal(UUID applicationId, AuthPrincipalType type, UUID id, String tokenSalt, boolean useSecret) throws Exception { if ((type == null) || (id == null)) { return null; } String principalSecret = null; if (useSecret) { principalSecret = getSecret(applicationId, type, id); } String secret = (tokenSalt != null ? tokenSalt : "") + (principalSecret != null ? principalSecret : ""); return new AuthPrincipalInfo(type, id, applicationId) .constructAccessToken(sessionSecretSalt, secret); } public EntityRef getEntityRefFromAccessToken(UUID applicationId, String token, AuthPrincipalType expectedType, long maxAge, String tokenSalt, boolean useSecret) throws Exception { AuthPrincipalInfo principal = AuthPrincipalInfo .getFromAccessToken(token); if (principal == null) { return null; } if ((expectedType != null) && !principal.getType().equals(expectedType)) { logger.info("Token is not of expected type " + token); throw new BadAccessTokenException("Token is not of expected type " + token); } String digestPart = stringOrSubstringAfterLast(token, ':').substring( BASE64_PREFIX_LENGTH); ByteBuffer bytes = ByteBuffer.wrap(decodeBase64(digestPart)); if (bytes.remaining() != 28) { String error_str = "Token digest is wrong size: " + digestPart + " is " + bytes.remaining() + " bytes, expected 28"; logger.info(error_str); throw new BadAccessTokenException(error_str); } long timestamp = bytes.getLong(); long current_time = System.currentTimeMillis(); long age = current_time - timestamp; if ((maxAge > 0) && (age > maxAge)) { logger.info("Token expired " + (age / 1000 / 60) + " minutes ago"); throw new ExpiredAccessTokenException("Token expired " + (age / 1000 / 60) + " minutes ago"); } EntityRef user = new SimpleEntityRef(principal.getUuid()); String principalSecret = null; if (useSecret) { principalSecret = getSecret(applicationId, principal.getType(), principal.getUuid()); } String secret = (tokenSalt != null ? tokenSalt : "") + (principalSecret != null ? principalSecret : ""); ByteBuffer digest = ByteBuffer.wrap(sha(timestamp + sessionSecretSalt + secret + principal.getUuid())); boolean verified = digest.equals(bytes); if (!verified) { throw new InvalidAccessTokenException(); } return user; } public Entity geEntityFromAccessToken(UUID applicationId, String token) throws Exception { EntityManager em = emf .getEntityManager(applicationId != null ? applicationId : MANAGEMENT_APPLICATION_ID); Entity entity = em.get(getEntityRefFromAccessToken(applicationId, token, null, MAX_TOKEN_AGE, null, true)); return entity; } @Override public String getAccessTokenForAdminUser(UUID userId) throws Exception { return getTokenForPrincipal(MANAGEMENT_APPLICATION_ID, ADMIN_USER, userId, null, true); } @Override public Entity getAdminUserEntityFromAccessToken(String token) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Entity user = em.get(getEntityRefFromAccessToken( MANAGEMENT_APPLICATION_ID, token, ADMIN_USER, MAX_TOKEN_AGE, null, true)); return user; } @Override public UserInfo getAdminUserInfoFromAccessToken(String token) throws Exception { Entity user = getAdminUserEntityFromAccessToken(token); return new UserInfo(MANAGEMENT_APPLICATION_ID, user.getProperties()); } @Override public UUID getAdminUserIdFromAccessToken(String token) throws Exception { return AuthPrincipalInfo.getFromAccessToken(token).getUuid(); } @Override public BiMap<UUID, String> getOrganizationsForAdminUser(UUID userId) throws Exception { if (userId == null) { return null; } BiMap<UUID, String> organizations = HashBiMap.create(); EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Results results = em.getCollection(new SimpleEntityRef( User.ENTITY_TYPE, userId), "groups", null, 10000, Level.ALL_PROPERTIES, false); for (Entity entity : results.getEntities()) { organizations.put(entity.getUuid(), (String) entity.getProperty("path")); } return organizations; } @Override public Map<String, Object> getAdminUserOrganizationData(UUID userId) throws Exception { UserInfo user = getAdminUserByUuid(userId); return getAdminUserOrganizationData(user); } @Override public Map<String, Object> getAdminUserOrganizationData(UserInfo user) throws Exception { Map<String, Object> json = new HashMap<String, Object>(); json.putAll(JsonUtils.toJsonMap(user)); // json.put(PROPERTY_UUID, user.getUuid()); // json.put(PROPERTY_NAME, user.getName()); // json.put(PROPERTY_EMAIL, user.getEmail()); // json.put(PROPERTY_USERNAME, user.getUsername()); Map<String, Map<String, Object>> jsonOrganizations = new HashMap<String, Map<String, Object>>(); json.put("organizations", jsonOrganizations); Map<UUID, String> organizations = getOrganizationsForAdminUser(user .getUuid()); for (Entry<UUID, String> organization : organizations.entrySet()) { Map<String, Object> jsonOrganization = new HashMap<String, Object>(); jsonOrganizations.put(organization.getValue(), jsonOrganization); jsonOrganization.put(PROPERTY_NAME, organization.getValue()); jsonOrganization.put(PROPERTY_UUID, organization.getKey()); BiMap<UUID, String> applications = getApplicationsForOrganization(organization .getKey()); jsonOrganization.put("applications", applications.inverse()); List<UserInfo> users = getAdminUsersForOrganization(organization .getKey()); Map<String, Object> jsonUsers = new HashMap<String, Object>(); for (UserInfo u : users) { jsonUsers.put(u.getUsername(), u); } jsonOrganization.put("users", jsonUsers); } return json; } @Override public Map<String, Object> getOrganizationData(OrganizationInfo organization) throws Exception { Map<String, Object> jsonOrganization = new HashMap<String, Object>(); jsonOrganization.putAll(JsonUtils.toJsonMap(organization)); BiMap<UUID, String> applications = getApplicationsForOrganization(organization .getUuid()); jsonOrganization.put("applications", applications.inverse()); List<UserInfo> users = getAdminUsersForOrganization(organization .getUuid()); Map<String, Object> jsonUsers = new HashMap<String, Object>(); for (UserInfo u : users) { jsonUsers.put(u.getUsername(), u); } jsonOrganization.put("users", jsonUsers); return jsonOrganization; } @Override public void addAdminUserToOrganization(UUID userId, UUID organizationId) throws Exception { if ((userId == null) || (organizationId == null)) { return; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.addToCollection(new SimpleEntityRef(Group.ENTITY_TYPE, organizationId), "users", new SimpleEntityRef(User.ENTITY_TYPE, userId)); } @Override public void removeAdminUserFromOrganization(UUID userId, UUID organizationId) throws Exception { if ((userId == null) || (organizationId == null)) { return; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.removeFromCollection(new SimpleEntityRef(Group.ENTITY_TYPE, organizationId), "users", new SimpleEntityRef(User.ENTITY_TYPE, userId)); } @Override public UUID createApplication(UUID organizationId, String applicationName) throws Exception { if ((organizationId == null) || (applicationName == null)) { return null; } return createApplication(organizationId, applicationName, null); } @Override public UUID createApplication(UUID organizationId, String applicationName, Map<String, Object> properties) throws Exception { if ((organizationId == null) || (applicationName == null)) { return null; } if (properties == null) { properties = new HashMap<String, Object>(); } UUID applicationId = emf.createApplication(applicationName, properties); EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); properties.put("name", applicationName); Entity applicationEntity = em.create(applicationId, APPLICATION_INFO, properties); Map<String, CredentialsInfo> credentials = new HashMap<String, CredentialsInfo>(); credentials .put("secret", plainTextCredentials(generateOAuthSecretKey(AuthPrincipalType.APPLICATION))); em.addMapToDictionary(applicationEntity, DICTIONARY_CREDENTIALS, credentials); addApplicationToOrganization(organizationId, applicationId); UserInfo user = null; // if we call this method before the full stack is initialized // we'll get an exception try { user = SubjectUtils.getUser(); } catch (UnavailableSecurityManagerException e) { } if ((user != null) && user.isAdminUser()) { postOrganizationActivity(organizationId, user, "create", applicationEntity, "Application", applicationName, "<a mailto=\"" + user.getEmail() + "\">" + user.getName() + " (" + user.getEmail() + ")</a> created a new application named " + applicationName, null); } return applicationId; } @Override public OrganizationInfo getOrganizationForApplication(UUID applicationId) throws Exception { if (applicationId == null) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Results r = em.getConnectingEntities(applicationId, "owns", "group", Level.ALL_PROPERTIES); Entity entity = r.getEntity(); if (entity != null) { return new OrganizationInfo(entity.getUuid(), (String) entity.getProperty("path")); } return null; } @Override public BiMap<UUID, String> getApplicationsForOrganization( UUID organizationId) throws Exception { if (organizationId == null) { return null; } BiMap<UUID, String> applications = HashBiMap.create(); EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Results results = em.getConnectedEntities(organizationId, "owns", APPLICATION_INFO, Level.ALL_PROPERTIES); if (!results.isEmpty()) { for (Entity entity : results.getEntities()) { applications.put(entity.getUuid(), entity.getName()); } } return applications; } @Override public BiMap<UUID, String> getApplicationsForOrganizations( Set<UUID> organizationIds) throws Exception { if (organizationIds == null) { return null; } BiMap<UUID, String> applications = HashBiMap.create(); for (UUID organizationId : organizationIds) { BiMap<UUID, String> organizationApplications = getApplicationsForOrganization(organizationId); applications.putAll(organizationApplications); } return applications; } @Override public UUID addApplicationToOrganization(UUID organizationId, UUID applicationId) throws Exception { if ((organizationId == null) || (applicationId == null)) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.createConnection(new SimpleEntityRef("group", organizationId), "owns", new SimpleEntityRef(APPLICATION_INFO, applicationId)); return applicationId; } @Override public void deleteOrganizationApplication(UUID organizationId, UUID applicationId) throws Exception { // TODO Auto-generated method stub } @Override public void removeOrganizationApplication(UUID organizationId, UUID applicationId) throws Exception { // TODO Auto-generated method stub } @Override public ApplicationInfo getApplication(String applicationName) throws Exception { if (applicationName == null) { return null; } UUID applicationId = emf.lookupApplication(applicationName); if (applicationId == null) { return null; } return new ApplicationInfo(applicationId, applicationName.toLowerCase()); } @Override public ApplicationInfo getApplication(UUID applicationId) throws Exception { if (applicationId == null) { return null; } Entity entity = getApplicationEntityById(applicationId); if (entity != null) { return new ApplicationInfo(applicationId, entity.getName()); } return null; } @Override public ApplicationInfo getApplicationInfoFromAccessToken(String token) throws Exception { if (!AuthPrincipalType.APPLICATION.equals(AuthPrincipalType .getFromAccessToken(token))) { return null; } Entity entity = geEntityFromAccessToken(MANAGEMENT_APPLICATION_ID, token); return new ApplicationInfo(entity.getProperties()); } @Override public Entity getApplicationEntityById(UUID applicationId) throws Exception { if (applicationId == null) { return null; } EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); Entity entity = em.get(applicationId); return entity; } public String getSecret(UUID applicationId, AuthPrincipalType type, UUID id) throws Exception { EntityManager em = emf .getEntityManager(AuthPrincipalType.APPLICATION_USER .equals(type) ? applicationId : MANAGEMENT_APPLICATION_ID); if (AuthPrincipalType.ORGANIZATION.equals(type) || AuthPrincipalType.APPLICATION.equals(type)) { return getCredentialsSecret((CredentialsInfo) em .getDictionaryElementValue( new SimpleEntityRef(type.getEntityType(), id), DICTIONARY_CREDENTIALS, "secret")); } else if (AuthPrincipalType.ADMIN_USER.equals(type) || AuthPrincipalType.APPLICATION_USER.equals(type)) { return getCredentialsSecret((CredentialsInfo) em .getDictionaryElementValue( new SimpleEntityRef(type.getEntityType(), id), DICTIONARY_CREDENTIALS, "password")); } throw new IllegalArgumentException( "Must specify an admin user, organization or application principal"); } @Override public String getClientIdForOrganization(UUID organizationId) { return ClientCredentialsInfo.getClientIdForTypeAndUuid( AuthPrincipalType.ORGANIZATION, organizationId); } @Override public String getClientSecretForOrganization(UUID organizationId) throws Exception { return getSecret(MANAGEMENT_APPLICATION_ID, AuthPrincipalType.ORGANIZATION, organizationId); } @Override public String getClientIdForApplication(UUID applicationId) { return ClientCredentialsInfo.getClientIdForTypeAndUuid( AuthPrincipalType.APPLICATION, applicationId); } @Override public String getClientSecretForApplication(UUID applicationId) throws Exception { return getSecret(MANAGEMENT_APPLICATION_ID, AuthPrincipalType.APPLICATION, applicationId); } public String newSecretKey(AuthPrincipalType type, UUID id) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); String secret = generateOAuthSecretKey(type); em.addToDictionary(new SimpleEntityRef(type.getEntityType(), id), DICTIONARY_CREDENTIALS, "secret", plainTextCredentials(secret)); return secret; } @Override public String newClientSecretForOrganization(UUID organizationId) throws Exception { return newSecretKey(AuthPrincipalType.ORGANIZATION, organizationId); } @Override public String newClientSecretForApplication(UUID applicationId) throws Exception { return newSecretKey(AuthPrincipalType.APPLICATION, applicationId); } @Override public AccessInfo authorizeClient(String clientId, String clientSecret) throws Exception { if ((clientId == null) || (clientSecret == null)) { return null; } UUID uuid = getUUIDFromClientId(clientId); if (uuid == null) { return null; } AuthPrincipalType type = getTypeFromClientId(clientId); if (type == null) { return null; } AccessInfo access_info = null; if (clientSecret .equals(getSecret(MANAGEMENT_APPLICATION_ID, type, uuid))) { if (type.equals(AuthPrincipalType.APPLICATION)) { ApplicationInfo app = getApplication(uuid); access_info = new AccessInfo() .withExpiresIn(3600) .withAccessToken( getTokenForPrincipal(MANAGEMENT_APPLICATION_ID, type, uuid, null, true)) .withProperty("application", app.getId()); } else if (type.equals(AuthPrincipalType.ORGANIZATION)) { OrganizationInfo organization = getOrganizationByUuid(uuid); access_info = new AccessInfo() .withExpiresIn(3600) .withAccessToken( getTokenForPrincipal(MANAGEMENT_APPLICATION_ID, type, uuid, null, true)) .withProperty("organization", getOrganizationData(organization)); } } return access_info; } @Override public PrincipalCredentialsToken getPrincipalCredentialsTokenForClientCredentials( String clientId, String clientSecret) throws Exception { if ((clientId == null) || (clientSecret == null)) { return null; } UUID uuid = getUUIDFromClientId(clientId); if (uuid == null) { return null; } AuthPrincipalType type = getTypeFromClientId(clientId); if (type == null) { return null; } PrincipalCredentialsToken token = null; if (clientSecret .equals(getSecret(MANAGEMENT_APPLICATION_ID, type, uuid))) { if (type.equals(AuthPrincipalType.APPLICATION)) { ApplicationInfo app = getApplication(uuid); token = new PrincipalCredentialsToken(new ApplicationPrincipal( app), new ApplicationClientCredentials(clientId, clientSecret)); } else if (type.equals(AuthPrincipalType.ORGANIZATION)) { OrganizationInfo organization = getOrganizationByUuid(uuid); token = new PrincipalCredentialsToken( new OrganizationPrincipal(organization), new OrganizationClientCredentials(clientId, clientSecret)); } } return token; } public AccessInfo authorizeAppUser(String clientType, String clientId, String clientSecret) throws Exception { return null; } @Override public String getPasswordResetTokenForAdminUser(UUID userId) throws Exception { return getTokenForPrincipal(MANAGEMENT_APPLICATION_ID, ADMIN_USER, userId, "resetpw", true); } @Override public boolean checkPasswordResetTokenForAdminUser(UUID userId, String token) throws Exception { EntityRef userRef = null; try { userRef = getEntityRefFromAccessToken(MANAGEMENT_APPLICATION_ID, token, ADMIN_USER, 0, "resetpw", true); } catch (Exception e) { logger.error("Unable to verify token", e); } return (userRef != null) && userId.equals(userRef.getUuid()); } @Override public String getActivationTokenForAdminUser(UUID userId) throws Exception { return getTokenForPrincipal(MANAGEMENT_APPLICATION_ID, ADMIN_USER, userId, "activate", true); } @Override public boolean checkActivationTokenForAdminUser(UUID userId, String token) throws Exception { EntityRef userRef = getEntityRefFromAccessToken( MANAGEMENT_APPLICATION_ID, token, ADMIN_USER, 0, "activate", true); return (userRef != null) && userId.equals(userRef.getUuid()); } @Override public void activateAdminUser(UUID userId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(User.ENTITY_TYPE, userId), "activated", true); } @Override public void deactivateAdminUser(UUID userId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(User.ENTITY_TYPE, userId), "activated", false); } @Override public boolean isAdminUserActivated(UUID userId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); return Boolean.TRUE.equals(em.getProperty(new SimpleEntityRef( User.ENTITY_TYPE, userId), "activated")); } @Override public void enableAdminUser(UUID userId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(User.ENTITY_TYPE, userId), "disabled", false); } @Override public void disableAdminUser(UUID userId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(User.ENTITY_TYPE, userId), "disabled", true); } @Override public boolean isAdminUserEnabled(UUID userId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); return !Boolean.TRUE.equals(em.getProperty(new SimpleEntityRef( User.ENTITY_TYPE, userId), "disabled")); } private String emailMsg(Map<String, String> values, String propertyName) { return new StrSubstitutor(values).replace(properties .getProperty(propertyName)); } @Override public void sendAdminUserPasswordReminderEmail(UserInfo user) throws Exception { String token = getPasswordResetTokenForAdminUser(user.getUuid()); String reset_url = String.format(properties .getProperty("usergrid.admin.resetpw.url"), user.getUuid() .toString()) + "?token=" + token; sendHtmlMail( properties, user.getDisplayEmailAddress(), getPropertyValue(EMAIL_MAILER), "Password Reset", emailMsg(hashMap("reset_url", reset_url), EMAIL_ADMIN_PASSWORD_RESET)); } @Override public boolean newOrganizationsNeedSysAdminApproval() { return parseBoolean(properties .getProperty("usergrid.sysadmin.approve.organizations")); } @Override public boolean newAdminUsersNeedSysAdminApproval() { return parseBoolean(properties .getProperty("usergrid.sysadmin.approve.users")); } @Override public String getActivationTokenForOrganization(UUID organizationId) throws Exception { return getTokenForPrincipal(MANAGEMENT_APPLICATION_ID, AuthPrincipalType.ORGANIZATION, organizationId, "activate", true); } @Override public boolean checkActivationTokenForOrganization(UUID organizationId, String token) throws Exception { EntityRef organizationRef = getEntityRefFromAccessToken( MANAGEMENT_APPLICATION_ID, token, ORGANIZATION, 0, "activate", true); return (organizationRef != null) && organizationId.equals(organizationRef.getUuid()); } @Override public void sendOrganizationActivationEmail(OrganizationInfo organization) throws Exception { try { String token = getActivationTokenForOrganization(organization .getUuid()); String activation_url = String.format(properties .getProperty("usergrid.organization.activation.url"), organization.getUuid().toString()) + "?token=" + token; if (newOrganizationsNeedSysAdminApproval()) { activation_url += "&confirm=true"; sendHtmlMail( properties, getPropertyValue("usergrid.sysadmin.email"), getPropertyValue(EMAIL_MAILER), "Request For Organization Account Activation " + organization.getName(), emailMsg( hashMap("organization_name", organization.getName()).map( "activation_url", activation_url), EMAIL_SYSADMIN_ORGANIZATION_ACTIVATION)); } else { sendOrganizationEmail( organization, "Organization Account Confirmation", emailMsg( hashMap("organization_name", organization.getName()).map( "activation_url", activation_url), EMAIL_ORGANIZATION_ACTIVATION)); } } catch (Exception e) { logger.error( "Unable to send activation emails to " + organization.getName(), e); } } @Override public void sendOrganizationActivatedEmail(OrganizationInfo organization) throws Exception { sendOrganizationEmail( organization, "Organization Account Activated: " + organization.getName(), emailMsg(hashMap("organization_name", organization.getName()), EMAIL_ORGANIZATION_ACTIVATED)); } @Override public void sendOrganizationEmail(OrganizationInfo organization, String subject, String html) throws Exception { List<UserInfo> users = getAdminUsersForOrganization(organization .getUuid()); for (UserInfo user : users) { sendHtmlMail(properties, user.getDisplayEmailAddress(), getPropertyValue(EMAIL_MAILER), subject, html); } } @Override public void sendAdminUserActivationEmail(UserInfo user) throws Exception { String token = getActivationTokenForAdminUser(user.getUuid()); String activation_url = String.format(properties .getProperty("usergrid.admin.activation.url"), user.getUuid() .toString()) + "?token=" + token; if (newAdminUsersNeedSysAdminApproval()) { activation_url += "&confirm=true"; sendHtmlMail( properties, getPropertyValue("usergrid.sysadmin.email"), getPropertyValue(EMAIL_MAILER), "Request For User Account Activation " + user.getEmail(), emailMsg( hashMap("user_email", user.getEmail()).map( "activation_url", activation_url), EMAIL_SYSADMIN_ADMIN_ACTIVATION)); } else { sendAdminUserEmail( user, "User Account Confirmation: " + user.getEmail(), emailMsg( hashMap("user_email", user.getEmail()).map( "activation_url", activation_url), EMAIL_ADMIN_ACTIVATION)); } } @Override public void sendAdminUserActivatedEmail(UserInfo user) throws Exception { sendAdminUserEmail(user, "User Account Activated", getPropertyValue(EMAIL_ADMIN_ACTIVATED)); } @Override public void sendAdminUserEmail(UserInfo user, String subject, String html) throws Exception { sendHtmlMail(properties, user.getDisplayEmailAddress(), getPropertyValue(EMAIL_MAILER), subject, html); } @Override public void activateOrganization(UUID organizationId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(Group.ENTITY_TYPE, organizationId), "activated", true); List<UserInfo> users = getAdminUsersForOrganization(organizationId); for (UserInfo user : users) { if (!user.isActivated()) { activateAdminUser(user.getUuid()); } } } @Override public void deactivateOrganization(UUID organizationId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(Group.ENTITY_TYPE, organizationId), "activated", false); } @Override public boolean isOrganizationActivated(UUID organizationId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); return Boolean.TRUE.equals(em.getProperty(new SimpleEntityRef( Group.ENTITY_TYPE, organizationId), "activated")); } @Override public void enableOrganization(UUID organizationId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(Group.ENTITY_TYPE, organizationId), "disabled", false); } @Override public void disableOrganization(UUID organizationId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); em.setProperty(new SimpleEntityRef(Group.ENTITY_TYPE, organizationId), "disabled", true); } @Override public boolean isOrganizationEnabled(UUID organizationId) throws Exception { EntityManager em = emf.getEntityManager(MANAGEMENT_APPLICATION_ID); return !Boolean.TRUE.equals(em.getProperty(new SimpleEntityRef( Group.ENTITY_TYPE, organizationId), "disabled")); } @Override public void activateAppUser(UUID applicationId, UUID userId) throws Exception { EntityManager em = emf.getEntityManager(applicationId); em.setProperty(new SimpleEntityRef(User.ENTITY_TYPE, userId), "activated", true); } @Override public boolean checkActivationTokenForAppUser(UUID applicationId, UUID userId, String token) throws Exception { EntityRef userRef = getEntityRefFromAccessToken(applicationId, token, APPLICATION_USER, 0, "activate", true); return (userRef != null) && userId.equals(userRef.getUuid()); } @Override public boolean checkPasswordResetTokenForAppUser(UUID applicationId, UUID userId, String token) throws Exception { EntityRef userRef = null; try { userRef = getEntityRefFromAccessToken(applicationId, token, APPLICATION_USER, 0, "resetpw", true); } catch (Exception e) { logger.error("Unable to verify token", e); } return (userRef != null) && userId.equals(userRef.getUuid()); } @Override public String getAccessTokenForAppUser(UUID applicationId, UUID userId) throws Exception { return getTokenForPrincipal(applicationId, APPLICATION_USER, userId, null, true); } @Override public UserInfo getAppUserFromAccessToken(String token) throws Exception { AuthPrincipalInfo auth_principal = AuthPrincipalInfo .getFromAccessToken(token); if (AuthPrincipalType.APPLICATION_USER.equals(auth_principal.getType())) { UUID appId = auth_principal.getApplicationId(); if (appId != null) { EntityManager em = emf.getEntityManager(appId); Entity user = em.get(getEntityRefFromAccessToken(appId, token, APPLICATION_USER, MAX_TOKEN_AGE, null, true)); if (user != null) { return new UserInfo(appId, user.getProperties()); } } } return null; } @Override public User getAppUserByIdentifier(UUID applicationId, Identifier identifier) throws Exception { EntityManager em = emf.getEntityManager(applicationId); return em.get(em.getUserByIdentifier(identifier), User.class); } @Override public void sendAppUserPasswordReminderEmail(UUID applicationId, User user) throws Exception { String token = getPasswordResetTokenForAppUser(applicationId, user.getUuid()); String reset_url = String.format( properties.getProperty("usergrid.user.resetpw.url"), applicationId.toString(), user.getUuid().toString()) + "?token=" + token; sendHtmlMail( properties, user.getDisplayEmailAddress(), getPropertyValue(EMAIL_MAILER), "Password Reset", emailMsg(hashMap("reset_url", reset_url), EMAIL_USER_PASSWORD_RESET)); } @Override public void sendAppUserActivatedEmail(UUID applicationId, User user) throws Exception { sendAppUserEmail(user, "User Account Activated", getPropertyValue(EMAIL_USER_ACTIVATED)); } @Override public void sendAppUserActivationEmail(UUID applicationId, User user) throws Exception { String token = getActivationTokenForAppUser(applicationId, user.getUuid()); String activation_url = String.format( properties.getProperty("usergrid.user.activation.url"), applicationId.toString(), user.getUuid().toString()) + "?token=" + token; sendAppUserEmail( user, "User Account Confirmation: " + user.getEmail(), emailMsg(hashMap("activation_url", activation_url), EMAIL_USER_ACTIVATION)); } @Override public void setAppUserPassword(UUID applicationId, UUID userId, String newPassword) throws Exception { if ((userId == null) || (newPassword == null)) { return; } EntityManager em = emf.getEntityManager(applicationId); em.addToDictionary(new SimpleEntityRef(User.ENTITY_TYPE, userId), DICTIONARY_CREDENTIALS, "password", passwordCredentials(newPassword)); } @Override public void setAppUserPassword(UUID applicationId, UUID userId, String oldPassword, String newPassword) throws Exception { if ((userId == null) || (oldPassword == null) || (newPassword == null)) { return; } EntityManager em = emf.getEntityManager(applicationId); Entity user = em.get(userId); if (!checkPassword(oldPassword, (CredentialsInfo) em.getDictionaryElementValue(user, DICTIONARY_CREDENTIALS, "password"))) { logger.info("Old password doesn't match"); throw new IncorrectPasswordException(); } em.addToDictionary(user, DICTIONARY_CREDENTIALS, "password", passwordCredentials(newPassword)); } @Override public User verifyAppUserPasswordCredentials(UUID applicationId, String name, String password) throws Exception { User user = findUserEntity(applicationId, name); if (user == null) { return null; } EntityManager em = emf.getEntityManager(applicationId); if (checkPassword(password, (CredentialsInfo) em.getDictionaryElementValue(user, DICTIONARY_CREDENTIALS, "password"))) { if (!user.activated()) { throw new UnactivatedAdminUserException(); } if (user.disabled()) { throw new DisabledAdminUserException(); } return user; } return null; } public String getPasswordResetTokenForAppUser(UUID applicationId, UUID userId) throws Exception { return getTokenForPrincipal(applicationId, APPLICATION_USER, userId, "resetpw", true); } public void sendAppUserEmail(User user, String subject, String html) throws Exception { sendHtmlMail(properties, user.getDisplayEmailAddress(), getPropertyValue(EMAIL_MAILER), subject, html); } public String getActivationTokenForAppUser(UUID applicationId, UUID userId) throws Exception { return getTokenForPrincipal(applicationId, APPLICATION_USER, userId, "activate", true); } @Override public void setAppUserPin(UUID applicationId, UUID userId, String newPin) throws Exception { if ((userId == null) || (newPin == null)) { return; } EntityManager em = emf.getEntityManager(applicationId); em.addToDictionary(new SimpleEntityRef(User.ENTITY_TYPE, userId), DICTIONARY_CREDENTIALS, "pin", plainTextCredentials(newPin)); } @Override public void sendAppUserPin(UUID applicationId, UUID userId) throws Exception { EntityManager em = emf.getEntityManager(applicationId); User user = em.get(userId, User.class); if (user == null) { return; } if (user.getEmail() == null) { return; } String pin = getCredentialsSecret((CredentialsInfo) em .getDictionaryElementValue(user, DICTIONARY_CREDENTIALS, "pin")); sendHtmlMail(properties, user.getDisplayEmailAddress(), getPropertyValue(EMAIL_MAILER), "Your app pin", emailMsg(hashMap("pin", pin), EMAIL_USER_PIN_REQUEST)); } @Override public User verifyAppUserPinCredentials(UUID applicationId, String name, String pin) throws Exception { EntityManager em = emf.getEntityManager(applicationId); User user = findUserEntity(applicationId, name); if (user == null) { return null; } if (pin.equals(getCredentialsSecret((CredentialsInfo) em .getDictionaryElementValue(user, DICTIONARY_CREDENTIALS, "pin")))) { return user; } return null; } }
package edu.cmu.pocketsphinx; import static java.lang.String.format; import java.io.File; import java.util.Collection; import java.util.HashSet; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder.AudioSource; import android.os.*; import android.util.Log; import edu.cmu.pocketsphinx.Config; import edu.cmu.pocketsphinx.Decoder; import edu.cmu.pocketsphinx.Hypothesis; public class SpeechRecognizer { protected static final String TAG = SpeechRecognizer.class.getSimpleName(); private static final int MSG_START = 1; private static final int MSG_STOP = 2; private static final int MSG_CANCEL = 3; private static final int BUFFER_SIZE = 1024; private final Config config; private final Decoder decoder; private Thread recognizerThread; private final Handler mainHandler = new Handler(Looper.getMainLooper()); private final Collection<RecognitionListener> listeners = new HashSet<RecognitionListener>(); private final int sampleRate; protected SpeechRecognizer(Config config) { sampleRate = (int) config.getFloat("-samprate"); if (config.getFloat("-samprate") != sampleRate) throw new IllegalArgumentException("sampling rate must be integer"); this.config = config; decoder = new Decoder(config); } /** * Adds listener. */ public void addListener(RecognitionListener listener) { synchronized (listeners) { listeners.add(listener); } } /** * Removes listener. */ public void removeListener(RecognitionListener listener) { synchronized (listeners) { listeners.remove(listener); } } /** * Starts recognition. Does nothing if recognition is active. * * @return true if recognition was actually started */ public boolean startListening(String searchName) { if (null != recognizerThread) return false; Log.i(TAG, format("Start recognition \"%s\"", searchName)); decoder.setSearch(searchName); recognizerThread = new RecognizerThread(); recognizerThread.start(); return true; } private boolean stopRecognizerThread() { if (null == recognizerThread) return false; try { recognizerThread.interrupt(); recognizerThread.join(); } catch (InterruptedException e) { // Restore the interrupted status. Thread.currentThread().interrupt(); } recognizerThread = null; return true; } /** * Stops recognition. All listeners should receive final result if there is * any. Does nothing if recognition is not active. * * @return true if recognition was actually stopped */ public boolean stop() { boolean result = stopRecognizerThread(); if (result) Log.i(TAG, "Stop recognition"); return result; } /** * Cancels recogition. Listeners do not recevie final result. Does nothing * if recognition is not active. * * @return true if recognition was actually canceled */ public boolean cancel() { boolean result = stopRecognizerThread(); if (result) { Log.i(TAG, "Cancel recognition"); mainHandler.removeCallbacksAndMessages(null); } return result; } /** * Gets name of the currently active search. * * @return active search name or null if no search was started */ public String getSearchName() { return decoder.getSearch(); } public void addFsgSearch(String searchName, FsgModel fsgModel) { decoder.setFsg(searchName, fsgModel); } /** * Adds searches based on JSpeech grammar. * * @param name search name * @param file JSGF file */ public void addGrammarSearch(String name, File file) { Log.i(TAG, format("Load JSGF %s", file)); decoder.setGrammarSearch(name, file.getPath()); } /** * Adds search based on N-gram language model. * * @param name search name * @param file N-gram model file */ public void addNgramSearch(String name, File file) { Log.i(TAG, format("Load N-gram model %s", file)); decoder.setNgramSearch(name, file.getPath()); } /** * Adds search based on a single phrase. * * @param name search name * @param phrase search phrase */ public void addKeywordSearch(String name, String phrase) { decoder.setKws(name, phrase); } private final class RecognizerThread extends Thread { @Override public void run() { AudioRecord recorder = new AudioRecord(AudioSource.VOICE_RECOGNITION, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, 8192); // TODO:calculate properly decoder.startUtt(null); recorder.startRecording(); short[] buffer = new short[BUFFER_SIZE]; boolean vadState = decoder.getVadState(); while (!interrupted()) { int nread = recorder.read(buffer, 0, buffer.length); if (-1 == nread) { throw new RuntimeException("error reading audio buffer"); } else if (nread > 0) { decoder.processRaw(buffer, nread, false, false); if (decoder.getVadState() != vadState) { vadState = decoder.getVadState(); mainHandler.post(new VadStateChangeEvent(vadState)); } final Hypothesis hypothesis = decoder.hyp(); if (null != hypothesis) mainHandler.post(new ResultEvent(hypothesis, false)); } } recorder.stop(); int nread = recorder.read(buffer, 0, buffer.length); recorder.release(); decoder.processRaw(buffer, nread, false, false); decoder.endUtt(); // Remove all pending notifications. mainHandler.removeCallbacksAndMessages(null); final Hypothesis hypothesis = decoder.hyp(); if (null != hypothesis) mainHandler.post(new ResultEvent(hypothesis, true)); } } private abstract class RecognitionEvent implements Runnable { public void run() { RecognitionListener[] emptyArray = new RecognitionListener[0]; for (RecognitionListener listener : listeners.toArray(emptyArray)) execute(listener); } protected abstract void execute(RecognitionListener listener); } private class VadStateChangeEvent extends RecognitionEvent { private final boolean state; VadStateChangeEvent(boolean state) { this.state = state; } @Override protected void execute(RecognitionListener listener) { if (state) listener.onBeginningOfSpeech(); else listener.onEndOfSpeech(); } } private class ResultEvent extends RecognitionEvent { protected final Hypothesis hypothesis; private final boolean finalResult; ResultEvent(Hypothesis hypothesis, boolean finalResult) { this.hypothesis = hypothesis; this.finalResult = finalResult; } @Override protected void execute(RecognitionListener listener) { if (finalResult) listener.onResult(hypothesis); else listener.onPartialResult(hypothesis); } } } /* vim: set ts=4 sw=4: */
package org.verapdf.cli; import java.io.IOException; import org.verapdf.ReleaseDetails; import org.verapdf.cli.commands.VeraCliArgParser; import org.verapdf.pdfa.validation.ProfileDirectory; import org.verapdf.pdfa.validation.Profiles; import org.verapdf.pdfa.validation.ValidationProfile; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; /** * @author <a href="mailto:carl@openpreservation.org">Carl Wilson</a> * */ public final class VeraPdfCli { private static final String APP_NAME = "veraPDF"; private static final ReleaseDetails RELEASE_DETAILS = ReleaseDetails .getInstance(); private static final String FLAVOURS_HEADING = APP_NAME + " supported PDF/A profiles:"; private static final ProfileDirectory PROFILES = Profiles .getVeraProfileDirectory(); private VeraPdfCli() { // disable default constructor } /** * Main CLI entry point, process the command line arguments * * @param args * Java.lang.String array of command line args, to be processed * using Apache commons CLI. */ public static void main(final String[] args) { VeraCliArgParser cliArgParser = new VeraCliArgParser(); JCommander jCommander = new JCommander(cliArgParser); jCommander.setProgramName(APP_NAME); try { jCommander.parse(args); } catch (ParameterException e) { System.err.println(e.getMessage()); showVersionInfo(); jCommander.usage(); System.exit(1); } if (cliArgParser.isHelp()) { showVersionInfo(); jCommander.usage(); System.exit(0); } messagesFromParser(cliArgParser); try { VeraPdfCliProcessor processor = VeraPdfCliProcessor .createProcessorFromArgs(cliArgParser); processor.processPaths(cliArgParser.getPdfPaths()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void messagesFromParser(final VeraCliArgParser parser) { if (parser.listProfiles()) { listProfiles(); } if (parser.showVersion()) { showVersionInfo(); } } private static void listProfiles() { System.out.println(FLAVOURS_HEADING); for (ValidationProfile profile : PROFILES.getValidationProfiles()) { System.out.println(" " + profile.getPDFAFlavour().getId() + " - " + profile.getDetails().getName()); } System.out.println(); } private static void showVersionInfo() { System.out.println("Version: " + RELEASE_DETAILS.getVersion()); System.out.println("Built: " + RELEASE_DETAILS.getBuildDate()); System.out.println(RELEASE_DETAILS.getRights()); System.out.println(); } }
package org.telegram.abilitybots.api.bot; import com.google.common.collect.*; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.telegram.abilitybots.api.db.DBContext; import org.telegram.abilitybots.api.objects.*; import org.telegram.abilitybots.api.sender.DefaultSender; import org.telegram.abilitybots.api.sender.MessageSender; import org.telegram.abilitybots.api.sender.SilentSender; import org.telegram.abilitybots.api.toggle.AbilityToggle; import org.telegram.abilitybots.api.util.AbilityExtension; import org.telegram.abilitybots.api.util.AbilityUtils; import org.telegram.abilitybots.api.util.Pair; import org.telegram.abilitybots.api.util.Trio; import org.telegram.telegrambots.bots.DefaultAbsSender; import org.telegram.telegrambots.bots.DefaultBotOptions; import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberAdministrator; import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberOwner; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.Callable; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.collect.Sets.difference; import static java.lang.String.format; import static java.time.ZonedDateTime.now; import static java.util.Arrays.stream; import static java.util.Comparator.comparingInt; import static java.util.Objects.isNull; import static java.util.Optional.ofNullable; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.compile; import static java.util.stream.Collectors.toSet; import static org.telegram.abilitybots.api.objects.Locality.*; import static org.telegram.abilitybots.api.objects.MessageContext.newContext; import static org.telegram.abilitybots.api.objects.Privacy.*; import static org.telegram.abilitybots.api.objects.Stats.createStats; import static org.telegram.abilitybots.api.util.AbilityMessageCodes.*; import static org.telegram.abilitybots.api.util.AbilityUtils.*; /** * The <b>father</b> of all ability bots. Bots that need to utilize abilities need to extend this bot. * <p> * It's important to note that this bot strictly extends {@link DefaultAbsSender}. * <p> * All bots extending the {@link BaseAbilityBot} get implicit abilities: * <ul> * <li>/claim - Claims this bot</li> * <ul> * <li>Sets the user as the {@link Privacy#CREATOR} of the bot</li> * <li>Only the user with the ID returned by {@link BaseAbilityBot#creatorId()} can genuinely claim the bot</li> * </ul> * <li>/report - reports all user-defined commands (abilities)</li> * <ul> * <li>The same format acceptable by BotFather</li> * </ul> * <li>/commands - returns a list of all possible bot commands based on the privacy of the requesting user</li> * <li>/backup - returns a backup of the bot database</li> * <li>/recover - recovers the database</li> * <li>/promote <code>@username</code> - promotes user to bot admin</li> * <li>/demote <code>@username</code> - demotes bot admin to user</li> * <li>/ban <code>@username</code> - bans the user from accessing your bot commands and features</li> * <li>/unban <code>@username</code> - lifts the ban from the user</li> * </ul> * <p> * Additional information of the implicit abilities are present in the methods that declare them. * <p> * The two most important handles in the BaseAbilityBot are the {@link DBContext} <b><code>db</code></b> and the {@link MessageSender} <b><code>sender</code></b>. * All bots extending BaseAbilityBot can use both handles in their update consumers. * * @author Abbas Abou Daya */ @SuppressWarnings({"ConfusingArgumentToVarargsMethod", "UnusedReturnValue", "WeakerAccess", "unused", "ConstantConditions"}) public abstract class BaseAbilityBot extends DefaultAbsSender implements AbilityExtension { private static final Logger log = LoggerFactory.getLogger(BaseAbilityBot.class); protected static final String DEFAULT = "default"; // DB objects public static final String ADMINS = "ADMINS"; public static final String USERS = "USERS"; public static final String USER_ID = "USER_ID"; public static final String BLACKLIST = "BLACKLIST"; public static final String STATS = "ABILITYBOT_STATS"; // DB and sender protected final DBContext db; protected MessageSender sender; protected SilentSender silent; // Ability toggle private final AbilityToggle toggle; // Bot token and username private final String botToken; private final String botUsername; // Ability registry private final List<AbilityExtension> extensions = new ArrayList<>(); private Map<String, Ability> abilities; private Map<String, Stats> stats; // Reply registry private List<Reply> replies; public abstract long creatorId(); protected BaseAbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) { super(botOptions); this.botToken = botToken; this.botUsername = botUsername; this.db = db; this.toggle = toggle; this.sender = new DefaultSender(this); silent = new SilentSender(sender); } public void onRegister() { registerAbilities(); initStats(); } /** * @return the database of this bot */ public DBContext db() { return db; } /** * @return the message sender for this bot */ public MessageSender sender() { return sender; } /** * @return the silent sender for this bot */ public SilentSender silent() { return silent; } /** * @return the map of <ID,User> */ public Map<Long, User> users() { return db.getMap(USERS); } /** * @return the map of <Username,ID> */ public Map<String, Long> userIds() { return db.getMap(USER_ID); } /** * @return a blacklist containing all the IDs of the banned users */ public Set<Long> blacklist() { return db.getSet(BLACKLIST); } /** * @return an admin set of all the IDs of bot administrators */ public Set<Long> admins() { return db.getSet(ADMINS); } /** * @return a mapping of ability and reply names to their corresponding statistics */ public Map<String, Stats> stats() { return stats; } /** * @return the immutable map of <String,Ability> */ public Map<String, Ability> abilities() { return abilities; } /** * @return the immutable list carrying the embedded replies */ public List<Reply> replies() { return replies; } /** * This method contains the stream of actions that are applied on any update. * <p> * It will correctly handle addition of users into the DB and the execution of abilities and replies. * * @param update the update received by Telegram's API */ public void onUpdateReceived(Update update) { log.info(format("[%s] New update [%s] received at %s", botUsername, update.getUpdateId(), now())); log.info(update.toString()); long millisStarted = System.currentTimeMillis(); Stream.of(update) .filter(this::checkGlobalFlags) .filter(this::checkBlacklist) .map(this::addUser) .filter(this::filterReply) .filter(this::hasUser) .map(this::getAbility) .filter(this::validateAbility) .filter(this::checkPrivacy) .filter(this::checkLocality) .filter(this::checkInput) .filter(this::checkMessageFlags) .map(this::getContext) .map(this::consumeUpdate) .map(this::updateStats) .forEach(this::postConsumption); // Commit to DB now after all the actions have been dealt db.commit(); long processingTime = System.currentTimeMillis() - millisStarted; log.info(format("[%s] Processing of update [%s] ended at %s%n } public String getBotToken() { return botToken; } public String getBotUsername() { return botUsername; } public Privacy getPrivacy(Update update, long id) { return isCreator(id) ? CREATOR : isAdmin(id) ? ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ? GROUP_ADMIN : PUBLIC; } public boolean isGroupAdmin(Update update, long id) { return isGroupAdmin(getChatId(update), id); } public boolean isGroupAdmin(long chatId, long id) { GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build(); return silent.execute(admins) .orElse(new ArrayList<>()) .stream() .map(member -> { final String status = member.getStatus(); if (status.equals(ChatMemberOwner.STATUS) || status.equals(ChatMemberAdministrator.STATUS)) { return member.getUser().getId(); } return 0L; }) .anyMatch(member -> member == id); } public boolean isCreator(long id) { return id == creatorId(); } public boolean isAdmin(long id) { return admins().contains(id); } /** * Test the update against the provided global flags. The default implementation is a passthrough to all updates. * <p> * This method should be <b>overridden</b> if the user wants to restrict bot usage to only certain updates. * * @param update a Telegram {@link Update} * @return <tt>true</tt> if the update satisfies the global flags */ protected boolean checkGlobalFlags(Update update) { return true; } protected String getCommandPrefix() { return "/"; } protected String getCommandRegexSplit() { return " "; } protected boolean allowContinuousText() { return false; } protected void addExtension(AbilityExtension extension) { this.extensions.add(extension); } protected void addExtensions(AbilityExtension... extensions) { this.extensions.addAll(Arrays.asList(extensions)); } protected void addExtensions(Collection<AbilityExtension> extensions) { this.extensions.addAll(extensions); } /** * Registers the declared abilities using method reflection. Also, replies are accumulated using the built abilities and standalone methods that return a Reply. * <p> * <b>Only abilities and replies with the <u>public</u> accessor are registered!</b> */ private void registerAbilities() { try { // Collect all classes that implement AbilityExtension declared in the bot extensions.addAll(stream(getClass().getMethods()) .filter(checkReturnType(AbilityExtension.class)) .map(returnExtension(this)) .collect(Collectors.toList())); // Add the bot itself as it is an AbilityExtension extensions.add(this); DefaultAbilities defaultAbs = new DefaultAbilities(this); Stream<Ability> defaultAbsStream = stream(DefaultAbilities.class.getMethods()) .filter(checkReturnType(Ability.class)) .map(returnAbility(defaultAbs)) .filter(ab -> !toggle.isOff(ab)) .map(toggle::processAbility); // Extract all abilities from every single extension instance abilities = Stream.concat(defaultAbsStream, extensions.stream() .flatMap(ext -> stream(ext.getClass().getMethods()) .filter(checkReturnType(Ability.class)) .map(returnAbility(ext)))) // Abilities are immutable, build it respectively .collect(ImmutableMap::<String, Ability>builder, (b, a) -> b.put(a.name(), a), (b1, b2) -> b1.putAll(b2.build())) .build(); // Extract all replies from every single extension instance Stream<Reply> extensionReplies = extensions.stream() .flatMap(ext -> stream(ext.getClass().getMethods()) .filter(checkReturnType(Reply.class)) .map(returnReply(ext))) .flatMap(Reply::stream); // Extract all replies from extension instances methods, returning ReplyCollection Stream<Reply> extensionCollectionReplies = extensions.stream() .flatMap(extension -> stream(extension.getClass().getMethods()) .filter(checkReturnType(ReplyCollection.class)) .map(returnReplyCollection(extension)) .flatMap(ReplyCollection::stream)); // Replies can be standalone or attached to abilities, fetch those too Stream<Reply> abilityReplies = abilities.values().stream() .flatMap(ability -> ability.replies().stream()) .flatMap(Reply::stream); // Now create the replies registry (list) replies = Stream.of(abilityReplies, extensionReplies, extensionCollectionReplies) .flatMap(replyStream -> replyStream) .collect( ImmutableList::<Reply>builder, Builder::add, (b1, b2) -> b1.addAll(b2.build())) .build(); } catch (IllegalStateException e) { log.error("Duplicate names found while registering abilities. Make sure that the abilities declared don't clash with the reserved ones.", e); throw new RuntimeException(e); } } private void initStats() { Set<String> enabledStats = Stream.concat( replies.stream().filter(Reply::statsEnabled).map(Reply::name), abilities.entrySet().stream() .filter(entry -> entry.getValue().statsEnabled()) .map(Map.Entry::getKey)).collect(toSet()); stats = db.getMap(STATS); Set<String> toBeRemoved = difference(stats.keySet(), enabledStats); toBeRemoved.forEach(stats::remove); enabledStats.forEach(abName -> stats.computeIfAbsent(abName, name -> createStats(abName, 0))); } /** * @param clazz the type to be tested * @return a predicate testing the return type of the method corresponding to the class parameter */ private static Predicate<Method> checkReturnType(Class<?> clazz) { return method -> clazz.isAssignableFrom(method.getReturnType()); } /** * Invokes the method and retrieves its return {@link Reply}. * * @param obj a bot or extension that this method is invoked with * @return a {@link Function} which returns the {@link Reply} returned by the given method */ private Function<? super Method, AbilityExtension> returnExtension(Object obj) { return method -> { try { return (AbilityExtension) method.invoke(obj); } catch (IllegalAccessException | InvocationTargetException e) { log.error("Could not add ability extension", e); throw new RuntimeException(e); } }; } /** * Invokes the method and retrieves its return {@link Ability}. * * @param obj a bot or extension that this method is invoked with * @return a {@link Function} which returns the {@link Ability} returned by the given method */ private static Function<? super Method, Ability> returnAbility(Object obj) { return method -> { try { return (Ability) method.invoke(obj); } catch (IllegalAccessException | InvocationTargetException e) { log.error("Could not add ability", e); throw new RuntimeException(e); } }; } /** * Invokes the method and retrieves its return {@link Reply}. * * @param obj a bot or extension that this method is invoked with * @return a {@link Function} which returns the {@link Reply} returned by the given method */ private static Function<? super Method, Reply> returnReply(Object obj) { return method -> { try { return (Reply) method.invoke(obj); } catch (IllegalAccessException | InvocationTargetException e) { log.error("Could not add reply", e); throw new RuntimeException(e); } }; } /** * Invokes the method and retrieves its return {@link ReplyCollection}. * * @param obj a bot or extension that this method is invoked with * @return a {@link Function} which returns the {@link ReplyCollection} returned by the given method */ private static Function<? super Method, ReplyCollection> returnReplyCollection(Object obj) { return method -> { try { return (ReplyCollection) method.invoke(obj); } catch (IllegalAccessException | InvocationTargetException e) { log.error("Could not add Reply Collection", e); throw new RuntimeException(e); } }; } private void postConsumption(Pair<MessageContext, Ability> pair) { ofNullable(pair.b().postAction()) .ifPresent(consumer -> consumer.accept(pair.a())); } Pair<MessageContext, Ability> consumeUpdate(Pair<MessageContext, Ability> pair) { pair.b().action().accept(pair.a()); return pair; } Pair<MessageContext, Ability> updateStats(Pair<MessageContext, Ability> pair) { Ability ab = pair.b(); if (ab.statsEnabled()) { updateStats(pair.b().name()); } return pair; } private void updateReplyStats(Reply reply) { if (reply.statsEnabled()) { updateStats(reply.name()); } } void updateStats(String name) { Stats statsObj = stats.get(name); statsObj.hit(); stats.put(name, statsObj); } Pair<MessageContext, Ability> getContext(Trio<Update, Ability, String[]> trio) { Update update = trio.a(); User user = AbilityUtils.getUser(update); return Pair.of(newContext(update, user, getChatId(update), this, trio.c()), trio.b()); } boolean checkBlacklist(Update update) { User user = getUser(update); if (isNull(user)) { return true; } long id = user.getId(); return id == creatorId() || !blacklist().contains(id); } boolean checkInput(Trio<Update, Ability, String[]> trio) { String[] tokens = trio.c(); int abilityTokens = trio.b().tokens(); boolean isOk = abilityTokens == 0 || (tokens.length > 0 && tokens.length == abilityTokens); if (!isOk) silent.send( getLocalizedMessage( CHECK_INPUT_FAIL, AbilityUtils.getUser(trio.a()).getLanguageCode(), abilityTokens, abilityTokens == 1 ? "input" : "inputs"), getChatId(trio.a())); return isOk; } boolean checkLocality(Trio<Update, Ability, String[]> trio) { Update update = trio.a(); Locality locality = isUserMessage(update) ? USER : GROUP; Locality abilityLocality = trio.b().locality(); boolean isOk = abilityLocality == ALL || locality == abilityLocality; if (!isOk) silent.send( getLocalizedMessage( CHECK_LOCALITY_FAIL, AbilityUtils.getUser(trio.a()).getLanguageCode(), abilityLocality.toString().toLowerCase()), getChatId(trio.a())); return isOk; } boolean checkPrivacy(Trio<Update, Ability, String[]> trio) { Update update = trio.a(); User user = AbilityUtils.getUser(update); Privacy privacy; long id = user.getId(); privacy = getPrivacy(update, id); boolean isOk = privacy.compareTo(trio.b().privacy()) >= 0; if (!isOk) silent.send( getLocalizedMessage( CHECK_PRIVACY_FAIL, AbilityUtils.getUser(trio.a()).getLanguageCode()), getChatId(trio.a())); return isOk; } boolean validateAbility(Trio<Update, Ability, String[]> trio) { return trio.b() != null; } Trio<Update, Ability, String[]> getAbility(Update update) { // Handle updates without messages // Passing through this function means that the global flags have passed Message msg = update.getMessage(); if (!update.hasMessage() || !msg.hasText()) return Trio.of(update, abilities.get(DEFAULT), new String[]{}); Ability ability; String[] tokens; if (allowContinuousText()) { String abName = abilities.keySet().stream() .filter(name -> msg.getText().startsWith(format("%s%s", getCommandPrefix(), name))) .max(comparingInt(String::length)) .orElse(DEFAULT); tokens = msg.getText() .replaceFirst(getCommandPrefix() + abName, "") .split(getCommandRegexSplit()); ability = abilities.get(abName); } else { tokens = msg.getText().split(getCommandRegexSplit()); if (tokens[0].startsWith(getCommandPrefix())) { String abilityToken = stripBotUsername(tokens[0].substring(1)).toLowerCase(); ability = abilities.get(abilityToken); tokens = Arrays.copyOfRange(tokens, 1, tokens.length); } else { ability = abilities.get(DEFAULT); } } return Trio.of(update, ability, tokens); } private String stripBotUsername(String token) { return compile(format("@%s", botUsername), CASE_INSENSITIVE) .matcher(token) .replaceAll(""); } Update addUser(Update update) { User endUser = AbilityUtils.getUser(update); if (endUser.equals(EMPTY_USER)) { // Can't add an empty user, return the update as is return update; } users().compute(endUser.getId(), (id, user) -> { if (user == null) { updateUserId(user, endUser); return endUser; } if (!user.equals(endUser)) { updateUserId(user, endUser); return endUser; } return user; }); return update; } private boolean hasUser(Update update) { // Valid updates without users should return an empty user // Updates that are not recognized by the getUser method will throw an exception return !AbilityUtils.getUser(update).equals(EMPTY_USER); } private void updateUserId(User oldUser, User newUser) { if (oldUser != null && oldUser.getUserName() != null) { // Remove old username -> ID userIds().remove(oldUser.getUserName()); } if (newUser.getUserName() != null) { // Add new mapping with the new username userIds().put(newUser.getUserName().toLowerCase(), newUser.getId()); } } boolean filterReply(Update update) { return replies.stream() .filter(reply -> runSilently(() -> reply.isOkFor(update), reply.name())) .map(reply -> runSilently(() -> { reply.actOn(this, update); updateReplyStats(reply); return false; }, reply.name())) .reduce(true, Boolean::logicalAnd); } boolean runSilently(Callable<Boolean> callable, String name) { try { return callable.call(); } catch(Exception ex) { String msg = format("Reply [%s] failed to check for conditions. " + "Make sure you're safeguarding against all possible updates.", name); if (log.isDebugEnabled()) { log.error(msg, ex); } else { log.error(msg); } } return false; } boolean checkMessageFlags(Trio<Update, Ability, String[]> trio) { Ability ability = trio.b(); Update update = trio.a(); // The following variable is required to avoid bug #JDK-8044546 BiFunction<Boolean, Predicate<Update>, Boolean> flagAnd = (flag, nextFlag) -> flag && nextFlag.test(update); return ability.flags().stream() .reduce(true, flagAnd, Boolean::logicalAnd); } }
package javax.jmdns.impl.tasks; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import javax.jmdns.impl.DNSConstants; import javax.jmdns.impl.DNSOutgoing; import javax.jmdns.impl.DNSState; import javax.jmdns.impl.JmDNSImpl; import javax.jmdns.impl.ServiceInfoImpl; /** * The TextAnnouncer sends an accumulated query of all announces, and advances * the state of all serviceInfos, for which it has sent an announce. * The TextAnnouncer also sends announcements and advances the state of JmDNS itself. * <p/> * When the announcer has run two times, it finishes. */ public class TextAnnouncer extends TimerTask { static Logger logger = Logger.getLogger(TextAnnouncer.class.getName()); private final JmDNSImpl jmDNSImpl; /** * The state of the announcer. */ DNSState taskState = DNSState.ANNOUNCING_1; public TextAnnouncer(JmDNSImpl jmDNSImpl) { this.jmDNSImpl = jmDNSImpl; // Associate host to this, if it needs announcing if (this.jmDNSImpl.getState() == DNSState.ANNOUNCING_1) { this.jmDNSImpl.setTask(this); } // Associate services to this, if they need announcing synchronized (this.jmDNSImpl) { for (Iterator s = this.jmDNSImpl.getServices().values().iterator(); s.hasNext();) { ServiceInfoImpl info = (ServiceInfoImpl) s.next(); if (info.getState() == DNSState.ANNOUNCING_1) { info.setTask(this); } } } } public void start(Timer timer) { timer.schedule(this, DNSConstants.ANNOUNCE_WAIT_INTERVAL, DNSConstants.ANNOUNCE_WAIT_INTERVAL); } public boolean cancel() { // Remove association from host to this if (this.jmDNSImpl.getTask() == this) { this.jmDNSImpl.setTask(null); } // Remove associations from services to this synchronized (this.jmDNSImpl) { for (Iterator i = this.jmDNSImpl.getServices().values().iterator(); i.hasNext();) { ServiceInfoImpl info = (ServiceInfoImpl) i.next(); if (info.getTask() == this) { info.setTask(null); } } } return super.cancel(); } public void run() { DNSOutgoing out = null; try { // send announces for services // Defensively copy the services into a local list, // to prevent race conditions with methods registerService // and unregisterService. List list; synchronized (this.jmDNSImpl) { list = new ArrayList(this.jmDNSImpl.getServices().values()); } for (Iterator i = list.iterator(); i.hasNext();) { ServiceInfoImpl info = (ServiceInfoImpl) i.next(); synchronized (info) { if (info.getState().isAnnouncing() && info.getTask() == this) { info.advanceState(); logger.finer("run() JmDNS announcing " + info.getQualifiedName() + " state " + info.getState()); if (out == null) { out = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA); } info.addTextAnswer(out, DNSConstants.DNS_TTL); } } } if (out != null) { logger.finer("run() JmDNS announcing #" + taskState); this.jmDNSImpl.send(out); } else { // If we have nothing to send, another timer taskState ahead // of us has done the job for us. We can cancel. cancel(); } } catch (Throwable e) { logger.log(Level.WARNING, "run() exception ", e); this.jmDNSImpl.recover(); } taskState = taskState.advance(); if (!taskState.isAnnouncing()) { cancel(); this.jmDNSImpl.startRenewer(); } } }
package org.openlmis.pageobjects; import com.thoughtworks.selenium.SeleneseTestNgHelper; import org.openlmis.UiUtils.DBWrapper; import org.openlmis.UiUtils.TestWebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; import java.io.IOException; import java.sql.SQLException; public class InitiateRnRPage extends Page { @FindBy(how = How.XPATH, using = "//div[@id='requisition-header']/h2") private static WebElement requisitionHeader; @FindBy(how = How.XPATH, using = "//div[@id='requisition-header']/div[@class='info-box']/div[@class='row-fluid'][1]/div[1]") private static WebElement facilityLabel; @FindBy(how = How.XPATH, using = "//input[@value='Save']") private static WebElement saveButton; @FindBy(how = How.XPATH, using = "//input[@value='Submit']") private static WebElement submitButton; @FindBy(how = How.XPATH, using = "//input[@value='Authorize']") private static WebElement authorizeButton; @FindBy(how = How.XPATH, using = "//div[@id='saveSuccessMsgDiv' and @openlmis-message='message']") private static WebElement successMessage; @FindBy(how = How.XPATH, using = "//div[@id='submitSuccessMsgDiv' and @openlmis-message='submitMessage']") private static WebElement submitSuccessMessage; @FindBy(how = How.XPATH, using = "//div[@id='submitFailMessage' and @openlmis-message='submitError']") private static WebElement submitErrorMessage; @FindBy(how = How.ID, using = "A_0") private static WebElement beginningBalance; @FindBy(how = How.ID, using = "B_0") private static WebElement quantityReceived; @FindBy(how = How.ID, using = "C_0") private static WebElement quantityDispensed; @FindBy(how = How.ID, using = "D_0") private static WebElement lossesAndAdjustments; @FindBy(how = How.ID, using = "E_7") private static WebElement stockOnHand; @FindBy(how = How.ID, using = "F_0") private static WebElement newPatient; @FindBy(how = How.XPATH, using = "//table[@id='fullSupplyTable']/tbody/tr[1]/td[13]/ng-switch/span/ng-switch/span") private static WebElement maximumStockQuantity; @FindBy(how = How.XPATH, using = "//table[@id='fullSupplyTable']/tbody/tr[1]/td[14]/ng-switch/span/ng-switch/span") private static WebElement caculatedOrderQuantity; @FindBy(how = How.ID, using = "J_0") private static WebElement requestedQuantity; @FindBy(how = How.XPATH, using = "//table[@id='fullSupplyTable']/tbody/tr[1]/td[11]/ng-switch/span/ng-switch/span") private static WebElement adjustedTotalConsumption; @FindBy(how = How.XPATH, using = "//table[@id='fullSupplyTable']/tbody/tr[1]/td[12]/ng-switch/span/ng-switch/span") private static WebElement amc; @FindBy(how = How.XPATH, using = "//table[@id='fullSupplyTable']/tbody/tr[1]/td[20]/ng-switch/span/ng-switch/span") private static WebElement totalCost; @FindBy(how = How.XPATH, using = "//table[@id='fullSupplyTable']/tbody/tr[1]/td[19]/ng-switch/span/ng-switch/span") private static WebElement pricePerPack; @FindBy(how = How.XPATH, using = "//table[@id='fullSupplyTable']/tbody/tr[1]/td[18]/ng-switch/span/ng-switch/span") private static WebElement packsToShip; @FindBy(how = How.XPATH, using = "//table[@id='nonFullSupplyTable']/tbody/tr/td[18]/ng-switch/span") private static WebElement packsToShipNonFullSupply; @FindBy(how = How.XPATH, using = "//table[@id='nonFullSupplyTable']/tbody/tr/td[19]/ng-switch/span/span[2]") private static WebElement pricePerPackNonFullSupply; @FindBy(how = How.XPATH, using = "//table[@id='nonFullSupplyTable']/tbody/tr/td[20]/ng-switch/span/span[2]") private static WebElement totalCostNonFullSupply; @FindBy(how = How.XPATH, using = "//span[@id='fullSupplyItemsCost']") private static WebElement totalCostFullSupplyFooter; @FindBy(how = How.XPATH, using = "//span[@id='nonFullSupplyItemsCost']") private static WebElement totalCostNonFullSupplyFooter; @FindBy(how = How.XPATH, using = "//span[@id='totalCost']") private static WebElement totalCostFooter; @FindBy(how = How.ID, using = "W_0") private static WebElement requestedQuantityExplanation; @FindBy(how = How.ID, using = "X_0") private static WebElement totalStockOutDays; @FindBy(how = How.XPATH, using = "//a[@class='rnr-adjustment']") private static WebElement addDescription; @FindBy(how = How.XPATH, using = "//div[@class='adjustment-field']/div[@class='row-fluid']/div[@class='span5']/select") private static WebElement lossesAndAdjustmentSelect; @FindBy(how = How.XPATH, using = "//input[@ng-model='lossAndAdjustment.quantity']") private static WebElement quantityAdj; @FindBy(how = How.ID, using = "addNonFullSupply") private static WebElement addButtonNonFullSupply; @FindBy(how = How.XPATH, using = "//table[@id='nonFullSupplyTable']/tbody/tr/td[2]/ng-switch/span") private static WebElement productDescriptionNonFullSupply; @FindBy(how = How.XPATH, using = "//table[@id='nonFullSupplyTable']/tbody/tr/td[1]/ng-switch/span") private static WebElement productCodeNonFullSupply; @FindBy(how = How.XPATH, using = "//div[@class='adjustment-list']/ul/li/span[@class='tpl-adjustment-type ng-binding']") private static WebElement adjList; @FindBy(how = How.XPATH, using = "//input[@id='D_6_0']") private static WebElement adjListValue; @FindBy(how = How.XPATH, using = "//div[@class='adjustment-total clearfix alert alert-warning']") private static WebElement totalAdj; @FindBy(how = How.XPATH, using = "//input[@value='Done']") private static WebElement doneButton; @FindBy(how = How.XPATH, using = "//span[@class='alert alert-warning reason-request']") private static WebElement requestedQtyWarningMessage; @FindBy(how = How.XPATH, using = "//div[@class='info-box']/div[2]/div[3]") private static WebElement reportingPeriodInitRnRScreen; @FindBy(how = How.XPATH, using = "//input[@value='Add']") private static WebElement addNonFullSupplyButton; @FindBy(how = How.ID, using = "nonFullSupplyTab") private static WebElement nonFullSupplyTab; @FindBy(how = How.ID, using = "fullSupplyTab") private static WebElement fullSupplyTab; @FindBy(how = How.XPATH, using = "//input[@id='J_undefined']") private static WebElement requestedQuantityNonFullSupply; @FindBy(how = How.XPATH, using = "//input[@id='W_undefined']") private static WebElement requestedQuantityExplanationNonFullSupply; @FindBy(how = How.XPATH, using = "//select[@id='nonFullSupplyProductsName']") private static WebElement productDropDown; @FindBy(how = How.XPATH, using = "//select[@id='nonFullSupplyProductsCode']") private static WebElement productCodeDropDown; @FindBy(how = How.NAME, using = "newNonFullSupply.quantityRequested") private static WebElement requestedQuantityField; @FindBy(how = How.ID, using = "reasonForRequestedQuantity") private static WebElement requestedQuantityExplanationField; @FindBy(how = How.XPATH, using = "//input[@value='Add']") private static WebElement addButton; @FindBy(how = How.XPATH, using = "//input[@ng-click='addNonFullSupplyLineItem()']") private static WebElement addButtonEnabled; @FindBy(how = How.XPATH, using = "//input[@value='Close']") private static WebElement closeButton; String successText = "R&R saved successfully!"; public InitiateRnRPage(TestWebDriver driver) throws IOException { super(driver); PageFactory.initElements(new AjaxElementLocatorFactory(testWebDriver.getDriver(), 10), this); testWebDriver.setImplicitWait(25); } public void verifyRnRHeader(String FCode, String FName, String FCstring, String program, String periodDetails) { testWebDriver.waitForElementToAppear(requisitionHeader); String headerText = testWebDriver.getText(requisitionHeader); SeleneseTestNgHelper.assertTrue(headerText.contains("Report and Requisition for " + program)); String facilityText = testWebDriver.getText(facilityLabel); SeleneseTestNgHelper.assertTrue(facilityText.contains(FCode + FCstring + " - " + FName + FCstring)); SeleneseTestNgHelper.assertEquals(reportingPeriodInitRnRScreen.getText().trim().substring("Reporting Period: ".length()), periodDetails.trim()); } public void enterBeginningBalance(String A) { testWebDriver.sleep(1000); testWebDriver.waitForElementToAppear(beginningBalance); beginningBalance.sendKeys(A); String beginningBalanceValue = testWebDriver.getAttribute(beginningBalance, "value"); SeleneseTestNgHelper.assertEquals(beginningBalanceValue, A); } public void enterQuantityReceived(String B) { testWebDriver.waitForElementToAppear(quantityReceived); quantityReceived.sendKeys(B); String quantityReceivedValue = testWebDriver.getAttribute(quantityReceived, "value"); SeleneseTestNgHelper.assertEquals(quantityReceivedValue, B); } public void enterQuantityDispensed(String C) { testWebDriver.waitForElementToAppear(quantityDispensed); quantityDispensed.sendKeys(C); String quantityDispensedValue = testWebDriver.getAttribute(quantityDispensed, "value"); SeleneseTestNgHelper.assertEquals(quantityDispensedValue, C); } public void enterLossesAndAdjustments(String adj) { testWebDriver.waitForElementToAppear(addDescription); addDescription.click(); testWebDriver.waitForElementToAppear(lossesAndAdjustmentSelect); testWebDriver.selectByVisibleText(lossesAndAdjustmentSelect, "Transfer In"); testWebDriver.waitForElementToAppear(quantityAdj); quantityAdj.clear(); quantityAdj.sendKeys(adj); addButton.click(); testWebDriver.waitForElementToAppear(adjList); String labelAdj = testWebDriver.getText(adjList); SeleneseTestNgHelper.assertEquals(labelAdj.trim(), "Transfer In"); String adjValue = testWebDriver.getAttribute(adjListValue, "value"); SeleneseTestNgHelper.assertEquals(adjValue, adj); testWebDriver.waitForElementToAppear(totalAdj); String totalAdjValue = testWebDriver.getText(totalAdj); SeleneseTestNgHelper.assertEquals(totalAdjValue.substring("Total ".length()), adj); doneButton.click(); testWebDriver.sleep(1000); } public void calculateAndVerifyStockOnHand(Integer A, Integer B, Integer C, Integer D) { enterBeginningBalance(A.toString()); enterQuantityReceived(B.toString()); enterQuantityDispensed(C.toString()); enterLossesAndAdjustments(D.toString()); beginningBalance.click(); testWebDriver.waitForElementToAppear(stockOnHand); Integer StockOnHand = A + B - C + D; testWebDriver.sleep(1000); String stockOnHandValue = stockOnHand.getText(); String StockOnHandValue = StockOnHand.toString(); SeleneseTestNgHelper.assertEquals(stockOnHandValue, StockOnHandValue); } public void enterAndVerifyRequestedQuantityExplanation(Integer A) { String expectedWarningMessage = "Please enter a reason"; testWebDriver.waitForElementToAppear(requestedQuantity); requestedQuantity.sendKeys(A.toString()); testWebDriver.waitForElementToAppear(requestedQtyWarningMessage); String warningMessage = testWebDriver.getText(requestedQtyWarningMessage); SeleneseTestNgHelper.assertEquals(warningMessage.trim(), expectedWarningMessage); requestedQuantityExplanation.sendKeys("Due to bad climate"); testWebDriver.sleep(1000); } public void enterValuesAndVerifyCalculatedOrderQuantity(Integer F, Integer X, Integer N, Integer P, Integer H, Integer I) { testWebDriver.waitForElementToAppear(newPatient); newPatient.sendKeys(F.toString()); testWebDriver.waitForElementToAppear(totalStockOutDays); totalStockOutDays.sendKeys(X.toString()); testWebDriver.waitForElementToAppear(adjustedTotalConsumption); String actualAdjustedTotalConsumption = testWebDriver.getText(adjustedTotalConsumption); SeleneseTestNgHelper.assertEquals(actualAdjustedTotalConsumption, N.toString()); String actualAmc = testWebDriver.getText(amc); SeleneseTestNgHelper.assertEquals(actualAmc.trim(), P.toString()); String actualMaximumStockQuantity = testWebDriver.getText(maximumStockQuantity); SeleneseTestNgHelper.assertEquals(actualMaximumStockQuantity.trim(), H.toString()); String actualCalculatedOrderQuantity = testWebDriver.getText(caculatedOrderQuantity); SeleneseTestNgHelper.assertEquals(actualCalculatedOrderQuantity.trim(), I.toString()); testWebDriver.sleep(1000); } public void verifyPacksToShip(Integer V) { testWebDriver.waitForElementToAppear(packsToShip); String actualPacksToShip = testWebDriver.getText(packsToShip); SeleneseTestNgHelper.assertEquals(actualPacksToShip.trim(), V.toString()); testWebDriver.sleep(500); } public void calculateAndVerifyTotalCost() { testWebDriver.waitForElementToAppear(packsToShip); String actualPacksToShip = testWebDriver.getText(packsToShip); testWebDriver.waitForElementToAppear(pricePerPack); String actualPricePerPack = testWebDriver.getText(pricePerPack).substring(1); Float actualTotalCost = Float.parseFloat(actualPacksToShip) * Float.parseFloat(actualPricePerPack); SeleneseTestNgHelper.assertEquals(actualTotalCost.toString() + "0", totalCost.getText().substring(1)); testWebDriver.sleep(500); } public void calculateAndVerifyTotalCostNonFullSupply() { testWebDriver.waitForElementToAppear(packsToShipNonFullSupply); String actualPacksToShip = testWebDriver.getText(packsToShipNonFullSupply); testWebDriver.waitForElementToAppear(pricePerPackNonFullSupply); String actualPricePerPack = testWebDriver.getText(pricePerPackNonFullSupply); Float actualTotalCost = Float.parseFloat(actualPacksToShip.trim()) * Float.parseFloat(actualPricePerPack.trim()); SeleneseTestNgHelper.assertEquals(actualTotalCost.toString() + "0", totalCostNonFullSupply.getText().trim()); testWebDriver.sleep(500); } public void verifyCostOnFooter() { testWebDriver.waitForElementToAppear(totalCostFullSupplyFooter); String totalCostFullSupplyFooterValue = testWebDriver.getText(totalCostFullSupplyFooter); testWebDriver.waitForElementToAppear(totalCostNonFullSupplyFooter); String totalCostNonFullSupplyFooterValue = testWebDriver.getText(totalCostNonFullSupplyFooter); Float actualTotalCost = Float.parseFloat(totalCostFullSupplyFooterValue.trim()) + Float.parseFloat(totalCostNonFullSupplyFooterValue.trim()); SeleneseTestNgHelper.assertEquals(actualTotalCost.toString() + "0", totalCostFooter.getText().trim()); testWebDriver.sleep(500); } public void addNonFullSupplyLineItems(String requestedQuantityValue, String requestedQuantityExplanationValue, String productPrimaryName, String productCode) throws IOException, SQLException { testWebDriver.waitForElementToAppear(nonFullSupplyTab); nonFullSupplyTab.click(); DBWrapper dbWrapper = new DBWrapper(); String nonFullSupplyItems = dbWrapper.fetchNonFullSupplyData(productCode, "2", "1"); testWebDriver.waitForElementToAppear(addNonFullSupplyButton); testWebDriver.sleep(1000); addNonFullSupplyButton.click(); testWebDriver.sleep(1000); testWebDriver.waitForElementToAppear(productDropDown); SeleneseTestNgHelper.assertFalse("Add button not enabled", addButtonNonFullSupply.isEnabled()); SeleneseTestNgHelper.assertTrue("Close button not displayed", closeButton.isDisplayed()); testWebDriver.waitForElementToAppear(productDropDown); testWebDriver.selectByVisibleText(productDropDown, productPrimaryName); testWebDriver.waitForElementToAppear(productCodeDropDown); testWebDriver.selectByVisibleText(productCodeDropDown, productCode); requestedQuantityField.clear(); requestedQuantityField.sendKeys(requestedQuantityValue); requestedQuantityExplanationField.clear(); requestedQuantityExplanationField.sendKeys(requestedQuantityExplanationValue); testWebDriver.waitForElementToAppear(closeButton); testWebDriver.sleep(1000); addButtonEnabled.click(); closeButton.click(); SeleneseTestNgHelper.assertEquals(productDescriptionNonFullSupply.getText().trim(), nonFullSupplyItems); SeleneseTestNgHelper.assertEquals(productCodeNonFullSupply.getText().trim(), productCode); SeleneseTestNgHelper.assertEquals(testWebDriver.getAttribute(requestedQuantityNonFullSupply, "value").trim(), requestedQuantityValue); SeleneseTestNgHelper.assertEquals(testWebDriver.getAttribute(requestedQuantityExplanationNonFullSupply, "value").trim(), requestedQuantityExplanationValue); } public void saveRnR() { saveButton.click(); testWebDriver.sleep(1500); SeleneseTestNgHelper.assertTrue("R&R saved successfully! message not displayed", successMessage.isDisplayed()); } public void submitRnR() { submitButton.click(); testWebDriver.sleep(1500); } public void authorizeRnR() { authorizeButton.click(); testWebDriver.sleep(1500); } public void verifySubmitRnrSuccessMsg() { SeleneseTestNgHelper.assertTrue("RnR Submit Success message not displayed", submitSuccessMessage.isDisplayed()); } public void verifyAuthorizeRnrSuccessMsg() { SeleneseTestNgHelper.assertTrue("RnR authorize Success message not displayed", submitSuccessMessage.isDisplayed()); } public void verifySubmitRnrErrorMsg() { SeleneseTestNgHelper.assertTrue("RnR Fail message not displayed", submitErrorMessage.isDisplayed()); } public void clearNewPatientField() { newPatient.sendKeys("\u0008"); testWebDriver.sleep(500); } public void verifyBeginningBalanceDisabled() { testWebDriver.waitForElementToAppear(fullSupplyTab); fullSupplyTab.click(); testWebDriver.waitForElementToAppear(beginningBalance); SeleneseTestNgHelper.assertFalse("BB Not disabled", beginningBalance.isEnabled()); } }
package org.apache.sling.junit.tests; import org.junit.Test; import org.apache.sling.junit.scriptable.TestAllPaths; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class TestAllPathsTest { @Test public void checkTestTest() throws Exception { final String comment = "# this is a comment" + "\n"; final String empty = " " + "\n"; final String testPassed = "TEST_PASSED" + "\n"; final String any = "this is any line" + " \n"; final String script1 = comment + empty + testPassed; final String script2 = comment + empty + testPassed + testPassed; final String script3 = comment + empty + testPassed + any; final String script4 = comment + empty; assertTrue(TestAllPaths.checkTest(script1)); assertFalse(TestAllPaths.checkTest(script2)); assertFalse(TestAllPaths.checkTest(script3)); assertFalse(TestAllPaths.checkTest(script4)); } }
package org.tinylog.core.test; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import javax.inject.Inject; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolver; import org.junit.jupiter.api.extension.TestInstances; import org.junit.platform.commons.support.AnnotationSupport; import org.junit.platform.commons.support.HierarchyTraversalMode; /** * Base extension class for custom parameterized JUnit5 extensions. */ public abstract class AbstractParameterizedExtension extends AbstractExtension implements ParameterResolver { private final Map<Class<?>, Function<ExtensionContext, ?>> parameters; public AbstractParameterizedExtension() { parameters = new HashMap<>(); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter().getType(); return parameters.containsKey(type); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter().getType(); Function<ExtensionContext, ?> producer = parameters.get(type); if (producer == null) { throw new IllegalStateException("Unexpected parameter type: " + type.getName()); } else { return producer.apply(extensionContext); } } /** * Registers a supported parameter that can be set by this extension. * * @param type The parameter type * @param producer Supplier function to produce a value for this parameter * @param <T> The generic parameter type */ protected <T> void registerParameter(Class<T> type, Function<ExtensionContext, T> producer) { parameters.put(type, producer); } protected <T> void injectFields(ExtensionContext context, T value) throws IllegalAccessException { Optional<TestInstances> instances = context.getTestInstances(); if (instances.isPresent()) { for (Object object : instances.get().getAllInstances()) { List<Field> fields = AnnotationSupport.findAnnotatedFields( object.getClass(), Inject.class, field -> field.getType().isAssignableFrom(value.getClass()), HierarchyTraversalMode.TOP_DOWN ); for (Field field : fields) { field.setAccessible(true); field.set(object, value); } } } } }
package org.uberfire.commons.async; import static javax.ejb.TransactionAttributeType.*; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.ejb.Asynchronous; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.TransactionAttribute; import javax.naming.InitialContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton @Startup @TransactionAttribute(NOT_SUPPORTED) public class SimpleAsyncExecutorService { private static final Logger LOG = LoggerFactory.getLogger( SimpleAsyncExecutorService.class ); private static final Integer AWAIT_TERMINATION_TIMEOUT = Integer.parseInt(System.getProperty("org.uberfire.watcher.quitetimeout", "3")); private static Object lock = new Object(); private final ExecutorService executorService; private static SimpleAsyncExecutorService instance; private static SimpleAsyncExecutorService unmanagedInstance; private final AtomicBoolean hasAlreadyShutdown = new AtomicBoolean( false ); private final Set<Future<?>> jobs = new CopyOnWriteArraySet<Future<?>>(); public static SimpleAsyncExecutorService getDefaultInstance() { synchronized (lock) { if ( instance == null ) { SimpleAsyncExecutorService _executorManager = null; try { _executorManager = InitialContext.doLookup( "java:module/SimpleAsyncExecutorService" ); } catch ( final Exception ignored ) { } if ( _executorManager == null ) { instance = new SimpleAsyncExecutorService( false ); } else { instance = _executorManager; } } } return instance; } public static SimpleAsyncExecutorService getUnmanagedInstance() { synchronized (lock) { if ( instance != null && instance.executorService != null ) { return instance; } else if ( unmanagedInstance == null ) { unmanagedInstance = new SimpleAsyncExecutorService( false ); } return unmanagedInstance; } } public static void shutdownInstances() { synchronized (lock) { if ( unmanagedInstance != null ) { unmanagedInstance.shutdown(); } if ( instance != null && instance.executorService != null ) { instance.shutdown(); } } } public SimpleAsyncExecutorService() { executorService = null; } public SimpleAsyncExecutorService( boolean notEJB ) { executorService = Executors.newCachedThreadPool( new DescriptiveThreadFactory() ); } @Asynchronous @Lock(LockType.READ) public void execute( final Runnable r ) { if ( executorService != null ) { jobs.add( executorService.submit( r ) ); } else { r.run(); } } private void shutdown() { if ( !hasAlreadyShutdown.getAndSet( true ) && executorService != null ) { for ( final Future<?> job : jobs ) { if ( !job.isCancelled() && !job.isDone() ) { job.cancel( true ); } } executorService.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if ( !executorService.awaitTermination( AWAIT_TERMINATION_TIMEOUT, TimeUnit.SECONDS ) ) { executorService.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if ( !executorService.awaitTermination( AWAIT_TERMINATION_TIMEOUT, TimeUnit.SECONDS ) ) { LOG.error( "Thread pool did not terminate." ); } } } catch ( InterruptedException ie ) { // (Re-)Cancel if current thread also interrupted executorService.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } executorService.shutdown(); } } }
package no.priv.bang.ukelonn.tests; import static org.junit.Assert.*; import static org.ops4j.pax.exam.CoreOptions.*; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.*; import java.io.File; import java.sql.ResultSet; import java.sql.SQLException; import javax.inject.Inject; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.web.itest.base.HttpTestClient; import no.priv.bang.ukelonn.UkelonnService; import no.priv.bang.ukelonn.UkelonnDatabase; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class UkelonnServiceIntegrationTest extends UkelonnServiceIntegrationTestBase { public static final String RMI_SERVER_PORT = "44445"; public static final String RMI_REG_PORT = "1100"; @Inject private UkelonnDatabase database; @Inject UkelonnService ukelonnService; @Configuration public Option[] config() { final String jmxPort = freePortAsString(); final String httpPort = freePortAsString(); final String httpsPort = freePortAsString(); final MavenArtifactUrlReference karafUrl = maven().groupId("org.apache.karaf").artifactId("apache-karaf-minimal").type("zip").versionAsInProject(); final MavenArtifactUrlReference paxJdbcRepo = maven().groupId("org.ops4j.pax.jdbc").artifactId("pax-jdbc-features").versionAsInProject().type("xml").classifier("features"); final MavenArtifactUrlReference ukelonnFeatureRepo = maven().groupId("no.priv.bang.ukelonn").artifactId("ukelonn.karaf").versionAsInProject().type("xml").classifier("features"); return options( karafDistributionConfiguration().frameworkUrl(karafUrl).unpackDirectory(new File("target/exam")).useDeployFolder(false).runEmbedded(true), configureConsole().ignoreLocalConsole().ignoreRemoteShell(), editConfigurationFilePut("etc/org.apache.karaf.management.cfg", "rmiRegistryPort", RMI_REG_PORT), editConfigurationFilePut("etc/org.apache.karaf.management.cfg", "rmiServerPort", RMI_SERVER_PORT), editConfigurationFilePut("etc/org.ops4j.pax.web.cfg", "org.osgi.service.http.port", httpPort), editConfigurationFilePut("etc/org.ops4j.pax.web.cfg", "org.osgi.service.http.port.secure", httpsPort), vmOptions("-Dtest-jmx-port=" + jmxPort), junitBundles(), features(paxJdbcRepo), features(ukelonnFeatureRepo, "ukelonn-db-derby-test", "ukelonn")); } @Test public void ukelonnServiceIntegrationTest() { // Verify that the service could be injected assertNotNull(ukelonnService); assertEquals("Hello world!", ukelonnService.getMessage()); } @Test public void testDerbyTestDatabase() throws SQLException { ResultSet onAccount = database.query("select * from accounts_view where username='jad'"); assertNotNull(onAccount); assertTrue(onAccount.next()); // Verify that there is at least one result int account_id = onAccount.getInt("account_id"); int user_id = onAccount.getInt("user_id"); String username = onAccount.getString("username"); String first_name = onAccount.getString("first_name"); String last_name = onAccount.getString("last_name"); assertEquals(3, account_id); assertEquals(3, user_id); assertEquals("jad", username); assertEquals("Jane", first_name); assertEquals("Doe", last_name); } @Ignore @Test public void webappAccessTest() throws Exception { Thread.sleep(20*1000); HttpTestClient testclient = new HttpTestClient(); try { String response = testclient.testWebPath("http://localhost:8081/ukelonn/", 404); assertEquals("", response); } finally { testclient.close(); testclient = null; } } }
package com.ushahidi.android.presentation.view.ui.adapter; import com.ushahidi.android.R; import com.ushahidi.android.presentation.model.FormModel; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Adapter for {@link com.orhanobut.dialogplus.DialogPlus} to display forms * * @author Ushahidi Team <team@ushahidi.com> */ public class FormAdapter extends BaseAdapter { private LayoutInflater mLayoutInflater; private final List<FormModel> mItems = new ArrayList<>(); public FormAdapter(Context context) { mLayoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return mItems.size(); } public void setItems(List<FormModel> items) { mItems.clear(); mItems.addAll(items); notifyDataSetChanged(); } @Override public FormModel getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; View view = convertView; if (view == null) { view = mLayoutInflater.inflate(R.layout.grid_form_item, parent, false); viewHolder = new ViewHolder(); viewHolder.textView = (TextView) view.findViewById(R.id.text_view); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } return view; } static class ViewHolder { TextView textView; } }
package de.behrfried.wikianalyzer.wawebapp.server; import de.behrfried.wikianalyzer.wawebapp.client.GreetingService; import de.behrfried.wikianalyzer.wawebapp.shared.FieldVerifier; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import de.behrfried.wikianalyzer.simplemath.*; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public String greetServer(String input) throws IllegalArgumentException { try { int n = Integer.bitCount(Integer.parseInt(input)); return "You passed an Integer " + input + "<br>Its fac is " + SimpleMath.fak(n) + "and fibo is " + SimpleMath.fibo(n); } catch(Exception e) { } // Verify that the input is valid. if (!FieldVerifier.isValidName(input)) { // the client. throw new IllegalArgumentException( "Name must be at least 4 characters long"); } String serverInfo = getServletContext().getServerInfo(); String userAgent = getThreadLocalRequest().getHeader("User-Agent"); // Escape data from the client to avoid cross-site script // vulnerabilities. input = escapeHtml(input); userAgent = escapeHtml(userAgent); return "Hello, " + input + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>" + userAgent; } /** * Escape an html string. Escaping data received from the client helps to * prevent cross-site script vulnerabilities. * * @param html * the html string to escape * @return the escaped string */ private String escapeHtml(String html) { if (html == null) { return null; } return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } }
package org.exist.jms.shared; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.jms.JMSException; import javax.jms.Message; import org.apache.commons.lang3.builder.ToStringBuilder; /** * Container class for clustering messages. * * @author Dannes Wessels */ public class eXistMessage { /** * Header to describe operation on resource, e.g. CREATE UPDATE */ public final static String EXIST_RESOURCE_OPERATION = "exist.resource.operation"; /** * Header to describe resource, DOCUMENT or COLLECTION */ public final static String EXIST_RESOURCE_TYPE = "exist.resource.type"; /** * Header to describe path of resource */ public final static String EXIST_SOURCE_PATH = "exist.source.path"; /** * Header to describe destination path, for COPY and MOVE operation */ public final static String EXIST_DESTINATION_PATH = "exist.destination.path"; private ResourceOperation resourceOperation = ResourceOperation.UNDEFINED; private ResourceType resourceType = ResourceType.UNDEFINED; private ContentType contentType = ContentType.UNDEFINED; private String path; private String destination; private byte[] payload; private Map<String, Object> metaData = new HashMap<>(); /** * Atomic operations on resources */ public enum ResourceOperation { CREATE, UPDATE, DELETE, MOVE, COPY, METADATA, UNDEFINED } /** * Types of exist-db resources */ public enum ResourceType { DOCUMENT, COLLECTION, UNDEFINED } /** * Types of exist-db resources */ public enum ContentType { XML, BINARY, UNDEFINED } public void setResourceOperation(ResourceOperation type) { resourceOperation = type; } public void setResourceOperation(String type) { resourceOperation = ResourceOperation.valueOf(type.toUpperCase(Locale.ENGLISH)); } public ResourceOperation getResourceOperation() { return resourceOperation; } public void setResourceType(ResourceType type) { resourceType = type; } public void setResourceType(String type) { resourceType = eXistMessage.ResourceType.valueOf(type.toUpperCase(Locale.ENGLISH)); } public ResourceType getResourceType() { return resourceType; } public void setResourcePath(String path) { this.path = path; } public String getResourcePath() { return path; } public void setDestinationPath(String path) { destination = path; } public String getDestinationPath() { return destination; } public byte[] getPayload() { return payload; } public void setPayload(byte[] data) { payload = data; } public void resetPayload(){ payload = new byte[0]; } public void setMetadata(Map<String, Object> props) { metaData = props; } public Map<String, Object> getMetadata() { return metaData; } public ContentType getDocumentType() { return contentType; } public void setDocumentType(ContentType documentType) { this.contentType = documentType; } /** * Get one-liner report of message, including the JMS properties. * @return Report of message */ public String getReport() { StringBuilder sb = new StringBuilder(); sb.append("Message summary: "); sb.append("ResourceType='").append(resourceType.toString()).append("' "); sb.append("ResourceOperation='").append(resourceOperation).append("' "); sb.append("ResourcePath='").append(path).append("' "); if(destination!=null){ sb.append("DestinationPath='").append(resourceType.toString()).append("' "); } if(payload!=null && payload.length>0){ sb.append("PayloadSize='").append(payload.length).append("' "); } // Iterate over properties if present Set<String> keys = metaData.keySet(); if(!keys.isEmpty()){ sb.append(" for(String key : keys){ Object val=metaData.get(key); if(val != null){ sb.append(key).append("='").append(val.toString()).append("' "); } } } return sb.toString(); } @Override public String toString(){ return ToStringBuilder.reflectionToString(this); } /** * Update JMS message properties with replication details. * * @param message JMS message. * @throws JMSException A property could not be set. */ public void updateMessageProperties(Message message) throws JMSException { // Set eXist-db clustering specific details message.setStringProperty(eXistMessage.EXIST_RESOURCE_OPERATION, getResourceOperation().name()); message.setStringProperty(eXistMessage.EXIST_RESOURCE_TYPE, getResourceType().name()); message.setStringProperty(eXistMessage.EXIST_SOURCE_PATH, getResourcePath()); if (getDestinationPath() != null) { message.setStringProperty(eXistMessage.EXIST_DESTINATION_PATH, getDestinationPath()); } // // Retrieve and set JMS identifier // String id = Identity.getInstance().getIdentity(); // if (id != null) { // message.setStringProperty(Constants.EXIST_INSTANCE_ID, id); // Set other details Map<String, Object> metaDataMap = getMetadata(); for (Map.Entry<String, Object> entry : metaDataMap.entrySet()) { String item = entry.getKey(); Object value = entry.getValue(); if (value instanceof String) { message.setStringProperty(item, (String) value); } else if (value instanceof Integer) { message.setIntProperty(item, (Integer) value); } else if (value instanceof Long) { message.setLongProperty(item, (Long) value); } else { message.setStringProperty(item, "" + value); } } } }
package org.jpos.iso; import java.io.IOException; import java.io.InputStream; import java.util.BitSet; /** * EBCDIC [unpacked] Bitmap * * @author apr * @see ISOComponent * @see ISOBitMapPackager */ public class IFE_BITMAP extends ISOBitMapPackager { public IFE_BITMAP() { super(); } /** * @param len - field len * @param description symbolic descrption */ public IFE_BITMAP(int len, String description) { super(len, description); } /** * @param c - a component * @return packed component * @exception ISOException */ public byte[] pack (ISOComponent c) throws ISOException { BitSet bitMapValue = (BitSet) c.getValue(); int maxBytesPossible = getLength(); int maxBitsAllowedPhysically = maxBytesPossible<<3; int lastBitOn = bitMapValue.length()-1; int actualLastBit=lastBitOn; // takes into consideration 2nd and 3rd bit map flags if (lastBitOn > 128) { if (bitMapValue.get(65)) { actualLastBit = 192; } else { actualLastBit = 128; } } else if (lastBitOn > 64) { actualLastBit = 128; } if (actualLastBit > maxBitsAllowedPhysically) { throw new ISOException ("Bitmap can only hold bits numbered up to " + maxBitsAllowedPhysically + " in the " + getLength() + " bytes available."); } int requiredLengthInBytes = (actualLastBit >> 3) + (actualLastBit % 8 > 0 ? 1 : 0); int requiredBitMapLengthInBytes; if (requiredLengthInBytes>4 && requiredLengthInBytes<=8) { requiredBitMapLengthInBytes = 8; } else if (requiredLengthInBytes>8 && requiredLengthInBytes<=16) { requiredBitMapLengthInBytes = 16; } else if (requiredLengthInBytes>16 && requiredLengthInBytes<=24) { requiredBitMapLengthInBytes = 24; } else { requiredBitMapLengthInBytes=maxBytesPossible; } byte[] b = ISOUtil.bitSet2byte (bitMapValue, requiredBitMapLengthInBytes); return ISOUtil.asciiToEbcdic(ISOUtil.hexString(b).getBytes()); } public int getMaxPackedLength() { return getLength() >> 2; } /** * @param c - the Component to unpack * @param b - binary image * @param offset - starting offset within the binary image * @return consumed bytes * @exception ISOException */ public int unpack (ISOComponent c, byte[] b, int offset) throws ISOException { // TODO: calculate bytes to read based on bits 1, 65 on/off in the actual data int bytes; byte [] b1 = ISOUtil.ebcdicToAsciiBytes (b, offset, getLength()*2 ); BitSet bmap = ISOUtil.hex2BitSet (b1, 0, getLength() << 3); c.setValue(bmap); bytes = b1.length; // check for 2nd bit map indicator if ((bytes > 16) && !bmap.get(1)) { bytes = 16; // check for 3rd bit map indicator } else if ((bytes > 32) && !bmap.get(65)) { bytes = 32; } return bytes; } public void unpack (ISOComponent c, InputStream in) throws IOException, ISOException { byte [] b1 = ISOUtil.ebcdicToAsciiBytes (readBytes (in, 16), 0, 16); BitSet bmap = ISOUtil.hex2BitSet (new BitSet (64), b1, 0); if (getLength() > 8 && bmap.get (1)) { byte [] b2 = ISOUtil.ebcdicToAsciiBytes (readBytes (in, 16), 0, 16); ISOUtil.hex2BitSet (bmap, b2, 64); } c.setValue(bmap); } }
/* * created 26 Oct 2008 for new cDVSTest chip * adapted apr 2011 for cDVStest30 chip by tobi * adapted 25 oct 2011 for SeeBetter10/11 chips by tobi */ package eu.seebetter.ini.chips.DAViS; import java.awt.Font; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeSupport; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import javax.swing.JFrame; import net.sf.jaer.Description; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.biasgen.BiasgenHardwareInterface; import net.sf.jaer.chip.Chip; import net.sf.jaer.chip.RetinaExtractor; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.TypedEvent; import net.sf.jaer.eventprocessing.filter.ApsDvsEventFilter; import net.sf.jaer.eventprocessing.filter.Info; import net.sf.jaer.eventprocessing.filter.RefractoryFilter; import net.sf.jaer.graphics.AEFrameChipRenderer; import net.sf.jaer.graphics.ChipRendererDisplayMethodRGBA; import net.sf.jaer.graphics.DisplayMethod; import net.sf.jaer.hardwareinterface.HardwareInterface; import net.sf.jaer.hardwareinterface.HardwareInterfaceException; import net.sf.jaer.util.HasPropertyTooltips; import net.sf.jaer.util.PropertyTooltipSupport; import net.sf.jaer.util.RemoteControlCommand; import net.sf.jaer.util.RemoteControlled; import net.sf.jaer.util.histogram.AbstractHistogram; import net.sf.jaer.util.histogram.SimpleHistogram; import ch.unizh.ini.jaer.config.cpld.CPLDInt; import com.jogamp.opengl.util.awt.TextRenderer; import eu.seebetter.ini.chips.ApsDvsChip; import eu.seebetter.ini.chips.DAViS.IMUSample.IncompleteIMUSampleException; /** * <p> * DAViS240a/b have 240x180 pixels and are built in 180nm technology. DAViS240a has a rolling shutter APS readout and * DAViS240b has global shutter readout (but rolling shutter also possible with DAViS240b with different CPLD logic). * Both do APS CDS in digital domain off-chip, on host side, using difference between reset and signal reads. * <p> * * Describes retina and its event extractor and bias generator. Two constructors ara available, the vanilla constructor * is used for event playback and the one with a HardwareInterface parameter is useful for live capture. * {@link #setHardwareInterface} is used when the hardware interface is constructed after the retina object. The * constructor that takes a hardware interface also constructs the biasgen interface. * * @author tobi, christian */ @Description("DAViS240a/b 240x180 pixel APS-DVS DAVIS sensor") public class DAViS240 extends ApsDvsChip implements RemoteControlled, Observer { private final int ADC_NUMBER_OF_TRAILING_ZEROS = Integer.numberOfTrailingZeros(ApsDvsChip.ADC_READCYCLE_MASK); // speedup // loop // following define bit masks for various hardware data types. // The hardware interface translateEvents method packs the raw device data into 32 bit 'addresses' and timestamps. // timestamps are unwrapped and timestamp resets are handled in translateEvents. Addresses are filled with either AE // or ADC data. // AEs are filled in according the XMASK, YMASK, XSHIFT, YSHIFT below. /** * bit masks/shifts for cDVS AE data */ private DAViS240DisplayMethod davisDisplayMethod = null; private final AEFrameChipRenderer apsDVSrenderer; private int frameExposureStartTimestampUs = 0; // timestamp of first sample from frame (first sample read after // reset released) private int frameExposureEndTimestampUs; // end of exposure (first events of signal read) private int exposureDurationUs; // internal measured variable, set during rendering. Duration of frame expsosure in private int frameIntervalUs; // internal measured variable, set during rendering. Time between this frame and // previous one. /** * holds measured variable in Hz for GUI rendering of rate */ protected float frameRateHz; /** * holds measured variable in ms for GUI rendering */ protected float exposureMs; /** * Holds count of frames obtained by end of frame events */ private int frameCount = 0; private boolean snapshot = false; private DAViS240Config config; JFrame controlFrame = null; public static final short WIDTH = 240; public static final short HEIGHT = 180; int sx1 = getSizeX() - 1, sy1 = getSizeY() - 1; private int autoshotThresholdEvents = getPrefs().getInt("DAViS240.autoshotThresholdEvents", 0); private IMUSample imuSample; // latest IMUSample from sensor private final String CMD_EXPOSURE = "exposure"; private final String CMD_EXPOSURE_CC = "exposureCC"; private final String CMD_RS_SETTLE_CC = "resetSettleCC"; private final AutoExposureController autoExposureController = new AutoExposureController(); /** * Creates a new instance of cDVSTest20. */ public DAViS240() { setName("DAViS240"); setDefaultPreferencesFile("biasgenSettings/Davis240a/David240aBasic.xml"); setEventClass(ApsDvsEvent.class); setSizeX(DAViS240.WIDTH); setSizeY(DAViS240.HEIGHT); setNumCellTypes(3); // two are polarity and last is intensity setPixelHeightUm(18.5f); setPixelWidthUm(18.5f); setEventExtractor(new DAViS240Extractor(this)); setBiasgen(config = new DAViS240Config(this)); // hardware interface is ApsDvsHardwareInterface apsDVSrenderer = new AEFrameChipRenderer(this); apsDVSrenderer.setMaxADC(ApsDvsChip.MAX_ADC); setRenderer(apsDVSrenderer); davisDisplayMethod = new DAViS240DisplayMethod(this); getCanvas().addDisplayMethod(davisDisplayMethod); getCanvas().setDisplayMethod(davisDisplayMethod); addDefaultEventFilter(ApsDvsEventFilter.class); addDefaultEventFilter(HotPixelFilter.class); addDefaultEventFilter(RefractoryFilter.class); addDefaultEventFilter(Info.class); if (getRemoteControl() != null) { getRemoteControl() .addCommandListener(this, CMD_EXPOSURE, CMD_EXPOSURE + " val - sets exposure. val in ms."); getRemoteControl().addCommandListener(this, CMD_EXPOSURE_CC, CMD_EXPOSURE_CC + " val - sets exposure. val in clock cycles"); getRemoteControl().addCommandListener(this, CMD_RS_SETTLE_CC, CMD_RS_SETTLE_CC + " val - sets reset settling time. val in clock cycles"); } addObserver(this); // we observe ourselves so that if hardware interface for example calls notifyListeners we // get informed } @Override public String processRemoteControlCommand(final RemoteControlCommand command, final String input) { Chip.log.info("processing RemoteControlCommand " + command + " with input=" + input); if (command == null) { return null; } final String[] tokens = input.split(" "); if (tokens.length < 2) { return input + ": unknown command - did you forget the argument?"; } if ((tokens[1] == null) || (tokens[1].length() == 0)) { return input + ": argument too short - need a number"; } float v = 0; try { v = Float.parseFloat(tokens[1]); } catch (final NumberFormatException e) { return input + ": bad argument? Caught " + e.toString(); } final String c = command.getCmdName(); if (c.equals(CMD_EXPOSURE)) { config.setExposureDelayMs((int) v); } else if (c.equals(CMD_EXPOSURE_CC)) { config.exposure.set((int) v); } else if (c.equals(CMD_RS_SETTLE_CC)) { config.resSettle.set((int) v); } else { return input + ": unknown command"; } return "successfully processed command " + input; } @Override public void setPowerDown(final boolean powerDown) { config.powerDown.set(powerDown); try { config.sendOnChipConfigChain(); } catch (final HardwareInterfaceException ex) { Logger.getLogger(DAViS240.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void setADCEnabled(final boolean adcEnabled) { config.apsReadoutControl.setAdcEnabled(adcEnabled); } /** * Creates a new instance of DAViS240 * * @param hardwareInterface * an existing hardware interface. This constructor * is preferred. It makes a new cDVSTest10Biasgen object to talk to the * on-chip biasgen. */ public DAViS240(final HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } @Override public void controlExposure() { getAutoExposureController().controlExposure(); } /** * @return the autoExposureController */ public AutoExposureController getAutoExposureController() { return autoExposureController; } // int pixcnt=0; // TODO debug /** * The event extractor. Each pixel has two polarities 0 and 1. * * <p> * The bits in the raw data coming from the device are as follows. * <p> * Bit 0 is polarity, on=1, off=0<br> * Bits 1-9 are x address (max value 320)<br> * Bits 10-17 are y address (max value 240) <br> * <p> */ public class DAViS240Extractor extends RetinaExtractor { private static final long serialVersionUID = 3890914720599660376L; private int autoshotEventsSinceLastShot = 0; // autoshot counter private int warningCount = 0; private static final int WARNING_COUNT_DIVIDER = 10000; public DAViS240Extractor(final DAViS240 chip) { super(chip); } private IncompleteIMUSampleException incompleteIMUSampleException = null; private static final int IMU_WARNING_INTERVAL = 1000; private int missedImuSampleCounter = 0; private int badImuDataCounter = 0; /** * extracts the meaning of the raw events. * * @param in * the raw events, can be null * @return out the processed events. these are partially processed * in-place. empty packet is returned if null is supplied as in. */ @Override synchronized public EventPacket extractPacket(final AEPacketRaw in) { if (!(chip instanceof ApsDvsChip)) { return null; } if (out == null) { out = new ApsDvsEventPacket(chip.getEventClass()); } else { out.clear(); } out.setRawPacket(in); if (in == null) { return out; } final int n = in.getNumEvents(); // addresses.length; sx1 = chip.getSizeX() - 1; sy1 = chip.getSizeY() - 1; final int[] datas = in.getAddresses(); final int[] timestamps = in.getTimestamps(); final OutputEventIterator outItr = out.outputIterator(); // NOTE we must make sure we write ApsDvsEvents when we want them, not reuse the IMUSamples // at this point the raw data from the USB IN packet has already been digested to extract timestamps, // including timestamp wrap events and timestamp resets. // The datas array holds the data, which consists of a mixture of AEs and ADC values. // Here we extract the datas and leave the timestamps alone. // TODO entire rendering / processing approach is not very efficient now // System.out.println("Extracting new packet "+out); for (int i = 0; i < n; i++) { // TODO implement skipBy/subsampling, but without missing the frame start/end // events and still delivering frames final int data = datas[i]; if ((incompleteIMUSampleException != null) || ((ApsDvsChip.ADDRESS_TYPE_IMU & data) == ApsDvsChip.ADDRESS_TYPE_IMU)) { if (IMUSample.extractSampleTypeCode(data) == 0) { // / only start getting an IMUSample at code 0, // the first sample type try { final IMUSample possibleSample = IMUSample.constructFromAEPacketRaw(in, i, incompleteIMUSampleException); i += IMUSample.SIZE_EVENTS - 1; incompleteIMUSampleException = null; imuSample = possibleSample; // asking for sample from AEChip now gives this value, but no // access to intermediate IMU samples imuSample.imuSampleEvent = true; outItr.writeToNextOutput(imuSample); // also write the event out to the next output event // slot continue; } catch (final IMUSample.IncompleteIMUSampleException ex) { incompleteIMUSampleException = ex; if ((missedImuSampleCounter++ % DAViS240Extractor.IMU_WARNING_INTERVAL) == 0) { Chip.log.warning(String.format("%s (obtained %d partial samples so far)", ex.toString(), missedImuSampleCounter)); } break; // break out of loop because this packet only contained part of an IMUSample and // formed the end of the packet anyhow. Next time we come back here we will complete // the IMUSample } catch (final IMUSample.BadIMUDataException ex2) { if ((badImuDataCounter++ % DAViS240Extractor.IMU_WARNING_INTERVAL) == 0) { Chip.log.warning(String.format("%s (%d bad samples so far)", ex2.toString(), badImuDataCounter)); } incompleteIMUSampleException = null; continue; // continue because there may be other data } } } else if ((data & ApsDvsChip.ADDRESS_TYPE_MASK) == ApsDvsChip.ADDRESS_TYPE_DVS) { // DVS event final ApsDvsEvent e = nextApsDvsEvent(outItr); if ((data & ApsDvsChip.EVENT_TYPE_MASK) == ApsDvsChip.EXTERNAL_INPUT_EVENT_ADDR) { e.adcSample = -1; // TODO hack to mark as not an ADC sample e.special = true; // TODO special is set here when capturing frames which will mess us up if // this is an IMUSample used as a plain ApsDvsEvent e.address = data; e.timestamp = (timestamps[i]); e.setIsDVS(true); } else { e.adcSample = -1; // TODO hack to mark as not an ADC sample e.special = false; e.address = data; e.timestamp = (timestamps[i]); e.polarity = (data & ApsDvsChip.POLMASK) == ApsDvsChip.POLMASK ? ApsDvsEvent.Polarity.On : ApsDvsEvent.Polarity.Off; e.type = (byte) ((data & ApsDvsChip.POLMASK) == ApsDvsChip.POLMASK ? 1 : 0); if ((getHardwareInterface() != null) && (getHardwareInterface() instanceof net.sf.jaer.hardwareinterface.usb.cypressfx3libusb.CypressFX3)) { // New logic already rights the address in FPGA. e.x = (short) ((data & ApsDvsChip.XMASK) >>> ApsDvsChip.XSHIFT); } else { e.x = (short) (sx1 - ((data & ApsDvsChip.XMASK) >>> ApsDvsChip.XSHIFT)); } e.y = (short) ((data & ApsDvsChip.YMASK) >>> ApsDvsChip.YSHIFT); e.setIsDVS(true); // System.out.println(data); // autoshot triggering autoshotEventsSinceLastShot++; // number DVS events captured here } } else if ((data & ApsDvsChip.ADDRESS_TYPE_MASK) == ApsDvsChip.ADDRESS_TYPE_APS) { // APS event // We first calculate the positions, so we can put events such as StartOfFrame at their // right place, before the actual APS event denoting (0, 0) for example. final int timestamp = timestamps[i]; final short x = (short) (((data & ApsDvsChip.XMASK) >>> ApsDvsChip.XSHIFT)); final short y = (short) ((data & ApsDvsChip.YMASK) >>> ApsDvsChip.YSHIFT); final boolean pixFirst = (x == sx1) && (y == sy1); // First event of frame (addresses get flipped) final boolean pixLast = (x == 0) && (y == 0); // Last event of frame (addresses get flipped) ApsDvsEvent.ReadoutType readoutType = ApsDvsEvent.ReadoutType.Null; switch ((data & ApsDvsChip.ADC_READCYCLE_MASK) >> ADC_NUMBER_OF_TRAILING_ZEROS) { case 0: readoutType = ApsDvsEvent.ReadoutType.ResetRead; break; case 1: readoutType = ApsDvsEvent.ReadoutType.SignalRead; break; case 3: Chip.log.warning("Event with readout cycle null was sent out!"); break; default: if ((warningCount < 10) || ((warningCount % DAViS240Extractor.WARNING_COUNT_DIVIDER) == 0)) { Chip.log .warning("Event with unknown readout cycle was sent out! You might be reading a file that had the deprecated C readout mode enabled."); } warningCount++; break; } if (pixFirst && (readoutType == ApsDvsEvent.ReadoutType.ResetRead)) { createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOF, timestamp); if (!config.chipConfigChain.configBits[6].isSet()) { // rolling shutter start of exposure (SOE) createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOE, timestamp); frameIntervalUs = timestamp - frameExposureStartTimestampUs; frameExposureStartTimestampUs = timestamp; } } if (pixLast && (readoutType == ApsDvsEvent.ReadoutType.ResetRead) && config.chipConfigChain.configBits[6].isSet()) { // global shutter start of exposure (SOE) createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOE, timestamp); frameIntervalUs = timestamp - frameExposureStartTimestampUs; frameExposureStartTimestampUs = timestamp; } final ApsDvsEvent e = nextApsDvsEvent(outItr); e.adcSample = data & ApsDvsChip.ADC_DATA_MASK; e.readoutType = readoutType; e.special = false; e.timestamp = timestamp; e.address = data; e.x = x; e.y = y; e.type = (byte) (2); // end of exposure, same for both if (pixFirst && (readoutType == ApsDvsEvent.ReadoutType.SignalRead)) { createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.EOE, timestamp); frameExposureEndTimestampUs = timestamp; exposureDurationUs = timestamp - frameExposureStartTimestampUs; } if (pixLast && (readoutType == ApsDvsEvent.ReadoutType.SignalRead)) { // if we use ResetRead+SignalRead+C readout, OR, if we use ResetRead-SignalRead readout and we // are at last APS pixel, then write EOF event // insert a new "end of frame" event not present in original data createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.EOF, timestamp); if (snapshot) { snapshot = false; config.apsReadoutControl.setAdcEnabled(false); } setFrameCount(getFrameCount() + 1); } } } if ((getAutoshotThresholdEvents() > 0) && (autoshotEventsSinceLastShot > getAutoshotThresholdEvents())) { takeSnapshot(); autoshotEventsSinceLastShot = 0; } return out; } // extractPacket // TODO hack to reuse IMUSample events as ApsDvsEvents holding only APS or DVS data by using the special flags private ApsDvsEvent nextApsDvsEvent(final OutputEventIterator outItr) { final ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput(); e.special = false; e.adcSample = -1; if (e instanceof IMUSample) { ((IMUSample) e).imuSampleEvent = false; } return e; } /** * creates a special ApsDvsEvent in output packet just for flagging APS * frame markers such as start of frame, reset, end of frame. * * @param outItr * @param flag * @param timestamp * @return */ private ApsDvsEvent createApsFlagEvent(final OutputEventIterator outItr, final ApsDvsEvent.ReadoutType flag, final int timestamp) { final ApsDvsEvent a = nextApsDvsEvent(outItr); a.adcSample = 0; // set this effectively as ADC sample even though fake a.timestamp = timestamp; a.x = -1; a.y = -1; a.readoutType = flag; return a; } @Override public AEPacketRaw reconstructRawPacket(final EventPacket packet) { if (raw == null) { raw = new AEPacketRaw(); } if (!(packet instanceof ApsDvsEventPacket)) { return null; } final ApsDvsEventPacket apsDVSpacket = (ApsDvsEventPacket) packet; raw.ensureCapacity(packet.getSize()); raw.setNumEvents(0); final int[] a = raw.addresses; final int[] ts = raw.timestamps; apsDVSpacket.getSize(); final Iterator evItr = apsDVSpacket.fullIterator(); int k = 0; while (evItr.hasNext()) { final ApsDvsEvent e = (ApsDvsEvent) evItr.next(); // not writing out these EOF events (which were synthesized on extraction) results in reconstructed // packets with giant time gaps, reason unknown if (e.isEndOfFrame()) { continue; // these EOF events were synthesized from data in first place } ts[k] = e.timestamp; a[k++] = reconstructRawAddressFromEvent(e); } raw.setNumEvents(k); return raw; } /** * To handle filtered ApsDvsEvents, this method rewrites the fields of * the raw address encoding x and y addresses to reflect the event's x * and y fields. * * @param e * the ApsDvsEvent * @return the raw address */ @Override public int reconstructRawAddressFromEvent(final TypedEvent e) { int address = e.address; // if(e.x==0 && e.y==0){ // log.info("start of frame event "+e); // if(e.x==-1 && e.y==-1){ // log.info("end of frame event "+e); // e.x came from e.x = (short) (chip.getSizeX()-1-((data & XMASK) >>> XSHIFT)); // for DVS event, no x flip // if APS event if (((ApsDvsEvent) e).adcSample >= 0) { address = (address & ~ApsDvsChip.XMASK) | ((e.x) << ApsDvsChip.XSHIFT); } else { address = (address & ~ApsDvsChip.XMASK) | ((sx1 - e.x) << ApsDvsChip.XSHIFT); } // e.y came from e.y = (short) ((data & YMASK) >>> YSHIFT); address = (address & ~ApsDvsChip.YMASK) | (e.y << ApsDvsChip.YSHIFT); return address; } private void setFrameCount(final int i) { frameCount = i; } } // extractor /** * overrides the Chip setHardware interface to construct a biasgen if one * doesn't exist already. Sets the hardware interface and the bias * generators hardware interface * * @param hardwareInterface * the interface */ @Override public void setHardwareInterface(final HardwareInterface hardwareInterface) { this.hardwareInterface = hardwareInterface; try { if (getBiasgen() == null) { setBiasgen(new DAViS240Config(this)); // now we can addConfigValue the control panel } else { getBiasgen().setHardwareInterface((BiasgenHardwareInterface) hardwareInterface); } } catch (final ClassCastException e) { Chip.log.warning(e.getMessage() + ": probably this chip object has a biasgen but the hardware interface doesn't, ignoring"); } } /** * Displays data from SeeBetter test chip SeeBetter10/11. * * @author Tobi */ public class DAViS240DisplayMethod extends ChipRendererDisplayMethodRGBA { private static final int FONTSIZE = 10; private static final int FRAME_COUNTER_BAR_LENGTH_FRAMES = 10; private final TextRenderer exposureRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, DAViS240DisplayMethod.FONTSIZE), true, true); public DAViS240DisplayMethod(final DAViS240 chip) { super(chip.getCanvas()); } @Override public void display(final GLAutoDrawable drawable) { getCanvas().setBorderSpacePixels(50); super.display(drawable); if ((config.videoControl != null) && config.videoControl.displayFrames) { final GL2 gl = drawable.getGL().getGL2(); exposureRender(gl); } // draw sample histogram if (showImageHistogram && (renderer instanceof AEFrameChipRenderer)) { // System.out.println("drawing hist"); final int size = 100; final AbstractHistogram hist = ((AEFrameChipRenderer) renderer).getAdcSampleValueHistogram(); final GL2 gl = drawable.getGL().getGL2(); gl.glPushAttrib(GL.GL_COLOR_BUFFER_BIT); gl.glColor3f(0, 0, 1); hist.draw(drawable, exposureRenderer, (sizeX / 2) - (size / 2), (sizeY / 2) + (size / 2), size, size); gl.glPopAttrib(); } // Draw last IMU output if (config.isDisplayImu() && (chip instanceof DAViS240)) { final IMUSample imuSample = ((DAViS240) chip).getImuSample(); if (imuSample != null) { imuRender(drawable, imuSample); } } } TextRenderer imuTextRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 36)); GLU glu = null; GLUquadric accelCircle = null; private void imuRender(final GLAutoDrawable drawable, final IMUSample imuSample) { // System.out.println("on rendering: "+imuSample.toString()); final GL2 gl = drawable.getGL().getGL2(); gl.glPushMatrix(); gl.glTranslatef(chip.getSizeX() / 2, chip.getSizeY() / 2, 0); gl.glLineWidth(3); final float vectorScale = 1.5f; final float textScale = .2f; final float trans = .7f; float x, y; // gyro pan/tilt gl.glColor3f(1f, 0, 1); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, 0); x = (vectorScale * imuSample.getGyroYawY() * DAViS240.HEIGHT) / IMUSample.getFullScaleGyroDegPerSec(); y = (vectorScale * imuSample.getGyroTiltX() * DAViS240.HEIGHT) / IMUSample.getFullScaleGyroDegPerSec(); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(1f, 0, 1, trans); imuTextRenderer.draw3D(String.format("%.2f,%.2f dps", imuSample.getGyroYawY(), imuSample.getGyroTiltX()), x, y + 5, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // gyro roll x = (vectorScale * imuSample.getGyroRollZ() * DAViS240.HEIGHT) / IMUSample.getFullScaleGyroDegPerSec(); y = chip.getSizeY() * .25f; gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, y); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.draw3D(String.format("%.2f dps", imuSample.getGyroRollZ()), x, y, 0, textScale); imuTextRenderer.end3DRendering(); // acceleration x,y x = (vectorScale * imuSample.getAccelX() * DAViS240.HEIGHT) / IMUSample.getFullScaleAccelG(); y = (vectorScale * imuSample.getAccelY() * DAViS240.HEIGHT) / IMUSample.getFullScaleAccelG(); gl.glColor3f(0, 1, 0); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, 0); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(0, .5f, 0, trans); imuTextRenderer.draw3D(String.format("%.2f,%.2f g", imuSample.getAccelX(), imuSample.getAccelY()), x, y, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // acceleration z, drawn as circle if (glu == null) { glu = new GLU(); } if (accelCircle == null) { accelCircle = glu.gluNewQuadric(); } final float az = ((vectorScale * imuSample.getAccelZ() * DAViS240.HEIGHT)) / IMUSample.getFullScaleAccelG(); final float rim = .5f; glu.gluQuadricDrawStyle(accelCircle, GLU.GLU_FILL); glu.gluDisk(accelCircle, az - rim, az + rim, 16, 1); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(0, .5f, 0, trans); final String saz = String.format("%.2f g", imuSample.getAccelZ()); final Rectangle2D rect = imuTextRenderer.getBounds(saz); imuTextRenderer.draw3D(saz, az, -(float) rect.getHeight() * textScale * 0.5f, 0, textScale); imuTextRenderer.end3DRendering(); // color annotation to show what is being rendered imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(1, 1, 1, trans); final String ratestr = String.format("IMU: timestamp=%-+9.3fs last dtMs=%-6.1fms avg dtMs=%-6.1fms", 1e-6f * imuSample.getTimestampUs(), imuSample.getDeltaTimeUs() * .001f, IMUSample.getAverageSampleIntervalUs() / 1000); final Rectangle2D raterect = imuTextRenderer.getBounds(ratestr); imuTextRenderer.draw3D(ratestr, -(float) raterect.getWidth() * textScale * 0.5f * .7f, -12, 0, textScale * .7f); // x,y,z, scale factor imuTextRenderer.end3DRendering(); gl.glPopMatrix(); } private void exposureRender(final GL2 gl) { gl.glPushMatrix(); exposureRenderer.begin3DRendering(); if (frameIntervalUs > 0) { setFrameRateHz((float) 1000000 / frameIntervalUs); } setExposureMs((float) exposureDurationUs / 1000); final String s = String.format("Frame: %d; Exposure %.2f ms; Frame rate: %.2f Hz", getFrameCount(), exposureMs, frameRateHz); exposureRenderer.draw3D(s, 0, DAViS240.HEIGHT + (DAViS240DisplayMethod.FONTSIZE / 2), 0, .5f); // x,y,z, // scale // factor exposureRenderer.end3DRendering(); final int nframes = frameCount % DAViS240DisplayMethod.FRAME_COUNTER_BAR_LENGTH_FRAMES; final int rectw = DAViS240.WIDTH / DAViS240DisplayMethod.FRAME_COUNTER_BAR_LENGTH_FRAMES; gl.glColor4f(1, 1, 1, .5f); for (int i = 0; i < nframes; i++) { gl.glRectf(nframes * rectw, DAViS240.HEIGHT + 1, ((nframes + 1) * rectw) - 3, (DAViS240.HEIGHT + (DAViS240DisplayMethod.FONTSIZE / 2)) - 1); } gl.glPopMatrix(); } } /** * Returns the preferred DisplayMethod, or ChipRendererDisplayMethod if null * preference. * * @return the method, or null. * @see #setPreferredDisplayMethod */ @Override public DisplayMethod getPreferredDisplayMethod() { return new ChipRendererDisplayMethodRGBA(getCanvas()); } @Override public int getMaxADC() { return ApsDvsChip.MAX_ADC; } /** * Sets the measured frame rate. Does not change parameters, only used for * recording measured quantity and informing GUI listeners. * * @param frameRateHz * the frameRateHz to set */ private void setFrameRateHz(final float frameRateHz) { final float old = this.frameRateHz; this.frameRateHz = frameRateHz; getSupport().firePropertyChange(ApsDvsChip.PROPERTY_FRAME_RATE_HZ, old, this.frameRateHz); } /** * Sets the measured exposure. Does not change parameters, only used for * recording measured quantity. * * @param exposureMs * the exposureMs to set */ private void setExposureMs(final float exposureMs) { final float old = this.exposureMs; this.exposureMs = exposureMs; getSupport().firePropertyChange(ApsDvsChip.PROPERTY_EXPOSURE_MS, old, this.exposureMs); } @Override public float getFrameRateHz() { return frameRateHz; } @Override public float getExposureMs() { return exposureMs; } @Override public int getFrameExposureStartTimestampUs() { return frameExposureStartTimestampUs; } @Override public int getFrameExposureEndTimestampUs() { return frameExposureEndTimestampUs; } /** * Returns the frame counter. This value is set on each end-of-frame sample. * It increases without bound and is not affected by rewinding a played-back recording, for instance. * * @return the frameCount */ @Override public int getFrameCount() { return frameCount; } /** * Triggers shot of one APS frame */ @Override public void takeSnapshot() { snapshot = true; config.apsReadoutControl.setAdcEnabled(true); } /** * Sets threshold for shooting a frame automatically * * @param thresholdEvents * the number of events to trigger shot on. Less than * or equal to zero disables auto-shot. */ @Override public void setAutoshotThresholdEvents(int thresholdEvents) { if (thresholdEvents < 0) { thresholdEvents = 0; } autoshotThresholdEvents = thresholdEvents; getPrefs().putInt("DAViS240.autoshotThresholdEvents", thresholdEvents); if (autoshotThresholdEvents == 0) { config.runAdc.set(true); } } /** * Returns threshold for auto-shot. * * @return events to shoot frame */ @Override public int getAutoshotThresholdEvents() { return autoshotThresholdEvents; } @Override public void setAutoExposureEnabled(final boolean yes) { getAutoExposureController().setAutoExposureEnabled(yes); } @Override public boolean isAutoExposureEnabled() { return getAutoExposureController().isAutoExposureEnabled(); } private boolean showImageHistogram = getPrefs().getBoolean("DAViS240.showImageHistogram", false); @Override public boolean isShowImageHistogram() { return showImageHistogram; } @Override public void setShowImageHistogram(final boolean yes) { showImageHistogram = yes; getPrefs().putBoolean("DAViS240.showImageHistogram", yes); } /** * Controls exposure automatically to try to optimize captured gray levels * */ public class AutoExposureController implements HasPropertyTooltips { // TODO not implemented yet private boolean autoExposureEnabled = getPrefs().getBoolean("autoExposureEnabled", false); private float expDelta = .05f; // exposure change if incorrectly exposed private float underOverFractionThreshold = 0.2f; // threshold for fraction of total pixels that are underexposed // or overexposed private final PropertyTooltipSupport tooltipSupport = new PropertyTooltipSupport(); private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); SimpleHistogram hist = null; SimpleHistogram.Statistics stats = null; private float lowBoundary = getPrefs().getFloat("AutoExposureController.lowBoundary", 0.1f); private float highBoundary = getPrefs().getFloat("AutoExposureController.highBoundary", 0.9f); public AutoExposureController() { tooltipSupport.setPropertyTooltip("expDelta", "fractional change of exposure when under or overexposed"); tooltipSupport.setPropertyTooltip("underOverFractionThreshold", "fraction of pixel values under xor over exposed to trigger exposure change"); tooltipSupport.setPropertyTooltip("lowBoundary", "Upper edge of histogram range considered as low values"); tooltipSupport .setPropertyTooltip("highBoundary", "Lower edge of histogram range considered as high values"); tooltipSupport.setPropertyTooltip("autoExposureEnabled", "Exposure time is automatically controlled when this flag is true"); } @Override public String getPropertyTooltip(final String propertyName) { return tooltipSupport.getPropertyTooltip(propertyName); } public void setAutoExposureEnabled(final boolean yes) { final boolean old = autoExposureEnabled; autoExposureEnabled = yes; propertyChangeSupport.firePropertyChange("autoExposureEnabled", old, yes); getPrefs().putBoolean("autoExposureEnabled", yes); } public boolean isAutoExposureEnabled() { return autoExposureEnabled; } public void controlExposure() { if (!autoExposureEnabled) { return; } hist = apsDVSrenderer.getAdcSampleValueHistogram(); if (hist == null) { return; } stats = hist.getStatistics(); if (stats == null) { return; } stats.setLowBoundary(lowBoundary); stats.setHighBoundary(highBoundary); hist.computeStatistics(); final CPLDInt exposure = config.exposure; final int currentExposure = exposure.get(); int newExposure = 0; if ((stats.fracLow >= underOverFractionThreshold) && (stats.fracHigh < underOverFractionThreshold)) { newExposure = Math.round(currentExposure * (1 + expDelta)); if (newExposure == currentExposure) { newExposure++; // ensure increase } if (newExposure > exposure.getMax()) { newExposure = exposure.getMax(); } if (newExposure != currentExposure) { exposure.set(newExposure); } Chip.log.log( Level.INFO, "Underexposed: {0}\n{1}", new Object[] { stats.toString(), String.format("oldExposure=%8d newExposure=%8d", currentExposure, newExposure) }); } else if ((stats.fracLow < underOverFractionThreshold) && (stats.fracHigh >= underOverFractionThreshold)) { newExposure = Math.round(currentExposure * (1 - expDelta)); if (newExposure == currentExposure) { newExposure--; // ensure decrease even with rounding. } if (newExposure < exposure.getMin()) { newExposure = exposure.getMin(); } if (newExposure != currentExposure) { exposure.set(newExposure); } Chip.log.log( Level.INFO, "Overexposed: {0}\n{1}", new Object[] { stats.toString(), String.format("oldExposure=%8d newExposure=%8d", currentExposure, newExposure) }); } else { // log.info(stats.toString()); } } /** * Gets by what relative amount the exposure is changed on each frame if * under or over exposed. * * @return the expDelta */ public float getExpDelta() { return expDelta; } /** * Sets by what relative amount the exposure is changed on each frame if * under or over exposed. * * @param expDelta * the expDelta to set */ public void setExpDelta(final float expDelta) { this.expDelta = expDelta; getPrefs().putFloat("expDelta", expDelta); } /** * Gets the fraction of pixel values that must be under xor over exposed * to change exposure automatically. * * @return the underOverFractionThreshold */ public float getUnderOverFractionThreshold() { return underOverFractionThreshold; } /** * Gets the fraction of pixel values that must be under xor over exposed * to change exposure automatically. * * @param underOverFractionThreshold * the underOverFractionThreshold to * set */ public void setUnderOverFractionThreshold(final float underOverFractionThreshold) { this.underOverFractionThreshold = underOverFractionThreshold; getPrefs().putFloat("underOverFractionThreshold", underOverFractionThreshold); } public float getLowBoundary() { return lowBoundary; } public void setLowBoundary(final float lowBoundary) { this.lowBoundary = lowBoundary; getPrefs().putFloat("AutoExposureController.lowBoundary", lowBoundary); } public float getHighBoundary() { return highBoundary; } public void setHighBoundary(final float highBoundary) { this.highBoundary = highBoundary; getPrefs().putFloat("AutoExposureController.highBoundary", highBoundary); } /** * @return the propertyChangeSupport */ public PropertyChangeSupport getPropertyChangeSupport() { return propertyChangeSupport; } } /** * Returns the current Inertial Measurement Unit sample. * * @return the imuSample, or null if there is no sample */ public IMUSample getImuSample() { return imuSample; } @Override public void update(final Observable o, final Object arg) { // TODO Auto-generated method stub } }
package com.semmle.js.extractor; import com.semmle.js.extractor.ExtractorConfig.HTMLHandling; import com.semmle.js.extractor.ExtractorConfig.Platform; import com.semmle.js.extractor.ExtractorConfig.SourceType; import com.semmle.js.extractor.FileExtractor.FileType; import com.semmle.js.extractor.trapcache.DefaultTrapCache; import com.semmle.js.extractor.trapcache.DummyTrapCache; import com.semmle.js.extractor.trapcache.ITrapCache; import com.semmle.js.parser.ParsedProject; import com.semmle.js.parser.TypeScriptParser; import com.semmle.ts.extractor.TypeExtractor; import com.semmle.ts.extractor.TypeTable; import com.semmle.util.data.StringUtil; import com.semmle.util.data.UnitParser; import com.semmle.util.exception.ResourceError; import com.semmle.util.exception.UserError; import com.semmle.util.extraction.ExtractorOutputConfig; import com.semmle.util.files.FileUtil; import com.semmle.util.files.PathMatcher; import com.semmle.util.io.WholeIO; import com.semmle.util.language.LegacyLanguage; import com.semmle.util.process.ArgsParser; import com.semmle.util.process.ArgsParser.FileMode; import com.semmle.util.trap.TrapWriter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** The main entry point of the JavaScript extractor. */ public class Main { /** * A version identifier that should be updated every time the extractor changes in such a way that * it may produce different tuples for the same file under the same {@link ExtractorConfig}. */ public static final String EXTRACTOR_VERSION = "2019-10-07"; public static final Pattern NEWLINE = Pattern.compile("\n"); // symbolic constants for command line parameter names private static final String P_ABORT_ON_PARSE_ERRORS = "--abort-on-parse-errors"; private static final String P_DEBUG_EXCLUSIONS = "--debug-exclusions"; private static final String P_DEFAULT_ENCODING = "--default-encoding"; private static final String P_EXCLUDE = "--exclude"; private static final String P_EXPERIMENTAL = "--experimental"; private static final String P_EXTERNS = "--externs"; private static final String P_EXTRACT_PROGRAM_TEXT = "--extract-program-text"; private static final String P_FILE_TYPE = "--file-type"; private static final String P_HTML = "--html"; private static final String P_INCLUDE = "--include"; private static final String P_PLATFORM = "--platform"; private static final String P_QUIET = "--quiet"; private static final String P_SOURCE_TYPE = "--source-type"; private static final String P_TRAP_CACHE = "--trap-cache"; private static final String P_TRAP_CACHE_BOUND = "--trap-cache-bound"; private static final String P_TYPESCRIPT = "--typescript"; private static final String P_TYPESCRIPT_FULL = "--typescript-full"; private static final String P_TYPESCRIPT_RAM = "--typescript-ram"; // symbolic constants for deprecated command line parameter names private static final String P_EXCLUDE_PATH = "--exclude-path"; private static final String P_TOLERATE_PARSE_ERRORS = "--tolerate-parse-errors"; private static final String P_NODEJS = "--nodejs"; private static final String P_MOZ_EXTENSIONS = "--mozExtensions"; private static final String P_JSCRIPT = "--jscript"; private static final String P_HELP = "--help"; private static final String P_ECMA_VERSION = "--ecmaVersion"; private final ExtractorOutputConfig extractorOutputConfig; private ExtractorConfig extractorConfig; private PathMatcher includeMatcher, excludeMatcher; private FileExtractor fileExtractor; private ExtractorState extractorState; private final Set<File> projectFiles = new LinkedHashSet<>(); private final Set<File> files = new LinkedHashSet<>(); private final Set<File> extractedFiles = new LinkedHashSet<>(); /* used to detect cyclic directory hierarchies */ private final Set<String> seenDirectories = new LinkedHashSet<>(); /** * If true, the extractor state is shared with other extraction jobs. * * <p>This is used by the test runner. */ private boolean hasSharedExtractorState = false; public Main(ExtractorOutputConfig extractorOutputConfig) { this.extractorOutputConfig = extractorOutputConfig; this.extractorState = new ExtractorState(); } public Main(ExtractorOutputConfig extractorOutputConfig, ExtractorState extractorState) { this.extractorOutputConfig = extractorOutputConfig; this.extractorState = extractorState; this.hasSharedExtractorState = true; } public void run(String[] args) { ArgsParser ap = addArgs(new ArgsParser(args)); ap.parse(); extractorConfig = parseJSOptions(ap); ITrapCache trapCache; if (ap.has(P_TRAP_CACHE)) { Long sizeBound = null; if (ap.has(P_TRAP_CACHE_BOUND)) { String tcb = ap.getString(P_TRAP_CACHE_BOUND); sizeBound = DefaultTrapCache.asFileSize(tcb); if (sizeBound == null) ap.error("Invalid TRAP cache size bound: " + tcb); } trapCache = new DefaultTrapCache(ap.getString(P_TRAP_CACHE), sizeBound, EXTRACTOR_VERSION); } else { if (ap.has(P_TRAP_CACHE_BOUND)) ap.error( P_TRAP_CACHE_BOUND + " should only be specified together with " + P_TRAP_CACHE + "."); trapCache = new DummyTrapCache(); } fileExtractor = new FileExtractor(extractorConfig, extractorOutputConfig, trapCache); setupMatchers(ap); collectFiles(ap); if (files.isEmpty()) { verboseLog(ap, "Nothing to extract."); return; } TypeScriptParser tsParser = extractorState.getTypeScriptParser(); tsParser.setTypescriptRam(extractorConfig.getTypeScriptRam()); if (containsTypeScriptFiles()) { tsParser.verifyInstallation(!ap.has(P_QUIET)); } for (File projectFile : projectFiles) { long start = verboseLogStartTimer(ap, "Opening project " + projectFile); ParsedProject project = tsParser.openProject(projectFile); verboseLogEndTimer(ap, start); // Extract all files belonging to this project which are also matched // by our include/exclude filters. List<File> filesToExtract = new ArrayList<>(); for (File sourceFile : project.getSourceFiles()) { if (files.contains(normalizeFile(sourceFile)) && !extractedFiles.contains(sourceFile.getAbsoluteFile())) { filesToExtract.add(sourceFile); } } tsParser.prepareFiles(filesToExtract); for (int i = 0; i < filesToExtract.size(); ++i) { ensureFileIsExtracted(filesToExtract.get(i), ap); } // Close the project to free memory. This does not need to be in a `finally` as // the project is not a system resource. tsParser.closeProject(projectFile); } if (!projectFiles.isEmpty()) { // Extract all the types discovered when extracting the ASTs. TypeTable typeTable = tsParser.getTypeTable(); extractTypeTable(projectFiles.iterator().next(), typeTable); } List<File> remainingTypescriptFiles = new ArrayList<>(); for (File f : files) { if (!extractedFiles.contains(f.getAbsoluteFile()) && FileType.forFileExtension(f) == FileType.TYPESCRIPT) { remainingTypescriptFiles.add(f); } } if (!remainingTypescriptFiles.isEmpty()) { tsParser.prepareFiles(remainingTypescriptFiles); for (File f : remainingTypescriptFiles) { ensureFileIsExtracted(f, ap); } } // The TypeScript compiler instance is no longer needed - free up some memory. if (hasSharedExtractorState) { tsParser.reset(); // This is called from a test runner, so keep the process alive. } else { tsParser.killProcess(); } // Extract files that were not part of a project. for (File f : files) { ensureFileIsExtracted(f, ap); } } private void extractTypeTable(File fileHandle, TypeTable table) { TrapWriter trapWriter = extractorOutputConfig.getTrapWriterFactory().mkTrapWriter(fileHandle); try { new TypeExtractor(trapWriter, table).extract(); } finally { FileUtil.close(trapWriter); } } private void ensureFileIsExtracted(File f, ArgsParser ap) { if (!extractedFiles.add(f.getAbsoluteFile())) { // The file has already been extracted as part of a project. return; } long start = verboseLogStartTimer(ap, "Extracting " + f); try { fileExtractor.extract(f.getAbsoluteFile(), extractorState); verboseLogEndTimer(ap, start); } catch (IOException e) { throw new ResourceError("Extraction of " + f + " failed.", e); } } private void verboseLog(ArgsParser ap, String message) { if (!ap.has(P_QUIET)) { System.out.println(message); } } private long verboseLogStartTimer(ArgsParser ap, String message) { if (!ap.has(P_QUIET)) { System.out.print(message + "..."); System.out.flush(); } return System.currentTimeMillis(); } private void verboseLogEndTimer(ArgsParser ap, long start) { long end = System.currentTimeMillis(); if (!ap.has(P_QUIET)) { System.out.println(" done (" + (end - start) / 1000 + " seconds)."); } } /** Returns true if the project contains a TypeScript file to be extracted. */ private boolean containsTypeScriptFiles() { for (File file : files) { // The file headers have already been checked, so don't use I/O. if (FileType.forFileExtension(file) == FileType.TYPESCRIPT) { return true; } } return false; } public void collectFiles(ArgsParser ap) { for (File f : ap.getOneOrMoreFiles("files", FileMode.FILE_OR_DIRECTORY_MUST_EXIST)) collectFiles(f, true); } public void setupMatchers(ArgsParser ap) { Set<String> includes = new LinkedHashSet<>(); // only extract HTML and JS by default addIncludesFor(includes, FileType.HTML); addIncludesFor(includes, FileType.JS); // extract TypeScript if `--typescript` or `--typescript-full` was specified if (getTypeScriptMode(ap) != TypeScriptMode.NONE) addIncludesFor(includes, FileType.TYPESCRIPT); // add explicit include patterns for (String pattern : ap.getZeroOrMore(P_INCLUDE)) addPathPattern(includes, System.getProperty("user.dir"), pattern); this.includeMatcher = new PathMatcher(includes); // if we are extracting (potential) Node.js code, we also want to // include package.json files, and files without extension if (getPlatform(ap) != Platform.WEB) { PathMatcher innerIncludeMatcher = this.includeMatcher; this.includeMatcher = new PathMatcher("**/package.json") { @Override public boolean matches(String path) { // match files without extension String basename = path.substring(path.lastIndexOf(File.separatorChar) + 1); if (FileUtil.extension(basename).isEmpty()) return true; // match package.json and anything matched by the inner matcher return super.matches(path) || innerIncludeMatcher.matches(path); } }; } Set<String> excludes = new LinkedHashSet<>(); for (String pattern : ap.getZeroOrMore(P_EXCLUDE)) addPathPattern(excludes, System.getProperty("user.dir"), pattern); for (String excl : ap.getZeroOrMore(P_EXCLUDE_PATH)) { File exclFile = new File(excl).getAbsoluteFile(); String base = exclFile.getParent(); for (String pattern : NEWLINE.split(new WholeIO().strictread(exclFile))) addPathPattern(excludes, base, pattern); } this.excludeMatcher = new PathMatcher(excludes); if (ap.has(P_DEBUG_EXCLUSIONS)) { System.out.println("Inclusion patterns: " + this.includeMatcher); System.out.println("Exclusion patterns: " + this.excludeMatcher); } } private void addIncludesFor(Set<String> includes, FileType filetype) { for (String extension : filetype.getExtensions()) includes.add("**/*" + extension); } private void addPathPattern(Set<String> patterns, String base, String pattern) { pattern = pattern.trim(); if (pattern.isEmpty()) return; if (!FileUtil.isAbsolute(pattern) && base != null) { pattern = base + "/" + pattern; } if (pattern.endsWith("/")) pattern = pattern.substring(0, pattern.length() - 1); patterns.add(pattern); } private ArgsParser addArgs(ArgsParser argsParser) { argsParser.addDeprecatedFlag( P_ECMA_VERSION, 1, "Files are now always extracted as ECMAScript 2017."); argsParser.addFlag( P_EXCLUDE, 1, "Do not extract files matching the given filename pattern.", true); argsParser.addToleratedFlag(P_EXCLUDE_PATH, 1, true); argsParser.addFlag( P_EXPERIMENTAL, 0, "Enable experimental support for pending ECMAScript proposals " + "(public class fields, function.sent, decorators, export extensions, function bind, " + "parameter-less catch, dynamic import, numeric separators, bigints, top-level await), " + "as well as other language extensions (E4X, JScript, Mozilla and v8-specific extensions) and full HTML extraction."); argsParser.addFlag( P_EXTERNS, 0, "Extract the given JavaScript files as Closure-style externs."); argsParser.addFlag( P_EXTRACT_PROGRAM_TEXT, 0, "Extract a representation of the textual content of the program " + "(in addition to its syntactic structure)."); argsParser.addFlag( P_FILE_TYPE, 1, "Assume all files to be of the given type, regardless of extension; " + "the type must be one of " + StringUtil.glue(", ", FileExtractor.FileType.allNames) + "."); argsParser.addFlag(P_HELP, 0, "Display this help."); argsParser.addFlag( P_HTML, 1, "Control extraction of HTML files: " + "'scripts' extracts JavaScript code embedded inside HTML, but not the HTML itself; " + "'elements' additionally extracts HTML elements and their attributes, as well as HTML comments, but not textual content (default); " + "'all' extracts elements, embedded scripts, comments and text."); argsParser.addFlag( P_INCLUDE, 1, "Extract files matching the given filename pattern (in addition to HTML and JavaScript files).", true); argsParser.addDeprecatedFlag(P_JSCRIPT, 0, "Use '" + P_EXPERIMENTAL + "' instead."); argsParser.addDeprecatedFlag(P_MOZ_EXTENSIONS, 0, "Use '" + P_EXPERIMENTAL + "' instead."); argsParser.addDeprecatedFlag(P_NODEJS, 0, "Use '" + P_PLATFORM + " node' instead."); argsParser.addFlag( P_PLATFORM, 1, "Extract the given JavaScript files as code for the given platform: " + "'node' extracts them as Node.js modules; " + "'web' as plain JavaScript files; " + "'auto' uses heuristics to automatically detect " + "Node.js modules and extracts everything else as plain JavaScript files. " + "The default is 'auto'."); argsParser.addFlag(P_QUIET, 0, "Produce less output."); argsParser.addFlag( P_SOURCE_TYPE, 1, "The source type to use; must be one of 'script', 'module' or 'auto'. " + "The default is 'auto'."); argsParser.addToleratedFlag(P_TOLERATE_PARSE_ERRORS, 0); argsParser.addFlag( P_ABORT_ON_PARSE_ERRORS, 0, "Abort extraction if a parse error is encountered."); argsParser.addFlag(P_TRAP_CACHE, 1, "Use the given directory as the TRAP cache."); argsParser.addFlag( P_TRAP_CACHE_BOUND, 1, "A (soft) upper limit on the size of the TRAP cache, " + "in standard size units (e.g., 'g' for gigabytes)."); argsParser.addFlag(P_DEFAULT_ENCODING, 1, "The encoding to use; default is UTF-8."); argsParser.addFlag(P_TYPESCRIPT, 0, "Enable basic TypesScript support."); argsParser.addFlag( P_TYPESCRIPT_FULL, 0, "Enable full TypeScript support with static type information."); argsParser.addFlag( P_TYPESCRIPT_RAM, 1, "Amount of memory allocated to the TypeScript compiler process. The default is 1G."); argsParser.addToleratedFlag(P_DEBUG_EXCLUSIONS, 0); argsParser.addTrailingParam("files", "Files and directories to extract."); return argsParser; } private boolean enableExperimental(ArgsParser ap) { return ap.has(P_EXPERIMENTAL) || ap.has(P_JSCRIPT) || ap.has(P_MOZ_EXTENSIONS); } private static TypeScriptMode getTypeScriptMode(ArgsParser ap) { if (ap.has(P_TYPESCRIPT_FULL)) return TypeScriptMode.FULL; if (ap.has(P_TYPESCRIPT)) return TypeScriptMode.BASIC; return TypeScriptMode.NONE; } private ExtractorConfig parseJSOptions(ArgsParser ap) { ExtractorConfig cfg = new ExtractorConfig(enableExperimental(ap)) .withExterns(ap.has(P_EXTERNS)) .withPlatform(getPlatform(ap)) .withTolerateParseErrors( ap.has(P_TOLERATE_PARSE_ERRORS) || !ap.has(P_ABORT_ON_PARSE_ERRORS)) .withHtmlHandling( ap.getEnum( P_HTML, HTMLHandling.class, ap.has(P_EXPERIMENTAL) ? HTMLHandling.ALL : HTMLHandling.ELEMENTS)) .withFileType(getFileType(ap)) .withSourceType(ap.getEnum(P_SOURCE_TYPE, SourceType.class, SourceType.AUTO)) .withExtractLines(ap.has(P_EXTRACT_PROGRAM_TEXT)) .withTypeScriptMode(getTypeScriptMode(ap)) .withTypeScriptRam( ap.has(P_TYPESCRIPT_RAM) ? UnitParser.parseOpt(ap.getString(P_TYPESCRIPT_RAM), UnitParser.MEGABYTES) : 0); if (ap.has(P_DEFAULT_ENCODING)) cfg = cfg.withDefaultEncoding(ap.getString(P_DEFAULT_ENCODING)); return cfg; } private String getFileType(ArgsParser ap) { String fileType = null; if (ap.has(P_FILE_TYPE)) { fileType = StringUtil.uc(ap.getString(P_FILE_TYPE)); if (!FileExtractor.FileType.allNames.contains(fileType)) ap.error("Invalid file type " + ap.getString(P_FILE_TYPE)); } return fileType; } private Platform getPlatform(ArgsParser ap) { if (ap.has(P_NODEJS)) return Platform.NODE; return ap.getEnum(P_PLATFORM, Platform.class, Platform.AUTO); } /** * Collect files to extract under a given root, which may be either a file or a directory. The * {@code explicit} flag indicates whether {@code root} was explicitly passed to the extractor as * a command line argument, or whether it is examined as part of a recursive traversal. */ private void collectFiles(File root, boolean explicit) { if (!root.exists()) { System.err.println("Skipping " + root + ", which does not exist."); return; } if (root.isDirectory()) { // exclude directories we've seen before if (seenDirectories.add(FileUtil.tryMakeCanonical(root).getPath())) // apply exclusion filters for directories if (!excludeMatcher.matches(root.getAbsolutePath())) { File[] gs = root.listFiles(); if (gs == null) System.err.println("Skipping " + root + ", which cannot be listed."); else for (File g : gs) collectFiles(g, false); } } else { String path = root.getAbsolutePath(); // extract files that are supported, match the layout (if any), pass the includeMatcher, // and do not pass the excludeMatcher if (fileExtractor.supports(root) && extractorOutputConfig.shouldExtract(root) && (explicit || includeMatcher.matches(path) && !excludeMatcher.matches(path))) { files.add(normalizeFile(root)); } if (extractorConfig.getTypeScriptMode() == TypeScriptMode.FULL && root.getName().equals("tsconfig.json") && !excludeMatcher.matches(path)) { projectFiles.add(root); } } } private File normalizeFile(File root) { return root.getAbsoluteFile().toPath().normalize().toFile(); } public static void main(String[] args) { try { new Main(new ExtractorOutputConfig(LegacyLanguage.JAVASCRIPT)).run(args); } catch (UserError e) { System.err.println(e.getMessage()); if (!e.reportAsInfoMessage()) System.exit(1); } } }
package org.jpos.util; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DirPollOperationTest { volatile boolean fileProcessed; private static final int LITTLE_SLEEP = 10; private static final String RELATIVE_ARCHIVE_DIR = "archive"; private static final String RELATIVE_BAD_DIR = "bad"; private static final String RELATIVE_REQUEST_DIR = "request"; private static final long DIRPOLL_CHECK_INTERVAL = 500L; private DirPoll dirPoll; private File testIncomingFile; private String basePath; public static final String DATE_FORMAT_STRING = "yyyyMMddHHmmss"; @Before public void createDirPoll() throws Exception { basePath = createTempDir(); dirPoll = new DirPoll(); dirPoll.setPath(basePath); dirPoll.setPollInterval(DIRPOLL_CHECK_INTERVAL); dirPoll.setProcessor(new DirPoll.FileProcessor() { @Override public void process(File name) { fileProcessed = true; } }); dirPoll.createDirs(); emptyDirectories(); new Thread(dirPoll).start(); } private String createTempDir() throws IOException { File temp = File.createTempFile("dir_poll", "tmp"); temp.delete(); // delete the file, we want a dir temp.mkdirs(); return temp.getAbsolutePath(); } @After public void destroyDirPoll() throws Exception { dirPoll.destroy(); emptyDirectories(); dirPoll = null; testIncomingFile = null; } @Test public void testBadFile() throws Exception { String filename = "dodgyTestFile.test"; dirPoll.setProcessor(new DirPoll.FileProcessor() { @Override public void process(File name) throws DirPoll.DirPollException { fileProcessed = true; throw new DirPoll.DirPollException(); } }); dirPoll.setShouldArchive(true); dirPoll.setArchiveDateFormat(DATE_FORMAT_STRING); dirPoll.setShouldTimestampArchive(true); testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, filename)); FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile); fileOutputStream.write("test".getBytes()); fileOutputStream.flush(); fileOutputStream.close(); assertThat(testIncomingFile.exists(), is(true)); File badDirectory = new File(absolutePathTo(RELATIVE_BAD_DIR)); waitForFileProcessed(); waitForNumFilesInDirOrTimeout(1, badDirectory, 200); assertThat(badDirectory.listFiles().length, is(1)); assertThat(badDirectory.listFiles()[0].getName().length(), is(DATE_FORMAT_STRING.length() + filename.length() + 1)); } @Test public void testArchiveFile() throws IOException, InterruptedException { String filename = "dodgyTestFile.test"; dirPoll.setShouldArchive(true); dirPoll.setArchiveDateFormat(DATE_FORMAT_STRING); dirPoll.setShouldTimestampArchive(true); testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, filename)); FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile); fileOutputStream.write("test".getBytes()); fileOutputStream.flush(); fileOutputStream.close(); assertThat(testIncomingFile.exists(), is(true)); File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR)); waitForFileProcessed(); waitForNumFilesInDirOrTimeout(1, archiveDirectory, 200); assertThat(archiveDirectory.listFiles().length, is(1)); assertThat(archiveDirectory.listFiles()[0].getName().length(), is(DATE_FORMAT_STRING.length() + filename.length() + 1)); } @Test public void testCompressArchiveFile() throws IOException, InterruptedException { String filename = "dodgyTestFile.test"; dirPoll.setShouldArchive(true); dirPoll.setShouldCompressArchive(true); dirPoll.setArchiveDateFormat(DATE_FORMAT_STRING); dirPoll.setShouldTimestampArchive(false); testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, filename)); FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile); fileOutputStream.write("test".getBytes()); fileOutputStream.flush(); fileOutputStream.close(); assertThat(testIncomingFile.exists(), is(true)); File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR)); waitForFileProcessed(); waitForNumFilesInDirOrTimeout(1, archiveDirectory, 5000); assertThat(archiveDirectory.listFiles().length, is(1)); assertThat(archiveDirectory.listFiles()[0].getName(), is(testIncomingFile.getName() + ".zip")); } @Test public void testDoNotArchiveFile() throws IOException, InterruptedException { dirPoll.setShouldArchive(false); testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, "dodgyTestFile2.test")); FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile); fileOutputStream.write("test".getBytes()); fileOutputStream.flush(); fileOutputStream.close(); assertThat(testIncomingFile.exists(), is(true)); waitForFileProcessed(); Thread.sleep(200); File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR)); assertThat(archiveDirectory.listFiles().length, is(0)); } @Test public void testArchiveNoTimestamp() throws Exception { String filename = "dodgyTestFile3.test"; dirPoll.setShouldArchive(true); dirPoll.setShouldTimestampArchive(false); testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, filename)); FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile); fileOutputStream.write("test".getBytes()); fileOutputStream.flush(); fileOutputStream.close(); assertThat(testIncomingFile.exists(), is(true)); waitForFileProcessed(); File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR)); waitForNumFilesInDirOrTimeout(1, archiveDirectory, 200); assertThat(archiveDirectory.listFiles().length, is(1)); assertThat(archiveDirectory.listFiles()[0].getName().length(), is(filename.length())); assertThat(archiveDirectory.listFiles()[0].getName(), is(filename)); } @Test public void testPause() throws Exception { dirPoll.setShouldArchive(false); dirPoll.pause(); testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, "dodgyTestFile3.test")); FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile); fileOutputStream.write("test".getBytes()); fileOutputStream.flush(); fileOutputStream.close(); assertThat(testIncomingFile.exists(), is(true)); // Sleep for enough time for dirpoll to pick up the file, if it wasn't paused Thread.sleep(DIRPOLL_CHECK_INTERVAL); assertThat(testIncomingFile.exists(), is(true)); assertThat(dirPoll.isPaused(), is(true)); dirPoll.unpause(); waitForFileProcessed(); assertThat(testIncomingFile.exists(), is(false)); } private void waitForFileProcessed() throws InterruptedException { while (!fileProcessed) { Thread.sleep(LITTLE_SLEEP); } } private void waitForNumFilesInDirOrTimeout(int numFiles, File dir, int timeout) throws InterruptedException { long waitedFor = 0; while (dir.listFiles().length != numFiles || waitedFor < timeout) { waitedFor += LITTLE_SLEEP; Thread.sleep(LITTLE_SLEEP); } } private void emptyDirectories() { File archiveDir = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR)); File[] files = archiveDir.listFiles(); for (File file : files) { file.delete(); } File badDir = new File(absolutePathTo(RELATIVE_BAD_DIR)); files = badDir.listFiles(); for (File file : files) { file.delete(); } } private String absolutePathTo(String... relativePaths) { String path = basePath; for (String relativePath : relativePaths) { path = path + File.separator + relativePath; } return path; } }
package k57ca.pmp.askeverywhere; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.ListActivity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; @SuppressLint("NewApi") public class MainActivity extends ListActivity { private ProgressDialog pDialog; // URL to get contacts JSON private static String url = "http://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow&filter=withBody"; // JSON Node names private static final String TAG_CONTACTS = "contacts"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_EMAIL = "email"; private static final String TAG_ADDRESS = "address"; private static final String TAG_GENDER = "gender"; private static final String TAG_PHONE = "phone"; private static final String TAG_PHONE_MOBILE = "mobile"; private static final String TAG_PHONE_HOME = "home"; private static final String TAG_PHONE_OFFICE = "office"; private static final String TAG_ITEMS = "items"; private static final String TAG_TITLE = "title"; private static final String TAG_LINK = "link"; private static final String TAG_BODY = "body"; // contacts JSONArray JSONArray items = null; // Hashmap for ListView public ArrayList<HashMap<String, String>> itemList; public static String[] titles = new String[30]; public static String[] bodys = new String[30]; int index = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Calling async task to get json new GetQuestions().execute(); } /** * Async task class to get json by making HTTP call * */ private class GetQuestions extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node items = jsonObj.getJSONArray(TAG_ITEMS); // looping through All Contacts for (int i = 0; i < items.length(); i++) { JSONObject q = items.getJSONObject(i); String title = q.getString(TAG_TITLE); String link = q.getString(TAG_LINK); String body = q.getString(TAG_BODY); titles[index] = title; bodys[index] = body; Log.d(title, body); index++; } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); int base = Menu.FIRST; MenuItem search = menu.add(base, 1, 1, "Newsfeed"); // MenuItem addQuestion = menu.add(base, 2, 2, "Add question"); // MenuItem help = menu.add(base, 3, 3, "Help"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case 1: IntentsUtils.newsfeed(this); break; case 2: break; case 3: break; default: return super.onOptionsItemSelected(item); } return true; } }
package client.controllers; import client.SimpleCallback; import client.view.ErrorHighlighter; import client.windows.BudgetsListWindow; import client.windows.SignUpWindow; import common.*; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.stage.Stage; import javax.naming.AuthenticationException; import java.io.IOException; import java.net.URL; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; import java.util.ResourceBundle; public class LoginController implements Initializable { @FXML Button btnSignUp, btnLogIn; @FXML TextField txtFieldEmail; @FXML PasswordField txtFieldPassword; @FXML Label errorLabel; public static DBHandler dbController; public static AccessProvider ac; public static User currentUser; private static String host; private RemoteCallback rc; private Stage currentStage; public void setStage(Stage stage) { currentStage = stage; } public void setDbController(DBHandler dbhandler) { dbController = dbhandler; } public void connectWithRMIHost(String host) { this.host = (host == null ? "localhost" : host); if (System.getSecurityManager() == null) System.setSecurityManager(new SecurityManager()); try { ac = (AccessProvider) LocateRegistry.getRegistry(host).lookup("AccessProvider"); } catch (Exception e) { e.printStackTrace(); displayUnableToConnectWithServerAlert(); System.exit(1); } try { rc = new SimpleCallback(); RemoteCallback exp = (RemoteCallback) UnicastRemoteObject.exportObject(rc, 1101); ((CallbackManager) LocateRegistry.getRegistry(host).lookup("UpdateManager")).register(exp); } catch (RemoteException|NotBoundException re) { System.out.println("Cannot register callback"); re.printStackTrace(); } } private void displayUnableToConnectWithServerAlert() { Alert unableToConnectAlert = new Alert(Alert.AlertType.ERROR); unableToConnectAlert.setTitle("Unable to connect with server"); unableToConnectAlert.setHeaderText("Unable to connect with server!"); unableToConnectAlert.setContentText("Check your connection and try again."); unableToConnectAlert.showAndWait(); } public void fillDataFields(String email, String password) { txtFieldEmail.setText(email); txtFieldPassword.setText(password); } @Override public void initialize(URL location, ResourceBundle resources) { btnSignUp.setOnAction(event -> { try { SignUpWindow signUpWindow = new SignUpWindow(this); signUpWindow.initOwner(currentStage); signUpWindow.showAndWait(); } catch (Exception e) { e.printStackTrace(); } }); btnLogIn.setOnAction(event -> { if (System.getSecurityManager() == null) System.setSecurityManager(new SecurityManager()); try { errorLabel.setText(""); ErrorHighlighter.unhighlitghtFields(txtFieldEmail, txtFieldPassword); tryToLogIn(); displayBudgetsListWindow(); } catch (AuthenticationException | IllegalArgumentException e) { errorLabel.setText("Incorrect email or password"); ErrorHighlighter.highlightInvalidFields(txtFieldEmail, txtFieldPassword); } catch (IOException e) { errorLabel.setText("Connection with server error"); e.printStackTrace(); } }); btnLogIn.setOnKeyPressed(event -> { if (event.getCode().compareTo(KeyCode.ENTER) == 0) btnLogIn.fire(); }); } private void tryToLogIn() throws RemoteException, AuthenticationException { final Email email = new Email(txtFieldEmail.getText()); final String passwordHash = SHA1Hasher.hash(txtFieldPassword.getText()); dbController = (DBHandler) ac.getDBHandler(email, passwordHash); currentUser = dbController.getUserByEmail(txtFieldEmail.getText()); } private void displayBudgetsListWindow() throws IOException { BudgetsListWindow budgetsListWindow = new BudgetsListWindow(); budgetsListWindow.setOnHidden(e -> currentStage.show()); currentStage.hide(); txtFieldPassword.clear(); budgetsListWindow.show(); } }
package ceylon; public final class Boolean extends Object { private final boolean value; private Boolean(boolean b) { value = b; } public static ceylon.Boolean instance(boolean b) { return new ceylon.Boolean(b); } @Extension public ceylon.String string() { return ceylon.String.instance(java.lang.Boolean.toString(value)); } @Extension public boolean booleanValue() { return value; } }
package com.DCSP.screen; import com.DCSP.http.HttpConnection; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable; public class MainMenuScreen extends ScreenInterface{ private int WIDTH, HEIGHT; private SpriteBatch batch; private Sprite background; private SpriteDrawable settings; private Stage menuStage; private Table menuTable,gear; private Skin skin; private Label nameLbl, passLbl; private TextField nameTxt,passTxt; private TextButton playBtn, quitBtn, register,login; private ImageButton settingsBtn; // Windows private Window successWindow; @Override public void show() { WIDTH = Gdx.graphics.getWidth(); HEIGHT = Gdx.graphics.getHeight(); menuStage = new Stage(); Gdx.input.setInputProcessor(menuStage); Gdx.input.setCatchBackKey(true); menuTable = new Table(); menuTable.setFillParent(true); gear = new Table(); gear.setFillParent(true); Texture splashTexture = new Texture("img/menu.png"); background = new Sprite(splashTexture); background.setSize(WIDTH, HEIGHT); Texture settingsTexture = new Texture("img/settings.png"); Sprite settingsSprite = new Sprite(settingsTexture); settingsSprite.setSize(30, 30); settings = new SpriteDrawable(settingsSprite); skin = new Skin(Gdx.files.internal("uiskin.json")); nameLbl = new Label("Username", skin); nameTxt = new TextField("", skin,"user"); passLbl = new Label("Password", skin); passTxt = new TextField("", skin,"user"); passTxt.setPasswordMode(true); passTxt.setPasswordCharacter('*'); settingsBtn = new ImageButton(settings); playBtn = new TextButton("Play Demo", skin); quitBtn = new TextButton("Exit", skin); login = new TextButton("Login", skin); register = new TextButton("Register", skin); playBtn.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { gameParent.setScreen(new MazeScreen()); //*testing*/gameParent.setScreen(new GameMenuScreen()); } }); settingsBtn.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { HttpConnection test = new HttpConnection(gameParent); //test.getHighScores(); test.getChallenges(0); test.getFriends(6); //gameParent.setScreen(gameParent.settingsScreen); } }); quitBtn.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { Gdx.app.exit(); } }); login.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { HttpConnection httpCon = new HttpConnection(gameParent); httpCon.login(nameTxt.getText(), passTxt.getText(), successWindow); } }); register.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { gameParent.setScreen(new RegistrationScreen()); } }); gear.add(settingsBtn).pad(15); gear.top().right(); menuStage.addActor(gear); menuTable.defaults().pad(10).minHeight(HEIGHT/9); menuTable.add(nameLbl).minWidth(90); // 10 difference due to padding menuTable.add(nameTxt).minWidth(WIDTH/2 - 100); menuTable.row(); menuTable.add(passLbl).minWidth(90); menuTable.add(passTxt).minWidth(WIDTH/2 - 100); menuTable.row(); menuTable.add(login).colspan(2).minWidth(WIDTH/2); menuTable.row(); menuTable.add(register).colspan(2).minWidth(WIDTH/2); menuTable.row(); menuTable.add(playBtn).colspan(2).minWidth(WIDTH/2); menuTable.row(); menuTable.add(quitBtn).colspan(2).minWidth(WIDTH/2); menuStage.addActor(menuTable); //Check window /* * make this method call to put the login failed window appear * successWindow.setVisible(true); */ successWindow = new Window("Login Failed", skin); successWindow.setMovable(false); successWindow.padTop(20); Label successWindowLbl = new Label("Incorrect Username or Password.\nPlease try again.\n", skin, "small"); successWindow.add(successWindowLbl); successWindow.setWidth(successWindowLbl.getWidth() + 20); successWindow.row(); TextButton successOK = new TextButton("Ok", skin); successOK.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { successWindow.setVisible(false); } }); successWindow.add(successOK); successWindow.setVisible(false); successWindow.setPosition(WIDTH/2, HEIGHT/2, Align.center); successWindow.pack(); menuStage.addActor(successWindow); //end check window // Always add the generic message window menuStage.addActor(gameParent.getMessageWindow().getWindow()); batch = new SpriteBatch(); } @Override public void render(float delta) { Gdx.gl.glClearColor(0,1,0,1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); background.draw(batch); batch.end(); menuStage.act(delta); menuStage.draw(); } @Override public void resize(int width, int height) { menuStage.getViewport().update(width,height); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { batch.dispose(); background.getTexture().dispose(); menuStage.dispose(); } }
package com.starseed.game; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.starseed.screens.GameMultiplayerScreen; import com.starseed.screens.MainScreen; import com.starseed.util.Constants; import com.starseed.util.SoundManager; import com.starseed.screens.AbstractScreen; public class StarSeedGame extends Game { private Music bgMusic; @Override public void create () { setUpSound(); GameMultiplayerScreen gameScreen = new GameMultiplayerScreen(); MainScreen mainScreen = new MainScreen(); mainScreen.setNextScreen(gameScreen); gameScreen.setBackScreen(mainScreen); setScreen(mainScreen); } private void setUpSound() { bgMusic = Gdx.audio.newMusic(Gdx.files.internal(Constants.MAIN_SOUND_FILE)); bgMusic.play(); // plays the sound a second time, this is treated as a different instance bgMusic.setVolume(0.12f); bgMusic.setLooping(true); // keeps the sound looping SoundManager.preloadSounds(); } @Override public void dispose() { super.dispose(); bgMusic.stop(); bgMusic.dispose(); } @Override public void render() { super.render(); AbstractScreen currentScreen = (AbstractScreen) getScreen(); if (currentScreen.goBack) { AbstractScreen tmp = currentScreen.getBackScreen(); if (tmp != null) { setScreen(tmp); } else { Gdx.app.exit(); } } else if (currentScreen.goToNextScreen) { AbstractScreen tmp = currentScreen.getNextScreen(); if (tmp != null) { setScreen(tmp); } else { Gdx.app.exit(); } } } }
import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.util.*; import java.security.*; import org.jibble.pircbot.Colors; import java.util.regex.*; import java.io.*; /** * Choob nickserv checker * * @author bucko * * Anyone who needs further docs for this module has some serious Java issues. * :) */ // Holds the NickServ result public class ResultObj { int result; long time; } public class NickServ { public String[] info() { return new String[] { "NickServ checker plugin.", "The Choob Team", "choob@uwcs.co.uk", "$Rev$$Date$" }; } private boolean ip_overrides=false; // If this is enabled, all nickserv checks will also be validates against a /USERIP. This can be poked on, but will be automatically disabled if a nickserv check succeeds or the file fails to read. private static int TIMEOUT = 10000; // Timeout on nick checks. // private static int CACHE_TIMEOUT = 3600000; // Timeout on nick check cache (1 hour). // ^^ Can only be used once we can verify a user is in a channel and thus trust their online-ness. private static int CACHE_TIMEOUT = 300000; // Timeout on nick check cache (5 mins). private Map<String,ResultObj> nickChecks; Modules mods; IRCInterface irc; /** Enable horrible hacks. If you know which network you're going to be using the bot on, finalize this, and all of the other code will get removed by the compiler. */ boolean infooverride=false; final Pattern validInfoReply=Pattern.compile("^(?:\\s*Nickname: ([^\\s]+) ?(<< ONLINE >>)?)|(?:The nickname \\[([^\\s]+)\\] is not registered)$"); public NickServ(Modules mods, IRCInterface irc) { nickChecks = new HashMap<String,ResultObj>(); this.irc = irc; this.mods = mods; if (infooverride==false) // Check ensure that our NickServ is sane, and, if not, enable workarounds. mods.interval.callBack(null, 100); } // This is triggered by the constructor. public synchronized void interval( Object parameter, Modules mods, IRCInterface irc ) throws ChoobException { String nick = "ignore-me"; // It's completely irrelevant what this nick is. ResultObj result = getNewNickCheck( nick ); } public void destroy(Modules mods) { synchronized(nickChecks) { Iterator<String> nicks = nickChecks.keySet().iterator(); while(nicks.hasNext()) { ResultObj result = getNickCheck(nicks.next()); synchronized(result) { result.notifyAll(); } } } } public String[] helpApi = { "NickServ allows your plugin to poke NickServ and get auth status on" + " nicknames. It gives you two API methods: Check and Status. Both" + " take a single String parameter and Check returns a Boolean, Status" + " an Integer. If the status is 3, the nick is considered authed," + " anything lower is not." }; public String[] helpCommandCheck = { "Check if someone's authed with NickServ.", "[<NickName>]", "<NickName> is an optional nick to check" }; public void commandCheck( Message mes ) throws ChoobException { String nick = mods.util.getParamString( mes ); if (nick.length() == 0) nick = mes.getNick(); int check1 = (Integer)mods.plugin.callAPI("NickServ", "Status", nick); if ( check1 == 3 ) { irc.sendContextReply(mes, nick + " is authed (" + check1 + ")!"); } else { irc.sendContextReply(mes, nick + " is not authed (" + check1 + ")!"); } } public int apiStatus( String nick ) { ResultObj result = getCachedNickCheck( nick.toLowerCase() ); if (result != null) { return result.result; } result = getNewNickCheck( nick.toLowerCase() ); synchronized(result) { try { result.wait(30000); // Make sure if NickServ breaks we're not screwed } catch (InterruptedException e) { // Ooops, timeout ip_overrides=true; return -1; } } int status = result.result; return status; } public boolean apiCheck( String nick ) { return apiCheck( nick, false ); } public boolean apiCheck( String nick, boolean assumption ) { int stat = apiStatus( nick ); if (stat == -1) return assumption; else return stat >= 3; } private ResultObj getNewNickCheck( final String nick ) { ResultObj result; synchronized(nickChecks) { result = nickChecks.get( nick ); if ( result == null ) { // Not already waiting on this one result = new ResultObj(); result.result = -1; AccessController.doPrivileged( new PrivilegedAction() { public Object run() { irc.sendMessage("NickServ", (infooverride ? "INFO " : "STATUS ") + nick); if (ip_overrides) irc.sendRawLine("USERIP " + nick); return null; } }); nickChecks.put( nick, result ); } } return result; } private ResultObj getNickCheck( String nick ) { synchronized(nickChecks) { return (ResultObj)nickChecks.get( nick ); } } private ResultObj getCachedNickCheck( String nick ) { ResultObj result; synchronized(nickChecks) { result = (ResultObj)nickChecks.get( nick ); if ( result == null ) // !!! This should never really happen return null; if (result.result == -1) return null; if ( result.time + TIMEOUT < System.currentTimeMillis() ) { // expired! // TODO - do this in an interval... nickChecks.remove( nick ); return null; } } return result; } public String[] optionsGeneral = { "Password" }; public boolean optionCheckGeneralPassword( String value ) { return true; } public String[] helpOptionPassword = { "Set this to the bot's NickServ password to make it identify with NickServ." }; public String[] helpCommandEnableOverride = { "Private use only, mmkay?" }; public void commandEnableOverride(Message mes) { ip_overrides=true; irc.sendContextReply(mes, "Kay."); } public void onServerResponse(ServerResponse resp) { if (resp.getCode() == 401) // 401 Nick Not Found. { Matcher ma = Pattern.compile("^[^ ]+ ([^ ]+) ").matcher(resp.getResponse().trim()); if (ma.find() && ma.group(1).trim().toLowerCase().equals("nickserv")) ip_overrides=true; } if (ip_overrides && resp.getCode()==340) // USERIP response, not avaliable through PircBOT, gogo magic numbers. { /* * General response ([]s as quotes): * [Botnick] :[Nick]=+[User]@[ip, or, more likely, hash] * * for (a terrible) example: * Choobie| :Faux=+Faux@87029A85.60BE439B.C4C3F075.IP */ Matcher ma=Pattern.compile("^[^ ]+ :([^=]+)=(.*)").matcher(resp.getResponse().trim()); if (!ma.find()) { System.err.println("Unexpected non-match."); return; } ResultObj result = getNickCheck( ma.group(1).trim().toLowerCase() ); if ( result == null ) { // Something else handled it, we shouldn't be here. ip_overrides=false; return; } synchronized(result) { String line; result.result = 0; try { BufferedReader allowed = new BufferedReader(new FileReader("userip.list")); while((line=allowed.readLine())!=null) if (ma.group(2).equals(line)) { result.result=3; break; } } catch (IOException e) { // e.printStackTrace(); ip_overrides=false; System.err.println("Error reading userip.list, disabling overrides."); } result.time = System.currentTimeMillis(); result.notifyAll(); } } } public void onPrivateNotice( Message mes ) { if ( ! (mes instanceof PrivateNotice) ) return; // Only interested in private notices if ( ! mes.getNick().toLowerCase().equals( "nickserv" ) ) return; // Not from NickServ --> also don't care if (!infooverride && mes.getMessage().trim().toLowerCase().equals("unknown command [status]")) { // Ohes nose, horribly broken network! Let's pretend that it didn't just slap us in the face with a glove. System.err.println("Reverting to badly broken NickServ handling."); infooverride = true; synchronized (nickChecks) { nickChecks.clear(); // <-- Ooh, lets break things. } // Any pending nick checks will fail, but.. well, bah. return; } List<String> params = mods.util.getParams( mes ); String nick; int status; if (infooverride) { if (mes.getMessage().indexOf("Nickname: ") == -1 && mes.getMessage().indexOf("The nickname [") == -1) return; // Wrong type of message! Matcher ma = validInfoReply.matcher(Colors.removeFormattingAndColors(mes.getMessage())); if (!ma.matches()) return; nick = ma.group(1); if (nick == null) { // Unregistered nick = ma.group(3); status = 0; } else // Registered status = (ma.group(2) == null || ma.group(2).equals("")) ? 1 : 3; } else { if ( mes.getMessage().matches(".*(?i:/msg NickServ IDENTIFY).*") ) { // must identify String pass = null; try { pass = (String)mods.plugin.callAPI("Options", "GetGeneralOption", "password"); } catch (ChoobNoSuchCallException e) { System.err.println("Options plugin not loaded; can't get NickServ password."); return; } if (pass != null) { System.err.println("Sending NickServ password!"); irc.sendContextMessage(mes, "IDENTIFY " + pass); } else System.err.println("Password option for plugin NickServ not set..."); return; } else if ( params.size() > 2 && params.get(1).equalsIgnoreCase("is") ) { // Online! But not registered (I'd hope) nick = params.get(0); status = 1; } else if ( params.size() == 4 && params.get(0).equalsIgnoreCase("nickname") && params.get(2).equalsIgnoreCase("isn't") && params.get(3).equalsIgnoreCase("registered.") ) { // Registered but offline. nick = Colors.removeFormattingAndColors(params.get(1)); status = 0; } else if ( params.get(0).equalsIgnoreCase("status") ) { nick = (String)params.get(1); status = Integer.valueOf((String)params.get(2)); if (status == 0) { // We'd like 0 = not registered, 1 = offline/not identified. // As such we need to check existence too. now. irc.sendContextMessage(mes, "INFO " + nick); return; } } else return; // Wrong type of message! } ResultObj result = getNickCheck( nick.toLowerCase() ); if ( result == null ) return; // XXX synchronized(result) { result.result = status; result.time = System.currentTimeMillis(); result.notifyAll(); } ip_overrides=false; } // Expire old checks when appropriate... public void onNickChange( NickChange nc ) { synchronized(nickChecks) { nickChecks.remove(nc.getNick()); nickChecks.remove(nc.getNewNick()); } } public void onJoin( ChannelJoin cj ) { synchronized(nickChecks) { nickChecks.remove(cj.getNick()); } } public void onKick( ChannelKick ck ) { synchronized(nickChecks) { nickChecks.remove(ck.getTarget()); } } public void onPart( ChannelPart cp ) { synchronized(nickChecks) { nickChecks.remove(cp.getNick()); } } public void onQuit( QuitEvent qe ) { synchronized(nickChecks) { nickChecks.remove(qe.getNick()); } } }
package bisq.core.locale; import bisq.core.app.BisqEnvironment; import bisq.core.btc.BaseCurrencyNetwork; import bisq.common.UserThread; import bisq.common.app.DevEnv; import org.apache.commons.lang3.StringUtils; import java.text.MessageFormat; import java.net.URL; import java.net.URLConnection; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Locale; import java.util.MissingResourceException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; @Slf4j public class Res { public static void setup() { BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); setBaseCurrencyCode(baseCurrencyNetwork.getCurrencyCode()); setBaseCurrencyName(baseCurrencyNetwork.getCurrencyName()); } @SuppressWarnings("CanBeFinal") private static ResourceBundle resourceBundle = ResourceBundle.getBundle("i18n.displayStrings", GlobalSettings.getLocale(), new UTF8Control()); static { GlobalSettings.localeProperty().addListener((observable, oldValue, newValue) -> { if ("en".equalsIgnoreCase(newValue.getLanguage())) newValue = Locale.ROOT; resourceBundle = ResourceBundle.getBundle("i18n.displayStrings", newValue, new UTF8Control()); }); } public static String getWithCol(String key) { return get(key) + ":"; } public static String getWithColAndCap(String key) { return StringUtils.capitalize(get(key)) + ":"; } public static ResourceBundle getResourceBundle() { return resourceBundle; } private static String baseCurrencyCode; private static String baseCurrencyName; private static String baseCurrencyNameLowerCase; public static void setBaseCurrencyCode(String baseCurrencyCode) { Res.baseCurrencyCode = baseCurrencyCode; } public static void setBaseCurrencyName(String baseCurrencyName) { Res.baseCurrencyName = baseCurrencyName; baseCurrencyNameLowerCase = baseCurrencyName.toLowerCase(); } public static String getBaseCurrencyCode() { return baseCurrencyCode; } public static String getBaseCurrencyName() { return baseCurrencyName; } // Capitalize first character public static String getWithCap(String key) { return StringUtils.capitalize(get(key)); } public static String getWithCol(String key, Object... arguments) { return get(key, arguments) + ":"; } public static String get(String key, Object... arguments) { return MessageFormat.format(Res.get(key), arguments); } public static String get(String key) { try { return resourceBundle.getString(key) .replace("BTC", baseCurrencyCode) .replace("Bitcoin", baseCurrencyName) .replace("bitcoin", baseCurrencyNameLowerCase); } catch (MissingResourceException e) { log.warn("Missing resource for key: " + key); e.printStackTrace(); if (DevEnv.isDevMode()) UserThread.runAfter(() -> { // We delay a bit to not throw while UI is not ready throw new RuntimeException("Missing resource for key: " + key); }, 1); return key; } } } // Adds UTF8 support for property files class UTF8Control extends ResourceBundle.Control { public ResourceBundle newBundle(String baseName, @NotNull Locale locale, @NotNull String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { // The below is a copy of the default implementation. final String bundleName = toBundleName(baseName, locale); final String resourceName = toResourceName(bundleName, "properties"); ResourceBundle bundle = null; InputStream stream = null; if (reload) { final URL url = loader.getResource(resourceName); if (url != null) { final URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { try { // Only this line is changed to make it to read properties files as UTF-8. bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8")); } finally { stream.close(); } } return bundle; } }
package battlecode.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.LinkedList; import java.util.List; import battlecode.server.controller.Controller; import battlecode.server.controller.ControllerFactory; import battlecode.server.controller.SQLController; import battlecode.server.proxy.Proxy; import battlecode.server.proxy.ProxyFactory; import battlecode.util.SQLQueue; public class ServerFactory { public static Server createLocalServer(Config options, Proxy proxy, String saveFile) throws IOException { Controller controller = ControllerFactory.createLocalController(options, proxy); List<Proxy> proxies = new LinkedList<Proxy>(); if (saveFile != null) proxies.add(ProxyFactory.createProxyFromFile(saveFile)); proxies.add(proxy); Server server = new Server(options, Server.Mode.LOCAL, controller, proxies.toArray(new Proxy[0])); controller.addObserver(server); return server; } public static Server createHeadlessServer(Config options, String saveFile) throws IOException { Controller controller = ControllerFactory .createHeadlessController(options); Proxy[] proxies = new Proxy[] { ProxyFactory .createProxyFromFile(saveFile) }; Server server = new Server(options, Server.Mode.HEADLESS, controller, proxies); controller.addObserver(server); return server; } public static Server createRemoteServer(Config options, int port, String saveFile) throws IOException { RPCServer rpcServer; Thread rpcThread; final MatchInputFinder finder = new MatchInputFinder(); // Start a new RPC server for handling match input requests. rpcServer = new RPCServer() { public Object handler(Object arg) { if ("find-match-inputs".equals(arg)) return finder.findMatchInputsLocally(); return null; } }; // Run it in a new thread. rpcThread = new Thread(rpcServer); rpcThread.setDaemon(true); rpcThread.start(); // Start a server socket listening on the default port. ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); // serverSocket.close(); (?) Controller controller = ControllerFactory .createTCPController(clientSocket.getInputStream(),options); List<Proxy> proxies = new LinkedList<Proxy>(); if (saveFile != null) proxies.add(ProxyFactory.createProxyFromFile(saveFile)); proxies.add(ProxyFactory.createProxy(clientSocket.getOutputStream())); Server server = new Server(options, Server.Mode.TCP, controller, proxies.toArray(new Proxy[proxies.size()])); controller.addObserver(server); return server; } public static Server createPipeServer(Config options, String saveFile) throws IOException { Controller controller = ControllerFactory .createTCPController(System.in,options); List<Proxy> proxies = new LinkedList<Proxy>(); if (saveFile != null) proxies.add(ProxyFactory.createProxyFromFile(saveFile)); proxies.add(ProxyFactory.createProxy(System.out)); // since we're sending the match file to System.out, don't send log // messages there System.setOut(System.err); Server server = new Server(options, Server.Mode.TCP, controller, proxies.toArray(new Proxy[proxies.size()])); controller.addObserver(server); return server; } public static Server createSQLServer(Config options, SQLQueue queue, Server.Mode mode) throws IOException { Controller controller = ControllerFactory.createSQLController(queue); boolean bestOfThree = (mode == Server.Mode.TOURNAMENT || mode == Server.Mode.SCRIMMAGE || mode == Server.Mode.AUTOTEST || mode == Server.Mode.MATCH); Server server = new Server(options, mode, controller, new Proxy[] { ProxyFactory.createSQLProxy(queue, bestOfThree) }); controller.addObserver(server); return server; } }
package hudson; import static hudson.init.InitMilestone.PLUGINS_PREPARED; import static hudson.init.InitMilestone.PLUGINS_STARTED; import static hudson.init.InitMilestone.PLUGINS_LISTED; import hudson.PluginWrapper.Dependency; import hudson.init.InitStrategy; import hudson.init.InitializerFinder; import hudson.model.AbstractModelObject; import hudson.model.Failure; import jenkins.model.Jenkins; import hudson.model.UpdateCenter; import hudson.model.UpdateSite; import hudson.util.CyclicGraphDetector; import hudson.util.CyclicGraphDetector.CycleDetectedException; import hudson.util.FormValidation; import hudson.util.PersistedList; import hudson.util.Service; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.LogFactory; import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.TaskBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.Map; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * Manages {@link PluginWrapper}s. * * @author Kohsuke Kawaguchi */ public abstract class PluginManager extends AbstractModelObject { /** * All discovered plugins. */ protected final List<PluginWrapper> plugins = new ArrayList<PluginWrapper>(); /** * All active plugins. */ protected final List<PluginWrapper> activePlugins = new CopyOnWriteArrayList<PluginWrapper>(); protected final List<FailedPlugin> failedPlugins = new ArrayList<FailedPlugin>(); /** * Plug-in root directory. */ public final File rootDir; /** * @deprecated as of 1.355 * {@link PluginManager} can now live longer than {@link jenkins.model.Jenkins} instance, so * use {@code Hudson.getInstance().servletContext} instead. */ public final ServletContext context; /** * {@link ClassLoader} that can load all the publicly visible classes from plugins * (and including the classloader that loads Hudson itself.) * */ // and load plugin-contributed classes. public final ClassLoader uberClassLoader = new UberClassLoader(); /** * Once plugin is uploaded, this flag becomes true. * This is used to report a message that Hudson needs to be restarted * for new plugins to take effect. */ public volatile boolean pluginUploaded = false; /** * The initialization of {@link PluginManager} splits into two parts; * one is the part about listing them, extracting them, and preparing classloader for them. * The 2nd part is about creating instances. Once the former completes this flags become true, * as the 2nd part can be repeated for each Hudson instance. */ private boolean pluginListed = false; /** * Strategy for creating and initializing plugins */ private final PluginStrategy strategy; public PluginManager(ServletContext context, File rootDir) { this.context = context; this.rootDir = rootDir; if(!rootDir.exists()) rootDir.mkdirs(); strategy = createPluginStrategy(); } /** * Called immediately after the construction. * This is a separate method so that code executed from here will see a valid value in * {@link jenkins.model.Jenkins#pluginManager}. */ public TaskBuilder initTasks(final InitStrategy initStrategy) { TaskBuilder builder; if (!pluginListed) { builder = new TaskGraphBuilder() { List<File> archives; Collection<String> bundledPlugins; { Handle loadBundledPlugins = add("Loading bundled plugins", new Executable() { public void run(Reactor session) throws Exception { bundledPlugins = loadBundledPlugins(); } }); Handle listUpPlugins = requires(loadBundledPlugins).add("Listing up plugins", new Executable() { public void run(Reactor session) throws Exception { archives = initStrategy.listPluginArchives(PluginManager.this); } }); requires(listUpPlugins).attains(PLUGINS_LISTED).add("Preparing plugins",new Executable() { public void run(Reactor session) throws Exception { // once we've listed plugins, we can fill in the reactor with plugin-specific initialization tasks TaskGraphBuilder g = new TaskGraphBuilder(); final Map<String,File> inspectedShortNames = new HashMap<String,File>(); for( final File arc : archives ) { g.followedBy().notFatal().attains(PLUGINS_LISTED).add("Inspecting plugin " + arc, new Executable() { public void run(Reactor session1) throws Exception { try { PluginWrapper p = strategy.createPluginWrapper(arc); if (isDuplicate(p)) return; p.isBundled = bundledPlugins.contains(arc.getName()); plugins.add(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(arc.getName(),e)); throw e; } } /** * Inspects duplication. this happens when you run hpi:run on a bundled plugin, * as well as putting numbered hpi files, like "cobertura-1.0.hpi" and "cobertura-1.1.hpi" */ private boolean isDuplicate(PluginWrapper p) { String shortName = p.getShortName(); if (inspectedShortNames.containsKey(shortName)) { LOGGER.info("Ignoring "+arc+" because "+inspectedShortNames.get(shortName)+" is already loaded"); return true; } inspectedShortNames.put(shortName,arc); return false; } }); } g.followedBy().attains(PLUGINS_LISTED).add("Checking cyclic dependencies", new Executable() { /** * Makes sure there's no cycle in dependencies. */ public void run(Reactor reactor) throws Exception { try { CyclicGraphDetector<PluginWrapper> cgd = new CyclicGraphDetector<PluginWrapper>() { @Override protected List<PluginWrapper> getEdges(PluginWrapper p) { List<PluginWrapper> next = new ArrayList<PluginWrapper>(); addTo(p.getDependencies(), next); addTo(p.getOptionalDependencies(), next); return next; } private void addTo(List<Dependency> dependencies, List<PluginWrapper> r) { for (Dependency d : dependencies) { PluginWrapper p = getPlugin(d.shortName); if (p != null) r.add(p); } } }; cgd.run(getPlugins()); // obtain topologically sorted list and overwrite the list ListIterator<PluginWrapper> litr = plugins.listIterator(); for (PluginWrapper p : cgd.getSorted()) { litr.next(); litr.set(p); if(p.isActive()) activePlugins.add(p); } } catch (CycleDetectedException e) { stop(); // disable all plugins since classloading from them can lead to StackOverflow throw e; // let Hudson fail } } }); session.addAll(g.discoverTasks(session)); pluginListed = true; // technically speaking this is still too early, as at this point tasks are merely scheduled, not necessarily executed. } }); } }; } else { builder = TaskBuilder.EMPTY_BUILDER; } final InitializerFinder initializerFinder = new InitializerFinder(uberClassLoader); // misc. stuff // lists up initialization tasks about loading plugins. return TaskBuilder.union(initializerFinder, // this scans @Initializer in the core once builder,new TaskGraphBuilder() {{ requires(PLUGINS_LISTED).attains(PLUGINS_PREPARED).add("Loading plugins",new Executable() { /** * Once the plugins are listed, schedule their initialization. */ public void run(Reactor session) throws Exception { Jenkins.getInstance().lookup.set(PluginInstanceStore.class,new PluginInstanceStore()); TaskGraphBuilder g = new TaskGraphBuilder(); // schedule execution of loading plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_PREPARED).add("Loading plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.resolvePluginDependencies(); strategy.load(p); } catch (IOException e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } // schedule execution of initializing plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { g.followedBy().notFatal().attains(PLUGINS_STARTED).add("Initializing plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { try { p.getPlugin().postInitialize(); } catch (Exception e) { failedPlugins.add(new FailedPlugin(p.getShortName(), e)); activePlugins.remove(p); plugins.remove(p); throw e; } } }); } g.followedBy().attains(PLUGINS_STARTED).add("Discovering plugin initialization tasks", new Executable() { public void run(Reactor reactor) throws Exception { // rescan to find plugin-contributed @Initializer reactor.addAll(initializerFinder.discoverTasks(reactor)); } }); // register them all session.addAll(g.discoverTasks(session)); } }); }}); } * If the war file has any "/WEB-INF/plugins/*.hpi", extract them into the plugin directory. * * @return * File names of the bundled plugins. Like {"ssh-slaves.hpi","subvesrion.hpi"} * @throws Exception * Any exception will be reported and halt the startup. */ protected abstract Collection<String> loadBundledPlugins() throws Exception; /** * Copies the bundled plugin from the given URL to the destination of the given file name (like 'abc.hpi'), * with a reasonable up-to-date check. A convenience method to be used by the {@link #loadBundledPlugins()}. */ protected void copyBundledPlugin(URL src, String fileName) throws IOException { long lastModified = src.openConnection().getLastModified(); File file = new File(rootDir, fileName); File pinFile = new File(rootDir, fileName+".pinned"); // update file if: // - no file exists today // - bundled version and current version differs (by timestamp), and the file isn't pinned. if (!file.exists() || (file.lastModified() != lastModified && !pinFile.exists())) { FileUtils.copyURLToFile(src, file); file.setLastModified(src.openConnection().getLastModified()); // lastModified is set for two reasons: // - to avoid unpacking as much as possible, but still do it on both upgrade and downgrade // - to make sure the value is not changed after each restart, so we can avoid // unpacking the plugin itself in ClassicPluginStrategy.explode } } /** * Creates a hudson.PluginStrategy, looking at the corresponding system property. */ protected PluginStrategy createPluginStrategy() { String strategyName = System.getProperty(PluginStrategy.class.getName()); if (strategyName != null) { try { Class<?> klazz = getClass().getClassLoader().loadClass(strategyName); Object strategy = klazz.getConstructor(PluginManager.class) .newInstance(this); if (strategy instanceof PluginStrategy) { LOGGER.info("Plugin strategy: " + strategyName); return (PluginStrategy) strategy; } else { LOGGER.warning("Plugin strategy (" + strategyName + ") is not an instance of hudson.PluginStrategy"); } } catch (ClassNotFoundException e) { LOGGER.warning("Plugin strategy class not found: " + strategyName); } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not instantiate plugin strategy: " + strategyName + ". Falling back to ClassicPluginStrategy", e); } LOGGER.info("Falling back to ClassicPluginStrategy"); } // default and fallback return new ClassicPluginStrategy(this); } public PluginStrategy getPluginStrategy() { return strategy; } /** * Returns true if any new plugin was added, which means a restart is required * for the change to take effect. */ public boolean isPluginUploaded() { return pluginUploaded; } public List<PluginWrapper> getPlugins() { return plugins; } public List<FailedPlugin> getFailedPlugins() { return failedPlugins; } public PluginWrapper getPlugin(String shortName) { for (PluginWrapper p : plugins) { if(p.getShortName().equals(shortName)) return p; } return null; } /** * Get the plugin instance that implements a specific class, use to find your plugin singleton. * Note: beware the classloader fun. * @param pluginClazz The class that your plugin implements. * @return The plugin singleton or <code>null</code> if for some reason the plugin is not loaded. */ public PluginWrapper getPlugin(Class<? extends Plugin> pluginClazz) { for (PluginWrapper p : plugins) { if(pluginClazz.isInstance(p.getPlugin())) return p; } return null; } /** * Get the plugin instances that extend a specific class, use to find similar plugins. * Note: beware the classloader fun. * @param pluginSuperclass The class that your plugin is derived from. * @return The list of plugins implementing the specified class. */ public List<PluginWrapper> getPlugins(Class<? extends Plugin> pluginSuperclass) { List<PluginWrapper> result = new ArrayList<PluginWrapper>(); for (PluginWrapper p : plugins) { if(pluginSuperclass.isInstance(p.getPlugin())) result.add(p); } return Collections.unmodifiableList(result); } public String getDisplayName() { return Messages.PluginManager_DisplayName(); } public String getSearchUrl() { return "pluginManager"; } /** * Discover all the service provider implementations of the given class, * via <tt>META-INF/services</tt>. */ public <T> Collection<Class<? extends T>> discover( Class<T> spi ) { Set<Class<? extends T>> result = new HashSet<Class<? extends T>>(); for (PluginWrapper p : activePlugins) { Service.load(spi, p.classLoader, result); } return result; } /** * Return the {@link PluginWrapper} that loaded the given class 'c'. * * @since 1.402. */ public PluginWrapper whichPlugin(Class c) { ClassLoader cl = c.getClassLoader(); for (PluginWrapper p : activePlugins) { if (p.classLoader==cl) return p; } return null; } /** * Orderly terminates all the plugins. */ public void stop() { for (PluginWrapper p : activePlugins) { p.stop(); p.releaseClassLoader(); } activePlugins.clear(); // Work around a bug in commons-logging. LogFactory.release(uberClassLoader); } public HttpResponse doUpdateSources(StaplerRequest req) throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); if (req.hasParameter("remove")) { UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(); BulkChange bc = new BulkChange(uc); try { for (String id : req.getParameterValues("sources")) uc.getSites().remove(uc.getById(id)); } finally { bc.commit(); } } else if (req.hasParameter("add")) return new HttpRedirect("addSite"); return new HttpRedirect("./sites"); } /** * Performs the installation of the plugins. */ public void doInstall(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Enumeration<String> en = req.getParameterNames(); while (en.hasMoreElements()) { String n = en.nextElement(); if(n.startsWith("plugin.")) { n = n.substring(7); if (n.indexOf(".") > 0) { String[] pluginInfo = n.split("\\."); UpdateSite.Plugin p = Jenkins.getInstance().getUpdateCenter().getById(pluginInfo[1]).getPlugin(pluginInfo[0]); if(p==null) throw new Failure("No such plugin: "+n); p.deploy(); } } } rsp.sendRedirect("../updateCenter/"); } /** * Bare-minimum configuration mechanism to change the update center. */ public HttpResponse doSiteConfigure(@QueryParameter String site) throws IOException { Jenkins hudson = Jenkins.getInstance(); hudson.checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = hudson.getUpdateCenter(); PersistedList<UpdateSite> sites = uc.getSites(); for (UpdateSite s : sites) { if (s.getId().equals("default")) sites.remove(s); } sites.add(new UpdateSite("default",site)); return HttpResponses.redirectToContextRoot(); } public HttpResponse doProxyConfigure( @QueryParameter("proxy.server") String server, @QueryParameter("proxy.port") String port, @QueryParameter("proxy.userName") String userName, @QueryParameter("proxy.password") String password) throws IOException { Jenkins hudson = Jenkins.getInstance(); hudson.checkPermission(Jenkins.ADMINISTER); server = Util.fixEmptyAndTrim(server); if(server==null) { hudson.proxy = null; ProxyConfiguration.getXmlFile().delete(); } else try { int proxyPort = Integer.parseInt(Util.fixNull(port)); if (proxyPort < 0 || proxyPort > 65535) { throw new Failure(Messages.PluginManager_PortNotInRange(0, 65535)); } hudson.proxy = new ProxyConfiguration(server, proxyPort, Util.fixEmptyAndTrim(userName),Util.fixEmptyAndTrim(password)); hudson.proxy.save(); } catch (NumberFormatException nfe) { throw new Failure(Messages.PluginManager_PortNotANumber()); } return new HttpRedirect("advanced"); } public FormValidation doCheckProxyPort(@QueryParameter String value) { value = Util.fixEmptyAndTrim(value); if (value == null) { return FormValidation.ok(); } int port; try { port = Integer.parseInt(value); } catch (NumberFormatException e) { return FormValidation.error(Messages.PluginManager_PortNotANumber()); } if (port < 0 || port > 65535) { return FormValidation.error(Messages.PluginManager_PortNotInRange(0, 65535)); } return FormValidation.ok(); } /** * Uploads a plugin. */ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException { try { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); // Parse the request FileItem fileItem = (FileItem) upload.parseRequest(req).get(0); String fileName = Util.getFileName(fileItem.getName()); if("".equals(fileName)) return new HttpRedirect("advanced"); if(!fileName.endsWith(".hpi")) throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName)); fileItem.write(new File(rootDir, fileName)); fileItem.delete(); PluginWrapper existing = getPlugin(FilenameUtils.getBaseName(fileName)); if (existing!=null && existing.isBundled) existing.doPin(); pluginUploaded = true; return new HttpRedirect("."); } catch (IOException e) { throw e; } catch (Exception e) {// grrr. fileItem.write throws this throw new ServletException(e); } } /** * {@link ClassLoader} that can see all plugins. */ public final class UberClassLoader extends ClassLoader { /** * Make generated types visible. * Keyed by the generated class name. */ private ConcurrentMap<String, WeakReference<Class>> generatedClasses = new ConcurrentHashMap<String, WeakReference<Class>>(); public UberClassLoader() { super(PluginManager.class.getClassLoader()); } public void addNamedClass(String className, Class c) { generatedClasses.put(className,new WeakReference<Class>(c)); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { WeakReference<Class> wc = generatedClasses.get(name); if (wc!=null) { Class c = wc.get(); if (c!=null) return c; else generatedClasses.remove(name,wc); } for (PluginWrapper p : activePlugins) { try { return p.classLoader.loadClass(name); } catch (ClassNotFoundException e) { //not found. try next } } // not found in any of the classloader. delegate. throw new ClassNotFoundException(name); } @Override protected URL findResource(String name) { for (PluginWrapper p : activePlugins) { URL url = p.classLoader.getResource(name); if(url!=null) return url; } return null; } @Override protected Enumeration<URL> findResources(String name) throws IOException { List<URL> resources = new ArrayList<URL>(); for (PluginWrapper p : activePlugins) { resources.addAll(Collections.list(p.classLoader.getResources(name))); } return Collections.enumeration(resources); } @Override public String toString() { // only for debugging purpose return "classLoader " + getClass().getName(); } } private static final Logger LOGGER = Logger.getLogger(PluginManager.class.getName()); /** * Remembers why a plugin failed to deploy. */ public static final class FailedPlugin { public final String name; public final Exception cause; public FailedPlugin(String name, Exception cause) { this.name = name; this.cause = cause; } public String getExceptionString() { return Functions.printThrowable(cause); } } /** * Stores {@link Plugin} instances. */ /*package*/ static final class PluginInstanceStore { final Map<PluginWrapper,Plugin> store = new Hashtable<PluginWrapper,Plugin>(); } }
package ch.ech.ech0011; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.fluttercode.datafactory.impl.DataFactory; import org.minimalj.backend.Backend; import org.minimalj.model.Keys; import org.minimalj.model.ViewUtil; import org.minimalj.model.annotation.Materialized; import org.minimalj.model.annotation.NotEmpty; import org.minimalj.model.annotation.Size; import org.minimalj.repository.query.By; import org.minimalj.repository.sql.EmptyObjects; import org.minimalj.util.CloneHelper; import org.minimalj.util.StringUtils; import org.minimalj.util.mock.Mocking; import ch.ech.ech0007.SwissMunicipality; import ch.ech.ech0008.Country; import ch.ech.ech0011.NationalityData.CountryInfo; import ch.ech.ech0021.ArmedForcesData; import ch.ech.ech0021.BirthAddonData; import ch.ech.ech0021.CivilDefenseData; import ch.ech.ech0021.FireServiceData; import ch.ech.ech0021.GuardianRelationship; import ch.ech.ech0021.HealthInsuranceData; import ch.ech.ech0021.JobData; import ch.ech.ech0021.LockData; import ch.ech.ech0021.MaritalRelationship; import ch.ech.ech0021.MatrimonialInheritanceArrangementData; import ch.ech.ech0021.ParentalRelationship; import ch.ech.ech0021.PersonAdditionalData; import ch.ech.ech0021.PlaceOfOriginAddon; import ch.ech.ech0021.PoliticalRightData; import ch.ech.ech0044.PersonIdentification; import ch.ech.ech0044.Sex; import ch.ech.ech0071.Municipality; import ch.openech.frontend.ech0011.ReligionFormElement; import ch.openech.xml.YesNo; //handmade public class Person implements Mocking { public static final Person $ = Keys.of(Person.class); public Object id; @NotEmpty public PersonIdentification personIdentification; public final NameData nameData = new NameData(); public final BirthData birthData = new BirthData(); public final ReligionData religionData = new ReligionData(); public final MaritalData maritalData = new MaritalData(); public final NationalityData nationalityData = new NationalityData(); public DeathData deathData; public ContactData contactData; public List<PlaceOfOriginAddon> placeOfOrigin; // PlaceOfOriginAddon, nicht nur PlaceOfOrigin public ResidencePermitData residencePermit = new ResidencePermitData(); // PersonAddOn public final PersonAdditionalData personAdditionalData = new PersonAdditionalData(); public final PoliticalRightData politicalRightData = new PoliticalRightData(); public final BirthAddonData birthAddonData = new BirthAddonData(); public final DataLock dataLock = new DataLock(); public final PaperLock paperLock = new PaperLock(); public JobData jobData; public MaritalRelationship maritalRelationship; public List<ParentalRelationship> parentalRelationship; public List<GuardianRelationship> guardianRelationship; public final ArmedForcesData armedForcesData = new ArmedForcesData(); public final CivilDefenseData civilDefenseData = new CivilDefenseData(); public final FireServiceData fireServiceData = new FireServiceData(); public final HealthInsuranceData healthInsuranceData = new HealthInsuranceData(); public final MatrimonialInheritanceArrangementData matrimonialInheritanceArrangementData = new MatrimonialInheritanceArrangementData(); // ReportedPerson public ResidenceData residenceData; public SwissMunicipality mainResidence; public List<SwissMunicipality> secondaryResidence; @Materialized @Size(60) public String getStreet() { if (residenceData != null) { return residenceData.dwellingAddress.address.street; } else { return null; } } @Materialized @Size(40) public String getTown() { if (residenceData != null) { return residenceData.dwellingAddress.address.town; } else { return null; } } public String getLanguageOfCorrespondance() { return personAdditionalData.languageOfCorrespondance; } public void setLanguageOfCorrespondance(String languageOfCorrespondance) { personAdditionalData.languageOfCorrespondance = languageOfCorrespondance; } public Boolean getRestrictedVotingAndElectionRightFederation() { return politicalRightData.restrictedVotingAndElectionRightFederation; } public void setRestrictedVotingAndElectionRightFederation(Boolean restrictedVotingAndElectionRightFederation) { politicalRightData.restrictedVotingAndElectionRightFederation = restrictedVotingAndElectionRightFederation; } // for old ech 11 versions private final Coredata coredata = new Coredata(); @Size(100) public String alliancePartnershipName; public Coredata getCoredata() { return coredata; } public class Coredata { public String getOriginalName() { return nameData.originalName; } public void setOriginalName(String originalName) { nameData.originalName = originalName; } public String getAlliancePartnershipName() { return alliancePartnershipName; } public void setAlliancePartnershipName(String name) { alliancePartnershipName = name; } public String getAliasName() { return nameData.aliasName; } public void setAliasName(String aliasName) { nameData.aliasName = aliasName; } public String getOtherName() { return nameData.otherName; } public void setOtherName(String otherName) { nameData.otherName = otherName; } public String getCallName() { return nameData.callName; } public void setCallName(String callName) { nameData.callName = callName; } public Birthplace getPlaceOfBirth() { return placeOfBirth; } public LocalDate getDateOfDeath() { return deathData != null ? deathData.deathPeriod.dateFrom : null; } public void setDateOfDeath(LocalDate date) { if (date == null) { deathData = null; } else { if (deathData == null) { deathData = new DeathData(); } deathData.deathPeriod.dateFrom = date; } } public MaritalData getMaritalData() { return maritalData; } public Nationality getNationality() { return nationality; } public ContactData getContact() { return contactData; } public String getLanguageOfCorrespondance() { return personAdditionalData.languageOfCorrespondance; } public void setLanguageOfCorrespondance(String languageOfCorrespondance) { personAdditionalData.languageOfCorrespondance = languageOfCorrespondance; } public String getReligion() { return religionData.religion; } public void setReligion(String religion) { religionData.religion = religion; } } private final Birthplace placeOfBirth = new Birthplace(); public class Birthplace { private final SwissTown swissTown = new SwissTown(); private final ForeignCountry foreignCountry = new ForeignCountry(); public class SwissTown { private final Country swiss = new Country(); public ch.ech.ech0008.Country getCountry() { return swiss; } public ch.ech.ech0007.SwissMunicipality getMunicipality() { return birthData.placeOfBirth.swissTown; } } public class ForeignCountry { public Country getCountry() { return birthData.placeOfBirth.foreignCountry.country; } public void setCountry(Country country) { CloneHelper.deepCopy(country, birthData.placeOfBirth.foreignCountry.country); } public String getForeignBirthTown() { return birthData.placeOfBirth.foreignCountry.town; } public void setForeignBirthTown(String foreignBirthTown) { birthData.placeOfBirth.foreignCountry.town = foreignBirthTown; } } public Unknown getUnknown() { return birthData.placeOfBirth.unknown; } public SwissTown getSwissTown() { return swissTown; } public ForeignCountry getForeignCountry() { return foreignCountry; } } private final Nationality nationality = new Nationality(); public class Nationality { public NationalityStatus getNationalityStatus() { return nationalityData.nationalityStatus; } public void setNationalityStatus(NationalityStatus nationalityStatus) { nationalityData.nationalityStatus = nationalityStatus; } public Country getCountry() { if (nationalityData.countryInfo != null && !nationalityData.countryInfo.isEmpty()) { return nationalityData.countryInfo.get(0).country; } else { return null; } } public void setCountry(Country country) { if (country == null) { nationalityData.countryInfo = null; } else { nationalityData.countryInfo = new ArrayList<>(); CountryInfo countryInfo = new CountryInfo(); CloneHelper.deepCopy(country, countryInfo.country); nationalityData.countryInfo.add(countryInfo); } } } public LockData getLockData() { boolean emptyDataLock = dataLock.dataLock == ch.ech.ech0021.DataLock._0; boolean emptyPaperLock = paperLock.paperLock == null || paperLock.paperLock == false; if (emptyDataLock && emptyPaperLock) { return null; } else { LockData d = new LockData(); if (dataLock != null) { d.dataLock = dataLock.dataLock; d.dataLockValidFrom = dataLock.dataLockValidFrom; d.dataLockValidTill = dataLock.dataLockValidTill; } else { d.dataLock = ch.ech.ech0021.DataLock._0; } if (paperLock != null) { d.paperLock = Boolean.TRUE.equals(paperLock.paperLock) ? YesNo._1 : YesNo._0; d.paperLockValidFrom = paperLock.paperLockValidFrom; d.paperLockValidTill = paperLock.paperLockValidTill; } else { d.paperLock = YesNo._0; } return d; } } public void setDataLock(LockData d) { if (d == null) { d = EmptyObjects.getEmptyObject(LockData.class); } paperLock.paperLock = YesNo._1.equals(d.paperLock); paperLock.paperLockValidFrom = d.paperLockValidFrom; paperLock.paperLockValidTill = d.paperLockValidTill; dataLock.dataLock = d.dataLock; dataLock.dataLockValidFrom = d.dataLockValidFrom; dataLock.dataLockValidTill = d.dataLockValidTill; } @Override public void mock() { DataFactory df = new DataFactory(); Random r = new Random(); nameData.firstName = df.getFirstName(); nameData.officialName = df.getLastName(); birthData.dateOfBirth.value = LocalDate.now().minusDays(r.nextInt(10000)).toString(); List<Municipality> municipalities = Backend.find(Municipality.class, By.all()); Municipality municipality = municipalities.get(r.nextInt(municipalities.size())); birthData.placeOfBirth.swissTown = ViewUtil.view(municipality, new SwissMunicipality()); birthData.sex = Sex._1; religionData.religion = String .valueOf(ReligionFormElement.RELIGION_VALUES[r.nextInt(ReligionFormElement.RELIGION_VALUES.length)]); personIdentification = new PersonIdentification(); personIdentification.officialName = nameData.officialName; personIdentification.firstName = nameData.firstName; personIdentification.sex = birthData.sex; personIdentification.localPersonId.namedIdCategory = "OpenEch"; personIdentification.localPersonId.namedId = "test"; personIdentification.dateOfBirth.value = birthData.dateOfBirth.value; } public void render(StringBuilder s) { boolean empty = true; if (!StringUtils.isEmpty(nameData.firstName)) { s.append(nameData.firstName); empty = false; } if (!StringUtils.isEmpty(nameData.officialName)) { if (!empty) { s.append(' '); } s.append(nameData.officialName); empty = false; } if (!empty && residenceData != null) { String town = residenceData.dwellingAddress.address.town; if (!StringUtils.isEmpty(town)) { s.append(", ").append(town); } } if (!empty) { s.append('\n'); } } }
package at.ac.tuwien.kr.alpha; import java.util.*; import java.util.stream.Collector; import java.util.stream.Collectors; public class Util { public static <K, V> Map.Entry<K, V> entry(K key, V value) { return new AbstractMap.SimpleEntry<>(key, value); } public static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> entriesToMap() { return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue); } public static <E> void appendDelimited(StringBuilder sb, Iterable<E> iterable) { for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext();) { sb.append(iterator.next()); if (iterator.hasNext()) { sb.append(", "); } } } public static <E> void appendDelimitedPrefix(StringBuilder sb, String prefix, Iterable<E> iterable) { for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext();) { sb.append(prefix); sb.append(iterator.next()); if (iterator.hasNext()) { sb.append(", "); } } } public static <T extends Comparable<T>> int compareSortedSets(SortedSet<T> a, SortedSet<T> b) { if (a.size() != b.size()) { return a.size() - b.size(); } if (a.isEmpty() && b.isEmpty()) { return 0; } final Iterator<T> ita = a.iterator(); final Iterator<T> itb = b.iterator(); do { final int result = ita.next().compareTo(itb.next()); if (result != 0) { return result; } } while (ita.hasNext() && itb.hasNext()); return 0; } }
package com.pivotallabs.injected; import android.content.Context; import android.widget.TextView; import com.google.inject.Inject; import com.pivotallabs.R; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.*; @RunWith(InjectedTestRunner.class) public class InjectedActivityTest { @Inject Context context; @Inject InjectedActivity injectedActivity; @Inject Counter fieldCounter; @Inject FakeDateProvider fakeDateProvider; @Before public void setUp() { fakeDateProvider.setDate("December 8, 2010"); } @Test public void shouldAssignStringToTextView() throws Exception { injectedActivity.onCreate(null); TextView injectedTextView = (TextView) injectedActivity.findViewById(R.id.injected_text_view); assertThat(injectedTextView.getText().toString(), equalTo("Roboguice Activity tested with Robolectric - December 8, 2010")); } @Test public void shouldInjectSingletons() throws Exception { Counter instance = injectedActivity.getInjector().getInstance(Counter.class); assertEquals(0, instance.count); instance.count++; Counter instanceAgain = injectedActivity.getInjector().getInstance(Counter.class); assertEquals(1, instanceAgain.count); assertSame(fieldCounter, instance); } @Test public void shouldBeAbleToInjectAContext() throws Exception { assertNotNull(context); } }
package gamecontrollers.turn; import gamecontrollers.commands.GameplayActionCommand; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class ReplayController { private List<GameplayActionCommand> replayList; private ListIterator<GameplayActionCommand> iterator; public ReplayController(){ replayList = new ArrayList<GameplayActionCommand>(); } public void goForward(){ if(iterator.hasNext()){ iterator.next().execute(); } } public void goBackward(){ if(iterator.hasPrevious()){ iterator.previous().execute(); } } public void goAll(){ //iterate through the rest of the list and execute //DO NOT ITERATE THROUGH THE WHOLE LIST while(iterator.hasNext()){ iterator.next().execute(); } } public void setReplayList(List<GameplayActionCommand> replayListPassedIn){ ArrayList<GameplayActionCommand> tempList = new ArrayList<GameplayActionCommand>(); tempList.addAll(replayListPassedIn); //oops i forgot to undo everything lol //undo stuff //create iterator starting from the back of the passed in list ListIterator<GameplayActionCommand> it = tempList.listIterator(tempList.size()-1); //iterate backwards and undo while also adding to the replayList //this undoes all the commands in order and reverses the replayList while(it.hasPrevious()){ GameplayActionCommand command = it.previous(); command.undo(); replayList.add(command); } iterator = replayList.listIterator(); } }
package at.wrdlbrnft.helpers; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import at.wrdlbrnft.helpers.time.Time; public class Dates { private static final DateFormat dateFormat = DateFormat.getDateInstance(); private static final DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(); private static final DateFormat timeFormat = DateFormat.getTimeInstance(); private static final DateFormat shortTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); private static final DateFormat shortDateFormat = DateFormat.getDateInstance(DateFormat.SHORT); public static String format(Date date, String pattern) { if (date != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); return dateFormat.format(date); } return null; } public static String format(Date date, String pattern, Locale locale) { if (date != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale); return dateFormat.format(date); } return null; } public static String formatDate(Date date) { if (date != null) { return dateFormat.format(date); } return null; } public static String formatDateTime(Date date) { if (date != null) { return dateTimeFormat.format(date); } return null; } public static String formatTime(Date date) { if (date != null) { return timeFormat.format(date); } return null; } public static String formatShortTime(Date date) { if (date != null) { return shortTimeFormat.format(date); } return null; } public static String formatShortDate(Date date) { if (date != null) { return shortDateFormat.format(date); } return null; } public static Date parse(String dateString, String pattern) throws ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); return dateFormat.parse(dateString); } public static Date parse(String dateString, String pattern, Locale locale) throws ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale); return dateFormat.parse(dateString); } public static Date parse(String dateString) throws ParseException { return dateFormat.parse(dateString); } public static Date from(int year, int month, int day, int hour, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day, hour, minute); return calendar.getTime(); } public static Date now() { return new Date(); } public static boolean isInThePast(Date date) { final Date now = new Date(); return now.after(date); } public static boolean isInTheFuture(Date date) { final Date now = new Date(); return now.before(date); } public static Date combine(Date date, int hour, int minute) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); return calendar.getTime(); } public static Date combine(Date date, Time time) { return combine(date, time.getHour(), time.getMinute()); } public static Date nowWithOffset(long millis) { return new Date(System.currentTimeMillis() + millis); } public static Date nowWithOffset(long seconds, long millis) { return new Date(System.currentTimeMillis() + millisOf(seconds, millis)); } public static Date nowWithOffset(long minutes, long seconds, long millis) { return new Date(System.currentTimeMillis() + millisOf(minutes, seconds, millis)); } public static Date nowWithOffset(long hours, long minutes, long seconds, long millis) { return new Date(System.currentTimeMillis() + millisOf(hours, minutes, seconds, millis)); } public static Date nowWithOffset(long days, long hours, long minutes, long seconds, long millis) { return new Date(System.currentTimeMillis() + millisOf(days, hours, minutes, seconds, millis)); } public static Date dateWithOffset(Date date, long millis) { return new Date(millisOf(date) + millis); } public static Date dateWithOffset(Date date, long seconds, long millis) { return new Date(millisOf(date) + millisOf(seconds, millis)); } public static Date dateWithOffset(Date date, long minutes, long seconds, long millis) { return new Date(millisOf(date) + millisOf(minutes, seconds, millis)); } public static Date dateWithOffset(Date date, long hours, long minutes, long seconds, long millis) { return new Date(millisOf(date) + millisOf(hours, minutes, seconds, millis)); } public static Date dateWithOffset(Date date, long days, long hours, long minutes, long seconds, long millis) { return new Date(millisOf(date) + millisOf(days, hours, minutes, seconds, millis)); } public static long millisOf(Date date) { if(date == null) { return 0l; } return date.getTime(); } public static long millisOf(long seconds, long millis) { return seconds * 1000l + millis; } public static long millisOf(long minutes, long seconds, long millis) { return (minutes * 60l + seconds) * 1000l + millis; } public static long millisOf(long hours, long minutes, long seconds, long millis) { return ((hours * 60l + minutes) * 60l + seconds) * 1000l + millis; } public static long millisOf(long days, long hours, long minutes, long seconds, long millis) { return (((days * 24l + hours) * 60l + minutes) * 60l + seconds) * 1000l + millis; } public static Date newDate(long millis) { return new Date(millis); } public static int getDayOfMonth() { Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.DAY_OF_MONTH); } public static int getDayOfMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_MONTH); } public static int getDayOfWeek() { Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.DAY_OF_WEEK); } public static int getDayOfWeek(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_WEEK); } public static int getDayOfYear() { Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.DAY_OF_YEAR); } public static int getDayOfYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_WEEK); } public static int getYear() { Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.YEAR); } public static int getYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR); } public static int getDayDifference(Date date) { return getDayDifference(now(), date); } public static int getDayDifference(Date a, Date b) { Calendar calendar = Calendar.getInstance(); calendar.setTime(a); int aYear = calendar.get(Calendar.YEAR); int aDays = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTime(b); int bYear = calendar.get(Calendar.YEAR); int bDays = calendar.get(Calendar.DAY_OF_YEAR); return Math.abs((aYear - bYear) * 365 + aDays - bDays); } public static Date getDayStartOf(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } public static Date getDayStart() { return getDayStartOf(now()); } public static Date getDayEndOf(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); return calendar.getTime(); } public static Date getDayEnd() { return getDayEndOf(now()); } public static Date create(int year, int monthOfYear, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.set(year, monthOfYear, dayOfMonth); return calendar.getTime(); } public static Date create(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(year, monthOfYear, dayOfMonth, hourOfDay, minute); return calendar.getTime(); } public static Date create(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minute, int second) { Calendar calendar = Calendar.getInstance(); calendar.set(year, monthOfYear, dayOfMonth, hourOfDay, minute, second); return calendar.getTime(); } public static int getWeekOfYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.WEEK_OF_YEAR); } }
package org.sql2o; import org.sql2o.converters.Converter; import org.sql2o.converters.ConverterException; import org.sql2o.logging.LocalLoggerFactory; import org.sql2o.logging.Logger; import org.sql2o.quirks.Quirks; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.sql2o.converters.Convert.throwIfNull; /** * Represents a connection to the database with a transaction. */ public class Connection implements AutoCloseable { private final static Logger logger = LocalLoggerFactory.getLogger(Connection.class); private java.sql.Connection jdbcConnection; private Sql2o sql2o; private Integer result = null; private int[] batchResult = null; private List<Object> keys; private boolean canGetKeys; private boolean rollbackOnException = true; public boolean isRollbackOnException() { return rollbackOnException; } public Connection setRollbackOnException(boolean rollbackOnException) { this.rollbackOnException = rollbackOnException; return this; } final boolean autoClose; Connection(Sql2o sql2o, boolean autoClose) { this.autoClose = autoClose; this.sql2o = sql2o; createConnection(); } void onException() { if (isRollbackOnException()) { rollback(this.autoClose); } } public java.sql.Connection getJdbcConnection() { return jdbcConnection; } public Sql2o getSql2o() { return sql2o; } public Query createQuery(String queryText, String name){ boolean returnGeneratedKeys = this.sql2o.getQuirks().returnGeneratedKeysByDefault(); return createQuery(queryText, name, returnGeneratedKeys); } public Query createQuery(String queryText, String name, boolean returnGeneratedKeys){ try { if (jdbcConnection.isClosed()){ createConnection(); } } catch (SQLException e) { throw new RuntimeException(e); } return new Query(this, queryText, name, returnGeneratedKeys); } public Query createQueryWithParams(String queryText, Object... paramValues){ Query query = createQuery(queryText, null); boolean destroy = true; try { query.withParams(paramValues); destroy = false; return query; } finally { // instead of re-wrapping exception // just keep it as-is // but kill a query if(destroy) query.close(); } } public Query createQuery(String queryText){ return createQuery(queryText, null); } public Query createQuery(String queryText, boolean returnGeneratedKeys) { return createQuery(queryText, null, returnGeneratedKeys); } public Sql2o rollback(){ return this.rollback(true).sql2o; } public Connection rollback(boolean closeConnection){ try { jdbcConnection.rollback(); } catch (SQLException e) { logger.warn("Could not roll back transaction. message: {}", e); } finally { if(closeConnection) this.closeJdbcConnection(); } return this; } public Sql2o commit(){ return this.commit(true).sql2o; } public Connection commit(boolean closeConnection){ try { jdbcConnection.commit(); } catch (SQLException e) { throw new Sql2oException(e); } finally { if(closeConnection) this.closeJdbcConnection(); } return this; } public int getResult(){ if (this.result == null){ throw new Sql2oException("It is required to call executeUpdate() method before calling getResult()."); } return this.result; } void setResult(int result){ this.result = result; } public int[] getBatchResult() { if (this.batchResult == null){ throw new Sql2oException("It is required to call executeBatch() method before calling getBatchResult()."); } return this.batchResult; } void setBatchResult(int[] value) { this.batchResult = value; } void setKeys(ResultSet rs) throws SQLException { if (rs == null){ this.keys = null; return; } this.keys = new ArrayList<Object>(); while(rs.next()){ this.keys.add(rs.getObject(1)); } } public Object getKey(){ if (!this.canGetKeys){ throw new Sql2oException("Keys where not fetched from database. Please call executeUpdate(true) to fetch keys"); } if (this.keys != null && this.keys.size() > 0){ return keys.get(0); } return null; } @SuppressWarnings("unchecked") // need to change Convert public <V> V getKey(Class returnType){ final Quirks quirks = this.sql2o.getQuirks(); Object key = getKey(); try { Converter<V> converter = throwIfNull(returnType, quirks.converterOf(returnType)); return converter.convert(key); } catch (ConverterException e) { throw new Sql2oException("Exception occurred while converting value from database to type " + returnType.toString(), e); } } public Object[] getKeys(){ if (!this.canGetKeys){ throw new Sql2oException("Keys where not fetched from database. Please set the returnGeneratedKeys parameter in the createQuery() method to enable fetching of generated keys."); } if (this.keys != null){ return this.keys.toArray(); } return null; } @SuppressWarnings("unchecked") // need to change Convert public <V> List<V> getKeys(Class<V> returnType) { final Quirks quirks = sql2o.getQuirks(); if (!this.canGetKeys) { throw new Sql2oException("Keys where not fetched from database. Please set the returnGeneratedKeys parameter in the createQuery() method to enable fetching of generated keys."); } if (this.keys != null) { try { Converter<V> converter = throwIfNull(returnType, quirks.converterOf(returnType)); List<V> convertedKeys = new ArrayList<V>(this.keys.size()); for (Object key : this.keys) { convertedKeys.add(converter.convert(key)); } return convertedKeys; } catch (ConverterException e) { throw new Sql2oException("Exception occurred while converting value from database to type " + returnType.toString(), e); } } return null; } void setCanGetKeys(boolean canGetKeys) { this.canGetKeys = canGetKeys; } private final Set<Statement> statements = new HashSet<>(); void registerStatement(Statement statement){ statements.add(statement); } void removeStatement(Statement statement){ statements.remove(statement); } public void close() { boolean connectionIsClosed; try { connectionIsClosed = jdbcConnection.isClosed(); } catch (SQLException e) { throw new Sql2oException("Sql2o encountered a problem while trying to determine whether the connection is closed.", e); } if (!connectionIsClosed) { for (Statement statement : statements) { try { getSql2o().getQuirks().closeStatement(statement); } catch (Throwable e) { logger.warn("Could not close statement.", e); } } statements.clear(); boolean autoCommit = false; try { autoCommit = jdbcConnection.getAutoCommit(); } catch (SQLException e) { logger.warn("Could not determine connection auto commit mode.", e); } // if in transaction, rollback, otherwise just close if (autoCommit) { this.closeJdbcConnection(); } else { this.rollback(true); } } } private void createConnection(){ try{ this.jdbcConnection = this.sql2o.getDataSource().getConnection(); } catch(Exception ex){ throw new Sql2oException("Could not acquire a connection from DataSource - " + ex.getMessage(), ex); } } private void closeJdbcConnection() { try { jdbcConnection.close(); } catch (SQLException e) { logger.warn("Could not close connection. message: {}", e); } } }
package blog.engine; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import blog.DBLOGUtil; import blog.common.Util; import blog.io.TableWriter; import blog.model.Evidence; import blog.model.Model; import blog.model.Queries; import blog.model.Query; import blog.sample.AfterSamplingListener; import blog.sample.Sampler; import blog.type.Timestep; import blog.world.DefaultPartialWorld; /** * A Particle Filter. It works by keeping a set of {@link Particles}, each * representing a partial world, weighted by the * evidence. It uses the following properties: <code>numParticles</code> or * <code>numSamples</code>: number of particles (default is <code>1000</code>). * * The ParticleFilter is an unusual {@link InferenceEngine} in that it takes * evidence and queries additional to the ones taken by * {@link #setEvidence(Evidence)} and {@link #setQueries(List)}. The evidence * set by {@link #setEvidence(Evidence)} is used in the very beginning of * inference (thus keeping the general InferenceEngine semantics for it) and the * queries set by {@link #setQueries(List)} are used by {@link #answerQueries()} * only (again keeping the original InferenceEngine semantics). */ public class ParticleFilter extends InferenceEngine { /** * Creates a new particle filter for the given BLOG model, with configuration * parameters specified by the given properties table. */ public ParticleFilter(Model model, Properties properties) { super(model); String numParticlesStr = properties.getProperty("numParticles"); String numSamplesStr = properties.getProperty("numSamples"); if (numParticlesStr != null && numSamplesStr != null && !numParticlesStr.equals(numSamplesStr)) Util.fatalError("ParticleFilter received both numParticles and numSamples properties with distinct values."); if (numParticlesStr == null) numParticlesStr = numSamplesStr; if (numParticlesStr == null) numParticlesStr = "1000"; try { numParticles = Integer.parseInt(numParticlesStr); } catch (NumberFormatException e) { Util.fatalErrorWithoutStack("Invalid number of particles: " + numParticlesStr); // do not dump stack. } String idTypesString = properties.getProperty("idTypes", "none"); idTypes = model.getListedTypes(idTypesString); if (idTypes == null) { Util.fatalErrorWithoutStack("Fatal error: invalid idTypes list."); } String samplerClassName = properties.getProperty("samplerClass", "blog.sample.LWSampler"); System.out.println("Constructing sampler of class " + samplerClassName); particleSampler = Sampler.make(samplerClassName, model, properties); String queryReportIntervalStr = properties.getProperty( "queryReportInterval", "10"); try { queryReportInterval = Integer.parseInt(queryReportIntervalStr); } catch (NumberFormatException e) { Util.fatalError("Invalid reporting interval: " + queryReportIntervalStr, false); } dataLogLik = 0; } /** Answers the queries provided at construction time. */ public void answerQueries() { if (Util.verbose()) { System.out.println("Evidence: " + evidence); System.out.println("Query: " + queries); } System.out.println("Report every: " + queryReportInterval + " timesteps"); reset(); takeEvidenceAndAnswerQuery(); System.out.println("Log likelihood of data: " + dataLogLik); } private void reset() { System.out.println("Using " + numParticles + " particles..."); if (evidence == null) { evidence = new Evidence(model); } if (queries == null) { queries = new Queries(model); } particles = new ArrayList(); for (int i = 0; i < numParticles; i++) { Particle newParticle = makeParticle(idTypes); particles.add(newParticle); } needsToBeResampledBeforeFurtherSampling = false; } private void takeEvidenceAndAnswerQuery() { // Split evidence and queries according to the timestep it occurs in. Map<Timestep, Evidence> slicedEvidence = DBLOGUtil .splitEvidenceInTime(evidence); Map<Timestep, Queries> slicedQueries = DBLOGUtil .splitQueriesInTime(queries); // Process atemporal evidence (if any) before everything else. if (slicedEvidence.containsKey(null)) { take(slicedEvidence.get(null)); } // Process temporal evidence and queries in lockstep. List<Timestep> nonNullTimesteps = new ArrayList<Timestep>(); nonNullTimesteps.addAll(slicedEvidence.keySet()); nonNullTimesteps.addAll(slicedQueries.keySet()); nonNullTimesteps.removeAll(Collections.singleton(null)); // We use a TreeSet to remove duplicates and to sort the timesteps. // (We can't construct a TreeSet directly because it doesn't accept nulls.) TreeSet<Timestep> sortedTimesteps = new TreeSet<Timestep>(nonNullTimesteps); int querySlicesProcessed = 0; for (Timestep timestep : sortedTimesteps) { if (slicedEvidence.containsKey(timestep)) { take(slicedEvidence.get(timestep)); } if (slicedQueries.containsKey(timestep)) { List<Query> currentQueries = slicedQueries.get(timestep); for (Particle particle : particles) { particle.answer(currentQueries); } querySlicesProcessed++; if (querySlicesProcessed % queryReportInterval == 0) { TableWriter tableWriter = new TableWriter(currentQueries); tableWriter.setHeader("After timestep " + timestep.intValue()); tableWriter.writeResults(System.out); } } removePriorTimeSlice(timestep); } // Process atemporal queries (if any) after all the evidence. if (slicedQueries.containsKey(null)) { List<Query> currentQueries = slicedQueries.get(null); for (Particle particle : particles) { particle.answer(currentQueries); } } } /** * A method making a particle (by default, {@link Particle}). Useful for * extensions using specialized particles (don't forget to specialize * {@link Particle#copy()} for it to return an object of its own class). */ protected Particle makeParticle(Set idTypes) { DefaultPartialWorld world = new DefaultPartialWorld(idTypes); return new Particle(particleSampler, world); } /** * remove all the temporal variables prior to the specified timestep * * @param timestep * Timestep before which the vars should be removed */ public void removePriorTimeSlice(Timestep timestep) { for (Particle p : particles) { p.removePriorTimeSlice(timestep); } } /** Takes more evidence. */ public void take(Evidence evidence) { if (evidence.isEmpty()) { return; } if (needsToBeResampledBeforeFurtherSampling) { resample(); } if (beforeTakesEvidence != null) beforeTakesEvidence.evaluate(evidence, this); for (Particle p : particles) { if (beforeParticleTakesEvidence != null) beforeParticleTakesEvidence.evaluate(p, evidence, this); p.take(evidence); if (afterParticleTakesEvidence != null) afterParticleTakesEvidence.evaluate(p, evidence, this); } double logSumWeights = Double.NEGATIVE_INFINITY; ListIterator particleIt = particles.listIterator(); while (particleIt.hasNext()) { Particle particle = (Particle) particleIt.next(); if (particle.getLatestLogWeight() < Sampler.NEGLIGIBLE_LOG_WEIGHT) { particleIt.remove(); } else { logSumWeights = Util.logSum(logSumWeights, particle.getLatestLogWeight()); } } if (particles.size() == 0) throw new IllegalArgumentException("All particles have zero weight"); dataLogLik += logSumWeights; needsToBeResampledBeforeFurtherSampling = true; if (afterTakesEvidence != null) afterTakesEvidence.evaluate(evidence, this); } protected void resample() { double[] logWeights = new double[particles.size()]; boolean[] alreadySampled = new boolean[particles.size()]; double maxLogWeight = Double.NEGATIVE_INFINITY; double sumWeights = 0; double[] normalizedWeights = new double[particles.size()]; double[] sampleKeys = new double[particles.size()]; List newParticles = new ArrayList(); for (int i = 0; i < particles.size(); i++) { logWeights[i] = ((Particle) particles.get(i)).getLatestLogWeight(); maxLogWeight = Math.max(maxLogWeight, logWeights[i]); } if (maxLogWeight == Double.NEGATIVE_INFINITY) { throw new IllegalArgumentException("All particles have zero weight"); } for (int i = 0; i < particles.size(); i++) { normalizedWeights[i] = Math.exp(logWeights[i] - maxLogWeight); if (i > 0) normalizedWeights[i] += normalizedWeights[i - 1]; } sumWeights = normalizedWeights[particles.size() - 1]; for (int i = 0; i < numParticles; i++) { sampleKeys[i] = Util.random() * sumWeights; } Arrays.sort(sampleKeys); int selection = 0; for (int i = 0; i < numParticles; i++) { while (normalizedWeights[selection] < sampleKeys[i]) ++selection; if (!alreadySampled[selection]) { newParticles.add(particles.get(selection)); alreadySampled[selection] = true; } else { newParticles.add(((Particle) particles.get(selection)).copy()); } } particles = newParticles; } // PARTICLE TAKES EVIDENCE EVENT HANDLING /** * An interface specifying handlers for before and after a particle takes * evidence. */ public static interface ParticleTakesEvidenceHandler { public void evaluate(Particle particle, Evidence evidence, ParticleFilter particleFilter); } /** * The {@link ParticleTakesEvidenceHandler} invoked right before a particle * takes evidence. */ public ParticleTakesEvidenceHandler beforeParticleTakesEvidence; /** * The {@link ParticleTakesEvidenceHandler} invoked right after a particle * takes evidence. */ public ParticleTakesEvidenceHandler afterParticleTakesEvidence; // FILTER TAKES EVIDENCE EVENT HANDLING /** * An interface specifying handlers for before and after the particle filter * takes evidence. */ public static interface TakesEvidenceHandler { public void evaluate(Evidence evidence, ParticleFilter particleFilter); } /** * The {@link TakesEvidenceHandler} invoked right before a particle takes * evidence. */ public TakesEvidenceHandler beforeTakesEvidence; /** * The {@link TakesEvidenceHandler} invoked right after a particle takes * evidence. */ public TakesEvidenceHandler afterTakesEvidence; // END OF EVENT HANDLING public AfterSamplingListener getAfterSamplingListener() { return afterSamplingListener; } public void setAfterSamplingListener( AfterSamplingListener afterSamplingListener) { this.afterSamplingListener = afterSamplingListener; particleSampler.afterSamplingListener = afterSamplingListener; } private Set idTypes; // of Type private int numParticles; public List<Particle> particles; private boolean needsToBeResampledBeforeFurtherSampling = false; private Sampler particleSampler; private AfterSamplingListener afterSamplingListener; private int queryReportInterval; private double dataLogLik; // log likelihood of the data }
package br.com.dbsoft.util; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.google.gson.Gson; import br.com.dbsoft.core.DBSSDK.ENCODE; import br.com.dbsoft.error.DBSIOException; import br.com.dbsoft.util.DBSObject; public class DBSHttp { private static Logger wLogger = Logger.getLogger(DBSHttp.class); public static HttpServletResponse getHttpServletResponse(){ FacesContext xContext = FacesContext.getCurrentInstance(); return (HttpServletResponse) xContext.getExternalContext().getResponse(); } public static HttpServletRequest getHttpServletRequest(){ FacesContext xContext = FacesContext.getCurrentInstance(); return (HttpServletRequest) xContext.getExternalContext().getRequest(); } /** * Evia um arquivo local para o browser */ public static Boolean sendFile(ByteArrayOutputStream pByteArrayOutputStream, String pRemoteFileName, String pContentType){ FacesContext xFC = FacesContext.getCurrentInstance(); ExternalContext xEC = xFC.getExternalContext(); try { if (!DBSObject.isEmpty(pByteArrayOutputStream)) { xEC.responseReset(); xEC.setResponseContentType(pContentType); xEC.setResponseContentLength(pByteArrayOutputStream.size()); xEC.setResponseHeader("Content-Disposition", "attachment;filename=\"" + pRemoteFileName + "\""); OutputStream xOutputStream = xEC.getResponseOutputStream(); if (xOutputStream != null){ pByteArrayOutputStream.writeTo(xOutputStream); } xFC.responseComplete(); return true; } return false; } catch (IOException e) { wLogger.error(e); return false; } } public static String getRealPathWebInfClasses(ExternalContext pExternalContext){ return getRealPath(pExternalContext, "WEB-INF" + File.separator + "classes" + File.separator); } /** * Retorna o caminho real a partir de caminho virtual * @param pRelativePath * @return */ public static String getRealPath(ExternalContext pExternalContext, String pRelativePath){ return pExternalContext.getRealPath(pRelativePath); } /** * Retorna caminho da URL do servidor local a partir do ExternalContext * @return */ public static String getHTTPServerPath(ExternalContext pExternalContext){ if (pExternalContext == null){return "";} StringBuilder xLink = new StringBuilder(); xLink.append(pExternalContext.getRequestScheme()).append(": xLink.append(pExternalContext.getRequestServerName()); if (!DBSObject.isEmpty(pExternalContext.getRequestServerPort())){ xLink.append(":").append(pExternalContext.getRequestServerPort()); } // xLink += xEC.getRequestContextPath(); return xLink.toString(); } /** * Retorna URL do servidor local a partir doe um request * @param pContext * @return */ public static String getHTTPServerPath(HttpServletRequest pContext){ if (pContext == null){return "";} StringBuilder xLink = new StringBuilder(); xLink.append(pContext.getScheme()).append(": xLink.append(pContext.getServerName()); if (!DBSObject.isEmpty(pContext.getServerPort())){ xLink.append(":").append(pContext.getServerPort()); } return xLink.toString(); } public static String encodeParams(Map<String, String> pParams) throws DBSIOException { StringBuilder xString = new StringBuilder(); try { for (String xParametro:pParams.keySet()){ xString.append("&"); xString.append(xParametro.trim()); xString.append("="); String xValue = DBSString.toString(pParams.get(xParametro),"").trim(); xString.append(URLEncoder.encode(xValue, ENCODE.ISO_8859_1)); } return xString.toString(); } catch (UnsupportedEncodingException e) { DBSIO.throwIOException(e); } return null; } /** * Retorna lista com o nome do parametro e respectivo valor ja convertidos a partir de UTF-8; * @param pParams * @return * @throws DBSIOException * @throws UnsupportedEncodingException */ public static Map<String, String> decodeParams(String pParams) throws DBSIOException { try { Map<String, String> xParams = new HashMap<String, String>(); ArrayList<String> xList = DBSString.toArrayList(pParams, "&"); for (String xParam: xList){ ArrayList<String> xValues = DBSString.toArrayList(xParam, "="); if (xValues.size() == 2){ if (!DBSObject.isEmpty(xValues.get(0)) && !DBSObject.isEmpty(xValues.get(1))){ xParams.put(URLDecoder.decode(xValues.get(0), ENCODE.ISO_8859_1), URLDecoder.decode(xValues.get(1), ENCODE.ISO_8859_1)); } } } return xParams; } catch (UnsupportedEncodingException e) { DBSIO.throwIOException(e); } return null; } /** * Grava objeto JSON do outputstream.<br/> * @param pObjectOutputStream * @param pObject * @throws DBSIOException */ public static void ObjectOutputStreamWriteObject(ObjectOutputStream pObjectOutputStream, Object pObject) throws DBSIOException{ if (pObjectOutputStream == null){return;} try { Gson xJSON = new Gson(); pObjectOutputStream.writeObject(xJSON.toJson(pObject)); // wObjectOutputStream.writeObject(pObject); } catch (IOException e) { DBSIO.throwIOException(e); } } public static <T> T ObjectInputStreamReadObject(ObjectInputStream pObjectInputStream, Class<T> pClass) throws DBSIOException{ if (pObjectInputStream == null){return null;} try { Gson xJSON = new Gson(); String xS = pObjectInputStream.readObject().toString(); return xJSON.fromJson(xS, pClass); // return (T) wObjectInputStream.readObject(); } catch (EOFException e){ return null; } catch (IOException | ClassNotFoundException e) { DBSIO.throwIOException(e); return null; } } }
package go.graphics.swing.text; import go.graphics.text.EFontSize; import go.graphics.text.TextDrawer; import java.awt.Font; import java.awt.geom.Rectangle2D; import com.jogamp.opengl.util.awt.TextRenderer; /** * This class is a text drawer used to wrap the text renderer. * * @author michael */ public final class JOGLTextDrawer implements TextDrawer { private static final String FONTNAME = "Arial"; private static JOGLTextDrawer[] instances = new JOGLTextDrawer[EFontSize .values().length]; private final TextRenderer renderer; /** * Creates a new text drawer. * * @param size * The size of the text. */ private JOGLTextDrawer(EFontSize size) { Font font = new Font(FONTNAME, Font.TRUETYPE_FONT, size.getSize()); this.renderer = new TextRenderer(font, true, true, null, true); } /* * (non-Javadoc) * @see go.graphics.swing.text.TextDrawer#renderCentered(int, int, * java.lang.String) */ @Override public void renderCentered(int cx, int cy, String text) { Rectangle2D textBounds = this.renderer.getBounds(text); int halfWidth = (int) (textBounds.getWidth() / 2); int halfHeight = (int) (textBounds.getHeight() / 2); drawString(cx - halfWidth, cy - halfHeight, text); } /** * TODO: we should remove this. */ public void setColor(float red, float green, float blue, float alpha) { this.renderer.setColor(red, green, blue, alpha); } /* * (non-Javadoc) * @see go.graphics.swing.text.TextDrawer#drawString(int, int, * java.lang.String) */ @Override public void drawString(int x, int y, String string) { this.renderer.begin3DRendering(); this.renderer.draw3D(string, x, y, 0, 1); this.renderer.end3DRendering(); this.renderer.flush(); } /** * Gets a text drawer for the given text size. * * @param size * The size for the drawer. * @return An instance of a drawer for that size. */ public static TextDrawer getTextDrawer(EFontSize size) { if (instances[size.ordinal()] == null) { instances[size.ordinal()] = new JOGLTextDrawer(size); } return instances[size.ordinal()]; } @Override public double getWidth(String string) { Rectangle2D textBounds = this.renderer.getBounds(string); return textBounds.getWidth(); } @Override public double getHeight(String string) { Rectangle2D textBounds = this.renderer.getBounds(string); return textBounds.getHeight(); } }
package business.customer; public class Customer { private long customerId; private String name; private String email; private String phone; private String address; private String cityRegion; private String ccNumber; public Customer(long customerId, String name, String email, String phone, String address, String cityRegion, String ccNumber) { this.customerId = customerId; this.name = name; this.email = email; this.phone = phone; this.address = address; this.cityRegion = cityRegion; this.ccNumber = ccNumber; } public long getCustomerId() { return customerId; } public String getName() { return name; } public String getEmail() { return email; } public String getPhone() { return phone; } public String getAddress() { return address; } public String getCityRegion() { return cityRegion; } public String getCcNumber() { return ccNumber; } @Override public String toString() { return "business.customer.Customer[customerId=" + customerId + "]"; } }
package com.aol.simple.react; import static java.util.Arrays.asList; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.experimental.Wither; import lombok.extern.slf4j.Slf4j; import sun.misc.Unsafe; /** * * An Immutable Builder Class that represents a stage in a SimpleReact Dataflow. * Chain stages together to build complext reactive dataflows. * * Access the underlying CompletableFutures via the 'with' method. Return to * using JDK Collections and (parrellel) Streams via 'allOf' or 'block' * * @author johnmcclean * * @param <T> * Input parameter for this stage * @param <U> * Return parameter for this stage */ //lombok annotations to aid Immutability (Wither and AllArgsConstructor) @Wither @AllArgsConstructor @Slf4j public class Stage<T, U> { private final Executor taskExecutor; @SuppressWarnings("rawtypes") private final List<CompletableFuture> lastActive; private final Optional<Consumer<Throwable>> errorHandler; /** * * Construct a SimpleReact stage - this acts as a fluent SimpleReact builder * * @param stream * Stream that will generate the events that will be reacted to. * @param executor * The next stage's tasks will be submitted to this executor */ public Stage(final Stream<CompletableFuture<T>> stream, final Executor executor) { this.taskExecutor = executor; this.lastActive = stream.collect(Collectors.toList()); this.errorHandler = Optional.of( (e)-> { e.printStackTrace(); }); // log.error(e.getMessage(),e)); } /** * * React <b>with</b> * * Asynchronously apply the function supplied to the currently active event * tasks in the dataflow. * * While most methods in this class are fluent, and return a reference to a * SimpleReact Stage builder, this method can be used this method to access * the underlying CompletableFutures. * * <code> List<CompletableFuture<Integer>> futures = SimpleReact.<Integer, Integer> react(() -> 1, () -> 2, () -> 3) .with((it) -> it * 100); </code> * * In this instance, 3 suppliers generate 3 numbers. These may be executed * in parallel, when they complete each number will be multiplied by 100 - * as a separate parrellel task (handled by a ForkJoinPool or configurable * task executor). A List of Future objects will be returned immediately * from Simple React and the tasks will be executed asynchronously. * * React with does not block. * * @param fn * Function to be applied to the results of the currently active * event tasks * @return A list of CompletableFutures which will contain the result of the * application of the supplied function */ @SuppressWarnings("unchecked") public List<CompletableFuture<U>> with( final Function<T, ? extends Object> fn) { return lastActive .stream() .map(future -> (CompletableFuture<U>) future.thenApplyAsync(fn, taskExecutor)).collect(Collectors.toList()); } @SuppressWarnings("unchecked") public <R> Stage<U, R> then(final Function<T, U> fn) { return (Stage<U, R>) this.withLastActive(lastActive.stream() .map((ft) -> ft.thenApplyAsync(fn, taskExecutor)) .collect(Collectors.toList())); } /** * React <b>onFail</b> * * * Define a function that can be used to recover from exceptions during the * preceeding stage of the dataflow. e.g. * * * * onFail allows disaster recovery for each task (a separate onFail should * be configured for each react phase that can fail). E.g. if reading data * from an external service fails, but default value is acceptable - onFail * is a suitable mechanism to set the default value. Asynchronously apply * the function supplied to the currently active event tasks in the * dataflow. * * <code> List<String> strings = SimpleReact.<Integer, Integer> react(() -> 100, () -> 2, () -> 3) .then(it -> { if (it == 100) throw new RuntimeException("boo!"); return it; }) .onFail(e -> 1) .then(it -> "*" + it) .block(); </code> * * * In this example onFail recovers from the RuntimeException thrown when the * input to the first 'then' stage is 100. * * @param fn * Recovery function, the exception is input, and the recovery * value is output * @return A new builder object that can be used to define the next stage in * the dataflow */ @SuppressWarnings("unchecked") public <R> Stage<T, R> onFail(final Function<? extends Throwable, T> fn) { return (Stage<T, R>) this .withLastActive(lastActive.stream() .map((ft) -> ft.exceptionally(fn)) .collect(Collectors.toList())); } /** * React <b>capture</b> * * While onFail is used for disaster recovery (when it is possible to * recover) - capture is used to capture those occasions where the full * pipeline has failed and is unrecoverable. * * <code> * List<String> strings = SimpleReact.<Integer, Integer> react(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> { if (it == 100) throw new RuntimeException("boo!"); return it; }) .onFail(e -> 1) .then(it -> "*" + it) .then(it -> { if ("*200".equals(it)) throw new RuntimeException("boo!"); return it; }) .capture(e -> logger.error(e.getMessage(),e)) .block(); </code> * * In this case, strings will only contain the two successful results (for * ()->1 and ()->3), an exception for the chain starting from Supplier ()->2 * will be logged by capture. Capture will not capture the exception thrown * when an Integer value of 100 is found, but will catch the exception when * the String value "*200" is passed along the chain. * * @param errorHandler * A consumer that recieves and deals with an unrecoverable error * in the dataflow * @return A new builder object that can be used to define the next stage in * the dataflow */ @SuppressWarnings("unchecked") public Stage<T, U> capture(final Consumer<? extends Throwable> errorHandler) { return this.withErrorHandler(Optional .of((Consumer<Throwable>) errorHandler)); } /** * React and <b>block</b> * * <code> List<String> strings = SimpleReact.<Integer, Integer> react(() -> 1, () -> 2, () -> 3) .then((it) -> it * 100) .then((it) -> "*" + it) .block(); </code> * * In this example, once the current thread of execution meets the React * block method, it will block until all tasks have been completed. The * result will be returned as a List. The Reactive tasks triggered by the * Suppliers are non-blocking, and are not impacted by the block method * until they are complete. Block, only blocks the current thread. * * @return Results of currently active stage aggregated in a List */ @SuppressWarnings("hiding") public <U> List<U> block() { return block(Collectors.toList(),lastActive); } /** * @param collector to perform aggregation / reduction operation on the results (e.g. to Collect into a List or String) * @return Results of currently active stage in aggregated in form determined by collector */ @SuppressWarnings({ "hiding", "unchecked","rawtypes"}) public <U,R> R block(Collector collector) { return (R)block(collector,lastActive); } /** * Block until first result recieved * * @return first result. */ @SuppressWarnings({ "hiding", "unchecked","rawtypes"}) public <U,R> R first() { return blockAndExtract(Extractors.first(),status -> status.getCompleted() > 1); } /** * Block until all results recieved. * * @return last result */ @SuppressWarnings({ "hiding", "unchecked","rawtypes"}) public <U,R> R last() { return blockAndExtract(Extractors.last()); } /** * Block until tasks complete and return a value determined by the extractor supplied. * * @param extractor used to determine which value should be returned, recieves current collected input and extracts a return value * @return Value determined by the supplied extractor */ @SuppressWarnings({ "hiding", "unchecked","rawtypes"}) public <U,R> R blockAndExtract(Extractor extractor) { return blockAndExtract(extractor, status -> false); } /** * Block until tasks complete, or breakout conditions met and return a value determined by the extractor supplied. * * @param extractor used to determine which value should be returned, recieves current collected input and extracts a return value * @param breakout Predicate that determines whether the block should be * continued or removed * @return Value determined by the supplied extractor */ @SuppressWarnings({ "hiding", "unchecked","rawtypes"}) public <U,R> R blockAndExtract(Extractor extractor,Predicate<Status> breakout) { return (R)extractor.extract(block()); } /** * React and <b>block</b> with <b>breakout</b> * * Sometimes you may not need to block until all the work is complete, one * result or a subset may be enough. To faciliate this, block can accept a * Predicate functional interface that will allow SimpleReact to stop * blocking the current thread when the Predicate has been fulfilled. E.g. * * <code> List<String> strings = SimpleReact.<Integer, Integer> react(() -> 1, () -> 2, () -> 3) .then(it -> it * 100) .then(it -> "*" + it) .block(status -> status.getCompleted()>1); </code> * * In this example the current thread will unblock once more than one result * has been returned. * * @param breakout * Predicate that determines whether the block should be * continued or removed * @return List of Completed results of currently active stage at full completion * point or when breakout triggered (which ever comes first). */ @SuppressWarnings("hiding") public <U> List<U> block(final Predicate<Status> breakout) { return new Blocker<U>(lastActive, errorHandler).block(breakout); } /** * @param collector to perform aggregation / reduction operation on the results (e.g. to Collect into a List or String) * @param breakout Predicate that determines whether the block should be * continued or removed * @return Completed results of currently active stage at full completion * point or when breakout triggered (which ever comes first), in aggregated in form determined by collector */ @SuppressWarnings({ "hiding", "unchecked","rawtypes" }) public <U,R> R block(final Collector collector,final Predicate<Status> breakout) { return (R)block(breakout).stream().collect(collector); } /** * React and <b>allOf</b> * * allOf is a non-blocking equivalent of block. The current thread is not * impacted by the calculations, but the reactive chain does not continue * until all currently alloted tasks complete. The allOf task is then * provided with a list of the results from the previous tasks in the chain. * * <code> boolean blocked[] = {false}; SimpleReact.<Integer, Integer> react(() -> 1, () -> 2, () -> 3) .then(it -> { try { Thread.sleep(50000); } catch (Exception e) { } blocked[0] =true; return 10; }) .allOf( it -> it.size()); assertThat(blocked[0],is(false)); </code> * * In this example, the current thread will continue and assert that it is * not blocked, allOf could continue and be executed in a separate thread. * * @param fn * Function that recieves the results of all currently active * tasks as input * @return A new builder object that can be used to define the next stage in * the dataflow */ @SuppressWarnings("unchecked") public <R> Stage<U, R> allOf(final Function<List<T>, U> fn) { return allOf(Collectors.toList(), (Function<R, U>)fn); } /** * @param collector to perform aggregation / reduction operation on the results from active stage (e.g. to Collect into a List or String) * @param fn Function that recieves the results of all currently active * tasks as input * @return A new builder object that can be used to define the next stage in * the dataflow */ @SuppressWarnings({"unchecked","rawtypes"}) public <R> Stage<U, R> allOf(final Collector collector,final Function<R, U> fn) { return (Stage<U, R>) withLastActive(asList( CompletableFuture.allOf( lastActiveArray()).thenApplyAsync((result) -> { return fn.apply(aggregateResults(collector, lastActive)); }, taskExecutor))); } @SuppressWarnings({ "rawtypes", "unchecked", "hiding" }) private <U,R> R block(final Collector collector,final List<CompletableFuture> lastActive) { return (R)lastActive.stream().map((future) -> { return (U) getSafe(future); }).filter(v -> v != MISSING_VALUE).collect(collector); } @SuppressWarnings({ "rawtypes", "unchecked" }) private<R> R aggregateResults(final Collector collector, final List<CompletableFuture> completedFutures) { return (R) completedFutures.stream().map(next -> getSafe(next)).filter(v -> v != MISSING_VALUE) .collect(collector); } @SuppressWarnings("rawtypes") private CompletableFuture[] lastActiveArray() { return lastActive.toArray(new CompletableFuture[0]); } private void capture(final Exception e) { errorHandler.ifPresent((handler) -> handler.accept(e.getCause())); } @SuppressWarnings("rawtypes") private Object getSafe(final CompletableFuture next) { try { return next.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); capture(e); } catch (Exception e) { capture(e); } return MISSING_VALUE; } private final static MissingValue MISSING_VALUE =new MissingValue(); private static class MissingValue { } @AllArgsConstructor private static class Blocker<U> { private final Optional<Unsafe> unsafe = getUnsafe(); @SuppressWarnings("rawtypes") private final List<CompletableFuture> lastActive; private final Optional<Consumer<Throwable>> errorHandler; private final CompletableFuture<List<U>> promise = new CompletableFuture<>(); private final SimpleTimer timer = new SimpleTimer(); private final AtomicInteger completed = new AtomicInteger(); private final AtomicInteger errors = new AtomicInteger(); private final Queue<U> currentResults = new ConcurrentLinkedQueue<U>(); @SuppressWarnings("unchecked") public List<U> block(final Predicate<Status> breakout) { lastActive.forEach(f -> f.whenComplete((result, ex) -> { testBreakoutConditionsBeforeUnblockingCurrentThread(breakout, result, (Throwable)ex); })); try { return promise.get(); } catch (ExecutionException e) { throwSoftenedException(e); throw new RuntimeException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throwSoftenedException(e); throw new RuntimeException(e); } } private void throwSoftenedException(final Exception e) { unsafe.ifPresent(u -> u.throwException(e)); } private synchronized Status buildStatus(Throwable ex){ if (ex != null) { errors.incrementAndGet(); }else{ completed.incrementAndGet(); } return new Status(completed.get(), errors.get(), lastActive.size(), timer.getElapsedNanoseconds()); } private void testBreakoutConditionsBeforeUnblockingCurrentThread( final Predicate<Status> breakout, final Object result, final Throwable ex) { if (result != null) currentResults.add((U) result); final Status status = buildStatus(ex); if (ex != null) { errorHandler.ifPresent((handler) -> handler .accept(((Exception) ex).getCause())); } if (breakoutConditionsMet(breakout, status) || allResultsReturned(status.completed + status.errors)) { promise.complete(new LinkedList<U>(currentResults)); } } private boolean allResultsReturned(final int localComplete) { return localComplete == lastActive.size(); } private boolean breakoutConditionsMet(final Predicate<Status> breakout, final Status status) { return breakout.test(status); } private static Optional<Unsafe> getUnsafe() { try { final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); return Optional.of((Unsafe) field.get(null)); } catch (Exception ex) { log.error(ex.getMessage()); } return Optional.empty(); } } @AllArgsConstructor @Getter public static class Status { private final int completed; private final int errors; private final int total; private final long elapsedNanos; } }
package com.crowdin.client; import com.crowdin.client.core.http.exceptions.HttpBadRequestException; import com.crowdin.client.core.http.exceptions.HttpException; import com.crowdin.client.core.model.*; import com.crowdin.client.languages.model.Language; import com.crowdin.client.sourcefiles.model.*; import com.crowdin.client.translations.model.CrowdinTranslationCreateProjectBuildForm; import com.crowdin.client.translations.model.ProjectBuild; import com.crowdin.client.translations.model.UploadTranslationsRequest; import com.crowdin.util.NotificationUtil; import com.crowdin.util.RetryUtil; import com.crowdin.util.Util; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import static com.crowdin.Constants.MESSAGES_BUNDLE; public class Crowdin { private final Long projectId; private final Project project; private final com.crowdin.client.Client client; public Crowdin(@NotNull Project project, @NotNull Long projectId, @NotNull String apiToken, String baseUrl) { this.project = project; this.projectId = projectId; Credentials credentials = new Credentials(apiToken, null, baseUrl); ClientConfig clientConfig = ClientConfig.builder() .userAgent(Util.getUserAgent()) .build(); this.client = new Client(credentials, clientConfig); } public Long addStorage(String fileName, InputStream content) { try { return this.client.getStorageApi() .addStorage(fileName, content) .getData() .getId(); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public void updateSource(Long sourceId, UpdateFileRequest request) { try { this.client.getSourceFilesApi() .updateOrRestoreFile(this.projectId, sourceId, request) .getData(); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public void addSource(AddFileRequest request) { try { this.client.getSourceFilesApi() .addFile(this.projectId, request) .getData(); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public void uploadTranslation(String languageId, UploadTranslationsRequest request) { try { this.client.getTranslationsApi() .uploadTranslations(this.projectId, languageId, request) .getData(); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public Directory addDirectory(AddDirectoryRequest request) { try { return this.client.getSourceFilesApi() .addDirectory(this.projectId, request) .getData(); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public com.crowdin.client.projectsgroups.model.Project getProject() { try { return this.client.getProjectsGroupsApi() .getProject(this.projectId) .getData(); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public List<Language> extractProjectLanguages(com.crowdin.client.projectsgroups.model.Project crowdinProject) { return crowdinProject.getTargetLanguages(); } public File downloadTranslations(VirtualFile baseDir, Long branchId) { try { CrowdinTranslationCreateProjectBuildForm buildProjectTranslationRequest = new CrowdinTranslationCreateProjectBuildForm(); buildProjectTranslationRequest.setBranchId(branchId); ResponseObject<ProjectBuild> projectBuildResponseObject = this.client.getTranslationsApi().buildProjectTranslation(this.projectId, buildProjectTranslationRequest); Long buildId = projectBuildResponseObject.getData().getId(); boolean finished = false; while (!finished) { ResponseObject<ProjectBuild> projectBuildStatusResponseObject = this.client.getTranslationsApi().checkBuildStatus(this.projectId, buildId); finished = projectBuildStatusResponseObject.getData().getStatus().equalsIgnoreCase("finished"); } ResponseObject<DownloadLink> downloadLinkResponseObject = this.client.getTranslationsApi().downloadProjectTranslations(this.projectId, buildId); String link = downloadLinkResponseObject.getData().getUrl(); File file = new File(baseDir.getCanonicalPath() + "/all.zip"); try (ReadableByteChannel readableByteChannel = Channels.newChannel(new URL(link).openStream()); FileOutputStream fos = new FileOutputStream(file)) { fos.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE); } return file; } catch (Exception e) { NotificationUtil.showErrorMessage(this.project, this.getErrorMessage(e)); return null; } } public List<Language> getSupportedLanguages() { try { return client.getLanguagesApi().listSupportedLanguages(500, 0) .getData() .stream() .map(ResponseObject::getData) .collect(Collectors.toList()); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public Map<Long, Directory> getDirectories(Long branchId) { try { return executeRequestFullList((limit, offset) -> this.client.getSourceFilesApi() .listDirectories(this.projectId, branchId, null, true, limit, offset) .getData() ) .stream() .map(ResponseObject::getData) .filter(dir -> Objects.equals(dir.getBranchId(), branchId)) .collect(Collectors.toMap(Directory::getId, Function.identity())); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } public List<com.crowdin.client.sourcefiles.model.FileInfo> getFiles(Long branchId) { try { return executeRequestFullList((limit, offset) -> this.client.getSourceFilesApi() .listFiles(this.projectId, branchId, null, true, 500, 0) .getData() ) .stream() .map(ResponseObject::getData) .filter(file -> Objects.equals(file.getBranchId(), branchId)) .collect(Collectors.toList()); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } /** * @param request represents function that downloads list of models and has two args (limit, offset) * @param <T> represents model * @return list of models accumulated from request function */ private static <T> List<T> executeRequestFullList(BiFunction<Integer, Integer, List<T>> request) { List<T> models = new ArrayList<>(); long counter; int limit = 500; do { List<T> responseModels = request.apply(limit, models.size()); models.addAll(responseModels); counter = responseModels.size(); } while (counter == limit); return models; } public Branch addBranch(AddBranchRequest request) { try { return this.client.getSourceFilesApi() .addBranch(this.projectId, request) .getData(); } catch (Exception e) { String errorMessage = this.getErrorMessage(e); if (errorMessage.contains("regexNotMatch File name can't contain")) { throw new RuntimeException(MESSAGES_BUNDLE.getString("errors.branch_contains_forbidden_symbols")); } else { throw new RuntimeException(errorMessage, e); } } } public Optional<Branch> getBranch(String name) { List<ResponseObject<Branch>> branches = this.client.getSourceFilesApi().listBranches(this.projectId, name, 500, null).getData(); return branches.stream() .filter(e -> e.getData().getName().equalsIgnoreCase(name)) .map(ResponseObject::getData) .findFirst(); } public Map<String, Branch> getBranches() { try { return executeRequestFullList((limit, offset) -> this.client.getSourceFilesApi() .listBranches(this.projectId, null, limit, offset) .getData() ) .stream() .map(ResponseObject::getData) .collect(Collectors.toMap(Branch::getName, Function.identity())); } catch (Exception e) { throw new RuntimeException(this.getErrorMessage(e), e); } } private String getErrorMessage(Exception e) { if (e instanceof HttpException) { HttpException ex = (HttpException) e; String code = (ex.getError() != null && ex.getError().getCode() != null) ? ex.getError().getCode() : "<empty_code>"; String message = (ex.getError() != null && ex.getError().getMessage() != null) ? ex.getError().getMessage() : "<empty_message>"; if ("401".equals(code)) { return MESSAGES_BUNDLE.getString("errors.authorize"); } else { return String.format("Error from server: <Code: %s, Message: %s>", code, message); } } else if (e instanceof HttpBadRequestException) { HttpBadRequestException ex = (HttpBadRequestException) e; if (ex.getErrors() == null) { return "HttpBadRequestException<empty_error>"; } if (ex.getErrors() == null) { return "Wrong parameters: <Key: <empty_key>, Code: <empty_code>, Message: <empty_message>"; } return "Wrong parameters: \n" + ex.getErrors() .stream() .map(HttpBadRequestException.ErrorHolder::getError) .flatMap(holder -> holder.getErrors() .stream() .filter(Objects::nonNull) .map(error -> String.format("<Key: %s, Code: %s, Message: %s>", (holder.getKey() != null) ? holder.getKey() : "<empty_key>", (error.getCode() != null) ? error.getCode() : "<empty_code>", (error.getMessage() != null) ? error.getMessage() : "<empty_message>"))) .collect(Collectors.joining("\n")); } else { return e.getMessage(); } } private boolean concurrentIssue(Exception error) { return this.codeExists(error, "notUnique") || this.codeExists(error, "parallelCreation"); } private boolean codeExists(Exception e, String code) { if (e instanceof HttpException) { return ((HttpException) e).getError().getCode().equalsIgnoreCase(code); } else if (e instanceof HttpBadRequestException) { return ((HttpBadRequestException) e).getErrors().stream() .anyMatch(error -> error.getError().getErrors().stream() .anyMatch(er -> er.getCode().equalsIgnoreCase(code)) ); } else { return false; } } private Long waitAndFindBranch(String name) throws Exception { return RetryUtil.retry(() -> { ResponseList<Branch> branchResponseList = this.client.getSourceFilesApi().listBranches(this.projectId, name, 500, null); ResponseObject<Branch> branchResponseObject = branchResponseList.getData().stream() .filter(branch -> branch.getData().getName().equalsIgnoreCase(name)) .findFirst().orElse(null); if (branchResponseObject != null) { return branchResponseObject.getData().getId(); } else { throw new Exception(String.format(MESSAGES_BUNDLE.getString("errors.find_branch"), name)); } }); } private boolean customMessage(Exception e) { if (e instanceof HttpException) { HttpException ex = (HttpException) e; if (ex.getError().getCode().equalsIgnoreCase("401")) { return true; } } return false; } }
/** * Listens on TCP Port for messages. * Counts Messages based on value of sampleEveryMessages adds a point to the linear regresssion * After collecting three samples it will output the rate. * After 10 second pause the count and regression are reset. * * Creator: David Jennings */ package com.esri.simulator; import java.net.ServerSocket; import java.net.Socket; /** * * @author david */ public class TcpSink { public TcpSink(Integer port, Integer sampleEveryNSecs, boolean displaymessages) { try { ServerSocket ss = new ServerSocket(port); System.out.println("After starting this; create or restart the GeoEvent service."); System.out.println("Once connected you see a 'Listening' message"); while (true) { Socket cs = ss.accept(); TcpSinkServer ts = new TcpSinkServer(cs, sampleEveryNSecs, displaymessages); ts.start(); } } catch (Exception e) { } } public static void main(String[] args) { // Command Line Arg is port you want to listen on. 5565 /* NOTE: For latency calculations ensure all servers including the server running simulation are using time chrnonized. Run this command simulatneously on machines to compare time $ date +%s NTP command force update now: $ sudo ntpdate -s time.nist.gov CHRONYD check status: $ chronyc tracking */ int numargs = args.length; if (numargs < 1 || numargs > 3 ) { System.err.print("Usage: TcpSink <port-to-listen-on> (<sample-every-N-records/1000>) (<display-messages/false>)\n"); } else { WebSocketSink a = new WebSocketSink(); switch (numargs) { case 1: new TcpSink(Integer.parseInt(args[0]), 1000, false); break; case 2: new TcpSink(Integer.parseInt(args[0]), Integer.parseInt(args[1]), false); break; default: new TcpSink(Integer.parseInt(args[0]), Integer.parseInt(args[1]), Boolean.parseBoolean(args[2])); break; } } } }
package com.google.bqq; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryError; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.QueryRequest; import com.google.cloud.bigquery.QueryResponse; import com.google.cloud.bigquery.QueryResult; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; /** * Immutable Blocking BigQuery task to execute. */ public class BQQCallable implements Callable<QueryResult> { private String mProjectId; private String mServiceAccountPath = ""; private QueryRequest mQueryRequest; /** * Generates a new BQQCallable instance * If serviceAccountPath is an empty string / null, then default credentials used instead. * @param projectId project that the bq client bills / auths against * @param serviceAccountPath absolute path to a service account, or null/"" for default creds. * @param queryRequest the Query that needs to be run */ public BQQCallable(String projectId, String serviceAccountPath, QueryRequest queryRequest) { mProjectId = projectId; mServiceAccountPath = serviceAccountPath; mQueryRequest = queryRequest; } /** * Executes the instance's BigQuery SQL Query. * @throws BQQException query fails * @throws InterruptedException thread pool closed / killed before query finishes * @throws IOException if no Service Account Found * @throws FileNotFoundException if failed to read Service Account */ @Override public QueryResult call() throws BQQException, InterruptedException, FileNotFoundException, IOException { BigQuery bigquery = BQQServiceFactory.buildClient(mProjectId, mServiceAccountPath); QueryResponse response; try { response = bigquery.query(mQueryRequest); } catch (BigQueryException e) { throw new BQQException(e); } while (!response.jobCompleted()) { Thread.sleep(500L); try { response = bigquery.getQueryResults(response.getJobId()); } catch (BigQueryException e) { throw new BQQException("Failed to grab query results", e); } } List<BigQueryError> executionErrors = response.getExecutionErrors(); if (!executionErrors.isEmpty()) { throw new BQQException("BigQueryError", executionErrors); } QueryResult result = response.getResult(); return result; } }
// LMCurveFitter.java package loci.slim.fit; import jaolho.data.lma.LMA; import jaolho.data.lma.LMAFunction; import jaolho.data.lma.implementations.JAMAMatrix; import java.io.OutputStream; import java.io.PrintStream; public class LMCurveFitter extends CurveFitter { // -- Constants -- protected static final ExpFunction[] EXP_FUNCTIONS = { new ExpFunction(1), new ExpFunction(2) }; // -- Fields -- protected int maxVal; protected double[] xVals, yVals, weights; protected int iterCount; protected LMA lma; // -- Constructor -- public LMCurveFitter() { setComponentCount(1); } // -- LMCurveFitter methods -- public static PrintStream filter(PrintStream out) { return new ConsoleStream(out); } // -- ICurveFitter methods -- /** HACK - performs the actual fit. */ public void iterate() { iterCount++; lma.fit(); //log("\t\titerations=" + lma.iterationCount); // store parameters into curve array for (int i=0; i<components; i++) { int e = 2 * i; curveEstimate[i][0] = lma.parameters[e]; curveEstimate[i][1] = lma.parameters[e + 1]; } curveEstimate[0][2] = lma.parameters[2 * components]; } public int getIterations() { return iterCount; } public void setData(int[] data, int first, int last) { super.setData(data, first, last); int num = lastIndex - firstIndex + 1; xVals = new double[num]; yVals = new double[num]; weights = new double[num]; maxVal = 0; for (int i=0, q=firstIndex; i<num; i++, q++) { if (curveData[q] > maxVal) maxVal = curveData[q]; xVals[i] = i; yVals[i] = curveData[q]; weights[i] = 1; // no weighting } final double[] guess = {num / 10, num / 5}; double[] params = new double[2 * components + 1]; for (int i=0; i<components; i++) { int e = 2 * i; params[e] = maxVal / components; params[e + 1] = guess[i]; } lma = new LMA(EXP_FUNCTIONS[components - 1], params, new double[][] {xVals, yVals}, weights, new JAMAMatrix(params.length, params.length)); lma.maxIterations = 1; } // -- Helper classes -- /** * A summed exponential function of the form: * y(t) = a1*e^(-b1*t) + ... + an*e^(-bn*t) + c. */ public static class ExpFunction extends LMAFunction { /** Number of exponentials to fit. */ private int numExp = 1; /** Constructs a function with the given number of summed exponentials. */ public ExpFunction(int num) { numExp = num; } public double getY(double x, double[] a) { double sum = 0; for (int i=0; i<numExp; i++) { int e = 2 * i; sum += a[e] * Math.exp(-a[e + 1] * x); } sum += a[2 * numExp]; return sum; } public double getPartialDerivate(double x, double[] a, int parameterIndex) { if (parameterIndex == 2 * numExp) return 1; int e = parameterIndex / 2; int off = parameterIndex % 2; double aTerm = a[2 * e]; double bTerm = a[2 * e + 1]; switch (off) { case 0: return Math.exp(-bTerm * x); case 1: return -aTerm * x * Math.exp(-bTerm * x); } throw new RuntimeException("No such parameter index: " + parameterIndex); } } /** * HACK - OutputStream extension for filtering out hardcoded * RuntimeException.printStackTrace() exceptions within LMA library. */ public static class ConsoleStream extends PrintStream { private boolean ignore; public ConsoleStream(OutputStream out) { super(out); } public void println(String s) { if (s.equals("java.lang.RuntimeException: Matrix is singular.")) { ignore = true; } else if (ignore && !s.startsWith("\tat ")) ignore = false; if (!ignore) super.println(s); } public void println(Object o) { String s = o.toString(); println(s); } } }
package com.nucleus.vecmath; /** * This class is NOT thread safe since it uses static temp float arrays * 4 x 4 matrix laid out contiguously in memory, translation component is at the 3rd, 7th, and 11th element * Left handed coordinate system * Use this for classes that can represent the data as a matrix, for instance a scale or translation * * Matrices are 4 x 4 column-vector matrices stored in column-major * order: * * @author Richard Sahlin * */ public abstract class Matrix extends VecMath { /** * Number of elements (values) in a matrix */ public final static int MATRIX_ELEMENTS = 16; /** * Identity matrix to be used to read from * DO NOT WRITE TO THIS MATRIX */ public final static float[] IDENTITY_MATRIX = Matrix.setIdentity(Matrix.createMatrix(), 0); /** * Used to store the transform */ transient protected float[] matrix = Matrix.createMatrix(); private static float[] temp = new float[16]; private static float[] result = new float[16]; /** * Returns a matrix with the values contained in the implementing class, ie the rotate, translate and scale values. * * @return Matrix with the data contained in the implementing class */ public abstract float[] getMatrix(); /** * Creates a new, empty, matrix * * @return */ public final static float[] createMatrix() { return new float[MATRIX_ELEMENTS]; } /** * Sets the matrix to identity. * * @param matrix The matrix * @offset Offset into array where matrix values are stored. * @return The matrix, this is the same as passed into this method */ public final static float[] setIdentity(float[] matrix, int offset) { matrix[offset++] = 1f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 1f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 1f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 0f; matrix[offset++] = 1f; return matrix; } /** * Scales the matrix * * @param m * @param mOffset * @param x * @param y * @param z */ public static void scaleM(float[] matrix, int offset, float[] scale) { for (int i = 0; i < 4; i++) { int index = offset + i; matrix[index] *= scale[X]; matrix[index + 4] *= scale[Y]; matrix[index + 8] *= scale[Z]; } } /** * Multiply a number of 2 element vector with a matrix, the resultvectors will be transformed using the matrix * and stored sequentially * * @param matrix * @param offset Offset in matrix array where matrix starts * @param vec * @param resultVec The output vector, this may not be the same as vec * @param count Number of vectors to transform */ public final static void transformVec2(float[] matrix, int offset, float[] vec, float[] resultVec, int count) { int output = 0; int input = 0; for (int i = 0; i < count; i++) { resultVec[output++] = matrix[offset] * vec[input] + matrix[offset + 1] * vec[input + 1] + matrix[offset + 3]; resultVec[output++] = matrix[offset + 4] * vec[input] + matrix[offset + 5] * vec[input + 1] + matrix[offset + 7]; input += 2; } } /** * Transposes a 4 x 4 matrix. * * @param mTrans the array that holds the output inverted matrix * @param mTransOffset an offset into mInv where the inverted matrix is * stored. * @param m the input array * @param mOffset an offset into m where the matrix is stored. */ public static void transposeM(float[] mTrans, int mTransOffset, float[] m, int mOffset) { for (int i = 0; i < 4; i++) { int mBase = i * 4 + mOffset; mTrans[i + mTransOffset] = m[mBase]; mTrans[i + 4 + mTransOffset] = m[mBase + 1]; mTrans[i + 8 + mTransOffset] = m[mBase + 2]; mTrans[i + 12 + mTransOffset] = m[mBase + 3]; } } /** * Concatenate Matrix m1 with Matrix m2 and store the result in destination matrix. * * @param m1 * @param m2 * @param destination */ public final static void mul4(float[] m1, float[] m2, float[] destination) { // Concatenate matrix 1 with matrix 2, 4*4 destination[0] = (m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]); destination[4] = (m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]); destination[8] = (m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]); destination[12] = (m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]); destination[1] = (m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]); destination[5] = (m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]); destination[9] = (m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]); destination[13] = (m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]); destination[2] = (m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]); destination[6] = (m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]); destination[10] = (m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]); destination[14] = (m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]); destination[3] = (m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]); destination[7] = (m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]); destination[11] = (m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]); destination[15] = (m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]); } /** * Concatenate matrix with matrix2 and store the result in matrix * * @param matrix Source 1 matrix - matrix1 * matrix2 stored here * @param matrix2 Source 2 matrix */ public static void mul4(float[] matrix, float[] matrix2) { float temp_float1, temp_float2, temp_float3, temp_float4; // Concatenate this with matrix 2, 4*4 temp_float1 = (matrix[0] * matrix2[0] + matrix[1] * matrix2[4] + matrix[2] * matrix2[8] + matrix[3] * matrix2[12]); temp_float2 = (matrix[0] * matrix2[1] + matrix[1] * matrix2[5] + matrix[2] * matrix2[9] + matrix[3] * matrix2[13]); temp_float3 = (matrix[0] * matrix2[2] + matrix[1] * matrix2[6] + matrix[2] * matrix2[10] + matrix[3] * matrix2[14]); temp_float4 = (matrix[0] * matrix2[3] + matrix[1] * matrix2[7] + matrix[2] * matrix2[11] + matrix[3] * matrix2[15]); matrix[0] = temp_float1; matrix[4] = temp_float2; matrix[8] = temp_float3; matrix[12] = temp_float4; temp_float1 = (matrix[4] * matrix2[0] + matrix[5] * matrix2[4] + matrix[6] * matrix2[8] + matrix[7] * matrix2[12]); temp_float2 = (matrix[4] * matrix2[1] + matrix[5] * matrix2[5] + matrix[6] * matrix2[9] + matrix[7] * matrix2[13]); temp_float3 = (matrix[4] * matrix2[2] + matrix[5] * matrix2[6] + matrix[6] * matrix2[10] + matrix[7] * matrix2[14]); temp_float4 = (matrix[4] * matrix2[3] + matrix[5] * matrix2[7] + matrix[6] * matrix2[11] + matrix[7] * matrix2[15]); matrix[1] = temp_float1; matrix[5] = temp_float2; matrix[9] = temp_float3; matrix[13] = temp_float4; temp_float1 = (matrix[8] * matrix2[0] + matrix[9] * matrix2[4] + matrix[10] * matrix2[8] + matrix[11] * matrix2[12]); temp_float2 = (matrix[8] * matrix2[1] + matrix[9] * matrix2[5] + matrix[10] * matrix2[9] + matrix[11] * matrix2[13]); temp_float3 = (matrix[8] * matrix2[2] + matrix[9] * matrix2[6] + matrix[10] * matrix2[10] + matrix[11] * matrix2[14]); temp_float4 = (matrix[8] * matrix2[3] + matrix[9] * matrix2[7] + matrix[10] * matrix2[11] + matrix[11] * matrix2[15]); matrix[2] = temp_float1; matrix[6] = temp_float2; matrix[10] = temp_float3; matrix[14] = temp_float4; temp_float1 = (matrix[12] * matrix2[0] + matrix[13] * matrix2[4] + matrix[14] * matrix2[8] + matrix[15] * matrix2[12]); temp_float2 = (matrix[12] * matrix2[1] + matrix[13] * matrix2[5] + matrix[14] * matrix2[9] + matrix[15] * matrix2[13]); temp_float3 = (matrix[12] * matrix2[2] + matrix[13] * matrix2[6] + matrix[14] * matrix2[10] + matrix[15] * matrix2[14]); temp_float4 = (matrix[12] * matrix2[3] + matrix[13] * matrix2[7] + matrix[14] * matrix2[11] + matrix[15] * matrix2[15]); matrix[3] = temp_float1; matrix[7] = temp_float2; matrix[11] = temp_float3; matrix[15] = temp_float4; } /** * Inverts a 4 x 4 matrix. * * @param mInv the array that holds the output inverted matrix * @param mInvOffset an offset into mInv where the inverted matrix is * stored. * @param m the input array * @param mOffset an offset into m where the matrix is stored. * @return true if the matrix could be inverted, false if it could not. */ public static boolean invertM(float[] mInv, int mInvOffset, float[] m, int mOffset) { // Invert a 4 x 4 matrix using Cramer's Rule // array of transpose source matrix float[] src = new float[16]; // transpose matrix transposeM(src, 0, m, mOffset); // temp array for pairs float[] tmp = new float[12]; // calculate pairs for first 8 elements (cofactors) tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; // Holds the destination matrix while we're building it up. float[] dst = new float[16]; // calculate first 8 elements (cofactors) dst[0] = tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7]; dst[0] -= tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7]; dst[1] = tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7]; dst[1] -= tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7]; dst[2] = tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7]; dst[2] -= tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7]; dst[3] = tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6]; dst[3] -= tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6]; dst[4] = tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3]; dst[4] -= tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3]; dst[5] = tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3]; dst[5] -= tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3]; dst[6] = tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3]; dst[6] -= tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3]; dst[7] = tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2]; dst[7] -= tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2]; // calculate pairs for second 8 elements (cofactors) tmp[0] = src[2] * src[7]; tmp[1] = src[3] * src[6]; tmp[2] = src[1] * src[7]; tmp[3] = src[3] * src[5]; tmp[4] = src[1] * src[6]; tmp[5] = src[2] * src[5]; tmp[6] = src[0] * src[7]; tmp[7] = src[3] * src[4]; tmp[8] = src[0] * src[6]; tmp[9] = src[2] * src[4]; tmp[10] = src[0] * src[5]; tmp[11] = src[1] * src[4]; // calculate second 8 elements (cofactors) dst[8] = tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15]; dst[8] -= tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15]; dst[9] = tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15]; dst[9] -= tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15]; dst[10] = tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15]; dst[10] -= tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15]; dst[11] = tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14]; dst[11] -= tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14]; dst[12] = tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9]; dst[12] -= tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10]; dst[13] = tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10]; dst[13] -= tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8]; dst[14] = tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8]; dst[14] -= tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9]; dst[15] = tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9]; dst[15] -= tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8]; // calculate determinant float det = src[0] * dst[0] + src[1] * dst[1] + src[2] * dst[2] + src[3] * dst[3]; if (det == 0.0f) { } // calculate matrix inverse det = 1 / det; for (int j = 0; j < 16; j++) mInv[j + mInvOffset] = dst[j] * det; return true; } /** * Computes an orthographic projection matrix for a left handed coordinate system. * * @param m returns the result * @param mOffset * @param left * @param right * @param bottom * @param top * @param near * @param far */ public static void orthoM(float[] m, int mOffset, float left, float right, float bottom, float top, float near, float far) { if (left == right) { throw new IllegalArgumentException("left == right"); } if (bottom == top) { throw new IllegalArgumentException("bottom == top"); } if (near == far) { throw new IllegalArgumentException("near == far"); } final float r_width = 1.0f / (right - left); final float r_height = 1.0f / (top - bottom); final float r_depth = 1.0f / (far - near); final float x = 2.0f * (r_width); final float y = 2.0f * (r_height); final float z = 2.0f * (r_depth); final float tx = -(right + left) * r_width; final float ty = -(top + bottom) * r_height; final float tz = -(far + near) * r_depth; m[mOffset + 0] = x; m[mOffset + 5] = y; m[mOffset + 10] = z; m[mOffset + 12] = tx; m[mOffset + 13] = ty; m[mOffset + 14] = tz; m[mOffset + 15] = 1.0f; m[mOffset + 1] = 0.0f; m[mOffset + 2] = 0.0f; m[mOffset + 3] = 0.0f; m[mOffset + 4] = 0.0f; m[mOffset + 6] = 0.0f; m[mOffset + 7] = 0.0f; m[mOffset + 8] = 0.0f; m[mOffset + 9] = 0.0f; m[mOffset + 11] = 0.0f; // float[] transpose = Matrix.createMatrix(); // transposeM(transpose, 0, m, 0); // System.arraycopy(transpose, 0, m, 0, 16); } /** * Define a projection matrix in terms of six clip planes * * @param m the float array that holds the perspective matrix * @param offset the offset into float array m where the perspective * matrix data is written * @param left * @param right * @param bottom * @param top * @param near * @param far */ public static void frustumM(float[] m, int offset, float left, float right, float bottom, float top, float near, float far) { if (left == right) { throw new IllegalArgumentException("left == right"); } if (top == bottom) { throw new IllegalArgumentException("top == bottom"); } if (near == far) { throw new IllegalArgumentException("near == far"); } if (near <= 0.0f) { throw new IllegalArgumentException("near <= 0.0f"); } if (far <= 0.0f) { throw new IllegalArgumentException("far <= 0.0f"); } final float r_width = 1.0f / (right - left); final float r_height = 1.0f / (top - bottom); final float r_depth = 1.0f / (near - far); final float x = 2.0f * (near * r_width); final float y = 2.0f * (near * r_height); final float A = 2.0f * ((right + left) * r_width); final float B = (top + bottom) * r_height; final float C = -(far + near) * r_depth; final float D = 2.0f * (far * near * r_depth); m[offset + 0] = x; m[offset + 5] = y; m[offset + 8] = A; m[offset + 9] = B; m[offset + 10] = C; m[offset + 14] = D; m[offset + 11] = 1.0f; m[offset + 1] = 0.0f; m[offset + 2] = 0.0f; m[offset + 3] = 0.0f; m[offset + 4] = 0.0f; m[offset + 6] = 0.0f; m[offset + 7] = 0.0f; m[offset + 12] = 0.0f; m[offset + 13] = 0.0f; m[offset + 15] = 0.0f; } /** * Computes the length of a vector * * @param x x coordinate of a vector * @param y y coordinate of a vector * @param z z coordinate of a vector * @return the length of a vector */ public static float length(float x, float y, float z) { return (float) Math.sqrt(x * x + y * y + z * z); } /** * Sets matrix m to the identity matrix. * * @param sm returns the result * @param smOffset index into sm where the result matrix starts */ public static void setIdentityM(float[] sm, int smOffset) { for (int i = 0; i < 16; i++) { sm[smOffset + i] = 0; } for (int i = 0; i < 16; i += 5) { sm[smOffset + i] = 1.0f; } } /** * Scales matrix m in place by sx, sy, and sz * * @param m matrix to scale * @param mOffset index into m where the matrix starts * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void scaleM(float[] m, int mOffset, float x, float y, float z) { for (int i = 0; i < 4; i++) { int mi = mOffset + i; m[mi] *= x; m[4 + mi] *= y; m[8 + mi] *= z; } } /** * Translate the matrix, OpenGL row wise, along x,y and z axis * * @param matrix * @param x * @param y * @param z */ public final static void translate(float[] matrix, float x, float y, float z) { matrix[3] = x; matrix[7] = y; matrix[11] = z; } /** * Translate the matrix, OpenGL row wise, along x,y and z axis * * @param matrix * @param translate */ public final static void translate(float[] matrix, float[] translate) { matrix[3] = translate[0]; matrix[7] = translate[1]; matrix[11] = translate[2]; } public static void rotateM(float[] m, AxisAngle axisAngle) { if (axisAngle != null) { // TODO - should a check be made for 0 values in X,Y,Z axis which results in NaN? float[] values = axisAngle.axisAngle; setRotateM(temp, 0, values[AxisAngle.ANGLE], values[AxisAngle.X], values[AxisAngle.Y], values[AxisAngle.Z]); mul4(m, temp, result); System.arraycopy(result, 0, m, 0, 16); } } /** * Rotates matrix m by angle a (in degrees) around the axis (x, y, z) using left handed coordinate system. * * @param rm returns the result * @param rmOffset index into rm where the result matrix starts * @param a angle to rotate in radians * @param x scale factor x * @param y scale factor y * @param z scale factor z */ public static void setRotateM(float[] rm, int rmOffset, float a, float x, float y, float z) { rm[rmOffset + 3] = 0; rm[rmOffset + 7] = 0; rm[rmOffset + 11] = 0; rm[rmOffset + 12] = 0; rm[rmOffset + 13] = 0; rm[rmOffset + 14] = 0; rm[rmOffset + 15] = 1; float s = (float) Math.sin(a); float c = (float) Math.cos(a); if (1.0f == x && 0.0f == y && 0.0f == z) { rm[rmOffset + 5] = c; rm[rmOffset + 10] = c; rm[rmOffset + 6] = s; rm[rmOffset + 9] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 2] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 0] = 1; } else if (0.0f == x && 1.0f == y && 0.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 10] = c; rm[rmOffset + 8] = s; rm[rmOffset + 2] = -s; rm[rmOffset + 1] = 0; rm[rmOffset + 4] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 5] = 1; } else if (0.0f == x && 0.0f == y && 1.0f == z) { rm[rmOffset + 0] = c; rm[rmOffset + 5] = c; rm[rmOffset + 1] = s; rm[rmOffset + 4] = -s; rm[rmOffset + 2] = 0; rm[rmOffset + 6] = 0; rm[rmOffset + 8] = 0; rm[rmOffset + 9] = 0; rm[rmOffset + 10] = 1; } else { float len = length(x, y, z); if (1.0f != len) { float recipLen = 1.0f / len; x *= recipLen; y *= recipLen; z *= recipLen; } float nc = 1.0f - c; float xy = x * y; float yz = y * z; float zx = z * x; float xs = x * s; float ys = y * s; float zs = z * s; rm[rmOffset + 0] = x * x * nc + c; rm[rmOffset + 4] = xy * nc - zs; rm[rmOffset + 8] = zx * nc + ys; rm[rmOffset + 1] = xy * nc + zs; rm[rmOffset + 5] = y * y * nc + c; rm[rmOffset + 9] = yz * nc - xs; rm[rmOffset + 2] = zx * nc - ys; rm[rmOffset + 6] = yz * nc + xs; rm[rmOffset + 10] = z * z * nc + c; } } }
package com.sigopt.model; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Type; public class APIObject { Map<String, Object> model; public APIObject() { this.model = new HashMap<String, Object>(); } Object get(String key) { return this.model.get(key); } private Object adaptForStorage(Object value) { if (value instanceof APIObject) { return ((APIObject) value).model; } else if (value instanceof Collection) { List<Object> ret = new ArrayList<Object>(); for (Object v: (Collection) value) { ret.add(this.adaptForStorage(v)); } return ret; } else if (value instanceof Map) { Map<Object, Object> ret = new HashMap<Object, Object>(); Map valueAsMap = (Map) value; for (Object key: valueAsMap.keySet()) { ret.put(key, this.adaptForStorage(valueAsMap.get(key))); } return ret; } else { return value; } } <T extends Object> void set(String key, T value) { this.model.put(key, this.adaptForStorage(value)); } void setAll(Map<String, Object> map) { this.model.clear(); if (map != null) { this.model.putAll(map); } } public static final Gson GSON = new GsonBuilder() .serializeNulls() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); public static final Gson PRETTY_PRINT_GSON = new GsonBuilder() .setPrettyPrinting() .serializeNulls() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); public String toJson() { return GSON.toJson(this.model); } public static Map<String, Object> fromJson(String json, Type t) { return GSON.fromJson(json, t); } @Override public String toString() { return String.format( "<%s@%s> Attributes: %s", this.getClass().getName(), System.identityHashCode(this), this.toJson() ); } @Override public boolean equals(Object other) { return ( other != null && this.getClass().equals(other.getClass()) && this.model.equals(((APIObject)other).model) ); } @Override public int hashCode() { return this.model.hashCode(); } public static boolean equals(Object a, Object b) { return a == null ? b == null : a.equals(b); } }
package com.theisenp.harbor; import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; import lcm.lcm.LCM; import org.joda.time.Duration; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.theisenp.harbor.lcm.Initialize; import com.theisenp.harbor.lcm.Publisher; import com.theisenp.harbor.lcm.Subscribe; import com.theisenp.harbor.lcm.Subscriber; import com.theisenp.harbor.lcm.Unsubscribe; import com.theisenp.harbor.utils.HarborUtils; /** * An LCM based peer discovery utility * * @author patrick.theisen */ public class Harbor { public static final String DEFAULT_ADDRESS = "239.255.76.67"; public static final int DEFAULT_PORT = 7667; public static final int DEFAULT_TTL = 0; public static final Duration DEFAULT_PERIOD = Duration.standardSeconds(1); public static final Duration DEFAULT_TIMEOUT = Duration.standardSeconds(5); private final String address; private final int port; private final int ttl; private final Duration period; private final Duration timeout; private final Peer peer; private final ListeningScheduledExecutorService executor; private final ListenableFuture<LCM> lcm; private final Subscriber subscriber; private ListenableFuture<Object> publisher; /** * @param address * @param port * @param ttl * @param periodMillis * @param timeoutMillis */ public Harbor(String address, int port, int ttl, Duration period, Duration timeout, Peer peer) { this.address = address; this.port = port; this.ttl = ttl; this.period = period; this.timeout = timeout; this.peer = peer; // Validate the parameters HarborUtils.validateAddress(address); HarborUtils.validatePort(port); HarborUtils.validateTtl(ttl); HarborUtils.validatePeriod(period); HarborUtils.validateTimeout(timeout); // Initialize the LCM instance on a background thread executor = listeningDecorator(newSingleThreadScheduledExecutor()); lcm = executor.submit(new Initialize(address, port, ttl)); subscriber = new Subscriber(executor, timeout); } /** * Adds the given {@link Listener} to the set of those that will be notified * when peers change status * * @param listener */ public void addListener(Listener listener) { subscriber.addListener(listener); } /** * Removes the given {@link Listener} from the set of those that will be * notified when peers change status * * @param listener */ public void removeListener(Listener listener) { subscriber.removeListener(listener); } /** * @return */ public String getAddress() { return address; } /** * @return */ public int getPort() { return port; } /** * @return */ public int getTtl() { return ttl; } /** * @return */ public Duration getPeriod() { return period; } /** * @return */ public Duration getTimeout() { return timeout; } /** * @return */ public Peer getPeer() { return peer; } /** * Starts the publish and subscribe tasks */ public void open() { Futures.transform(lcm, new Subscribe(subscriber)); publisher = Futures.transform(lcm, new Publisher(executor, period, peer)); } /** * Stops the publish and subscribe tasks */ public void close() { Futures.transform(lcm, new Unsubscribe(subscriber)); // TODO: Remove all peers publisher.cancel(true); } /** * A fluent builder for {@link Harbor} * * @author patrick.theisen */ public static class Builder { private String address = DEFAULT_ADDRESS; private int port = DEFAULT_PORT; private int ttl = DEFAULT_TTL; private Duration period = DEFAULT_PERIOD; private Duration timeout = DEFAULT_TIMEOUT; private Peer peer; public Builder() { } /** * @param other */ public Builder(Harbor other) { this.address = other.address; this.port = other.port; this.ttl = other.ttl; this.period = other.period; this.timeout = other.timeout; this.peer = other.peer; } /** * @param address * @return This instance */ public Builder address(String address) { HarborUtils.validateAddress(address); this.address = address; return this; } /** * @param port * @return This instance */ public Builder port(int port) { HarborUtils.validatePort(port); this.port = port; return this; } /** * @param ttl * @return This instance */ public Builder ttl(int ttl) { HarborUtils.validateTtl(ttl); this.ttl = ttl; return this; } /** * @param period * @return This instance */ public Builder period(Duration period) { HarborUtils.validatePeriod(period); this.period = period; return this; } /** * @param timeout * @return This instance */ public Builder timeout(Duration timeout) { HarborUtils.validateTimeout(timeout); this.timeout = timeout; return this; } /** * @param peer * @return This instance */ public Builder peer(Peer peer) { this.peer = peer; return this; } /** * Clears any previously set parameters * * @return This instance */ public Builder reset() { address = DEFAULT_ADDRESS; port = DEFAULT_PORT; ttl = DEFAULT_TTL; period = DEFAULT_PERIOD; timeout = DEFAULT_TIMEOUT; peer = null; return this; } /** * A {@link Harbor} built from the current state * * @return */ public Harbor build() { validate(); return new Harbor(address, port, ttl, period, timeout, peer); } /** * Verifies that a valid {@link Harbor} can be produced from the current * state */ private void validate() { // Check the peer if(peer == null) { String message = "You must provide a peer"; throw new IllegalStateException(message); } } } /** * A collection of {@link Harbor} related callbacks * * @author patrick.theisen */ public static interface Listener { /** * Called when a new peer connects * * @param peer */ public void onConnected(Peer peer); /** * Called when a peer becomes active (either because it has just * connected or because it was previously inactive) * * @param peer */ public void onActive(Peer peer); /** * Called when a peer becomes inactive * * @param peer */ public void onInactive(Peer peer); /** * Called when a peer times out and disconnects * * @param peer */ public void onDisconnected(Peer peer); } }
package control; import data.Camera; import data.CameraShot; import data.CameraTimeline; import data.CameraType; import data.ScriptingProject; import gui.CameraShotBlock; import gui.CameraShotBlockUpdatedEvent; import gui.RootPane; import java.util.List; /** * Class that controls the timeline. * @author alex */ public class TimelineController { private RootPane rootPane; // private List<CameraTimeline> cameraTimelines; // Placeholder camera type until GUI allows personalized entry // TODO: Replace Camera Type and Scripting Project when XML functionality is available private final CameraType defType = new CameraType("AW-HE130 HD PTZ", "It's an IP Camera", 0.5); // Placeholder project in lieu of XML loading private final ScriptingProject scriptingProject = new ScriptingProject("BOSS Project", 1.0); /** * Constructor. * @param rootPane Root Pane. */ public TimelineController(RootPane rootPane) { this.rootPane = rootPane; initializeCameraTimelines(); } /** * Add a camera shot to the corresponding timeline. * @param cameraIndex Index of the camera track. * @param name Name of the shot. * @param description Shot description. * @param startCount Start count. * @param endCount End count. */ public void addCameraShot(int cameraIndex, String name, String description, int startCount, int endCount) { CameraShot newShot = new CameraShot(name,description, startCount, endCount); this.scriptingProject.getCameraTimelines().get(cameraIndex).addShot(newShot); CameraShotBlock shotBlock = new CameraShotBlock(newShot.getInstance(), cameraIndex, rootPane.getRootCenterArea(), startCount, endCount, this::shotChangedHandler); } /** * Handle updated camera shot. The previous timeline is used to retrieve the corresponding * shot. The correct {@link CameraShot} is then updated using the latest {@link CameraShotBlock} * position and counts. As the event is unclear as to whether the shot has switched timelines, * it is removed from the previous timeline and added to the new one. * @param event Camera shot change event. */ private void shotChangedHandler(CameraShotBlockUpdatedEvent event) { CameraShotBlock changedBlock = event.getCameraShotBlock(); CameraTimeline previousTimeline = this.scriptingProject.getCameraTimelines() .get(event.getOldTimelineNumber()); // Locate shot to be updated using id CameraShot shot = previousTimeline.getShots().stream() .filter(s -> s.getInstance() == changedBlock.getShotId()) .findFirst() .get(); // Adjust model shot.setStartCount(changedBlock.getBeginCount()); shot.setEndCount(changedBlock.getEndCount()); // Remove shot from previous timeline and add to new one previousTimeline.removeShot(shot); this.scriptingProject.getCameraTimelines() .get(changedBlock.getTimetableNumber()).addShot(shot); } /** * Create camera timelines based on GUI. (Anti-pattern) * TODO: Replace this with proper XML based project creation */ private void initializeCameraTimelines() { int timelinesN = this.rootPane.getRootCenterArea().getGrid().getNumberOfTimelines(); for (int i = 0; i < timelinesN; i++) { Camera defCam = new Camera("IP Cam " + i, "", defType); CameraTimeline timelineN = new CameraTimeline(defCam, "", scriptingProject); scriptingProject.addCameraTimeline(timelineN); } } }
package de.ailis.usb4java; import javax.usb.UsbDevice; import javax.usb.UsbException; import javax.usb.UsbHostManager; import javax.usb.UsbHub; import javax.usb.UsbServices; import javax.usb.event.UsbServicesEvent; import javax.usb.event.UsbServicesListener; import de.ailis.usb4java.libusb.Loader; import de.ailis.usb4java.libusb.LoaderException; /** * usb4java implementation of JSR-80 UsbServices. * * @author Klaus Reimer (k@ailis.de) */ public final class Services implements UsbServices { /** The implementation description. */ private static final String IMP_DESCRIPTION = "usb4java"; /** The implementation version. */ private static final String IMP_VERSION = "1.0.0"; /** The API version. */ private static final String API_VERSION = "1.0.2"; /** The USB services listeners. */ private final ServicesListenerList listeners = new ServicesListenerList(); /** The virtual USB root hub. */ private final RootHub rootHub; /** The USB device scanner. */ private final DeviceManager deviceScanner; /** If devices should be scanned by hierarchy. */ private final Config config; /** * Constructor. * * @throws UsbException * When properties could not be loaded. * @throws LoaderException * When native libraries could not be loaded. */ public Services() throws UsbException { this.config = new Config(UsbHostManager.getProperties()); Loader.load(); this.rootHub = new RootHub(); this.deviceScanner = new DeviceManager(this.rootHub); this.deviceScanner.start(); } @Override public UsbHub getRootUsbHub() { this.deviceScanner.firstScan(); return this.rootHub; } @Override public void addUsbServicesListener(final UsbServicesListener listener) { this.listeners.add(listener); } @Override public void removeUsbServicesListener(final UsbServicesListener listener) { this.listeners.remove(listener); } @Override public String getApiVersion() { return API_VERSION; } @Override public String getImpVersion() { return IMP_VERSION; } @Override public String getImpDescription() { return IMP_DESCRIPTION; } /** * Informs listeners about a new attached device. * * @param device * The new attached device. */ void usbDeviceAttached(final UsbDevice device) { this.listeners.usbDeviceAttached(new UsbServicesEvent(this, device)); } /** * Informs listeners about a detached device. * * @param device * The detached device. */ void usbDeviceDetached(final UsbDevice device) { this.listeners.usbDeviceDetached(new UsbServicesEvent(this, device)); } /** * Returns the configuration. * * @return The configuration. */ Config getConfig() { return this.config; } /** * Returns the usb4java services. * * @return The usb4java services. */ static Services getInstance() { try { UsbServices services = UsbHostManager.getUsbServices(); return (Services) services; } catch (final ClassCastException e) { throw new ServicesException("Looks like usb4java is not the " + "configured USB services implementation: " + e, e); } catch (final UsbException e) { throw new ServicesException("Unable to create USB services: " + e, e); } } }
package de.javagl.obj; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Methods for splitting {@link ReadableObj} objects into multiple parts, * based on different criteria. */ public class ObjSplitting { /** * Split the given {@link ReadableObj} based on its groups. This will * create one {@link Obj} from each (non-empty) group in the * given input. * * @param obj The input {@link ReadableObj} * @return One {@link Obj} for each non-empty group of the given input */ public static Map<String, Obj> splitByGroups(ReadableObj obj) { Map<String, Obj> objs = new LinkedHashMap<String, Obj>(); int numGroups = obj.getNumGroups(); for (int i = 0; i < numGroups; i++) { ObjGroup group = obj.getGroup(i); if (group.getNumFaces() > 0) { String groupName = group.getName(); Obj groupObj = ObjUtils.groupToObj(obj, group, null); objs.put(groupName, groupObj); } } return objs; } /** * Split the given {@link ReadableObj} based on its material groups. * This will create one {@link Obj} from each (non-empty) material * group in the given input. <br> * <br> * Note that if the given OBJ does not contain any material groups * (that is, when it does not refer to a material with a * <code>usemtl</code> directive), then the resulting map will * be empty. <br> * <br> * Faces that are not associated with any material group * will not be contained in the output. * * @param obj The input {@link ReadableObj} * @return The mapping from material group names (corresponding to the * <code>usemtl</code> directives in the input file) to the {@link Obj} * that represents this material group. */ public static Map<String, Obj> splitByMaterialGroups(ReadableObj obj) { Map<String, Obj> objs = new LinkedHashMap<String, Obj>(); int numMaterialGroups = obj.getNumMaterialGroups(); for (int i = 0; i < numMaterialGroups; i++) { ObjGroup materialGroup = obj.getMaterialGroup(i); if (materialGroup.getNumFaces() > 0) { String materialGroupName = materialGroup.getName(); Obj materialGroupObj = ObjUtils.groupToObj(obj, materialGroup, null); objs.put(materialGroupName, materialGroupObj); } } return objs; } public static List<Obj> splitByMaxNumVertices( ReadableObj obj, int maxNumVertices) { if (maxNumVertices < 3) { throw new IllegalArgumentException( "The given number of vertices must at least be 3"); } ObjSplitter splitter = new ObjSplitter(maxNumVertices); return splitter.split(obj); } /** * Private constructor to prevent instantiation */ private ObjSplitting() { // Private constructor to prevent instantiation } }
package hudson.remoting; import java.io.OutputStream; import java.util.logging.Logger; import static java.util.logging.Level.*; /** * Keeps track of the number of bytes that the sender can send without overwhelming the receiver of the pipe. * * <p> * {@link OutputStream} is a blocking operation in Java, so when we send byte[] to the remote to write to * {@link OutputStream}, it needs to be done in a separate thread (or else we'll fail to attend to the channel * in timely fashion.) This in turn means the byte[] being sent needs to go to a queue between a * channel reader thread and I/O processing thread, and thus in turn means we need some kind of throttling * mechanism, or else the queue can grow too much. * * <p> * This implementation solves the problem by using TCP/IP like window size tracking. The sender allocates * a fixed length window size. Every time the sender sends something we reduce this value. When the receiver * writes data to {@link OutputStream}, it'll send back the "ack" command, which adds to this value, allowing * the sender to send more data. * * @author Kohsuke Kawaguchi */ abstract class PipeWindow { abstract void increase(int delta); abstract int peek(); /** * Blocks until some space becomes available. */ abstract int get() throws InterruptedException; abstract void decrease(int delta); /** * Fake implementation used when the receiver side doesn't support throttling. */ static final PipeWindow FAKE = new PipeWindow() { void increase(int delta) { } int peek() { return Integer.MAX_VALUE; } int get() throws InterruptedException { return Integer.MAX_VALUE; } void decrease(int delta) { } }; static final class Key { public final int oid; Key(int oid) { this.oid = oid; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; return oid == ((Key) o).oid; } @Override public int hashCode() { return oid; } } static class Real extends PipeWindow { private int available; private long written; private long acked; private final int oid; /** * The only strong reference to the key, which in turn * keeps this object accessible in {@link Channel#pipeWindows}. */ private final Key key; Real(Key key, int initialSize) { this.key = key; this.oid = key.oid; this.available = initialSize; } public synchronized void increase(int delta) { if (LOGGER.isLoggable(FINER)) LOGGER.finer(String.format("increase(%d,%d)->%d",oid,delta,delta+available)); available += delta; acked += delta; notifyAll(); } public synchronized int peek() { return available; } /** * Blocks until some space becomes available. * * <p> * If the window size is empty, induce some delay outside the synchronized block, * to avoid fragmenting the window size. That is, if a bunch of small ACKs come in a sequence, * bundle them up into a bigger size before making a call. */ public int get() throws InterruptedException { synchronized (this) { if (available>0) return available; while (available==0) { wait(); } } Thread.sleep(10); synchronized (this) { return available; } } public synchronized void decrease(int delta) { if (LOGGER.isLoggable(FINER)) LOGGER.finer(String.format("decrease(%d,%d)->%d",oid,delta,available-delta)); available -= delta; written+= delta; if (available<0) throw new AssertionError(); } } private static final Logger LOGGER = Logger.getLogger(PipeWindow.class.getName()); }
package jfdi.storage; import java.lang.reflect.Method; import java.nio.file.Path; import java.util.ArrayList; import jfdi.storage.exceptions.ExistingFilesFoundException; import jfdi.storage.exceptions.FilePathPair; /** * This class manages operations related to all records in the Storage * component. All records (e.g. Task, Alias) are expected to implement * the following static methods that will be called via reflection: * * + load() * + getFilePath() * + setFilePath(String) * * @author Thng Kai Yuan */ public class RecordManager { /* * Public APIs */ /** * This method sets the filepath of each record accordingly, using * storageFolderPath as the root directory of all data. * * @param storageFolderPath * the root directory where all data will be stored */ public static void setAllFilePaths(String storageFolderPath) { for (Class<?> record : Constants.getRecords()) { setRecordFilePath(storageFolderPath, record); } } /** * This method loads/refreshes all records based on data contained within * the data file defined by the filepath of each record. * * @throws ExistingFilesFoundException * if unrecognized files were replaced (with backups made) */ public static void loadAllRecords() throws ExistingFilesFoundException { ArrayList<FilePathPair> replacedFiles = new ArrayList<FilePathPair>(); FilePathPair filePathPair = null; for (Class<?> record : Constants.getRecords()) { filePathPair = loadRecord(record); if (filePathPair != null) { replacedFiles.add(filePathPair); } } if (!replacedFiles.isEmpty()) { throw new ExistingFilesFoundException(replacedFiles); } } /** * @return an ArrayList of Paths where the existing data for each record is * stored. */ public static ArrayList<Path> getAllFilePaths() { ArrayList<Path> filePaths = new ArrayList<Path>(); for (Class<?> record : Constants.getRecords()) { Path filePath = getRecordFilePath(record); filePaths.add(filePath); } return filePaths; } /* * Private helper methods */ /** * This method executes the getFilePath method on the given record, that is, * it calls (something like) record.getFilePath(). * * @param record * the record which contains the getFilePath method * @return the Path of the existing data file for the record */ private static Path getRecordFilePath(Class<?> record) { Path filePath = null; try { Method method = record.getMethod("getFilePath"); filePath = (Path) method.invoke(null); } catch (Exception e) { e.printStackTrace(); } return filePath; } /** * This method executes the setFilePath method on the given record, that is, * it calls (something like) record.setFilePath(storageFolderPath). * * @param storageFolderPath * the parameter for the setFilePath method * @param record * the record which contains the setFilePath method */ private static void setRecordFilePath(String storageFolderPath, Class<?> record) { try { Method method = record.getMethod("setFilePath", String.class); method.invoke(null, storageFolderPath); } catch (Exception e) { e.printStackTrace(); } } /** * This method executes the load method on the given record, that is, it * calls (something like) record.load() and returns the return value of the * method call. * * @param record * the record which contains the load method * @return FilePathPair if a file was replaced, null otherwise */ private static FilePathPair loadRecord(Class<?> record) { FilePathPair filePathPair = null; try { Method method = record.getMethod("load"); filePathPair = (FilePathPair) method.invoke(null); } catch (Exception e) { e.printStackTrace(); } return filePathPair; } }
package kr.jm.utils; import kr.jm.utils.exception.JMExceptionManager; import kr.jm.utils.helper.JMFiles; import kr.jm.utils.helper.JMLog; import kr.jm.utils.helper.JMPath; import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream; import static java.nio.charset.StandardCharsets.UTF_8; /** * The type Jm file appender. */ public class JMFileAppender implements AutoCloseable { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory .getLogger(JMFileAppender.class); private Writer writer; private Path filePath; /** * Instantiates a new Jm file appender. * * @param filePath the file path */ public JMFileAppender(String filePath) { this(JMPath.getPath(filePath)); } /** * Instantiates a new Jm file appender. * * @param filePath the file path */ public JMFileAppender(Path filePath) { this(filePath, UTF_8); } /** * Instantiates a new Jm file appender. * * @param filePath the file path * @param charset the charset */ public JMFileAppender(String filePath, Charset charset) { this(JMPath.getPath(filePath), charset); } /** * Instantiates a new Jm file appender. * * @param filePath the file path * @param charset the charset */ public JMFileAppender(Path filePath, Charset charset) { JMLog.info(log, "JMFileAppender.new", filePath, charset); this.writer = JMFiles.buildBufferedAppendWriter(filePath, charset); this.filePath = filePath; } /** * Append jm file appender. * * @param string the string * @return the jm file appender */ public JMFileAppender append(String string) { JMFiles.append(this.writer, string); return this; } /** * Append line jm file appender. * * @param line the line * @return the jm file appender */ public JMFileAppender appendLine(String line) { JMFiles.appendLine(this.writer, line); return this; } /** * Append and close path. * * @param filePath the file path * @param charset the charset * @param writingString the writing string * @return the path */ public static Path appendAndClose(String filePath, Charset charset, String writingString) { return new JMFileAppender(filePath, charset).append(writingString) .closeAndGetFilePath(); } /** * Close and get file path path. * * @return the path */ public Path closeAndGetFilePath() { close(); return filePath; } /** * Append lines and close path. * * @param filePath the file path * @param lines the lines * @return the path */ public static Path appendLinesAndClose(String filePath, String... lines) { return appendLinesAndClose(filePath, UTF_8, lines); } /** * Append lines and close path. * * @param filePath the file path * @param lineCollection the line collection * @return the path */ public static Path appendLinesAndClose(String filePath, Collection<String> lineCollection) { return appendLinesAndClose(filePath, UTF_8, lineCollection); } /** * Append lines and close path. * * @param filePath the file path * @param charset the charset * @param lines the lines * @return the path */ public static Path appendLinesAndClose(String filePath, Charset charset, String... lines) { return appendLineStreamAndClose(filePath, charset, Arrays.stream(lines)); } /** * Append lines and close path. * * @param filePath the file path * @param charset the charset * @param lineCollection the line collection * @return the path */ public static Path appendLinesAndClose(String filePath, Charset charset, Collection<String> lineCollection) { return appendLineStreamAndClose(filePath, charset, lineCollection.stream()); } private static Path appendLineStreamAndClose(String filePath, Charset charset, Stream<String> lineStream) { return appendLineStreamAndClose(new JMFileAppender(filePath, charset), lineStream); } private static Path appendLineStreamAndClose(JMFileAppender jmFileAppender, Stream<String> lineStream) { lineStream.forEach(jmFileAppender::appendLine); return jmFileAppender.closeAndGetFilePath(); } /** * Gets file path. * * @return the file path */ public Path getFilePath() { return filePath; } @Override public void close() { try { writer.flush(); writer.close(); } catch (IOException e) { JMExceptionManager.logException(log, e, "close"); } } }
package m11.mib.paf.quiz.user; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Random; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.OneToMany; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonProperty; import m11.mib.paf.quiz.question.Question; import m11.mib.paf.quiz.result.Result; /** * Benutzer der Quiz-Applikation * * * @author M11 * @version 1.0 */ @Entity public class User { @Id private String id; private String password; private byte[] salt; private Boolean loggedIn; @Lob private byte[] portrait; @OneToMany(mappedBy = "resultOfUser") private List<Result> results; @OneToMany(mappedBy = "questioner") private List<Question> questions; @Transient @JsonProperty("id") private String jsonId; /** * Creates a hash out of the given password String. * Used for Saving the Password to the database and for validating during login procedure. * * @param password The password to be encrypted * @return The encrypted password hash */ private String encryptPassword(String password) { MessageDigest md = null; StringBuilder sb = new StringBuilder(); String encryptedPassword = null; byte[] hash; try { md = MessageDigest.getInstance("SHA-256"); md.update(this.salt); hash = md.digest(password.getBytes()); for (int i=0; i<hash.length; i++) { sb.append(Integer.toString((hash[i]&0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encryptedPassword; } /** * Constructor-Stub for JPA */ public User() {} /** * Create a new user with User-Id and password and generate a random salt. * * @param id * @param password */ public User(String id, String password) { Random randomizer = new Random(); this.id = id; this.salt = id.getBytes(); randomizer.nextBytes(this.salt); this.password = this.encryptPassword(password); this.loggedIn = false; } /** * @return The portrait of the user */ public byte[] getPortrait() { return portrait; } /** * Set the portrait of the user * * @param portrait The image to set as portrait */ public void setPortrait(byte[] portrait) { this.portrait = portrait; } /** * @return the jsonId */ public String getJsonId() { return id; } /** * @return Whether the User is currently logged into the system */ public Boolean isLoggedIn() { return loggedIn; } /** * Sets the loggedIn flag of the user * * @param password The password with which a User tries to login */ public void logIn(String password) { if ( this.password != encryptPassword(password) ) { throw new Error("Wrong Password!");//WrongPasswordException(); } this.loggedIn = true; } /** * Resets the loggedIn flag of the user */ public void logOut() { this.loggedIn = false; } }
package mjc.jasmin; import java.util.Map; import mjc.analysis.DepthFirstAdapter; import mjc.node.AArrayAccessExpression; import mjc.node.AArrayAssignStatement; import mjc.node.AAssignStatement; import mjc.node.ABlockStatement; import mjc.node.AClassDeclaration; import mjc.node.AFalseExpression; import mjc.node.AFieldDeclaration; import mjc.node.AIdentifierExpression; import mjc.node.AIntegerExpression; import mjc.node.AMainClassDeclaration; import mjc.node.AMethodDeclaration; import mjc.node.AMethodInvocationExpression; import mjc.node.AMinusExpression; import mjc.node.ANewInstanceExpression; import mjc.node.ANewIntArrayExpression; import mjc.node.ANotExpression; import mjc.node.APlusExpression; import mjc.node.APrintlnStatement; import mjc.node.AThisExpression; import mjc.node.ATimesExpression; import mjc.node.ATrueExpression; import mjc.node.Node; import mjc.symbol.ClassInfo; import mjc.symbol.MethodInfo; import mjc.symbol.SymbolTable; import mjc.symbol.VariableInfo; import mjc.types.Type; /** * Jasmin code generator. * * TODO: More docs. */ public class JasminGenerator extends DepthFirstAdapter { private final static int MAX_STACK_SIZE = 30; // TODO: Don't hardcode this. private final JasminHandler handler; private StringBuilder result; private SymbolTable symbolTable; private Map<Node, Type> types; private ClassInfo currentClass; private MethodInfo currentMethod; // Index of first user param/local (0 in static methods, 1 in non-static). private int baseIndex = 0; public JasminGenerator(JasminHandler handler) { this.handler = handler; } public void generate(Node ast, SymbolTable symbolTable, Map<Node, Type> types) { this.symbolTable = symbolTable; this.types = types; ast.apply(this); } /** * Adds a Jasmin directive to the result. * * @param directive Directive to add, including any format specifiers. * @param args Arguments matching format specifiers in @a directive. */ private void direc(String directive, Object... args) { result.append('.' + String.format(directive, args) + '\n'); } /** * Adds a Jasmin instruction to the result. * * @param instruction Instruction to add, including any format specifiers. * @param args Arguments matching format specifiers in @a instruction. */ private void instr(String instruction, Object... args) { result.append(" " + String.format(instruction, args) + '\n'); } /** * Adds a Jasmin label to the result. * * @param label Label to add. */ private void label(String label) { result.append(label + ":\n"); } /** * Adds a newline to the result. */ private void nl() { result.append("\n"); } /** * Returns a Jasmin type descriptor for the given MiniJava type. * * @param type A MiniJava type. * @return The Jasmin type descriptor. */ private String typeDescriptor(final Type type) { if (type.isInt()) { return "I"; } else if (type.isIntArray()) { return "[I"; } else if (type.isBoolean()) { return "Z"; } else if (type.isClass()) { return "L" + type.getName() + ";"; } else { throw new Error("Unknown Type"); } } /** * Returns a Jasmin method signature descriptor for the given method. * * @param methodInfo Method information. * @return A Jasmin method signature descriptor. */ private String methodSignatureDescriptor(final MethodInfo methodInfo) { String descriptor = "("; for (VariableInfo paramInfo : methodInfo.getParameters()) { descriptor += typeDescriptor(paramInfo.getType()); } descriptor += ")" + typeDescriptor(methodInfo.getReturnType()); return descriptor; } // Visitor methods below. @Override public void inAMainClassDeclaration(final AMainClassDeclaration declaration) { currentClass = symbolTable.getClassInfo(declaration.getName().getText()); currentMethod = currentClass.getMethod(declaration.getMethodName().getText()); currentMethod.enterBlock(); result = new StringBuilder(); direc("class public %s", currentClass.getName()); direc("super java/lang/Object"); nl(); // Default constructor. direc("method public <init>()V"); instr("aload_0"); instr("invokenonvirtual java/lang/Object/<init>()V"); instr("return"); direc("end method"); nl(); // Main method. direc("method public static main([Ljava/lang/String;)V"); direc("limit locals %d", baseIndex + currentMethod.getNextIndex()); direc("limit stack %d", MAX_STACK_SIZE); baseIndex = 0; } @Override public void outAMainClassDeclaration(final AMainClassDeclaration declaration) { // End of main method. instr("return"); direc("end method"); // Handle the result using the configured handler. handler.handle(currentClass.getName(), result); currentMethod.leaveBlock(); currentMethod = null; currentClass = null; } @Override public void inAClassDeclaration(final AClassDeclaration declaration) { currentClass = symbolTable.getClassInfo(declaration.getName().getText()); result = new StringBuilder(); direc("class public %s", currentClass.getName()); direc("super java/lang/Object"); nl(); baseIndex = 1; } @Override public void outAClassDeclaration(final AClassDeclaration declaration) { // Default constructor. nl(); direc("method public <init>()V"); instr("aload_0"); instr("invokenonvirtual java/lang/Object/<init>()V"); instr("return"); direc("end method"); nl(); // Handle the result using the configured handler. handler.handle(currentClass.getName(), result); currentClass = null; } @Override public void inAFieldDeclaration(final AFieldDeclaration declaration) { final String fieldName = declaration.getName().getText(); final Type fieldType = currentClass.getField(fieldName).getType(); direc("field protected %s %s", fieldName, typeDescriptor(fieldType)); } @Override public void inAMethodDeclaration(final AMethodDeclaration declaration) { currentMethod = currentClass.getMethod(declaration.getName().getText()); currentMethod.enterBlock(); final String methodName = currentMethod.getName(); final String methodSignature = methodSignatureDescriptor(currentMethod); nl(); direc("method public %s%s", methodName, methodSignature); direc("limit locals %d", baseIndex + currentMethod.getNextIndex()); direc("limit stack %d", MAX_STACK_SIZE); } @Override public void outAMethodDeclaration(final AMethodDeclaration declaration) { final Type type = currentMethod.getReturnType(); instr(type.isReference() ? "areturn" : "ireturn"); direc("end method"); currentMethod.leaveBlock(); currentMethod = null; } @Override public void inABlockStatement(final ABlockStatement block) { currentMethod.enterBlock(); } @Override public void outABlockStatement(final ABlockStatement block) { currentMethod.leaveBlock(); } @Override public void inAPrintlnStatement(final APrintlnStatement statement) { instr("getstatic java/lang/System/out Ljava/io/PrintStream;"); } @Override public void outAPrintlnStatement(final APrintlnStatement statement) { String typeDescriptor = typeDescriptor(types.get(statement.getValue())); instr("invokestatic java/lang/String/valueOf(%s)Ljava/lang/String;", typeDescriptor); instr("invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V"); } @Override public void inAAssignStatement(final AAssignStatement statement) { final String id = statement.getName().getText(); if (currentMethod.getLocal(id) == null && currentMethod.getParameter(id) == null) { // Load this pointer in preparation for putfield. instr("aload_0"); } } @Override public void outAAssignStatement(final AAssignStatement statement) { final String id = statement.getName().getText(); final VariableInfo localInfo, paramInfo, fieldInfo; if ((localInfo = currentMethod.getLocal(id)) != null) { final Type type = localInfo.getType(); instr("%s %d", type.isReference() ? "astore" : "istore", baseIndex + localInfo.getIndex()); } else if ((paramInfo = currentMethod.getParameter(id)) != null) { final Type type = paramInfo.getType(); instr("%s %d", type.isReference() ? "astore" : "istore", baseIndex + paramInfo.getIndex()); } else if ((fieldInfo = currentClass.getField(id)) != null) { final String typeDescriptor = typeDescriptor(fieldInfo.getType()); instr("putfield %s/%s %s", currentClass.getName(), id, typeDescriptor); } } @Override public void inAArrayAssignStatement(final AArrayAssignStatement statement) { final String id = statement.getName().getText(); final VariableInfo localInfo, paramInfo, fieldInfo; if ((localInfo = currentMethod.getLocal(id)) != null) { instr("aload %d", baseIndex + localInfo.getIndex()); } else if ((paramInfo = currentMethod.getParameter(id)) != null) { instr("aload %d", baseIndex + paramInfo.getIndex()); } else if ((fieldInfo = currentClass.getField(id)) != null) { final String typeDescriptor = typeDescriptor(fieldInfo.getType()); instr("aload_0"); instr("getfield %s/%s %s", currentClass.getName(), id, typeDescriptor); } } @Override public void outAArrayAssignStatement(final AArrayAssignStatement statement) { instr("iastore"); } @Override public void outAPlusExpression(final APlusExpression expression) { instr("iadd"); } @Override public void outAMinusExpression(final AMinusExpression expression) { instr("isub"); } @Override public void outATimesExpression(final ATimesExpression expression) { instr("imul"); } @Override public void outANewInstanceExpression(final ANewInstanceExpression expression) { final String className = expression.getClassName().getText(); instr("new %s", className); // Call default constructor. instr("dup"); instr("invokespecial %s/<init>()V", className); } @Override public void outANewIntArrayExpression(final ANewIntArrayExpression expression) { instr("newarray int"); } @Override public void outAIntegerExpression(final AIntegerExpression expression) { instr("ldc %d", Integer.valueOf(expression.getInteger().getText())); } @Override public void outATrueExpression(final ATrueExpression expression) { instr("iconst_1"); } @Override public void outAFalseExpression(final AFalseExpression expression) { instr("iconst_0"); } @Override public void inANotExpression(final ANotExpression expression) { instr("iconst_1"); } @Override public void outANotExpression(final ANotExpression expression) { instr("isub"); } @Override public void outAMethodInvocationExpression(final AMethodInvocationExpression expression) { final Type type = types.get(expression.getInstance()); final ClassInfo classInfo = symbolTable.getClassInfo(type.getName()); final MethodInfo methodInfo = classInfo.getMethod(expression.getName().getText()); instr("invokevirtual %s/%s%s", classInfo.getName(), methodInfo.getName(), methodSignatureDescriptor(methodInfo)); } @Override public void outAArrayAccessExpression(final AArrayAccessExpression expression) { instr("iaload"); } @Override public void outAIdentifierExpression(final AIdentifierExpression expression) { final String id = expression.getIdentifier().getText(); final VariableInfo localInfo, paramInfo, fieldInfo; if ((localInfo = currentMethod.getLocal(id)) != null) { final Type type = localInfo.getType(); instr("%s %d", type.isReference() ? "aload" : "iload", baseIndex + localInfo.getIndex()); } else if ((paramInfo = currentMethod.getParameter(id)) != null) { final Type type = paramInfo.getType(); instr("%s %d", type.isReference() ? "aload" : "iload", baseIndex + paramInfo.getIndex()); } else if ((fieldInfo = currentClass.getField(id)) != null) { final String typeDescriptor = typeDescriptor(fieldInfo.getType()); instr("aload_0"); instr("getfield %s/%s %s", currentClass.getName(), id, typeDescriptor); } } @Override public void outAThisExpression(final AThisExpression expression) { instr("aload_0"); } }
package net.sf.openschema; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; /** * A <tt>Frame</tt> implementation using <tt>java.util.Map</tt> * * @author Pablo Ariel Duboue <pablo.duboue@gmail.com> */ public class MapFrame extends HashMap<String, Object> implements Frame { private static final long serialVersionUID = 1L; /** * Construct a frame with a given id and type. The id is stored in the map as the value for the key "#ID", while the * type for the key "#TYPE". */ public MapFrame(String id, Object type) { super(); this.setID(id); this.setType(type); } /** Access the type of the frame. */ public Object getType() { return super.get("#TYPE"); } /** Modify the type of the frame. */ public void setType(Object type) { super.put("#TYPE", type); } /** Access the ID of the frame. */ public String getID() { return (String) super.get(" } /** Modify the type of the frame. */ public void setID(String id) { super.put("#ID", id); } /** * Access a value in the frame. Returns an EMPTY_LIST if the key is undefined. */ @SuppressWarnings("unchecked") public List<Object> get(String key) { if (key.equals("#TYPE")) return Collections.singletonList(super.get(key)); return super.containsKey(key) ? (List<Object>) super.get(key) : Collections.EMPTY_LIST; } /** Set the value of the key (previous values are erased). */ public void set(String key, Object value) { super.put(key, new ArrayList<Object>(Collections.singletonList(value))); } /** Set the values of the key (previous values are erased). */ public void set(String key, List<Object> values) { super.put(key, values); } /** Add a value to the existing values of a key. */ @SuppressWarnings("unchecked") public void add(String key, Object value) { if (!super.containsKey(key)) super.put(key, new ArrayList<Object>()); ((List<Object>) super.get(key)).add(value); } /** Check whether or not a key is defined. */ public boolean containsKey(String key) { return super.containsKey(key); } /** Retrieve the set of all keys. */ public Set<String> keySet() { Set<String> keySet = new HashSet<String>(super.keySet()); keySet.remove(" keySet.remove("#TYPE"); return keySet; } // need to redefine hashCode as Maps cannot be circular and hash public int hashCode() { return super.get("#ID").hashCode(); } // need to redefine equals as Maps cannot be circular and compare public boolean equals(Object other) { if (other instanceof Frame) return ((Frame) other).getID().equals(this.getID()); return false; } // need to redefine equals as Maps cannot be circular and stringify public String toString() { StringBuilder sb = new StringBuilder(); toString(sb, new HashSet<String>()); return sb.toString(); } @SuppressWarnings("rawtypes") protected void toString(StringBuilder sb, HashSet<String> seen) { String id = this.getID(); sb.append("Frame@").append(id).append('#').append(this.getType()).append('['); if (seen.contains(id)) { sb.append("..]"); return; } seen.add(id); boolean first = true; for (String key : this.keySet()) { if (first) first = false; else sb.append(';'); sb.append(key).append('='); Object value = this.get(key); if (value instanceof MapFrame) ((MapFrame) value).toString(sb, seen); else if (value instanceof List) { sb.append('{'); boolean first2 = true; for (Object o : ((List) value)) { if (first2) first2 = false; else sb.append(','); if (o instanceof MapFrame) ((MapFrame) o).toString(sb, seen); else sb.append(o.toString()); } } else sb.append(value.toString()); } } }