answer
stringlengths
17
10.2M
package am.drawable; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; /** * * DrawableViewPadding */ public class CornerDrawable extends Drawable { private final Paint mFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint mStrokePaint;// optional, set by the caller private final Rect mPaddingRect = new Rect(); private final Path mPath = new Path(); private final RectF mRoundRect = new RectF(); private int mAlpha = 0xFF; private int mColor; private int mCornerWidth; private int mCornerHeight; private boolean mCornerBezier; private int mDirection = Gravity.TOP; private int mLocation = Gravity.CENTER; private int mCornerMargin; private final Rect mContentPaddingRect = new Rect(); private float mContentRadius; private int mIntrinsicWidth; private int mIntrinsicHeight; private RectF mTempRect = new RectF(); public CornerDrawable(int color, int cornerWidth, int cornerHeight) { this(color, cornerWidth, cornerHeight, false, Gravity.TOP, Gravity.CENTER, 0); } public CornerDrawable(int color, int cornerWidth, int cornerHeight, boolean cornerBezier, int direction, int location, float contentRadius) { setColor(color); setCornerWidth(cornerWidth); setCornerHeight(cornerHeight); setCornerBezier(cornerBezier); setDirection(direction); setLocation(location); setContentRadius(contentRadius); } @Override public void setBounds(Rect bounds) { super.setBounds(bounds); } @Override public void draw(Canvas canvas) { // remember the alpha values, in case we temporarily overwrite them // when we modulate them with mAlpha final int prevFillAlpha = mFillPaint.getAlpha(); final int prevStrokeAlpha = mStrokePaint != null ? mStrokePaint.getAlpha() : 0; // compute the modulate alpha values final int currFillAlpha = modulateAlpha(prevFillAlpha); final int currStrokeAlpha = modulateAlpha(prevStrokeAlpha); final boolean haveStroke = currStrokeAlpha > 0 && mStrokePaint != null && mStrokePaint.getStrokeWidth() > 0; final boolean haveFill = currFillAlpha > 0; if (!haveFill && !haveStroke) { return; } mPath.rewind(); if (mCornerHeight == 0) { if (mContentRadius == 0) { mTempRect.set(getBounds()); mPath.addRect(mTempRect, Path.Direction.CW); } else { mTempRect.set(getBounds()); mPath.addRoundRect(mTempRect, mContentRadius, mContentRadius, Path.Direction.CCW); } } else { final int width = getBounds().width(); final int height = getBounds().height(); if (mContentRadius == 0) { switch (mDirection) { case Gravity.TOP: case Gravity.BOTTOM: if (height <= mCornerHeight) { makeTrianglePath(); } else if (width <= mCornerWidth) { makeTriangleRectPath(); } else { makeRectPath(); } break; case Gravity.LEFT: case Gravity.RIGHT: if (width <= mCornerHeight) { makeTrianglePath(); } else if (height <= mCornerWidth) { makeTriangleRectPath(); } else { makeRectPath(); } break; } } else { switch (mDirection) { case Gravity.TOP: case Gravity.BOTTOM: if (width > mCornerWidth + mContentRadius * 2 && height > mCornerHeight + mContentRadius * 2) { makeRoundRect(); } else if (width >= mCornerWidth + mContentRadius * 2 && height > mCornerHeight) { makeTriangleRoundRectPath(); } else if (width >= mCornerWidth + mContentRadius * 2) { makeTrianglePath(); } else if (width < mCornerWidth + mContentRadius * 2 && width > mCornerWidth) { makeRoundRectResizePath(); } else if (width == mCornerWidth) { makeTriangleSemicirclePath(); } else { makeTrianglePath(); } break; case Gravity.LEFT: case Gravity.RIGHT: if (height > mCornerWidth + mContentRadius * 2 && width > mCornerHeight + mContentRadius * 2) { makeRoundRect(); } else if (height >= mCornerWidth + mContentRadius * 2 && width > mCornerHeight) { makeTriangleRoundRectPath(); } else if (height >= mCornerWidth + mContentRadius * 2) { makeTrianglePath(); } else if (height < mCornerWidth + mContentRadius * 2 && height > mCornerWidth) { makeRoundRectResizePath(); } else if (height == mCornerWidth) { makeTriangleSemicirclePath(); } else { makeTrianglePath(); } break; } } } if (haveFill) { mFillPaint.setAlpha(currFillAlpha); mFillPaint.setColor(mColor); canvas.drawPath(mPath, mFillPaint); } if (haveStroke) { mStrokePaint.setAlpha(currStrokeAlpha); canvas.drawPath(mPath, mStrokePaint); } } private int modulateAlpha(int alpha) { int scale = mAlpha + (mAlpha >> 7); return alpha * scale >> 8; } private void makeCorner(float leftX, float leftY, float centerX, float centerY, float rightX, float rightY) { mPath.lineTo(leftX, leftY); mPath.lineTo(centerX, centerY); mPath.lineTo(rightX, rightY); } @SuppressWarnings("all") // TODO private void makeRectPath() { final int width = getBounds().width(); final int height = getBounds().height(); final float strokeSize = mStrokePaint != null ? mStrokePaint.getStrokeWidth() : 0; final float halfStokeSize = strokeSize * 0.5f; final float halfCornerWidth = mCornerWidth * 0.5f; final double temp = 2d * mCornerHeight * halfStokeSize / mCornerWidth; final float cornerStokeVertical = (float) (Math.sqrt(halfStokeSize * halfStokeSize + temp * temp)); float cornerOffset = 0; switch (mDirection) { case Gravity.TOP: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; } mPath.moveTo(halfStokeSize, mCornerHeight + cornerStokeVertical); makeCorner((width - mCornerWidth) * 0.5f + cornerOffset, mCornerHeight + cornerStokeVertical, width * 0.5f + cornerOffset, cornerStokeVertical, (width + mCornerWidth) * 0.5f + cornerOffset, mCornerHeight + cornerStokeVertical); mPath.lineTo(width - halfStokeSize, mCornerHeight + cornerStokeVertical); mPath.lineTo(width - halfStokeSize, height - halfStokeSize); mPath.lineTo(halfStokeSize, height - halfStokeSize); mPath.close(); break; case Gravity.BOTTOM: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; } mPath.moveTo(halfStokeSize, halfStokeSize); mPath.lineTo(width - halfStokeSize, halfStokeSize); mPath.lineTo(width - halfStokeSize, height - cornerStokeVertical - mCornerHeight); makeCorner((width + mCornerWidth) * 0.5f + cornerOffset, height - cornerStokeVertical - mCornerHeight, width * 0.5f + cornerOffset, height - cornerStokeVertical, (width - mCornerWidth) * 0.5f + cornerOffset, height - cornerStokeVertical - mCornerHeight); mPath.lineTo(halfStokeSize, height - cornerStokeVertical - mCornerHeight); mPath.close(); break; case Gravity.LEFT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; } mPath.moveTo(mCornerHeight + cornerStokeVertical, halfStokeSize); mPath.lineTo(width - halfStokeSize, halfStokeSize); mPath.lineTo(width - halfStokeSize, height - halfStokeSize); mPath.lineTo(mCornerHeight + cornerStokeVertical, height - halfStokeSize); makeCorner(mCornerHeight + cornerStokeVertical, (height + mCornerWidth) * 0.5f + cornerOffset, cornerStokeVertical, height * 0.5f + cornerOffset, mCornerHeight + cornerStokeVertical, (height - mCornerWidth) * 0.5f + cornerOffset); mPath.close(); break; case Gravity.RIGHT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; } mPath.moveTo(halfStokeSize, halfStokeSize); mPath.lineTo(width - mCornerHeight - cornerStokeVertical, halfStokeSize); makeCorner(width - mCornerHeight - cornerStokeVertical, (height - mCornerWidth) * 0.5f + cornerOffset, width - cornerStokeVertical, height * 0.5f + cornerOffset, width - mCornerHeight - cornerStokeVertical, (height + mCornerWidth) * 0.5f + cornerOffset); mPath.lineTo(width - mCornerHeight - cornerStokeVertical, height - halfStokeSize); mPath.lineTo(halfStokeSize, height - halfStokeSize); mPath.close(); break; } } @SuppressWarnings("all") // TODO private void makeRoundRect() { final int width = getBounds().width(); final int height = getBounds().height(); final float strokeSize = mStrokePaint != null ? mStrokePaint.getStrokeWidth() : 0; final float halfStokeSize = strokeSize * 0.5f; final float halfCornerWidth = mCornerWidth * 0.5f; final double temp = 2d * mCornerHeight * halfStokeSize / mCornerWidth; final float cornerStokeVertical = (float) (Math.sqrt(halfStokeSize * halfStokeSize + temp * temp)); float cornerOffset = 0; switch (mDirection) { case Gravity.TOP: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else if (mCornerMargin > width - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin + mContentRadius; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else if (mCornerMargin > width - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin - mContentRadius; } break; } mPath.moveTo(halfStokeSize + mContentRadius, mCornerHeight + cornerStokeVertical); makeCorner((width - mCornerWidth) * 0.5f + cornerOffset, mCornerHeight + cornerStokeVertical, width * 0.5f + cornerOffset, cornerStokeVertical, (width + mCornerWidth) * 0.5f + cornerOffset, mCornerHeight + cornerStokeVertical); mPath.lineTo(width - halfStokeSize - mContentRadius, mCornerHeight + cornerStokeVertical); mRoundRect.set(width - halfStokeSize - mContentRadius * 2, mCornerHeight + cornerStokeVertical, width - halfStokeSize, mCornerHeight + cornerStokeVertical + mContentRadius * 2); mPath.arcTo(mRoundRect, -90, 90); mPath.lineTo(width - halfStokeSize, height - halfStokeSize - mContentRadius); mRoundRect.set(width - halfStokeSize - mContentRadius * 2, height - halfStokeSize - mContentRadius * 2, width - halfStokeSize, height - halfStokeSize); mPath.arcTo(mRoundRect, 0, 90); mPath.lineTo(halfStokeSize + mContentRadius * 2, height - halfStokeSize); mRoundRect.set(halfStokeSize, height - halfStokeSize - mContentRadius * 2, halfStokeSize + mContentRadius * 2, height - halfStokeSize); mPath.arcTo(mRoundRect, 90, 90); mPath.lineTo(halfStokeSize, cornerStokeVertical + mCornerHeight + mContentRadius); mRoundRect.set(halfStokeSize, cornerStokeVertical + mCornerHeight, halfStokeSize + mContentRadius * 2, cornerStokeVertical + mCornerHeight + mContentRadius * 2); mPath.arcTo(mRoundRect, 180, 90); mPath.close(); break; case Gravity.BOTTOM: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else if (mCornerMargin > width - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin - mContentRadius; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else if (mCornerMargin > width - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin + mContentRadius; } break; } mPath.moveTo(halfStokeSize + mContentRadius, halfStokeSize); mPath.lineTo(width - halfStokeSize - mContentRadius, halfStokeSize); mRoundRect.set(width - halfStokeSize - mContentRadius * 2, halfStokeSize, width - halfStokeSize, halfStokeSize + mContentRadius * 2); mPath.arcTo(mRoundRect, -90, 90); mPath.lineTo(width - halfStokeSize, height - cornerStokeVertical - mCornerHeight - mContentRadius); mRoundRect.set(width - halfStokeSize - mContentRadius * 2, height - cornerStokeVertical - mCornerHeight - mContentRadius * 2, width - halfStokeSize, height - cornerStokeVertical - mCornerHeight); mPath.arcTo(mRoundRect, 0, 90); makeCorner((width + mCornerWidth) * 0.5f + cornerOffset, height - cornerStokeVertical - mCornerHeight, width * 0.5f + cornerOffset, height - cornerStokeVertical, (width - mCornerWidth) * 0.5f + cornerOffset, height - cornerStokeVertical - mCornerHeight); mPath.lineTo(halfStokeSize + mContentRadius, height - cornerStokeVertical - mCornerHeight); mRoundRect.set(halfStokeSize, height - cornerStokeVertical - mCornerHeight - mContentRadius * 2, halfStokeSize + mContentRadius * 2, height - cornerStokeVertical - mCornerHeight); mPath.arcTo(mRoundRect, 90, 90); mPath.lineTo(halfStokeSize, halfStokeSize + mContentRadius); mRoundRect.set(halfStokeSize, halfStokeSize, halfStokeSize + mContentRadius * 2, halfStokeSize + mContentRadius * 2); mPath.arcTo(mRoundRect, 180, 90); mPath.close(); break; case Gravity.LEFT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else if (mCornerMargin > height - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin - mContentRadius; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else if (mCornerMargin > height - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin + mContentRadius; } break; } mPath.moveTo(mCornerHeight + cornerStokeVertical + mContentRadius, halfStokeSize); mPath.lineTo(width - halfStokeSize - mContentRadius, halfStokeSize); mRoundRect.set(width - halfStokeSize - mContentRadius * 2, halfStokeSize, width - halfStokeSize, halfStokeSize + mContentRadius * 2); mPath.arcTo(mRoundRect, -90, 90); mPath.lineTo(width - halfStokeSize, height - halfStokeSize - mContentRadius); mRoundRect.set(width - halfStokeSize - mContentRadius * 2, height - halfStokeSize - mContentRadius * 2, width - halfStokeSize, height - halfStokeSize); mPath.arcTo(mRoundRect, 0, 90); mPath.lineTo(mCornerHeight + cornerStokeVertical + mContentRadius, height - halfStokeSize); mRoundRect.set(mCornerHeight + cornerStokeVertical, height - halfStokeSize - mContentRadius * 2, mCornerHeight + cornerStokeVertical + mContentRadius * 2, height - halfStokeSize); mPath.arcTo(mRoundRect, 90, 90); makeCorner(mCornerHeight + cornerStokeVertical, (height + mCornerWidth) * 0.5f + cornerOffset, cornerStokeVertical, height * 0.5f + cornerOffset, mCornerHeight + cornerStokeVertical, (height - mCornerWidth) * 0.5f + cornerOffset); mPath.lineTo(mCornerHeight + cornerStokeVertical, halfStokeSize + mContentRadius); mRoundRect.set(mCornerHeight + cornerStokeVertical, halfStokeSize, mCornerHeight + cornerStokeVertical + mContentRadius * 2, halfStokeSize + mContentRadius * 2); mPath.arcTo(mRoundRect, 180, 90); mPath.close(); break; case Gravity.RIGHT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else if (mCornerMargin > height - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin + mContentRadius; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mContentRadius; } else if (mCornerMargin > height - strokeSize - mCornerWidth - mContentRadius * 2) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mContentRadius; } else { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin - mContentRadius; } break; } mPath.moveTo(halfStokeSize + mContentRadius, halfStokeSize); mPath.lineTo(width - mCornerHeight - cornerStokeVertical - mContentRadius, halfStokeSize); mRoundRect.set(width - mCornerHeight - cornerStokeVertical - mContentRadius * 2, halfStokeSize, width - mCornerHeight - cornerStokeVertical, halfStokeSize + mContentRadius * 2); mPath.arcTo(mRoundRect, -90, 90); makeCorner(width - mCornerHeight - cornerStokeVertical, (height - mCornerWidth) * 0.5f + cornerOffset, width - cornerStokeVertical, height * 0.5f + cornerOffset, width - mCornerHeight - cornerStokeVertical, (height + mCornerWidth) * 0.5f + cornerOffset); mPath.lineTo(width - mCornerHeight - cornerStokeVertical, height - halfStokeSize - mContentRadius); mRoundRect.set(width - mCornerHeight - cornerStokeVertical - mContentRadius * 2, height - halfStokeSize - mContentRadius * 2, width - mCornerHeight - cornerStokeVertical, height - halfStokeSize); mPath.arcTo(mRoundRect, 0, 90); mPath.lineTo(halfStokeSize + mContentRadius * 2, height - halfStokeSize); mRoundRect.set(halfStokeSize, height - halfStokeSize - mContentRadius * 2, halfStokeSize + mContentRadius * 2, height - halfStokeSize); mPath.arcTo(mRoundRect, 90, 90); mPath.lineTo(halfStokeSize, halfStokeSize + mContentRadius); mRoundRect.set(halfStokeSize, halfStokeSize, halfStokeSize + mContentRadius * 2, halfStokeSize + mContentRadius * 2); mPath.arcTo(mRoundRect, 180, 90); mPath.close(); break; } } @SuppressWarnings("all") private void makeTrianglePath() { final int width = getBounds().width(); final int height = getBounds().height(); final float strokeSize = mStrokePaint != null ? mStrokePaint.getStrokeWidth() : 0; final float halfStokeSize = strokeSize * 0.5f; final float halfCornerWidth = mCornerWidth * 0.5f; final double temp = 2d * mCornerHeight * halfStokeSize / mCornerWidth; final float cornerStokeVertical = (float) (Math.sqrt(halfStokeSize * halfStokeSize + temp * temp)); final float cornerStokeHorizontal = halfCornerWidth - mCornerWidth * (mCornerHeight - cornerStokeVertical - halfStokeSize) * 0.5f / mCornerHeight; float cornerOffset = 0; switch (mDirection) { case Gravity.TOP: if (width > mCornerWidth) { switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; } } mPath.moveTo((width - mCornerWidth) * 0.5f + cornerStokeHorizontal + cornerOffset, height - halfStokeSize); makeCorner((width - mCornerWidth) * 0.5f + cornerStokeHorizontal + cornerOffset, height - halfStokeSize, width * 0.5f + cornerOffset, height - mCornerHeight + cornerStokeVertical, (width + mCornerWidth) * 0.5f - cornerStokeHorizontal + cornerOffset, height - halfStokeSize); mPath.close(); break; case Gravity.BOTTOM: if (width > mCornerWidth) { switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > width - strokeSize - mCornerWidth) { cornerOffset = (width - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(width - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; } } mPath.moveTo((width - mCornerWidth) * 0.5f + cornerStokeHorizontal + cornerOffset, halfStokeSize); makeCorner((width - mCornerWidth) * 0.5f + cornerStokeHorizontal + cornerOffset, halfStokeSize, width * 0.5f + cornerOffset, mCornerHeight - cornerStokeVertical, (width + mCornerWidth) * 0.5f - cornerStokeHorizontal + cornerOffset, halfStokeSize); mPath.close(); break; case Gravity.LEFT: if (height > mCornerWidth) { switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; } } mPath.moveTo(width - halfStokeSize, (height + mCornerWidth) * 0.5f - cornerStokeHorizontal + cornerOffset); makeCorner(width - halfStokeSize, (height + mCornerWidth) * 0.5f - cornerStokeHorizontal + cornerOffset, width - mCornerHeight + cornerStokeVertical, height * 0.5f + cornerOffset, width - halfStokeSize, (height - mCornerWidth) * 0.5f + cornerStokeHorizontal + cornerOffset); mPath.close(); break; case Gravity.RIGHT: if (height > mCornerWidth) { switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: if (mCornerMargin <= 0) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth + mCornerMargin; } break; case Gravity.RIGHT: if (mCornerMargin <= 0) { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth; } else if (mCornerMargin > height - strokeSize - mCornerWidth) { cornerOffset = -(height - strokeSize) * 0.5f + halfCornerWidth; } else { cornerOffset = (height - strokeSize) * 0.5f - halfCornerWidth - mCornerMargin; } break; } } mPath.moveTo(halfStokeSize, (height + mCornerWidth) * 0.5f - cornerStokeHorizontal + cornerOffset); makeCorner(halfStokeSize, (height + mCornerWidth) * 0.5f - cornerStokeHorizontal + cornerOffset, mCornerHeight - cornerStokeVertical, height * 0.5f + cornerOffset, halfStokeSize, (height - mCornerWidth) * 0.5f + cornerStokeHorizontal + cornerOffset); mPath.close(); break; } } @SuppressWarnings("all") private void makeTriangleRectPath() { final int width = getBounds().width(); final int height = getBounds().height(); final float strokeSize = mStrokePaint != null ? mStrokePaint.getStrokeWidth() : 0; final float halfStokeSize = strokeSize * 0.5f; final float mCornerWidth = (mDirection == Gravity.TOP || mDirection == Gravity.BOTTOM) ? width : height; final float halfCornerWidth = mCornerWidth * 0.5f; final float cornerStokeVertical = (float) (Math.sqrt(halfCornerWidth * halfCornerWidth + mCornerHeight * mCornerHeight) * halfStokeSize / halfCornerWidth); final float cornerHeightOffset = 2 * mCornerHeight * (mCornerWidth - strokeSize) / mCornerWidth - mCornerHeight + cornerStokeVertical; switch (mDirection) { case Gravity.TOP: mPath.moveTo(halfStokeSize, mCornerHeight + cornerHeightOffset); makeCorner(halfStokeSize, mCornerHeight + cornerHeightOffset, width * 0.5f, cornerStokeVertical, width - halfStokeSize, mCornerHeight + cornerHeightOffset); mPath.lineTo(width - halfStokeSize, height - halfStokeSize); mPath.lineTo(halfStokeSize, height - halfStokeSize); mPath.close(); break; case Gravity.BOTTOM: mPath.moveTo(width - halfStokeSize, height - mCornerHeight - cornerHeightOffset); makeCorner(width - halfStokeSize, height - mCornerHeight - cornerHeightOffset, width * 0.5f, height - cornerStokeVertical, halfStokeSize, height - mCornerHeight - cornerHeightOffset); mPath.lineTo(halfStokeSize, halfStokeSize); mPath.lineTo(width - halfStokeSize, halfStokeSize); mPath.close(); break; case Gravity.LEFT: mPath.moveTo(mCornerHeight + cornerHeightOffset, height - halfStokeSize); makeCorner(mCornerHeight + cornerHeightOffset, height - halfStokeSize, cornerStokeVertical, height * 0.5f, mCornerHeight + cornerHeightOffset, halfStokeSize); mPath.lineTo(width - halfStokeSize, halfStokeSize); mPath.lineTo(width - halfStokeSize, height - halfStokeSize); mPath.close(); break; case Gravity.RIGHT: mPath.moveTo(width - mCornerHeight - cornerHeightOffset, halfStokeSize); makeCorner(width - mCornerHeight - cornerHeightOffset, halfStokeSize, width - cornerStokeVertical, height * 0.5f, width - mCornerHeight - cornerHeightOffset, height - halfStokeSize); mPath.lineTo(halfStokeSize, height - halfStokeSize); mPath.lineTo(halfStokeSize, halfStokeSize); mPath.close(); break; } } private void makeTriangleRoundRectPath() { // TODO switch (mDirection) { case Gravity.TOP: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.BOTTOM: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.LEFT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.RIGHT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; } } private void makeRoundRectResizePath() { // TODO switch (mDirection) { case Gravity.TOP: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.BOTTOM: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.LEFT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.RIGHT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; } } private void makeTriangleSemicirclePath() { // TODO switch (mDirection) { case Gravity.TOP: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.BOTTOM: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.LEFT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; case Gravity.RIGHT: switch (mLocation) { case Gravity.CENTER: break; case Gravity.LEFT: break; case Gravity.RIGHT: break; } break; } } @Override public void setAlpha(int alpha) { if (alpha != mAlpha) { mAlpha = alpha; invalidateSelf(); } } @Override public int getAlpha() { return mAlpha; } @Override public void setColorFilter(ColorFilter cf) { mFillPaint.setColorFilter(cf); if (mStrokePaint != null) mStrokePaint.setColorFilter(cf); invalidateSelf(); } @Override public int getOpacity() { return mAlpha == 255 ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT; } @Override public int getIntrinsicWidth() { return mIntrinsicWidth; } @Override public int getIntrinsicHeight() { return mIntrinsicHeight; } @Override @SuppressWarnings("all") public boolean getPadding(Rect padding) { padding.set(mPaddingRect); return true; } @SuppressWarnings("all") private void calculateValue() { if (mCornerHeight <= 0) { mPaddingRect.set(mContentPaddingRect.left, mContentPaddingRect.top, mContentPaddingRect.right, mContentPaddingRect.bottom); mIntrinsicWidth = 0; mIntrinsicHeight = 0; } else { switch (mDirection) { case Gravity.LEFT: mPaddingRect.set(mContentPaddingRect.left + mCornerHeight, mContentPaddingRect.top, mContentPaddingRect.right, mContentPaddingRect.bottom); mIntrinsicWidth = mCornerHeight; mIntrinsicHeight = mCornerWidth; break; case Gravity.RIGHT: mPaddingRect.set(mContentPaddingRect.left, mContentPaddingRect.top, mContentPaddingRect.right + mCornerHeight, mContentPaddingRect.bottom); mIntrinsicWidth = mCornerHeight; mIntrinsicHeight = mCornerWidth; break; case Gravity.BOTTOM: mPaddingRect.set(mContentPaddingRect.left, mContentPaddingRect.top, mContentPaddingRect.right, mContentPaddingRect.bottom + mCornerHeight); mIntrinsicWidth = mCornerWidth; mIntrinsicHeight = mCornerHeight; break; default: case Gravity.TOP: mPaddingRect.set(mContentPaddingRect.left, mContentPaddingRect.top + mCornerHeight, mContentPaddingRect.right, mContentPaddingRect.bottom); mIntrinsicWidth = mCornerWidth; mIntrinsicHeight = mCornerHeight; break; } } } /** * * * @param color */ public void setColor(int color) { if (mColor != color) { mColor = color; invalidateSelf(); } } /** * * * @param width */ public void setCornerWidth(int width) { if (width >= 0 && mCornerWidth != width) { mCornerWidth = width; calculateValue(); invalidateSelf(); DrawableHelper.invalidateCallbackPadding(this); DrawableHelper.requestCallbackLayout(this); } } /** * * * @param height */ public void setCornerHeight(int height) { if (height >= 0 && mCornerHeight != height) { mCornerHeight = height; calculateValue(); invalidateSelf(); DrawableHelper.invalidateCallbackPadding(this); DrawableHelper.requestCallbackLayout(this); } } /** * * * @param cornerBezier */ public void setCornerBezier(boolean cornerBezier) { if (mCornerBezier != cornerBezier) { mCornerBezier = cornerBezier; invalidateSelf(); } } /** * * * @param direction */ @SuppressWarnings("all") public void setDirection(int direction) { if (direction != Gravity.LEFT && direction != Gravity.TOP && direction != Gravity.RIGHT && direction != Gravity.BOTTOM) return; if (mDirection != direction) { mDirection = direction; calculateValue(); invalidateSelf(); DrawableHelper.invalidateCallbackPadding(this); DrawableHelper.requestCallbackLayout(this); } } /** * * * @param location */ @SuppressWarnings("all") public void setLocation(int location) { if (location != Gravity.LEFT && location != Gravity.CENTER && location != Gravity.RIGHT) return; if (mLocation != location) { mLocation = location; invalidateSelf(); } } /** * * * @param margin */ public void setCornerMargin(int margin) { if (margin >= 0 && mCornerMargin != margin) { mCornerMargin = margin; invalidateSelf(); } } /** * Padding * * @param left * @param top * @param right * @param bottom */ public void setPadding(int left, int top, int right, int bottom) { mContentPaddingRect.set(left, top, right, bottom); calculateValue(); invalidateSelf(); DrawableHelper.invalidateCallbackPadding(this); DrawableHelper.requestCallbackLayout(this); } /** * Padding * * @param padding Padding */ public void setPadding(Rect padding) { if (padding != null) { setPadding(padding.left, padding.top, padding.right, padding.bottom); } } /** * * * @param contentRadius */ public void setContentRadius(float contentRadius) { if (contentRadius >= 0 && mContentRadius != contentRadius) { mContentRadius = contentRadius; invalidateSelf(); } } /** * * * @param width * @param color * @param dashWidth * @param dashGap */ public void setStroke(int width, int color, float dashWidth, float dashGap) { if (mStrokePaint == null) { mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mStrokePaint.setStyle(Paint.Style.STROKE); } mStrokePaint.setStrokeWidth(width); mStrokePaint.setColor(color); DashPathEffect e = null; if (dashWidth > 0) { e = new DashPathEffect(new float[]{dashWidth, dashGap}, 0); } mStrokePaint.setPathEffect(e); invalidateSelf(); } }
package org.batfish.datamodel; import java.io.Serializable; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonValue; public class Prefix6Space implements Serializable { private static class BitTrie implements Serializable { private static final long serialVersionUID = 1L; private BitTrieNode _root; public BitTrie() { _root = new BitTrieNode(); } public void addPrefix6Range(Prefix6Range prefix6Range) { Prefix6 prefix6 = prefix6Range.getPrefix6(); int prefixLength = prefix6.getPrefixLength(); BitSet bits = getAddressBits(prefix6.getAddress()); _root.addPrefix6Range(prefix6Range, bits, prefixLength, 0); } public void addTrieNodeSpace(BitTrieNode node) { if (node._left != null) { addTrieNodeSpace(node._left); } if (node._right != null) { addTrieNodeSpace(node._right); } for (Prefix6Range prefix6Range : node._prefix6Ranges) { addPrefix6Range(prefix6Range); } } public boolean containsPrefix6Range(Prefix6Range prefix6Range) { Prefix6 prefix6 = prefix6Range.getPrefix6(); int prefixLength = prefix6.getPrefixLength(); BitSet bits = getAddressBits(prefix6.getAddress()); return _root.containsPrefix6Range(prefix6Range, bits, prefixLength, 0); } public Set<Prefix6Range> getPrefix6Ranges() { Set<Prefix6Range> prefix6Ranges = new HashSet<Prefix6Range>(); _root.collectPrefix6Ranges(prefix6Ranges); return prefix6Ranges; } } private static class BitTrieNode implements Serializable { private static final long serialVersionUID = 1L; private BitTrieNode _left; private Set<Prefix6Range> _prefix6Ranges; private BitTrieNode _right; public BitTrieNode() { _prefix6Ranges = new HashSet<Prefix6Range>(); } public void addPrefix6Range(Prefix6Range prefix6Range, BitSet bits, int prefixLength, int depth) { for (Prefix6Range nodeRange : _prefix6Ranges) { if (nodeRange.includesPrefix6Range(prefix6Range)) { return; } } if (prefixLength == depth) { _prefix6Ranges.add(prefix6Range); prune(prefix6Range); } else { boolean currentBit = bits.get(depth); if (currentBit) { if (_right == null) { _right = new BitTrieNode(); } _right.addPrefix6Range(prefix6Range, bits, prefixLength, depth + 1); } else { if (_left == null) { _left = new BitTrieNode(); } _left.addPrefix6Range(prefix6Range, bits, prefixLength, depth + 1); } } } public void collectPrefix6Ranges(Set<Prefix6Range> prefix6Ranges) { prefix6Ranges.addAll(_prefix6Ranges); if (_left != null) { _left.collectPrefix6Ranges(prefix6Ranges); } if (_right != null) { _right.collectPrefix6Ranges(prefix6Ranges); } } public boolean containsPrefix6Range(Prefix6Range prefix6Range, BitSet bits, int prefixLength, int depth) { for (Prefix6Range nodeRange : _prefix6Ranges) { if (nodeRange.includesPrefix6Range(prefix6Range)) { return true; } } if (prefixLength == depth) { return false; } else { boolean currentBit = bits.get(depth); if (currentBit) { if (_right == null) { return false; } else { return _right.containsPrefix6Range(prefix6Range, bits, prefixLength, depth + 1); } } else { if (_left == null) { return false; } else { return _left.containsPrefix6Range(prefix6Range, bits, prefixLength, depth + 1); } } } } private boolean isEmpty() { return _left == null && _right == null && _prefix6Ranges.isEmpty(); } private void prune(Prefix6Range prefix6Range) { if (_left != null) { _left.prune(prefix6Range); if (_left.isEmpty()) { _left = null; } } if (_right != null) { _right.prune(prefix6Range); if (_right.isEmpty()) { _right = null; } } Set<Prefix6Range> oldPrefix6Ranges = new HashSet<Prefix6Range>(); oldPrefix6Ranges.addAll(_prefix6Ranges); for (Prefix6Range oldPrefix6Range : oldPrefix6Ranges) { if (!prefix6Range.equals(oldPrefix6Range) && prefix6Range.includesPrefix6Range(oldPrefix6Range)) { _prefix6Ranges.remove(oldPrefix6Range); } } } } private static final long serialVersionUID = 1L; private static final int NUM_BITS = 128; // TODO: verify that this has been correctly modified for Ip6 / BigInteger private static BitSet getAddressBits(Ip6 address) { int numBytes = NUM_BITS / 8; BigInteger addressAsBigInteger = address.asBigInteger(); byte[] addressAsByteArray = addressAsBigInteger.toByteArray(); byte[] addressAs128BitByteArray = Arrays.copyOfRange(addressAsByteArray, 0, numBytes); ByteBuffer b = ByteBuffer.allocate(numBytes); b.order(ByteOrder.LITTLE_ENDIAN); b.put(addressAs128BitByteArray); BitSet bitsWithHighestMostSignificant = BitSet.valueOf(b.array()); BitSet bits = new BitSet(NUM_BITS); for (int i = NUM_BITS - 1, j = 0; i >= 0; i bits.set(j, bitsWithHighestMostSignificant.get(i)); } return bits; } private BitTrie _trie; public Prefix6Space() { _trie = new BitTrie(); } @JsonCreator public Prefix6Space(Set<Prefix6Range> prefix6Ranges) { _trie = new BitTrie(); for (Prefix6Range prefix6Range : prefix6Ranges) { _trie.addPrefix6Range(prefix6Range); } } public void addPrefix6(Prefix6 prefix6) { addPrefix6Range(Prefix6Range.fromPrefix6(prefix6)); } public void addPrefix6Range(Prefix6Range prefix6Range) { _trie.addPrefix6Range(prefix6Range); } public void addSpace(Prefix6Space prefix6Space) { _trie.addTrieNodeSpace(prefix6Space._trie._root); } public boolean containsPrefix6(Prefix6 prefix6) { return containsPrefix6Range(Prefix6Range.fromPrefix6(prefix6)); } public boolean containsPrefix6Range(Prefix6Range prefix6Range) { return _trie.containsPrefix6Range(prefix6Range); } @JsonValue public Set<Prefix6Range> getPrefix6Ranges() { return _trie.getPrefix6Ranges(); } public Prefix6Space intersection(Prefix6Space intersectSpace) { Prefix6Space newSpace = new Prefix6Space(); Set<Prefix6Range> intersectRanges = intersectSpace.getPrefix6Ranges(); for (Prefix6Range intersectRange : intersectRanges) { if (containsPrefix6Range(intersectRange)) { newSpace.addPrefix6Range(intersectRange); } } return newSpace; } @JsonIgnore public boolean isEmpty() { return _trie._root.isEmpty(); } public boolean overlaps(Prefix6Space intersectSpace) { Prefix6Space intersection = intersection(intersectSpace); return !intersection.isEmpty(); } @Override public String toString() { return getPrefix6Ranges().toString(); } }
package gov.nih.nci.cabig.caaers.web.study; import gov.nih.nci.cabig.caaers.domain.Agent; import gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyAgent; import gov.nih.nci.cabig.caaers.domain.StudyAgentINDAssociation; import gov.nih.nci.cabig.caaers.web.fields.DefaultInputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputField; import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes; import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeanWrapper; import org.springframework.validation.Errors; /** * @author Rhett Sutphin */ public class AgentsTab extends StudyTab { public static int IND_TYPE_NOT_USED = 0; public static int IND_TYPE_CTEP = 1; public static int IND_TYPE_OTHER = 2; public static int CTEP_IND = -111; private LinkedHashMap<Object, Object> indTypeMap = new LinkedHashMap<Object, Object>(); public AgentsTab() { super("Study Agents", "Agents", "study/study_agents"); // setAutoPopulateHelpKey(true); indTypeMap.put(AgentsTab.IND_TYPE_NOT_USED, "Not Used"); indTypeMap.put(AgentsTab.IND_TYPE_CTEP, "CTEP IND"); indTypeMap.put(AgentsTab.IND_TYPE_OTHER, "Other"); } @Override public void postProcess(final HttpServletRequest request, final Study command, final Errors errors) { handleStudyAgentAction(command, request.getParameter("_action"), request.getParameter("_selected"), request .getParameter("_selectedInd")); } @Override protected void validate(final Study command, final BeanWrapper commandBean, final Map<String, InputFieldGroup> fieldGroups, final Errors errors) { boolean isAgentEmpty = false; StudyAgent studyAgent = null; List<StudyAgent> studyAgents = command.getStudyAgents(); for (int i = 0; i < command.getStudyAgents().size(); i++) { studyAgent = studyAgents.get(i); if (studyAgent.getAgent() == null && studyAgent.getOtherAgent() == null) { isAgentEmpty = true; errors.rejectValue("studyAgents[" + i + "].otherAgent", "REQUIRED", "Select either Agent or Other "); } if (studyAgent.getAgent() != null) { studyAgent.setOtherAgent(null); } } if (isAgentEmpty) { errors.rejectValue("studyAgents", "REQUIRED", "One or more Agents are missing or not in list"); } } @Override public Map<String, InputFieldGroup> createFieldGroups(final Study command) { InputFieldGroupMap map = new InputFieldGroupMap(); String baseName = "studyAgents"; int i = -1; for (StudyAgent sa : command.getStudyAgents()) { i++; InputFieldGroup fieldGrp = new DefaultInputFieldGroup("main" + i); List<InputField> fields = fieldGrp.getFields(); InputField agentField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].agent", "Agent", false); InputFieldAttributes.setSize(agentField, 70); agentField.getAttributes().put(InputField.ENABLE_CLEAR, false); fields.add(agentField); InputField otherAgentField = InputFieldFactory.createTextField(baseName + "[" + i + "].otherAgent", "Other", false); InputFieldAttributes.setSize(otherAgentField, 70); fields.add(otherAgentField); InputField indTypeField = InputFieldFactory.createSelectField(baseName + "[" + i + "].indType", "Enter IND information", indTypeMap); fields.add(indTypeField); if (sa.getStudyAgentINDAssociations() != null) { int j = -1; for (StudyAgentINDAssociation saInd : sa.getStudyAgentINDAssociations()) { // dont show IND field for CTEP unspecified IND InvestigationalNewDrug ind = saInd.getInvestigationalNewDrug(); if (ind != null && ind.getIndNumber() != null && ind.getIndNumber() == CTEP_IND) { continue; } j++; InputField indField = InputFieldFactory.createAutocompleterField(baseName + "[" + i + "].studyAgentINDAssociations[" + j + "].investigationalNewDrug", "IND #", true); indField.getAttributes().put(InputField.ENABLE_CLEAR, true); InputFieldAttributes.setSize(indField, 11); fields.add(indField); } } map.addInputFieldGroup(fieldGrp); } return map; } private void handleStudyAgentAction(final Study study, final String action, final String selected, final String selectedInd) { if ("addStudyAgent".equals(action)) { StudyAgent studyAgent = new StudyAgent(); studyAgent.setAgent(new Agent()); study.addStudyAgent(studyAgent); } else if ("removeStudyAgent".equals(action)) { study.getStudyAgents().remove(Integer.parseInt(selected)); } else if ("removeInd".equals(action)) { StudyAgent sa = study.getStudyAgents().get(Integer.parseInt(selected)); List<StudyAgentINDAssociation> sas = sa.getStudyAgentINDAssociations(); if (sas.size() > 0) { sas.remove(Integer.parseInt(selectedInd)); } } } }
package com.orm; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.text.TextUtils; import android.util.Log; import com.orm.dsl.Table; import com.orm.util.NamingHelper; import com.orm.util.ReflectionUtil; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import static com.orm.SugarContext.getSugarContext; public class SugarRecord { protected Long id = null; public static <T> void deleteAll(Class<T> type) { SugarDb db = getSugarContext().getSugarDb(); SQLiteDatabase sqLiteDatabase = db.getDB(); sqLiteDatabase.delete(NamingHelper.toSQLName(type), null, null); } public static <T> void deleteAll(Class<T> type, String whereClause, String... whereArgs) { SugarDb db = getSugarContext().getSugarDb(); SQLiteDatabase sqLiteDatabase = db.getDB(); sqLiteDatabase.delete(NamingHelper.toSQLName(type), whereClause, whereArgs); } @SuppressWarnings("deprecation") public static <T> void saveInTx(T... objects) { saveInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> void saveInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarContext().getSugarDb().getDB(); try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object: objects) { SugarRecord.save(object); } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { Log.i("Sugar", "Error in saving in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } } @SuppressWarnings("deprecation") public static <T> void deleteInTx(T... objects) { deleteInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> void deleteInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarContext().getSugarDb().getDB(); try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object : objects) { SugarRecord.delete(object); } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { Log.i("Sugar", "Error in deleting in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } } public static <T> List<T> listAll(Class<T> type) { return find(type, null, null, null, null, null); } public static <T> List<T> listAll(Class<T> type, String orderBy) { return find(type, null, null, null, orderBy, null); } public static <T> T findById(Class<T> type, Long id) { List<T> list = find(type, "id=?", new String[]{String.valueOf(id)}, null, null, "1"); if (list.isEmpty()) return null; return list.get(0); } public static <T> T findById(Class<T> type, Integer id) { return findById(type, Long.valueOf(id)); } public static <T> Iterator<T> findAll(Class<T> type) { return findAsIterator(type, null, null, null, null, null); } public static <T> Iterator<T> findAsIterator(Class<T> type, String whereClause, String... whereArgs) { return findAsIterator(type, whereClause, whereArgs, null, null, null); } public static <T> Iterator<T> findWithQueryAsIterator(Class<T> type, String query, String... arguments) { SugarDb db = getSugarContext().getSugarDb(); SQLiteDatabase sqLiteDatabase = db.getDB(); Cursor c = sqLiteDatabase.rawQuery(query, arguments); return new CursorIterator<T>(type, c); } public static <T> Iterator<T> findAsIterator(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { SugarDb db = getSugarContext().getSugarDb(); SQLiteDatabase sqLiteDatabase = db.getDB(); Cursor c = sqLiteDatabase.query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return new CursorIterator<T>(type, c); } public static <T> List<T> find(Class<T> type, String whereClause, String... whereArgs) { return find(type, whereClause, whereArgs, null, null, null); } public static <T> List<T> findWithQuery(Class<T> type, String query, String... arguments) { SugarDb db = getSugarContext().getSugarDb(); SQLiteDatabase sqLiteDatabase = db.getDB(); T entity; List<T> toRet = new ArrayList<T>(); Cursor c = sqLiteDatabase.rawQuery(query, arguments); try { while (c.moveToNext()) { entity = type.getDeclaredConstructor().newInstance(); SugarRecord.inflate(c, entity); toRet.add(entity); } } catch (Exception e) { e.printStackTrace(); } finally { c.close(); } return toRet; } public static void executeQuery(String query, String... arguments) { getSugarContext().getSugarDb().getDB().execSQL(query, arguments); } public static <T> List<T> find(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { SugarDb db = getSugarContext().getSugarDb(); SQLiteDatabase sqLiteDatabase = db.getDB(); T entity; List<T> toRet = new ArrayList<T>(); Cursor c = sqLiteDatabase.query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); try { while (c.moveToNext()) { entity = type.getDeclaredConstructor().newInstance(); SugarRecord.inflate(c, entity); toRet.add(entity); } } catch (Exception e) { e.printStackTrace(); } finally { c.close(); } return toRet; } public static <T> long count(Class<?> type) { return count(type, null, null, null, null, null); } public static <T> long count(Class<?> type, String whereClause, String[] whereArgs) { return count(type, whereClause, whereArgs, null, null, null); } public static <T> long count(Class<?> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { SugarDb db = getSugarContext().getSugarDb(); SQLiteDatabase sqLiteDatabase = db.getDB(); long toRet = -1; String filter = (!TextUtils.isEmpty(whereClause)) ? " where " + whereClause : ""; SQLiteStatement sqliteStatement; try { sqliteStatement = sqLiteDatabase.compileStatement("SELECT count(*) FROM " + NamingHelper.toSQLName(type) + filter); } catch (SQLiteException e) { e.printStackTrace(); return toRet; } if (whereArgs != null) { for (int i = whereArgs.length; i != 0; i sqliteStatement.bindString(i, whereArgs[i - 1]); } } try { toRet = sqliteStatement.simpleQueryForLong(); } finally { sqliteStatement.close(); } return toRet; } public static long save(Object object) { return save(getSugarContext().getSugarDb().getDB(), object); } static long save(SQLiteDatabase db, Object object) { List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); ContentValues values = new ContentValues(columns.size()); Field idField = null; for (Field column : columns) { ReflectionUtil.addFieldValueToColumn(values, column, object); if (column.getName() == "id") { idField = column; } } long id = db.insertWithOnConflict(NamingHelper.toSQLName(object.getClass()), null, values, SQLiteDatabase.CONFLICT_REPLACE); if (object.getClass().isAnnotationPresent(Table.class)) { if (idField != null) { idField.setAccessible(true); try { idField.set(object, new Long(id)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } else if (SugarRecord.class.isAssignableFrom(object.getClass())) { ((SugarRecord) object).setId(id); } Log.i("Sugar", object.getClass().getSimpleName() + " saved : " + id); return id; } private static void inflate(Cursor cursor, Object object) { List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); for (Field field : columns) { field.setAccessible(true); Class<?> fieldType = field.getType(); if (fieldType.isAnnotationPresent(Table.class) || SugarRecord.class.isAssignableFrom(fieldType)) { try { long id = cursor.getLong(cursor.getColumnIndex(NamingHelper.toSQLName(field))); field.set(object, (id > 0) ? findById(fieldType, id) : null); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { ReflectionUtil.setFieldValueFromCursor(cursor, field, object); } } } public void delete() { SQLiteDatabase db = getSugarContext().getSugarDb().getDB(); db.delete(NamingHelper.toSQLName(getClass()), "Id=?", new String[]{getId().toString()}); Log.i("Sugar", getClass().getSimpleName() + " deleted : " + getId().toString()); } public static void delete(Object object) { if (!(object instanceof SugarRecord)) { Log.i("Sugar", "Cannot delete object: " + object.getClass().getSimpleName() + " - not a sugarRecord"); return; } ((SugarRecord) object).delete(); } public long save() { return save(getSugarContext().getSugarDb().getDB(), this); } @SuppressWarnings("unchecked") void inflate(Cursor cursor) { inflate(cursor, this); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } static class CursorIterator<E> implements Iterator<E> { Class<E> type; Cursor cursor; public CursorIterator(Class<E> type, Cursor cursor) { this.type = type; this.cursor = cursor; } @Override public boolean hasNext() { return cursor != null && !cursor.isClosed() && !cursor.isAfterLast(); } @Override public E next() { E entity = null; if (cursor == null || cursor.isAfterLast()) { throw new NoSuchElementException(); } if (cursor.isBeforeFirst()) { cursor.moveToFirst(); } try { entity = type.getDeclaredConstructor().newInstance(); SugarRecord.inflate(cursor, entity); } catch (Exception e) { e.printStackTrace(); } finally { cursor.moveToNext(); if (cursor.isAfterLast()) { cursor.close(); } } return entity; } @Override public void remove() { throw new UnsupportedOperationException(); } } }
package com.m4gik; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Collection; import java.util.LinkedList; import java.util.Random; import es.usc.citius.common.parallel.Parallel; public class ElGamal { /** * The length for ElGamal key. */ private static final int KEY_LENGTH = 4; /** * The separator which separates the given string from another. */ private static final String SEPARATOR = "x"; /** * The object to code/decode public key. */ private BigInteger alpha; /** * The filed to keep probable prime value. */ private BigInteger p; /** * The variable keeping the public key. */ private BigInteger publicKey; /** * The filed to keep value for future verification. */ private BigInteger r; /** * The variable keeping the private key. */ private BigInteger secretKey; /** * The random instance for generating secure random values. */ private Random secureRandom = new SecureRandom(); /** * The constructor for {@link ElGamal} class, which creates the instance. * * @param secretKey * The private key. */ public ElGamal(String secretKey) { setPrivateKey(secretKey); generatePublicKey(this.secretKey); } /** * This method generates public key from private key. * * @param secretKey */ private void generatePublicKey(BigInteger secretKey) { this.p = BigInteger.probablePrime(KEY_LENGTH, this.secureRandom); this.alpha = new BigInteger(Integer.toString(secureRandom.nextInt())); this.publicKey = alpha.modPow(secretKey, p); } /** * This method gets iterable instance for given array. * * @param splitOrginalMessage * The message for wich will be collects indexes. * @return The iterable instance with indexes for given array. */ private Iterable<Integer> getIndexes(String[] splitOrginalMessage) { LinkedList<Integer> indexes = new LinkedList<Integer>(); Integer index = 0; for (@SuppressWarnings("unused") String string : splitOrginalMessage) { indexes.add(index++); } return indexes; } /** * This method return value probably prime for k which is relative to p - 1. * * @return The probably prime value relative to p - 1. */ private BigInteger getProbablyPrime() { BigInteger k = new BigInteger(KEY_LENGTH, this.secureRandom); while ((this.p.subtract(BigInteger.ONE)).gcd(k).intValue() != 1) { k = new BigInteger(KEY_LENGTH, this.secureRandom); } return k; } /** * This method gets value for verification of sign. * * @return the r */ public BigInteger getValueToVerification() { return r; } /** * This method sets the private key. * * @param secretKey */ private void setPrivateKey(String secretKey) { this.secretKey = new BigInteger(secretKey); } /** * This method sets value to after verification of sign. * * @param r * the r to set */ public void setValueToVerification(BigInteger r) { this.r = r; } /** * This method signs the given message using ElGamal algorithm. * * @param message * The message to sign. * @return The signed message. */ public String sign(String message) { String encryptedMessage = ""; String split[] = message.split("(?!^)"); BigInteger k = getProbablyPrime(); setValueToVerification(this.alpha.modPow(k, this.p)); for (String string : split) { encryptedMessage += signPart(Integer.parseInt(string, 16), k); encryptedMessage += SEPARATOR; } return encryptedMessage; } /** * This method sing the given part of message to avoid long verify. * * @param partOfMessage * The part of message to sign * @param k * The value of k which is probably prime. * @return The part of encrypted and sign message. */ private String signPart(Integer partOfMessage, BigInteger k) { BigInteger messageToEncrypt = new BigInteger(partOfMessage.toString()); BigInteger encryptedMessage = (messageToEncrypt.subtract(this.secretKey .multiply(getValueToVerification()))).multiply(k .modInverse(this.p.subtract(BigInteger.ONE))); return encryptedMessage.toString(); } /** * This method verifies sign. * * @param encryptedMessage * The message which was encrypted. * @param valueToVerification * The value which allows to identify encrypted message with * original. * @param orginalMessage * The original context message to verify with encrypted. * @return True if encrypted message can be verified with original message, * false if did not. */ public Boolean verify(String encryptedMessage, final BigInteger valueToVerification, String orginalMessage) { Boolean isVeryfied = true; final String splitEncryptedMessage[] = encryptedMessage .split(SEPARATOR); final String splitOrginalMessage[] = orginalMessage.split("(?!^)"); Iterable<Integer> indexes = getIndexes(splitOrginalMessage); Collection<Boolean> verifyCollection = Parallel.ForEach(indexes, new Parallel.F<Integer, Boolean>() { public Boolean apply(Integer index) { return verifyPart(Integer.parseInt( splitOrginalMessage[index], 16), Integer .parseInt(splitEncryptedMessage[index]), valueToVerification); } }); for (Boolean isVerify : verifyCollection) { if (isVeryfied) { isVeryfied = isVerify; } } return isVeryfied; } /** * This method verify the part of message. This performance is to avoid long * verification. * * @param orginalMessage * The part of original message, to verify with part of encrypted * message. * @param encryptedMessage * The portion of encrypted message. * @param valueToVerification * The value which allows to identify encrypted message with * original. * @return True if part of encrypted message can be verified with part of * original message, false if did not. */ private Boolean verifyPart(Integer orginalMessage, Integer encryptedMessage, BigInteger valueToVerification) { Boolean isVeryfied = false; BigInteger left = this.alpha.pow(orginalMessage).mod(this.p); BigInteger right = ((publicKey.modPow(valueToVerification, this.p)) .multiply(valueToVerification.modPow(new BigInteger( encryptedMessage.toString()), this.p))).mod(this.p); if (left.equals(right)) { isVeryfied = true; } return isVeryfied; } }
package cgeo.geocaching.utils; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.R; import cgeo.geocaching.models.Image; import cgeo.geocaching.storage.ContentStorage; import cgeo.geocaching.storage.LocalStorage; import android.app.Application; import android.content.ContentValues; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.util.Base64; import android.util.Base64InputStream; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.FileProvider; import androidx.core.text.HtmlCompat; import androidx.exifinterface.media.ExifInterface; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.WeakReference; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.Consumer; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; public final class ImageUtils { private static final String OFFLINE_LOG_IMAGE_PRAEFIX = "cgeo-image-"; private static final int[] ORIENTATIONS = { ExifInterface.ORIENTATION_ROTATE_90, ExifInterface.ORIENTATION_ROTATE_180, ExifInterface.ORIENTATION_ROTATE_270 }; private static final int[] ROTATION = { 90, 180, 270 }; private static final int MAX_DISPLAY_IMAGE_XY = 800; // Images whose URL contains one of those patterns will not be available on the Images tab // for opening into an external application. private static final String[] NO_EXTERNAL = { "geocheck.org" }; private ImageUtils() { // Do not let this class be instantiated, this is a utility class. } /** * Scales a bitmap to the device display size. * * @param image * The image Bitmap representation to scale * @return BitmapDrawable The scaled image */ @NonNull public static BitmapDrawable scaleBitmapToFitDisplay(@NonNull final Bitmap image) { final Point displaySize = DisplayUtils.getDisplaySize(); final int maxWidth = displaySize.x - 25; final int maxHeight = displaySize.y - 25; return scaleBitmapTo(image, maxWidth, maxHeight); } /** * Reads and scales an image to the device display size. * * @param imageData * The image data to read and scale * @return Bitmap The scaled image or Null if source image can't be read */ @Nullable public static Bitmap readAndScaleImageToFitDisplay(@NonNull final Uri imageData) { final Point displaySize = DisplayUtils.getDisplaySize(); // Restrict image size to 800 x 800 to prevent OOM on tablets final int maxWidth = Math.min(displaySize.x - 25, MAX_DISPLAY_IMAGE_XY); final int maxHeight = Math.min(displaySize.y - 25, MAX_DISPLAY_IMAGE_XY); final Bitmap image = readDownsampledImage(imageData, maxWidth, maxHeight); if (image == null) { return null; } final BitmapDrawable scaledImage = scaleBitmapTo(image, maxWidth, maxHeight); return scaledImage.getBitmap(); } /** * Scales a bitmap to the given bounds if it is larger, otherwise returns the original bitmap (except when "force" is set to true) * * @param image * The bitmap to scale * @return BitmapDrawable The scaled image */ @NonNull private static BitmapDrawable scaleBitmapTo(@NonNull final Bitmap image, final int maxWidth, final int maxHeight) { final Application app = CgeoApplication.getInstance(); Bitmap result = image; final ImmutableTriple<Integer, Integer, Boolean> scaledSize = calculateScaledImageSizes(image.getWidth(), image.getHeight(), maxWidth, maxHeight); if (scaledSize.right) { result = Bitmap.createScaledBitmap(image, scaledSize.left, scaledSize.middle, true); } final BitmapDrawable resultDrawable = new BitmapDrawable(app.getResources(), result); resultDrawable.setBounds(new Rect(0, 0, scaledSize.left, scaledSize.middle)); return resultDrawable; } public static ImmutableTriple<Integer, Integer, Boolean> calculateScaledImageSizes(final int originalWidth, final int originalHeight, final int maxWidth, final int maxHeight) { int width = originalWidth; int height = originalHeight; final int realMaxWidth = maxWidth <= 0 ? width : maxWidth; final int realMaxHeight = maxHeight <= 0 ? height : maxHeight; final boolean imageTooLarge = width > realMaxWidth || height > realMaxHeight; if (!imageTooLarge) { return new ImmutableTriple<>(width, height, false); } final double ratio = Math.min((double) realMaxHeight / (double) height, (double) realMaxWidth / (double) width); width = (int) Math.ceil(width * ratio); height = (int) Math.ceil(height * ratio); return new ImmutableTriple<>(width, height, true); } /** * Store a bitmap to uri. * * @param bitmap * The bitmap to store * @param format * The image format * @param quality * The image quality * @param targetUri * Path to store to */ public static void storeBitmap(final Bitmap bitmap, final Bitmap.CompressFormat format, final int quality, final Uri targetUri) { final BufferedOutputStream bos = null; try { bitmap.compress(format, quality, CgeoApplication.getInstance().getApplicationContext().getContentResolver().openOutputStream(targetUri)); } catch (final IOException e) { Log.e("ImageHelper.storeBitmap", e); } finally { IOUtils.closeQuietly(bos); } } public static File scaleAndCompressImageToTemporaryFile(@NonNull final Uri imageUri, final int maxXY) { final Bitmap image = readDownsampledImage(imageUri, maxXY, maxXY); if (image == null) { return null; } final File targetFile = FileUtils.getUniqueNamedFile(new File(LocalStorage.getInternalCgeoDirectory(), "offline_log_image.tmp")); final Uri newImageUri = Uri.fromFile(targetFile); if (newImageUri == null) { Log.e("ImageUtils.readScaleAndWriteImage: unable to write scaled image"); return null; } final BitmapDrawable scaledImage = scaleBitmapTo(image, maxXY, maxXY); storeBitmap(scaledImage.getBitmap(), Bitmap.CompressFormat.JPEG, 75, newImageUri); return targetFile; } /** * Reads and scales an image with downsampling in one step to prevent memory consumption. * * @param imageUri image to read * @param maxX The desired width. If <= 0 then actual bitmap width is used * @param maxY The desired height. If <= 0 then actual bitmap height is used * @return Bitmap the image or null if image can't be read */ @Nullable private static Bitmap readDownsampledImage(@NonNull final Uri imageUri, final int maxX, final int maxY) { final BitmapFactory.Options sizeOnlyOptions = getBitmapSizeOptions(openImageStream(imageUri)); if (sizeOnlyOptions == null) { return null; } final int myMaxXY = Math.max(sizeOnlyOptions.outHeight, sizeOnlyOptions.outWidth); final int maxXY = Math.max(maxX <= 0 ? sizeOnlyOptions.outWidth : maxX, maxY <= 0 ? sizeOnlyOptions.outHeight : maxY); final int sampleSize = maxXY <= 0 ? 1 : myMaxXY / maxXY; final BitmapFactory.Options sampleOptions = new BitmapFactory.Options(); if (sampleSize > 1) { sampleOptions.inSampleSize = sampleSize; } return readDownsampledImageInternal(imageUri, sampleOptions); } private static Bitmap readDownsampledImageInternal(final Uri imageUri, final BitmapFactory.Options sampleOptions) { final int orientation = getImageOrientation(imageUri); try (InputStream imageStream = openImageStream(imageUri)) { if (imageStream == null) { return null; } final Bitmap decodedImage = BitmapFactory.decodeStream(imageStream, null, sampleOptions); if (decodedImage != null) { for (int i = 0; i < ORIENTATIONS.length; i++) { if (orientation == ORIENTATIONS[i]) { final Matrix matrix = new Matrix(); matrix.postRotate(ROTATION[i]); return Bitmap.createBitmap(decodedImage, 0, 0, decodedImage.getWidth(), decodedImage.getHeight(), matrix, true); } } } return decodedImage; } catch (final IOException e) { Log.e("ImageUtils.readDownsampledImage(decode)", e); } return null; } private static int getImageOrientation(@NonNull final Uri imageUri) { int orientation = ExifInterface.ORIENTATION_NORMAL; try (InputStream imageStream = openImageStream(imageUri)) { if (imageStream != null) { final ExifInterface exif = new ExifInterface(imageStream); orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); } } catch (final IOException e) { Log.e("ImageUtils.getImageOrientation(ExifIf)", e); } return orientation; } /** stream will be consumed and closed by method */ @NonNull private static BitmapFactory.Options getBitmapSizeOptions(@NonNull final InputStream imageStream) { if (imageStream == null) { return null; } BitmapFactory.Options sizeOnlyOptions = null; try { sizeOnlyOptions = new BitmapFactory.Options(); sizeOnlyOptions.inJustDecodeBounds = true; BitmapFactory.decodeStream(imageStream, null, sizeOnlyOptions); } finally { IOUtils.closeQuietly(imageStream); } return sizeOnlyOptions; } @Nullable public static ImmutablePair<Integer, Integer> getImageSize(@Nullable final Uri imageData) { if (imageData == null) { return null; } try (InputStream imageStream = openImageStream(imageData)) { if (imageStream == null) { return null; } final Bitmap bm = BitmapFactory.decodeStream(imageStream); return bm == null ? null : new ImmutablePair<>(bm.getWidth(), bm.getHeight()); } catch (IOException e) { Log.e("ImageUtils.getImageSize", e); } return null; } /** * Check if the URL contains one of the given substrings. * * @param url the URL to check * @param patterns a list of substrings to check against * @return <tt>true</tt> if the URL contains at least one of the patterns, <tt>false</tt> otherwise */ public static boolean containsPattern(final String url, final String[] patterns) { for (final String entry : patterns) { if (StringUtils.containsIgnoreCase(url, entry)) { return true; } } return false; } /** * Decode a base64-encoded string and save the result into a file. * * @param inString the encoded string * @param outFile the file to save the decoded result into */ public static void decodeBase64ToFile(final String inString, final File outFile) { FileOutputStream out = null; try { out = new FileOutputStream(outFile); decodeBase64ToStream(inString, out); } catch (final IOException e) { Log.e("HtmlImage.decodeBase64ToFile: cannot write file for decoded inline image", e); } finally { IOUtils.closeQuietly(out); } } /** * Decode a base64-encoded string and save the result into a stream. * * @param inString * the encoded string * @param out * the stream to save the decoded result into */ public static void decodeBase64ToStream(final String inString, final OutputStream out) throws IOException { Base64InputStream in = null; try { in = new Base64InputStream(new ByteArrayInputStream(inString.getBytes(StandardCharsets.US_ASCII)), Base64.DEFAULT); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } } @NonNull public static BitmapDrawable getTransparent1x1Drawable(final Resources res) { return new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.image_no_placement)); } /** * Add images present in the HTML description to the existing collection. * @param images a collection of images * @param geocode the common title for images in the description * @param htmlText the HTML description to be parsed, can be repeated */ public static void addImagesFromHtml(final Collection<Image> images, final String geocode, final String... htmlText) { final Set<String> urls = new LinkedHashSet<>(); for (final Image image : images) { urls.add(image.getUrl()); } for (final String text: htmlText) { HtmlCompat.fromHtml(StringUtils.defaultString(text), HtmlCompat.FROM_HTML_MODE_LEGACY, source -> { if (!urls.contains(source) && canBeOpenedExternally(source)) { images.add(new Image.Builder() .setUrl(source) .setTitle(StringUtils.defaultString(geocode)) .build()); urls.add(source); } return null; }, null); } } /** * Container which can hold a drawable (initially an empty one) and get a newer version when it * becomes available. It also invalidates the view the container belongs to, so that it is * redrawn properly. * <p/> * When a new version of the drawable is available, it is put into a queue and, if needed (no other elements * waiting in the queue), a refresh is launched on the UI thread. This refresh will empty the queue (including * elements arrived in the meantime) and ensures that the view is uploaded only once all the queued requests have * been handled. */ public static class ContainerDrawable extends BitmapDrawable implements Consumer<Drawable> { private static final Object lock = new Object(); // Used to lock the queue to determine if a refresh needs to be scheduled private static final LinkedBlockingQueue<ImmutablePair<ContainerDrawable, Drawable>> REDRAW_QUEUE = new LinkedBlockingQueue<>(); private static final Set<TextView> VIEWS = new HashSet<>(); private static final Runnable REDRAW_QUEUED_DRAWABLES = ContainerDrawable::redrawQueuedDrawables; private Drawable drawable; protected final WeakReference<TextView> viewRef; @SuppressWarnings("deprecation") public ContainerDrawable(@NonNull final TextView view, final Observable<? extends Drawable> drawableObservable) { viewRef = new WeakReference<>(view); drawable = null; setBounds(0, 0, 0, 0); drawableObservable.subscribe(this); } @Override public final void draw(final Canvas canvas) { if (drawable != null) { drawable.draw(canvas); } } @Override public final void accept(final Drawable newDrawable) { final boolean needsRedraw; synchronized (lock) { // Check for emptiness inside the call to match the behaviour in redrawQueuedDrawables(). needsRedraw = REDRAW_QUEUE.isEmpty(); REDRAW_QUEUE.add(ImmutablePair.of(this, newDrawable)); } if (needsRedraw) { AndroidSchedulers.mainThread().scheduleDirect(REDRAW_QUEUED_DRAWABLES); } } /** * Update the container with the new drawable. Called on the UI thread. * * @param newDrawable the new drawable * @return the view to update or <tt>null</tt> if the view is not alive anymore */ protected TextView updateDrawable(final Drawable newDrawable) { setBounds(0, 0, newDrawable.getIntrinsicWidth(), newDrawable.getIntrinsicHeight()); drawable = newDrawable; return viewRef.get(); } private static void redrawQueuedDrawables() { if (!REDRAW_QUEUE.isEmpty()) { // Add a small margin so that drawables arriving between the beginning of the allocation and the draining // of the queue might be absorbed without reallocation. final List<ImmutablePair<ContainerDrawable, Drawable>> toRedraw = new ArrayList<>(REDRAW_QUEUE.size() + 16); synchronized (lock) { // Empty the queue inside the lock to match the check done in call(). REDRAW_QUEUE.drainTo(toRedraw); } for (final ImmutablePair<ContainerDrawable, Drawable> redrawable : toRedraw) { final TextView view = redrawable.left.updateDrawable(redrawable.right); if (view != null) { VIEWS.add(view); } } for (final TextView view : VIEWS) { // This forces the relayout of the text around the updated images. view.setText(view.getText()); } VIEWS.clear(); } } } /** * Image that automatically scales to fit a line of text in the containing {@link TextView}. */ public static final class LineHeightContainerDrawable extends ContainerDrawable { public LineHeightContainerDrawable(@NonNull final TextView view, final Observable<? extends Drawable> drawableObservable) { super(view, drawableObservable); } @Override protected TextView updateDrawable(final Drawable newDrawable) { final TextView view = super.updateDrawable(newDrawable); if (view != null) { setBounds(scaleImageToLineHeight(newDrawable, view)); } return view; } } public static boolean canBeOpenedExternally(final String source) { return !containsPattern(source, NO_EXTERNAL); } @NonNull public static Rect scaleImageToLineHeight(final Drawable drawable, final TextView view) { final int lineHeight = (int) (view.getLineHeight() * 0.8); final int width = drawable.getIntrinsicWidth() * lineHeight / drawable.getIntrinsicHeight(); return new Rect(0, 0, width, lineHeight); } @Nullable public static Bitmap convertToBitmap(final Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } // handle solid colors, which have no width int width = drawable.getIntrinsicWidth(); width = width > 0 ? width : 1; int height = drawable.getIntrinsicHeight(); height = height > 0 ? height : 1; final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } @Nullable private static InputStream openImageStream(final Uri imageUri) { return ContentStorage.get().openForRead(imageUri); } public static boolean deleteImage(final Uri uri) { if (uri != null && StringUtils.isNotBlank(uri.toString())) { return ContentStorage.get().delete(uri); } return false; } /** Returns image name and size in bytes */ public static ContentStorage.FileInformation getImageFileInfos(final Image image) { return ContentStorage.get().getFileInfo(image.getUri()); } /** * Creates a new image Uri for a public image. * Just the filename and uri is created, no data is stored. * @param geocode an identifier which will become part of the filename. Might be e.g. the gccode * @return left: created filename, right: uri for the image */ public static ImmutablePair<String, Uri> createNewPublicImageUri(final String geocode) { final String imageFileName = FileNameCreator.OFFLINE_LOG_IMAGE.createName(geocode == null ? "x" : geocode); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { final ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DISPLAY_NAME, imageFileName); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES); return new ImmutablePair<>(imageFileName, CgeoApplication.getInstance().getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)); } //the following only works until Version Q final File imageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); final File image = new File(imageDir, imageFileName); //go through file provider so we can share the Uri with e.g. camera app return new ImmutablePair<>(imageFileName, FileProvider.getUriForFile( CgeoApplication.getInstance().getApplicationContext(), CgeoApplication.getInstance().getApplicationContext().getString(R.string.file_provider_authority), image)); } /** Create a new image Uri for an offline log image */ public static ImmutablePair<String, Uri> createNewOfflineLogImageUri(final String geocode) { final String imageFileName = FileNameCreator.OFFLINE_LOG_IMAGE.createName(geocode == null ? "shared" : geocode); return new ImmutablePair<>(imageFileName, Uri.fromFile(getFileForOfflineLogImage(imageFileName))); } public static void deleteOfflineLogImagesFor(final String geocode, final List<Image> keep) { if (geocode == null) { return; } final Set<String> filenamesToKeep = CollectionStream.of(keep).map(i -> i.getFile() == null ? null : i.getFile().getName()).toSet(); final String fileNamePraefix = OFFLINE_LOG_IMAGE_PRAEFIX + geocode; CollectionStream.of(LocalStorage.getOfflineLogImageDir(geocode).listFiles()) .filter(f -> f.getName().startsWith(fileNamePraefix) && !filenamesToKeep.contains(f.getName())) .forEach(f -> f.delete()); } public static boolean deleteOfflineLogImageFile(final Image delete) { final File imageFile = getFileForOfflineLogImage(delete.getFileName()); return imageFile.isFile() && imageFile.delete(); } public static File getFileForOfflineLogImage(final String imageFileName) { //extract geocode String geocode = null; if (imageFileName.startsWith(OFFLINE_LOG_IMAGE_PRAEFIX)) { final int idx = imageFileName.indexOf("-", OFFLINE_LOG_IMAGE_PRAEFIX.length()); if (idx >= 0) { geocode = imageFileName.substring(OFFLINE_LOG_IMAGE_PRAEFIX.length(), idx); } } return new File(LocalStorage.getOfflineLogImageDir(geocode), imageFileName); } /** adjusts a previously stored offline log image uri to maybe changed realities on the file system */ public static Uri adjustOfflineLogImageUri(final Uri imageUri) { if (imageUri == null) { return imageUri; } // if image folder was moved, try to find image in actual folder using its name if (UriUtils.isFileUri(imageUri)) { final File imageFileCandidate = new File(imageUri.getPath()); if (!imageFileCandidate.isFile()) { return Uri.fromFile(getFileForOfflineLogImage(imageFileCandidate.getName())); } } return imageUri; } }
package edu.wustl.catissuecore.dao; import java.util.List; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Query; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import edu.wustl.catissuecore.audit.AuditManager; import edu.wustl.catissuecore.domain.Biohazard; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.TissueSpecimen; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Variables; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.dbManager.DBUtil; import edu.wustl.common.util.logger.Logger; /** * Default implemention of AbstractDAO through Hibernate ORM tool. * @author kapil_kaveeshwar */ public class HibernateDAO extends AbstractDAO { protected Session session = null; protected Transaction transaction = null; protected AuditManager auditManager; public void openSession() throws DAOException { try { session = DBUtil.currentSession(); transaction = session.beginTransaction(); auditManager = new AuditManager(); } catch (HibernateException dbex) { Logger.out.error(dbex.getMessage(),dbex); new DAOException("Error in opening connection", dbex); } } public void closeSession() throws DAOException { try { DBUtil.closeSession(); } catch(HibernateException dx) { Logger.out.error(dx.getMessage(),dx); new DAOException("Error in closing connection", dx); } session = null; transaction = null; auditManager = null; } public void commit() throws DAOException { try { auditManager.insert(this); if (transaction != null) transaction.commit(); } catch (HibernateException dbex) { Logger.out.error(dbex.getMessage(),dbex); new DAOException("Error in commit", dbex); } } public void rollback() throws DAOException { try { if (transaction != null) transaction.rollback(); } catch (HibernateException dbex) { Logger.out.error(dbex.getMessage(),dbex); new DAOException("Error in rollback", dbex); } } /** * Saves the persistent object in the database. * @param session The session in which the object is saved. * @param obj The object to be saved. * @throws HibernateException Exception thrown during hibernate operations. * @throws DAOException */ public void insert(Object obj,boolean isAuditable) throws DAOException { try { session.save(obj); // if(isAuditable) // auditManager.compare((AbstractDomainObject)obj,null,"INSERT"); } catch(HibernateException hibExp) { throw handleError(hibExp); } // catch(AuditException hibExp) // throw handleError(hibExp); } private DAOException handleError(Exception hibExp) { Logger.out.error(hibExp.getMessage(),hibExp); String msg = generateErrorMessage(hibExp); return new DAOException(msg , hibExp); } private String generateErrorMessage(Exception ex) { if(ex instanceof HibernateException) { HibernateException hibernateException = (HibernateException)ex; StringBuffer message = new StringBuffer(); String str[] = hibernateException.getMessages(); if(message!=null) { for (int i = 0; i < str.length; i++) { message.append(str[i]+" "); } } else { return "Unknown Error"; } return message.toString(); } else { return ex.getMessage(); } } /** * Updates the persistent object in the database. * @param session The session in which the object is saved. * @param obj The object to be updated. * @throws HibernateException Exception thrown during hibernate operations. * @throws DAOException */ public void update(Object obj) throws DAOException { try { session.update(obj); // if(isAuditable) // auditManager.compare((AbstractDomainObject)obj,null,"INSERT"); } catch (HibernateException hibExp) { Logger.out.error(hibExp.getMessage(),hibExp); throw new DAOException("Error in update",hibExp); } } /** * Deletes the persistent object from the database. * @param obj The object to be deleted. */ public void delete(Object obj) throws DAOException { try { session.delete(obj); // if(isAuditable) // auditManager.compare((AbstractDomainObject)obj,null,"INSERT"); } catch (HibernateException hibExp) { Logger.out.error(hibExp.getMessage(),hibExp); throw new DAOException("Error in delete",hibExp); } } /** * Retrieves all the records for class name in sourceObjectName. * @param sourceObjectName Contains the classname whose records are to be retrieved. */ public List retrieve(String sourceObjectName) throws DAOException { return retrieve(sourceObjectName, null, null, null, null, null); } public List retrieve(String sourceObjectName, String whereColumnName, Object whereColumnValue) throws DAOException { String whereColumnNames[] = {whereColumnName}; String colConditions[] = {"="}; Object whereColumnValues[] = {whereColumnValue}; return retrieve(sourceObjectName, null, whereColumnNames, colConditions, whereColumnValues, Constants.AND_JOIN_CONDITION); } /* (non-Javadoc) * @see edu.wustl.catissuecore.dao.AbstractDAO#retrieve(java.lang.String, java.lang.String[]) */ public List retrieve(String sourceObjectName, String[] selectColumnName) throws DAOException { String[] whereColumnName = null; String[] whereColumnCondition = null; Object[] whereColumnValue = null; String joinCondition = null; return retrieve(sourceObjectName, selectColumnName,whereColumnName, whereColumnCondition,whereColumnValue,joinCondition); } /** * Retrieves the records for class name in sourceObjectName according to field values passed in the passed session. * @param whereColumnName An array of field names. * @param whereColumnCondition The comparision condition for the field values. * @param whereColumnValue An array of field values. * @param joinCondition The join condition. * @param The session object. */ public List retrieve(String sourceObjectName, String[] selectColumnName, String[] whereColumnName, String[] whereColumnCondition, Object[] whereColumnValue, String joinCondition) throws DAOException { List list = null; try { StringBuffer sqlBuff = new StringBuffer(); String className = parseClassName(sourceObjectName); if(selectColumnName != null && selectColumnName.length>0) { sqlBuff.append("Select "); for(int i = 0; i< selectColumnName.length;i++) { sqlBuff.append(className+"."+selectColumnName[i]); if(i != selectColumnName.length-1) { sqlBuff.append(", "); } } sqlBuff.append(" "); } Logger.out.debug(" String : "+sqlBuff.toString()); Query query = null; sqlBuff.append("from " + sourceObjectName + " " + className); Logger.out.debug(" String : "+sqlBuff.toString()); if ((whereColumnName != null && whereColumnName.length > 0) && (whereColumnCondition != null && whereColumnCondition.length == whereColumnName.length) && (whereColumnValue != null && whereColumnName.length == whereColumnValue.length)) { if (joinCondition == null) joinCondition = Constants.AND_JOIN_CONDITION; sqlBuff.append(" where "); //Adds the column name and search condition in where clause. for (int i = 0; i < whereColumnName.length; i++) { sqlBuff.append(className + "." + whereColumnName[i] + " "); sqlBuff.append(whereColumnCondition[i] + " ? "); if (i < (whereColumnName.length - 1)) sqlBuff.append(" " + joinCondition + " "); } System.out.println(sqlBuff.toString()); query = session.createQuery(sqlBuff.toString()); //Adds the column values in where clause for (int i = 0; i < whereColumnValue.length; i++) { Logger.out.debug("whereColumnValue[i]. " + whereColumnValue[i]); query.setParameter(i, whereColumnValue[i]); } } else { query = session.createQuery(sqlBuff.toString()); } list = query.list(); Logger.out.debug(" String : "+sqlBuff.toString()); } catch (HibernateException hibExp) { Logger.out.error(hibExp.getMessage(),hibExp); throw new DAOException("Error in retrieve " + hibExp.getMessage(),hibExp); } catch (Exception exp) { Logger.out.error(exp.getMessage(), exp); throw new DAOException("Logical Erroe in retrieve method "+exp.getMessage(), exp); } return list; } /** * Parses the fully qualified classname and returns only the classname. * @param fullyQualifiedName The fully qualified classname. * @return The classname. */ private String parseClassName(String fullyQualifiedName) { try { return fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf(".") + 1); } catch (Exception e) { return fullyQualifiedName; } } public Object retrieve (String sourceObjectName, Long systemIdentifier) throws DAOException { try { return session.load(Class.forName(sourceObjectName), systemIdentifier); } catch (ClassNotFoundException cnFoundExp) { Logger.out.error(cnFoundExp.getMessage(),cnFoundExp); throw new DAOException("Error in retrieve " + cnFoundExp.getMessage(),cnFoundExp); } catch (HibernateException hibExp) { Logger.out.error(hibExp.getMessage(),hibExp); throw new DAOException("Error in retrieve " + hibExp.getMessage(),hibExp); } } public static void main(String[] args) throws Exception { Variables.catissueHome = System.getProperty("user.dir"); Logger.configure("Application.properties"); HibernateDAO dao = new HibernateDAO(); try { dao.openSession(); Specimen specimen = new TissueSpecimen(); Biohazard biohazard1 = (Biohazard)dao.retrieve(Biohazard.class.getName(),new Long(1)); Biohazard biohazard2 = (Biohazard)dao.retrieve(Biohazard.class.getName(),new Long(2)); specimen.getBiohazardCollection().add(biohazard1); specimen.getBiohazardCollection().add(biohazard2); dao.insert(specimen,false); dao.commit(); } catch(DAOException ex) { ex.printStackTrace(); try { dao.rollback(); } catch(DAOException sex) { } } dao.closeSession(); } }
package org.rabix.engine.jdbi.impl; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.UUID; import org.rabix.bindings.model.Job; import org.rabix.bindings.model.Resources; import org.rabix.common.helper.JSONHelper; import org.rabix.engine.jdbi.impl.JDBIJobRepository.JobMapper; import org.rabix.engine.repository.JobRepository; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.Binder; import org.skife.jdbi.v2.sqlobject.BinderFactory; import org.skife.jdbi.v2.sqlobject.BindingAnnotation; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; @RegisterMapper(JobMapper.class) public interface JDBIJobRepository extends JobRepository { @Override @SqlUpdate("insert into job (id,root_id,name, parent_id, status, message, inputs, outputs, resources, group_id,app) values (:id,:root_id,:name,:parent_id,:status::job_status,:message,:inputs::jsonb,:outputs::jsonb,:resources::jsonb,:group_id,:app)") void insert(@BindJob Job job, @Bind("group_id") UUID groupId); @Override @SqlUpdate("update job set root_id=:root_id,name=:name, parent_id=:parent_id, status=:status::job_status, message=:message, inputs=:inputs::jsonb, outputs=:outputs::jsonb, resources=:resources::jsonb,app=:app where id=:id") void update(@BindJob Job job); @Override @SqlUpdate("update job set backend_id=:backend_id where id=:id") void updateBackendId(@Bind("id") UUID jobId, @Bind("backend_id") UUID backendId); @Override @SqlUpdate("update job set backend_id=null, status='READY'::job_status where backend_id=:backend_id and status in ('READY'::job_status,'RUNNING'::job_status)") void dealocateJobs(@Bind("backend_id") UUID backendId); @Override @SqlQuery("select * from job where id=:id") Job get(@Bind("id") UUID id); @Override @SqlQuery("select * from job") Set<Job> get(); @Override @SqlQuery("select backend_id from job where root_id=:root_id") Set<UUID> getBackendsByRootId(@Bind("root_id") UUID rootId); @Override @SqlQuery("select id from job where backend_id=:backend_id") Set<UUID> getJobsByBackendId(@Bind("backend_id") UUID backendId); @Override @SqlQuery("select * from job where root_id=:root_id") Set<Job> getByRootId(@Bind("root_id") UUID rootId); @Override @SqlQuery("select * from job where group_id=:group_id and status='READY'::job_status") Set<Job> getReadyJobsByGroupId(@Bind("group_id") UUID group_id); @Override @SqlQuery("select * from job where backend_id is null and status='READY'::job_status") Set<Job> getReadyFree(); public static class JobMapper implements ResultSetMapper<Job> { public Job map(int index, ResultSet r, StatementContext ctx) throws SQLException { UUID id = r.getObject("id", UUID.class); UUID root_id = r.getObject("root_id", UUID.class); UUID parent_id = r.getObject("parent_id", UUID.class); String name = r.getString("name"); String app = r.getString("app"); Job.JobStatus status = Job.JobStatus.valueOf(r.getString("status")); String message = r.getString("message"); String inputsJson = r.getString("inputs"); String outputsJson = r.getString("outputs"); String resourcesStr = r.getString("resources"); Resources res = JSONHelper.readObject(resourcesStr, Resources.class); Map<String, Object> inputs = JSONHelper.readMap(inputsJson); Map<String, Object> outputs = JSONHelper.readMap(outputsJson); return new Job(id, parent_id, root_id, name, app, status, message, inputs, outputs, Collections.emptyMap(), res, Collections.emptySet()); } } @BindingAnnotation(JDBIJobRepository.BindJob.JobBinderFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER }) public static @interface BindJob { public static class JobBinderFactory implements BinderFactory<Annotation> { public Binder<JDBIJobRepository.BindJob, Job> build(Annotation annotation) { return new Binder<JDBIJobRepository.BindJob, Job>() { public void bind(SQLStatement<?> q, JDBIJobRepository.BindJob bind, Job job) { q.bind("id", job.getId()); q.bind("root_id", job.getRootId()); q.bind("name", job.getName()); q.bind("parent_id", job.getParentId()); q.bind("status", job.getStatus().toString()); q.bind("message", job.getMessage()); q.bind("inputs", JSONHelper.writeObject(job.getInputs())); q.bind("outputs", JSONHelper.writeObject(job.getOutputs())); q.bind("app", job.getApp()); q.bind("resources", JSONHelper.writeObject(job.getResources())); } }; } } } }
package sagan.search.support; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.elasticsearch.client.Client; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @Configuration class InMemoryElasticSearchConfig { private static final Logger log = LoggerFactory.getLogger(InMemoryElasticSearchConfig.class); @Autowired private SearchService searchService; private Client client; private Node node; @PostConstruct public void configureSearchService() { searchService.setUseRefresh(true); new Thread(this::start).start(); } private void start() { log.info("Starting Elastic Search"); NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder().local(true); nodeBuilder.getSettings().put("network.host", "127.0.0.1"); node = nodeBuilder.node(); client = node.client(); log.info("Started Elastic Search"); } @PreDestroy public void shutDownElasticSearch() throws Exception { if (node != null) { try { client.close(); node.close(); } catch (Throwable e) { log.warn("Failed to shutdown Elastic Search"); } } } }
package org.broad.igv.feature; import org.broad.igv.feature.genome.Genome; import org.broad.igv.util.TestUtils; import org.broad.tribble.Feature; import org.junit.Test; import java.io.BufferedReader; import java.io.FileReader; import java.util.List; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; /** * @author Jim Robinson * @date 5/10/12 */ public class GFFParserTest { /** * This test verifies that the attributes from column 9 are retained for a CDS feature that does not have a parent. * This bugfix was released with 2.1.12. * * @throws Exception */ @Test public void testLoadSingleCDS() throws Exception { String gtfFile = TestUtils.DATA_DIR + "gtf/single_cds.gtf"; GFFParser parser = new GFFParser(gtfFile); Genome genome = null; BufferedReader br = new BufferedReader(new FileReader(gtfFile)); List<Feature> features = parser.loadFeatures(br, genome); br.close(); assertEquals(1, features.size()); BasicFeature bf = (BasicFeature) features.get(0); Exon exon = bf.getExons().get(0); assertNotNull(exon.getAttributes()); } }
package com.amos.project4.views; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SpringLayout; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.swing.tree.TreeSelectionModel; import com.amos.project4.controllers.ClientController; import javax.swing.JList; import java.awt.Choice; public class MainUI { private JFrame frame; private final Action action = new ExitAction(); ClientController client_controller; JScrollPane clienTable_scrollPane; private ClientTable tclients; private JTextField search_textField; private SearchParameters searc_params; private JComboBox drop_down; private String[] dd_input = {""}; //get_cat /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainUI window = new MainUI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public MainUI() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { initialize(); } private void initialize() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { // Initialized The Controller client_controller = new ClientController(); searc_params = new SearchParameters(); searc_params.addPropertyChangeListener(client_controller); // Initialise the Frame frame = new JFrame(); frame.setIconImage(Toolkit.getDefaultToolkit().getImage( "C:\\Users\\Lili\\Desktop\\Facebook.ico")); frame.setBounds(100, 100, 700, 700); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH); // set the system look and feel UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // Initialise The menus initMenus(); SpringLayout springLayout = new SpringLayout(); frame.getContentPane().setLayout(springLayout); JSplitPane horizontalSplitPane = new JSplitPane(); springLayout.putConstraint(SpringLayout.NORTH, horizontalSplitPane, 0, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, horizontalSplitPane, 0, SpringLayout.WEST, frame.getContentPane()); frame.getContentPane().add(horizontalSplitPane); // The Status bar JPanel StatusbarPanel = new JPanel(); springLayout.putConstraint(SpringLayout.SOUTH, horizontalSplitPane, 0, SpringLayout.NORTH, StatusbarPanel); springLayout.putConstraint(SpringLayout.EAST, horizontalSplitPane, 0, SpringLayout.EAST, StatusbarPanel); springLayout.putConstraint(SpringLayout.WEST, StatusbarPanel, 0, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.EAST, StatusbarPanel, 0, SpringLayout.EAST, frame.getContentPane()); StatusbarPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); springLayout.putConstraint(SpringLayout.NORTH, StatusbarPanel, -20, SpringLayout.SOUTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, StatusbarPanel, 0, SpringLayout.SOUTH, frame.getContentPane()); frame.getContentPane().add(StatusbarPanel); SpringLayout sl_StatusbarPanel = new SpringLayout(); StatusbarPanel.setLayout(sl_StatusbarPanel); JLabel lbl_statusBar = new JLabel("Loading ..."); sl_StatusbarPanel.putConstraint(SpringLayout.SOUTH, lbl_statusBar, 0, SpringLayout.SOUTH, StatusbarPanel); sl_StatusbarPanel.putConstraint(SpringLayout.WEST, lbl_statusBar, 5, SpringLayout.WEST, StatusbarPanel); StatusbarPanel.add(lbl_statusBar); // The left Panel // JPanel panel_left = new JPanel(); // horizontalSplitPane.setLeftComponent(panel_left); // The right Panel JPanel panel_right = new JPanel(); horizontalSplitPane.setRightComponent(panel_right); SpringLayout sl_panel_right = new SpringLayout(); panel_right.setLayout(sl_panel_right); JSplitPane verticalSplitPane = new JSplitPane(); sl_panel_right.putConstraint(SpringLayout.NORTH, verticalSplitPane, 0, SpringLayout.NORTH, panel_right); sl_panel_right.putConstraint(SpringLayout.WEST, verticalSplitPane, 0, SpringLayout.WEST, panel_right); sl_panel_right.putConstraint(SpringLayout.SOUTH, verticalSplitPane, 0, SpringLayout.SOUTH, panel_right); sl_panel_right.putConstraint(SpringLayout.EAST, verticalSplitPane, 0, SpringLayout.EAST, panel_right); verticalSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); panel_right.add(verticalSplitPane); // The right Top panel verticalSplitPane.setLeftComponent(initRightTopPanel()); // The right botom panel verticalSplitPane.setRightComponent(initRightBottomPanel()); // The left Panel JScrollPane left_scroll_pane = initLeftpanel(); horizontalSplitPane.setLeftComponent(left_scroll_pane); // Register The Views to the controller this.getClient_controller().addView(this.getTclients()); } public ClientController getClient_controller() { return client_controller; } private JScrollPane initLeftpanel() { JScrollPane left_scroll_pane = new JScrollPane(); left_scroll_pane.setPreferredSize(new Dimension(150, 0)); JPanel panel_left = new JPanel(); panel_left.setPreferredSize(new Dimension(150, 0)); left_scroll_pane.setViewportView(panel_left); panel_left.setLayout(new BorderLayout(0, 0)); JTree leftMenuTree = initLeftmenuTree(); panel_left.add(leftMenuTree); return left_scroll_pane; } private JTree initLeftmenuTree() { // Initialize the settings short cut Vector<String> settingsMenu_vec = new TreeNodeVector<String>( "Settings", new String[] { "General Settings" }); // Initialize the user menu short cut Vector<String> usersMenu_vec = new TreeNodeVector<String>("Users", new String[] { "Profile", "Change password" }); // Initialize the Social media menus short cut Vector<String> socialsMenu_vec = new TreeNodeVector<String>("Social", new String[] { "Search account", "Listen", "React" }); // Initialize the Social media menus short cut Vector<String> exitsMenu_vec = new TreeNodeVector<String>("Exit", new String[] { "Logout", "Exit" }); // Initialize the categories Object rootNodes[] = new Object[] { socialsMenu_vec, usersMenu_vec, settingsMenu_vec, exitsMenu_vec }; Vector<Object> root_vec = new TreeNodeVector<Object>("Menu Root", rootNodes); JTree leftMenuTree = new JTree(root_vec); leftMenuTree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); // Put horizontal line to separe the categories UIManager.put("Tree.line", Color.GREEN); leftMenuTree.putClientProperty("JTree.lineStyle", "Horizontal"); // expand all int row = 0; while (row < leftMenuTree.getRowCount()) { leftMenuTree.expandRow(row); row++; } return leftMenuTree; } private JPanel initRightTopPanel() { JPanel panel_right_top = new JPanel(); panel_right_top.setPreferredSize(new Dimension(10, 350)); SpringLayout sl_panel_right_top = new SpringLayout(); panel_right_top.setLayout(sl_panel_right_top); JButton btnCheckSocialMedia = new JButton("Check Social Media"); sl_panel_right_top.putConstraint(SpringLayout.NORTH, btnCheckSocialMedia, 10, SpringLayout.NORTH, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.EAST, btnCheckSocialMedia, -5, SpringLayout.EAST, panel_right_top); btnCheckSocialMedia.setPreferredSize(new Dimension(150, 25)); panel_right_top.add(btnCheckSocialMedia); // JButton btnFilter = new JButton("Filter"); // sl_panel_right_top.putConstraint(SpringLayout.NORTH, btnFilter, 0, // SpringLayout.NORTH, btnCheckSocialMedia); // sl_panel_right_top.putConstraint(SpringLayout.EAST, btnFilter, -5, // SpringLayout.WEST, btnCheckSocialMedia); // panel_right_top.add(btnFilter); // btnFilter.setPreferredSize(new Dimension(70, 25)); JButton btnSearch = new JButton("Search"); btnSearch.addActionListener(new searchAction()); sl_panel_right_top.putConstraint(SpringLayout.NORTH, btnSearch, 0, SpringLayout.NORTH, btnCheckSocialMedia); sl_panel_right_top.putConstraint(SpringLayout.EAST, btnSearch, -5, SpringLayout.WEST, btnCheckSocialMedia); panel_right_top.add(btnSearch); btnSearch.setPreferredSize(new Dimension(75, 25)); search_textField = new JTextField(); sl_panel_right_top.putConstraint(SpringLayout.NORTH, search_textField, 10, SpringLayout.NORTH, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.WEST, search_textField, 313, SpringLayout.WEST, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.EAST, search_textField, -5, SpringLayout.WEST, btnSearch); panel_right_top.add(search_textField); search_textField.setColumns(20); JPanel client_result_panel = InitClientTablePanel(); sl_panel_right_top.putConstraint(SpringLayout.NORTH, client_result_panel, 10, SpringLayout.SOUTH, btnCheckSocialMedia); sl_panel_right_top.putConstraint(SpringLayout.WEST, client_result_panel, 0, SpringLayout.WEST, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.SOUTH, client_result_panel, -10, SpringLayout.SOUTH, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.EAST, client_result_panel, 0, SpringLayout.EAST, btnCheckSocialMedia); panel_right_top.add(client_result_panel); JList list = new JList(); sl_panel_right_top.putConstraint(SpringLayout.NORTH, list, 22, SpringLayout.NORTH, panel_right_top); panel_right_top.add(list); JList list_1 = new JList(); sl_panel_right_top.putConstraint(SpringLayout.NORTH, list_1, 10, SpringLayout.NORTH, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.WEST, list_1, -7, SpringLayout.WEST, search_textField); sl_panel_right_top.putConstraint(SpringLayout.SOUTH, list_1, 30, SpringLayout.NORTH, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.EAST, list_1, -166, SpringLayout.WEST, search_textField); panel_right_top.add(list_1); drop_down = new JComboBox(dd_input); sl_panel_right_top.putConstraint(SpringLayout.NORTH, drop_down, 10, SpringLayout.NORTH, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.WEST, drop_down, 10, SpringLayout.EAST, list); sl_panel_right_top.putConstraint(SpringLayout.SOUTH, drop_down, 30, SpringLayout.NORTH, panel_right_top); sl_panel_right_top.putConstraint(SpringLayout.EAST, drop_down, 303, SpringLayout.EAST, list); panel_right_top.add(drop_down); return panel_right_top; } private JPanel InitClientTablePanel() { JPanel client_result_panel = new JPanel(); client_result_panel.setBorder(new TitledBorder(UIManager .getBorder("TitledBorder.border"), "Search results", TitledBorder.LEADING, TitledBorder.TOP, null, null)); client_result_panel.setLayout(new BorderLayout(0, 0)); clienTable_scrollPane = new JScrollPane(); client_result_panel.add(clienTable_scrollPane); tclients = new ClientTable(client_controller); clienTable_scrollPane.setViewportView(tclients); return client_result_panel; } private JPanel initRightBottomPanel() { JPanel panel_right_bottom = new JPanel(); panel_right_bottom.setLayout(new BorderLayout(0, 0)); JTabbedPane mediaPanes = new JTabbedPane(JTabbedPane.TOP); panel_right_bottom.add(mediaPanes, BorderLayout.CENTER); JTabbedPane facebookPane = new JTabbedPane(JTabbedPane.TOP); mediaPanes.addTab("Facebook", null, facebookPane, null); mediaPanes.setEnabledAt(0, true); JTabbedPane xingPane = new JTabbedPane(JTabbedPane.TOP); mediaPanes.addTab("Xing", null, xingPane, null); JTabbedPane linkedInPane = new JTabbedPane(JTabbedPane.TOP); mediaPanes.addTab("LinkedIn", null, linkedInPane, null); JTabbedPane twitterPane = new JTabbedPane(JTabbedPane.TOP); mediaPanes.addTab("Twitter", null, twitterPane, null); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); mediaPanes.addTab("Client data", null, tabbedPane, null); return panel_right_bottom; } private void initMenus() { JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); JMenuItem mntmUpdateDatabase = new JMenuItem("Update Database"); mnFile.add(mntmUpdateDatabase); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.setAction(action); mnFile.add(mntmExit); JMenu mnHelp = new JMenu("Help"); menuBar.add(mnHelp); JMenuItem mntmAbout = new JMenuItem("About"); mnHelp.add(mntmAbout); } @SuppressWarnings("serial") private class ExitAction extends AbstractAction { public ExitAction() { putValue(NAME, "Exit"); putValue(SHORT_DESCRIPTION, "Some short description"); } public void actionPerformed(ActionEvent e) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.exit(0); } } private class searchAction implements ActionListener { public void actionPerformed(ActionEvent e) { searc_params.setSearchParameters(6, search_textField.getText()); client_controller.setSearch(searc_params); tclients.model.fireTableDataChanged(); tclients.repaint(); clienTable_scrollPane.repaint(); } } public ClientTable getTclients() { return tclients; } }
import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; public class RobotTest { @Test public void testRobotIsCreatedWithCorrectInitialPosition() { final GridPosition initialGridPosition = new GridPosition(0, 0); final Robot robot = new Robot(initialGridPosition, Orientation.NORTH); assertEquals(robot.getGridPosition(), initialGridPosition); } @Ignore("Remove to run test") @Test public void testRobotIsCreatedWithCorrectInitialOrientation() { final Orientation initialOrientation = Orientation.NORTH; final Robot robot = new Robot(new GridPosition(0, 0), initialOrientation); assertEquals(robot.getOrientation(), initialOrientation); } @Ignore("Remove to run test") @Test public void testTurningRightDoesNotChangePosition() { final GridPosition initialGridPosition = new GridPosition(0, 0); final Robot robot = new Robot(initialGridPosition, Orientation.NORTH); robot.turnRight(); assertEquals(robot.getGridPosition(), initialGridPosition); } @Ignore("Remove to run test") @Test public void testTurningRightCorrectlyChangesOrientationFromNorthToEast() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); robot.turnRight(); final Orientation expectedOrientation = Orientation.EAST; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testTurningRightCorrectlyChangesOrientationFromEastToSouth() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.EAST); robot.turnRight(); final Orientation expectedOrientation = Orientation.SOUTH; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testTurningRightCorrectlyChangesOrientationFromSouthToWest() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.SOUTH); robot.turnRight(); final Orientation expectedOrientation = Orientation.WEST; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testTurningRightCorrectlyChangesOrientationFromWestToNorth() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.WEST); robot.turnRight(); final Orientation expectedOrientation = Orientation.NORTH; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testTurningLeftDoesNotChangePosition() { final GridPosition initialGridPosition = new GridPosition(0, 0); final Robot robot = new Robot(initialGridPosition, Orientation.NORTH); robot.turnLeft(); assertEquals(robot.getGridPosition(), initialGridPosition); } @Ignore("Remove to run test") @Test public void testTurningLeftCorrectlyChangesOrientationFromNorthToWest() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); robot.turnLeft(); final Orientation expectedOrientation = Orientation.WEST; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testTurningLeftCorrectlyChangesOrientationFromWestToSouth() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.WEST); robot.turnLeft(); final Orientation expectedOrientation = Orientation.SOUTH; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testTurningLeftCorrectlyChangesOrientationFromSouthToEast() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.SOUTH); robot.turnLeft(); final Orientation expectedOrientation = Orientation.EAST; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testTurningLeftCorrectlyChangesOrientationFromEastToNorth() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.EAST); robot.turnLeft(); final Orientation expectedOrientation = Orientation.NORTH; assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testAdvancingDoesNotChangeOrientation() { final Orientation initialOrientation = Orientation.NORTH; final Robot robot = new Robot(new GridPosition(0, 0), initialOrientation); robot.advance(); assertEquals(robot.getOrientation(), initialOrientation); } @Ignore("Remove to run test") @Test public void testAdvancingWhenFacingNorthIncreasesYCoordinateByOne() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); robot.advance(); final GridPosition expectedGridPosition = new GridPosition(0, 1); assertEquals(robot.getGridPosition(), expectedGridPosition); } @Ignore("Remove to run test") @Test public void testAdvancingWhenFacingSouthDecreasesYCoordinateByOne() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.SOUTH); robot.advance(); final GridPosition expectedGridPosition = new GridPosition(0, -1); assertEquals(robot.getGridPosition(), expectedGridPosition); } @Ignore("Remove to run test") @Test public void testAdvancingWhenFacingEastIncreasesXCoordinateByOne() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.EAST); robot.advance(); final GridPosition expectedGridPosition = new GridPosition(1, 0); assertEquals(robot.getGridPosition(), expectedGridPosition); } @Ignore("Remove to run test") @Test public void testAdvancingWhenFacingWestDecreasesXCoordinateByOne() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.WEST); robot.advance(); final GridPosition expectedGridPosition = new GridPosition(-1, 0); assertEquals(robot.getGridPosition(), expectedGridPosition); } @Ignore("Remove to run test") @Test public void testInstructionsToMoveWestAndNorth() { final Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); robot.simulate("LAAARALA"); final GridPosition expectedGridPosition = new GridPosition(-4, 1); final Orientation expectedOrientation = Orientation.WEST; assertEquals(robot.getGridPosition(), expectedGridPosition); assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testInstructionsToMoveWestAndSouth() { final Robot robot = new Robot(new GridPosition(2, -7), Orientation.EAST); robot.simulate("RRAAAAALA"); final GridPosition expectedGridPosition = new GridPosition(-3, -8); final Orientation expectedOrientation = Orientation.SOUTH; assertEquals(robot.getGridPosition(), expectedGridPosition); assertEquals(robot.getOrientation(), expectedOrientation); } @Ignore("Remove to run test") @Test public void testInstructionsToMoveEastAndNorth() { final Robot robot = new Robot(new GridPosition(8, 4), Orientation.SOUTH); robot.simulate("LAAARRRALLLL"); final GridPosition expectedGridPosition = new GridPosition(11, 5); final Orientation expectedOrientation = Orientation.NORTH; assertEquals(robot.getGridPosition(), expectedGridPosition); assertEquals(robot.getOrientation(), expectedOrientation); } }
package com.randombot.mygame; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.tools.texturepacker.TexturePacker; import com.badlogic.gdx.tools.texturepacker.TexturePacker.Settings; public class Packer { static String fontName = "dfpop-xhdpi"; /** * Packs the images and prepares the skin to be used... */ public static void compile() { String ppath = System.getProperty("user.dir"); ppath = ppath.replace("\\", "/"); System.out.println("Project path: " + ppath); // Auxiliar paths File createdDir = new File(ppath+"/design/created"); File stuffDir = new File(ppath+"/design/created/stuff"); File skinDir = new File(ppath+"/data/skin"); // empty tmp folder File tmpDir = new File(ppath+"/design/tmp"); if(!tmpDir.exists())tmpDir.mkdirs(); System.out.println("Empty tmp folder in " + tmpDir.getAbsolutePath()); //boolean res = tmpDir.mkdir(); // copy created files File[] files = createdDir.listFiles(); for (File f : files){ File newfile = new File(f.getAbsolutePath().replace("created", "tmp")); try { copyFileUsingStream(f, newfile); } catch (IOException e) {} } // copy JSON file updating content System.out.println("Copy json file in " + tmpDir.getAbsolutePath()); try { File skinSourceFile = new File(stuffDir.getCanonicalPath()+"/holo.json"); Reader r = new FileReader(skinSourceFile); File skinDestFile = new File(skinDir.getAbsolutePath()+"/skin.json"); Writer w = new FileWriter(skinDestFile); BufferedReader br = new BufferedReader(r); ArrayList<String> icNames = new ArrayList<String>(); String name; System.out.println("Reading icon files from " + tmpDir.getAbsolutePath()); File[] files2 = tmpDir.listFiles(); for (File f : files2){ File newfile = new File(f.getAbsolutePath()); name = newfile.getName().replace(".png", ""); if (name.contains("ic_")){ icNames.add(name); } } System.out.println("Modifyng json file in " + skinDir.getAbsolutePath()+"/skin.json"); try { String line = br.readLine(); while (line != null) { if (line.contains("<icon>")){ for (int i = 0; i < icNames.size(); ++i){ String aux = line.replace("<icon>", icNames.get(i)); w.append(aux + "\n"); } } else { w.append(line + "\n"); } line = br.readLine(); } br.close(); w.close(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } try { System.out.println("Copy fonts"); File fontSourceFile = new File(stuffDir.getCanonicalPath()+"/"+fontName+".fnt"); File fontDestFile = new File(skinDir.getCanonicalPath()+"/"+fontName+".fnt"); copyFileUsingStream(fontSourceFile, fontDestFile); fontSourceFile = new File(stuffDir.getCanonicalPath()+"/"+fontName+".png"); fontDestFile = new File(tmpDir.getCanonicalPath()+"/"+fontName+".png"); copyFileUsingStream(fontSourceFile, fontDestFile); } catch (IOException e) { } Settings set = new TexturePacker.Settings(); set.filterMag = TextureFilter.Linear; set.filterMin = TextureFilter.Linear; set.pot = false; set.maxHeight = 1024; set.maxWidth = 1024; set.paddingX = 2; set.paddingY = 2; System.out.println("TexturePacker"); try { TexturePacker.process(set, tmpDir.getCanonicalPath(), skinDir.getCanonicalPath()+"/", "skin"); } catch (IOException e) { } // Copy result to Android Project ? File[] finalfiles = skinDir.listFiles(); for (File f : finalfiles){ File newfile = new File(f.getAbsolutePath().replace(MyGame.GAME_NAME, MyGame.GAME_NAME+"-android/assets/")); try { copyFileUsingStream(f, newfile); } catch (IOException e) {} } // Remove tmp directory System.out.println("Removing Tmp"); removeDirectory(tmpDir); } private static void copyFileUsingStream(File source, File dest) throws IOException { System.out.println("Copy from " + source.getAbsolutePath() + " to " + dest.getAbsolutePath()); InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { if (is != null) is.close(); if (os != null) os.close(); } } public static boolean removeDirectory(File directory) { if (directory == null) return false; if (!directory.exists()) return true; if (!directory.isDirectory()) return false; String[] list = directory.list(); if (list != null) { for (int i = 0; i < list.length; i++) { File entry = new File(directory, list[i]); if (entry.isDirectory()) { if (!removeDirectory(entry)) return false; } else { if (!entry.delete()) return false; } } } return directory.delete(); } }
package net.somethingdreadful.MAL; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.PopupMenu; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewFlipper; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.MALApi.ListType; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.GenericRecord; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.tasks.NetworkTask; import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener; import net.somethingdreadful.MAL.tasks.TaskJob; import net.somethingdreadful.MAL.tasks.WriteDetailTask; import java.util.ArrayList; import java.util.Collection; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class IGF extends Fragment implements OnScrollListener, OnItemLongClickListener, OnItemClickListener, NetworkTaskCallbackListener { Context context; ListType listType = ListType.ANIME; // just to have it proper initialized TaskJob taskjob; GridView Gridview; PrefManager pref; ViewFlipper viewflipper; SwipeRefreshLayout swipeRefresh; Activity activity; ArrayList<GenericRecord> gl = new ArrayList<GenericRecord>(); ListViewAdapter<GenericRecord> ga; IGFCallbackListener callback; NetworkTask networkTask; int page = 1; int list = -1; int resource; boolean useSecondaryAmounts; boolean loading = true; boolean detail = false; /* setSwipeRefreshEnabled() may be called before swipeRefresh exists (before onCreateView() is * called), so save it and apply it in onCreateView() */ boolean swipeRefreshEnabled = true; String query; /* * set the watched/read count & status on the covers. */ public static void setStatus(String myStatus, TextView textview, TextView progressCount, ImageView actionButton) { actionButton.setVisibility(View.GONE); progressCount.setVisibility(View.GONE); if (myStatus == null) { textview.setText(""); } else if (myStatus.equals("watching")) { textview.setText(R.string.cover_Watching); progressCount.setVisibility(View.VISIBLE); actionButton.setVisibility(View.VISIBLE); } else if (myStatus.equals("reading")) { textview.setText(R.string.cover_Reading); progressCount.setVisibility(View.VISIBLE); actionButton.setVisibility(View.VISIBLE); } else if (myStatus.equals("completed")) { textview.setText(R.string.cover_Completed); } else if (myStatus.equals("on-hold")) { textview.setText(R.string.cover_OnHold); progressCount.setVisibility(View.VISIBLE); } else if (myStatus.equals("dropped")) { textview.setText(R.string.cover_Dropped); } else if (myStatus.equals("plan to watch")) { textview.setText(R.string.cover_PlanningToWatch); } else if (myStatus.equals("plan to read")) { textview.setText(R.string.cover_PlanningToRead); } else { textview.setText(""); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { setRetainInstance(true); View view = inflater.inflate(R.layout.record_igf_layout, container, false); viewflipper = (ViewFlipper) view.findViewById(R.id.viewFlipper); Gridview = (GridView) view.findViewById(R.id.gridview); Gridview.setOnItemClickListener(this); Gridview.setOnItemLongClickListener(this); Gridview.setOnScrollListener(this); context = getActivity(); activity = getActivity(); pref = new PrefManager(context); useSecondaryAmounts = pref.getUseSecondaryAmountsEnabled(); if (pref.getTraditionalListEnabled()) { Gridview.setColumnWidth((int) Math.pow(9999, 9999)); //remain in the listview mode resource = R.layout.record_igf_listview; } else { resource = R.layout.record_igf_gridview; } swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh); if (isOnHomeActivity()) { swipeRefresh.setOnRefreshListener((Home) getActivity()); swipeRefresh.setColorScheme( R.color.holo_blue_bright, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light ); } swipeRefresh.setEnabled(swipeRefreshEnabled); if ( gl.size() > 0 ) // there are already records, fragment has been rotated refresh(); NfcHelper.disableBeam(activity); if (callback != null) callback.onIGFReady(this); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = activity; if (IGFCallbackListener.class.isInstance(activity)) callback = (IGFCallbackListener)activity; } private boolean isOnHomeActivity() { return getActivity() != null && getActivity().getClass() == Home.class; } /* * add +1 episode/volume/chapters to the anime/manga. */ public void setProgressPlusOne(Anime anime, Manga manga) { if (listType.equals(ListType.ANIME)) { anime.setWatchedEpisodes(anime.getWatchedEpisodes() + 1); if (anime.getWatchedEpisodes() == anime.getEpisodes()) anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime); } else { manga.setProgress(useSecondaryAmounts, manga.getProgress(useSecondaryAmounts) + 1); if (manga.getProgress(useSecondaryAmounts) == manga.getTotal(useSecondaryAmounts)) manga.setReadStatus(GenericRecord.STATUS_COMPLETED); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga); } refresh(); } /* * mark the anime/manga as completed. */ public void setMarkAsComplete(Anime anime, Manga manga) { if (listType.equals(ListType.ANIME)) { anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED); if (anime.getEpisodes() > 0) anime.setWatchedEpisodes(anime.getEpisodes()); anime.setDirty(true); gl.remove(anime); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime); } else { manga.setReadStatus(GenericRecord.STATUS_COMPLETED); manga.setDirty(true); gl.remove(manga); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga); } refresh(); } /* * handle the loading indicator */ private void toggleLoadingIndicator(boolean show) { if (viewflipper != null) { viewflipper.setDisplayedChild(show ? 1 : 0); } } public void toggleSwipeRefreshAnimation(boolean show) { if (swipeRefresh != null) { swipeRefresh.setRefreshing(show); } } public void setSwipeRefreshEnabled(boolean enabled) { swipeRefreshEnabled = enabled; if (swipeRefresh != null) { swipeRefresh.setEnabled(enabled); } } /* * get the anime/manga lists. * (if clear is true the whole list will be cleared and loaded) */ public void getRecords(boolean clear, TaskJob task, int list) { if (task != null) { taskjob = task; } if (list != this.list) { this.list = list; } /* only show loading indicator if * - is not own list and not page 1 * - force sync and list is empty (only show swipe refresh animation if not empty) or should * be cleared */ boolean isEmpty = gl.isEmpty(); toggleLoadingIndicator((page == 1 && !isList()) || (taskjob.equals(TaskJob.FORCESYNC) && (isEmpty || clear))); /* show swipe refresh animation if * - loading more pages * - forced update */ toggleSwipeRefreshAnimation((page > 1 && !isList() || taskjob.equals(TaskJob.FORCESYNC)) && !taskjob.equals(TaskJob.SEARCH)); loading = true; try{ if (clear){ gl.clear(); if (ga == null) { setAdapter(); } ga.clear(); resetPage(); } Bundle data = new Bundle(); data.putInt("page", page); if (networkTask != null) networkTask.cancelTask(); networkTask = new NetworkTask(taskjob, listType, context, data, this); networkTask.execute(isList() ? MALManager.listSortFromInt(list, listType) : query); }catch (Exception e){ Log.e("MALX", "error getting records: " + e.getMessage()); } } public void searchRecords(String search) { if (search != null && !search.equals(query) && !search.equals("")) { // no need for searching the same again or empty string query = search; page = 1; setSwipeRefreshEnabled(false); getRecords(true, TaskJob.SEARCH, 0); } } /* * reset the page number of anime/manga lists. */ public void resetPage() { if (!isList()) { page = 1; Gridview.setSelection(0); } } /* * set the adapter anime/manga */ public void setAdapter() { ga = new ListViewAdapter<GenericRecord>(context, resource); ga.setNotifyOnChange(true); } /* * refresh the covers. */ public void refresh() { try { if (ga == null) setAdapter(); ga.clear(); ga.supportAddAll(gl); if (Gridview.getAdapter() == null) Gridview.setAdapter(ga); } catch (Exception e) { if (MALApi.isNetworkAvailable(context)) { e.printStackTrace(); if (taskjob.equals(TaskJob.SEARCH)) { Crouton.makeText(activity, R.string.crouton_error_Search, Style.ALERT).show(); } else { if (listType.equals(ListType.ANIME)) { Crouton.makeText(activity, R.string.crouton_error_Anime_Sync, Style.ALERT).show(); } else { Crouton.makeText(activity, R.string.crouton_error_Manga_Sync, Style.ALERT).show(); } } Log.e("MALX", "error on refresh: " + e.getMessage()); } else { Crouton.makeText(activity, R.string.crouton_error_noConnectivity, Style.ALERT).show(); } } loading = false; } /* * check if the taskjob is my personal anime/manga list */ public boolean isList() { return taskjob != null && (taskjob.equals(TaskJob.GETLIST) || taskjob.equals(TaskJob.FORCESYNC)); } /* * set the list with the new page/list. */ @SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions @Override public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) { if (!cancelled) // don't change the UI if cancelled toggleLoadingIndicator(false); if ( !cancelled || (cancelled && job.equals(TaskJob.FORCESYNC))) { // forced sync tasks are completed even after cancellation ArrayList resultList; try { if (type == ListType.ANIME) { resultList = (ArrayList<Anime>) result; } else { resultList = (ArrayList<Manga>) result; } } catch (ClassCastException e) { Log.e("MALX", "error reading result because of invalid result class: " + result.getClass().toString()); resultList = null; } if (resultList != null) { if (resultList.size() == 0 && taskjob.equals(TaskJob.SEARCH)) { if (this.page == 1) doRecordsLoadedCallback(type, job, false, true, cancelled); } else { if (job.equals(TaskJob.FORCESYNC)) doRecordsLoadedCallback(type, job, false, false, cancelled); if (!cancelled) { // only add results if not cancelled (on FORCESYNC) if (detail || job.equals(TaskJob.FORCESYNC)) { // a forced sync always reloads all data, so clear the list gl.clear(); detail = false; } gl.addAll(resultList); refresh(); } } } else { doRecordsLoadedCallback(type, job, true, false, cancelled); // no resultList ? something went wrong } } networkTask = null; toggleSwipeRefreshAnimation(false); toggleLoadingIndicator(false); } @Override public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) { doRecordsLoadedCallback(type, job, true, true, false); } private void doRecordsLoadedCallback(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) { if (callback != null) callback.onRecordsLoadingFinished(type, job, error, resultEmpty, cancelled); } /* * handle the gridview click by navigating to the detailview. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent startDetails = new Intent(getView().getContext(), DetailView.class); startDetails.putExtra("net.somethingdreadful.MAL.recordID", ga.getItem(position).getId()); startDetails.putExtra("net.somethingdreadful.MAL.recordType", listType); startActivity(startDetails); if (isList() || taskjob.equals(TaskJob.SEARCH)) this.detail = true; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } /* * load more pages if we are almost on the bottom. */ @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount - firstVisibleItem <= (visibleItemCount * 2) && !loading) { loading = true; if (taskjob != TaskJob.GETLIST && taskjob != TaskJob.FORCESYNC) { page = page + 1; getRecords(false, null, 0); } } } /* * corpy the anime title to the clipboard on long click. */ @SuppressLint("NewApi") @SuppressWarnings("deprecation") @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Crouton.makeText(activity, R.string.crouton_info_Copied, Style.CONFIRM).show(); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); c.setText(gl.get(position).getTitle()); } else { android.content.ClipboardManager c1 = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData c2; c2 = android.content.ClipData.newPlainText("Atarashii", gl.get(position).getTitle()); c1.setPrimaryClip(c2); } return false; } static class ViewHolder { TextView label; TextView progressCount; TextView flavourText; ImageView cover; ImageView bar; ImageView actionButton; } /* * the custom adapter for the covers anime/manga. */ public class ListViewAdapter<T> extends ArrayAdapter<T> { public ListViewAdapter(Context context, int resource) { super(context, resource); } @SuppressWarnings("deprecation") public View getView(int position, View view, ViewGroup parent) { final GenericRecord record = gl.get(position); ViewHolder viewHolder; if (view == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(resource, parent, false); viewHolder = new ViewHolder(); viewHolder.label = (TextView) view.findViewById(R.id.animeName); viewHolder.progressCount = (TextView) view.findViewById(R.id.watchedCount); viewHolder.cover = (ImageView) view.findViewById(R.id.coverImage); viewHolder.bar = (ImageView) view.findViewById(R.id.textOverlayPanel); viewHolder.actionButton = (ImageView) view.findViewById(R.id.popUpButton); viewHolder.flavourText = (TextView) view.findViewById(R.id.stringWatched); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } try { if (taskjob.equals(TaskJob.GETMOSTPOPULAR) || taskjob.equals(TaskJob.GETTOPRATED)) { viewHolder.progressCount.setVisibility(View.VISIBLE); viewHolder.progressCount.setText(Integer.toString(position + 1)); viewHolder.actionButton.setVisibility(View.GONE); viewHolder.flavourText.setText(R.string.label_Number); } else if (listType.equals(ListType.ANIME)) { viewHolder.progressCount.setText(Integer.toString(((Anime) record).getWatchedEpisodes())); setStatus(((Anime) record).getWatchedStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton); } else { if (useSecondaryAmounts) viewHolder.progressCount.setText(Integer.toString(((Manga) record).getVolumesRead())); else viewHolder.progressCount.setText(Integer.toString(((Manga) record).getChaptersRead())); setStatus(((Manga) record).getReadStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton); } viewHolder.label.setText(record.getTitle()); Picasso.with(context) .load(record.getImageUrl()) .error(R.drawable.cover_error) .placeholder(R.drawable.cover_loading) .into(viewHolder.cover); if (viewHolder.actionButton.getVisibility() == View.VISIBLE) { viewHolder.actionButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(context, v); popup.getMenuInflater().inflate(R.menu.record_popup, popup.getMenu()); if (!listType.equals(ListType.ANIME)) popup.getMenu().findItem(R.id.plusOne).setTitle(R.string.action_PlusOneRead); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.plusOne: if (listType.equals(ListType.ANIME)) setProgressPlusOne((Anime) record, null); else setProgressPlusOne(null, (Manga) record); break; case R.id.markCompleted: if (listType.equals(ListType.ANIME)) setMarkAsComplete((Anime) record, null); else setMarkAsComplete(null, (Manga) record); break; } return true; } }); popup.show(); } }); } viewHolder.bar.setAlpha(175); } catch (Exception e) { Log.e("MALX", "error on the ListViewAdapter: " + e.getMessage()); } return view; } public void supportAddAll(Collection<? extends T> collection) { for (T record : collection) { this.add(record); } } } }
/** * Create a new instance of class CelsiusToFahrenheit. Initialize instance * degC, degF variables to values of the arguments passed through the * constructor parameters. * * parameter degC - input; degrees Celsius * parameter degF - output; degrees Fahrenheit */ import java.util.Scanner; public class CelsiusToFahrenheit { public static void main(String[] args) { Scanner sc = new Scanner( System.in ); // Create Scanner object. int degC, degF; // get degC "Enter the temperature in Celsius: " System.out.print("Enter temperature in integer degrees Celsius: "); degC = sc.nextInt(); sc.nextLine(); // calculate degF F=C*(9/5)+32 degF = degC * 9 / 5 + 32; // output degF "The temperature in Fahrenheit is " System.out.printf("%n%d degrees Celsius is equivalent to %d degrees " + "Fahrenheit.", degC, degF); } //end main }
package be.ugent.service; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.google.gson.Gson; import be.ugent.Authentication; import be.ugent.dao.PatientDao; import be.ugent.entitity.Patient; @Path("/PatientService") public class PatientService { PatientDao patientDao = new PatientDao(); @GET @Path("/patients") @Produces({ MediaType.APPLICATION_JSON }) public Response getUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName, @HeaderParam("Authorization") String header) { if(!Authentication.isAuthorized(header)){ return Response.status(403).build(); } // System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName); Patient retrieved = patientDao.getPatient(firstName, lastName); retrieved.setPassword(""); return Response.ok(retrieved+"").build(); } @GET @Path("/advice") @Produces({ MediaType.TEXT_PLAIN }) public Response getAdvice(@QueryParam("patientID") String patientID, @HeaderParam("Authorization") String header) { if(!Authentication.isAuthorized(header)){ return Response.status(403).build(); } // System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName); Patient retrieved = patientDao.getPatienFromId(patientID); return Response.ok().entity(retrieved.getAdvice()+"").build(); } @GET @Path("/login") @Produces({ MediaType.APPLICATION_JSON }) public Response login(@HeaderParam("Authorization") String header) { if(!Authentication.isAuthorized(header)){ return Response.status(403).build(); } // System.out.println("User ingelogd met email:"+patientDao.getPatientFromHeader(header)); Patient retrieved = patientDao.getPatientFromHeader(header); retrieved.setPassword(""); return Response.ok(retrieved+"").build(); } @POST @Path("/patients/hello") @Consumes({MediaType.TEXT_PLAIN}) public Response hello(String user){ System.out.println("Hello "+user); return Response.ok("Hello "+user).build(); } @PUT @Path("/patients") @Consumes(MediaType.APPLICATION_JSON) public Response addUser(String user){ System.out.println("pat: "+user); System.out.println("Patient requested to add: "+user.toString()); Gson gson = new Gson(); Patient toAdd = gson.fromJson(user, Patient.class); if(toAdd.getPatientID()==0){ PatientDao patientDao = new PatientDao(); toAdd.setPatientID(patientDao.getNewId()); } JSONObject userJSON = null; try { userJSON = new JSONObject(user); toAdd.setRelation(""+userJSON.get("relation")); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return Response.status(417).build(); } // System.out.println("Patient to add:"+toAdd); if(patientDao.storePatient(toAdd)){ //return patient successfully created return Response.status(201).entity(patientDao.getPatienFromId(toAdd.getPatientID()+"")).build(); }else{ //return record was already in database, or was wrong format return Response.status(409).build(); } } @POST @Path("/patients/update") @Consumes(MediaType.APPLICATION_JSON) public Response changeUser(String user){ System.out.println("Patient requested to change: "+user.toString()); Gson gson = new Gson(); Patient toAdd = gson.fromJson(user, Patient.class); if(toAdd.getPatientID()<=0){ return Response.status(404).build(); } JSONObject userJSON = null; try { userJSON = new JSONObject(user); toAdd.setRelation(""+userJSON.get("relation")); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // System.out.println("Patient to add:"+toAdd); if(patientDao.updatePatient(toAdd)){ //return patient successfully created return Response.status(202).entity(toAdd.getPatientID()).build(); }else{ //return record was already in database, or was wrong format return Response.status(409).build(); } } @POST @Path("/patients/diagnose") @Consumes({MediaType.TEXT_PLAIN}) public Response diagnoseUser(@FormParam("patientID") String patientID,@FormParam("diagnoseID") String diagnoseID,@HeaderParam("Authorization") String header) { if(!Authentication.isAuthorized(header)){ return Response.status(403).build(); } System.out.println("Patient requested to diagnose: "+patientID); Gson gson = new Gson(); Patient toAdd = patientDao.getPatientFromHeader(header); if(toAdd.getPatientID()<=0){ return Response.status(404).build(); } toAdd.setDiagnoseID(Integer.parseInt(diagnoseID)); if(patientDao.updatePatient(toAdd)){ //return patient successfully created return Response.status(202).entity(toAdd.getPatientID()).build(); }else{ //return record was already in database, or was wrong format return Response.status(409).build(); } } }
package cgeo.watchdog; import static org.assertj.core.api.Java6Assertions.assertThat; import cgeo.CGeoTestCase; import cgeo.geocaching.SearchResult; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.oc.OCApiConnector; import cgeo.geocaching.connector.trackable.TrackableConnector; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.network.Network; import cgeo.geocaching.test.NotForIntegrationTests; import org.apache.commons.lang3.StringUtils; /** * This test is intended to run regularly on our CI server, to verify the availability of several geocaching websites * and our ability to parse a cache from it. * <p> * You need all the opencaching API keys for this test to run. * </p> * */ public class WatchdogTest extends CGeoTestCase { @NotForIntegrationTests public static void testOpenCachingDE() { downloadOpenCaching("OC1234"); } @NotForIntegrationTests public static void testOpenCachingNL() { downloadOpenCaching("OB1AF6"); } @NotForIntegrationTests public static void testOpenCachingPL() { downloadOpenCaching("OP89HC"); } @NotForIntegrationTests public static void testOpenCachingRO() { downloadOpenCaching("OR011D"); } @NotForIntegrationTests public static void testOpenCacheUK() { downloadOpenCaching("OK0384"); } @NotForIntegrationTests public static void testOpenCachingUS() { downloadOpenCaching("OU0331"); } private static void downloadOpenCaching(final String geocode) { final OCApiConnector connector = (OCApiConnector) ConnectorFactory.getConnector(geocode); assertThat(connector).overridingErrorMessage("Did not find c:geo connector for %s", geocode).isNotNull(); final SearchResult searchResult = connector.searchByGeocode(geocode, null, null); assertThat(searchResult).overridingErrorMessage("Failed to get response from %s", connector.getName()).isNotNull(); assertThat(searchResult.getCount()).overridingErrorMessage("Failed to download %s from %s", geocode, connector.getName()).isGreaterThan(0); final Geocache geocache = searchResult.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); assertThat(geocache).isNotNull(); assert geocache != null; // Eclipse null analysis weakness assertThat(geocache.getGeocode()).isEqualTo(geocode); } private static void checkWebsite(final String connectorName, final String url) { // temporarily disable oc.uk if (connectorName.equalsIgnoreCase("geocaching website opencache.uk")) { return; } // temporarily disable extremcaching.com if (connectorName.equalsIgnoreCase("geocaching website extremcaching.com")) { return; } final String page = Network.getResponseData(Network.getRequest(url)); assertThat(page).overridingErrorMessage("Failed to get response from " + connectorName).isNotEmpty(); } @NotForIntegrationTests public static void testTrackableWebsites() { for (final TrackableConnector trackableConnector : ConnectorFactory.getTrackableConnectors()) { if (!trackableConnector.equals(ConnectorFactory.UNKNOWN_TRACKABLE_CONNECTOR)) { checkWebsite("trackable website " + trackableConnector.getHost(), trackableConnector.getTestUrl()); if (StringUtils.isNotBlank(trackableConnector.getProxyUrl())) { checkWebsite("trackable website " + trackableConnector.getHost() + " proxy " + trackableConnector.getProxyUrl(), trackableConnector.getProxyUrl()); } } } } @NotForIntegrationTests public static void testGeocachingWebsites() { for (final IConnector connector : ConnectorFactory.getConnectors()) { if (!connector.equals(ConnectorFactory.UNKNOWN_CONNECTOR)) { checkWebsite("geocaching website " + connector.getName(), connector.getTestUrl()); } } } }
package org.knopflerfish.ant.taskdefs.bundle; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Utility; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.FileScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Jar; import org.apache.tools.ant.taskdefs.Manifest; import org.apache.tools.ant.taskdefs.ManifestException; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.ZipFileSet; //import org.apache.tools.zip.ZipFile; public class Bundle extends Jar { // private fields private static final String BUNDLE_CLASS_PATH_KEY = "Bundle-ClassPath"; private static final String BUNDLE_ACTIVATOR_KEY = "Bundle-Activator"; private static final String IMPORT_PACKAGE_KEY = "Import-Package"; private static final String EXPORT_PACKAGE_KEY = "Export-Package"; private static final String ACTIVATOR_NONE = "none"; private static final String ACTIVATOR_AUTO = "auto"; private static final String PACKAGE_ANALYSIS_NONE = "none"; private static final String PACKAGE_ANALYSIS_WARN = "warn"; private static final String PACKAGE_ANALYSIS_AUTO = "auto"; private String activator = ACTIVATOR_AUTO; private String packageAnalysis = PACKAGE_ANALYSIS_WARN; private Map importPackage = new HashMap(); private Map exportPackage = new HashMap(); private List libs = new ArrayList(); private List classes = new ArrayList(); private File baseDir = null; private List zipgroups = new ArrayList(); private List srcFilesets = new ArrayList(); private Manifest generatedManifest = new Manifest(); private Set activatorClasses = new HashSet(); private Set availablePackages = new HashSet(); private Set referencedPackages = new HashSet(); private Set standardPackagePrefixes = new HashSet(); { standardPackagePrefixes.add("java."); } // private methods private void analyze() { if (activator == ACTIVATOR_AUTO || packageAnalysis != PACKAGE_ANALYSIS_NONE) { addZipGroups(); addImplicitFileset(); for (Iterator i = srcFilesets.iterator(); i.hasNext();) { FileSet fileset = (FileSet) i.next(); File srcFile = getZipFile(fileset); if (srcFile == null) { File filesetBaseDir = fileset.getDir(getProject()); DirectoryScanner ds = fileset.getDirectoryScanner(getProject()); String[] files = ds.getIncludedFiles(); for (int j = 0; j < files.length; j++) { String fileName = files[j]; if (fileName.endsWith(".class")) { File file = new File(filesetBaseDir, fileName); try { analyzeClass(new ClassParser(file.getAbsolutePath())); } catch (IOException ioe) { throw new BuildException ("Failed to parse class file: " +file.getAbsolutePath(), ioe); } } } } else { try { ZipFile zipFile = new ZipFile(srcFile); DirectoryScanner ds = fileset.getDirectoryScanner(getProject()); String[] entries = ds.getIncludedFiles(); log("Files matching for "+srcFile, Project.MSG_WARN); for (int kk = 0; kk<entries.length; kk++) { if (entries[kk].endsWith(".class")) { try { ZipEntry entry = zipFile.getEntry(entries[kk]); analyzeClass(new ClassParser(zipFile.getInputStream(entry), entries[kk])); } catch (IOException ioe) { throw new BuildException ("Failed to parse class file " +entries[kk] +" from zip file: " +srcFile.getAbsolutePath(), ioe); } } } } catch (IOException ioe) { throw new BuildException ("Failed to read zip file: " +srcFile.getAbsolutePath(), ioe); } } } Set publicPackages = exportPackage.keySet(); if (packageAnalysis != PACKAGE_ANALYSIS_NONE) { for (Iterator i = publicPackages.iterator(); i.hasNext();) { String packageName = (String) i.next(); if (!availablePackages.contains(packageName)) { log("Exported package not found in bundle: " + packageName, Project.MSG_WARN); } } } Set privatePackages = new HashSet(availablePackages); privatePackages.removeAll(publicPackages); referencedPackages.removeAll(privatePackages); for (Iterator iterator = referencedPackages.iterator(); iterator.hasNext();) { String packageName = (String) iterator.next(); if (!isStandardPackage(packageName) && !importPackage.containsKey(packageName)) { if (packageAnalysis == PACKAGE_ANALYSIS_AUTO) { if (exportPackage.containsKey(packageName)) { importPackage.put(packageName, exportPackage.get(packageName)); // TODO: do we want to import with version? } else { importPackage.put(packageName, null); } } else if (packageAnalysis == PACKAGE_ANALYSIS_WARN) { log("Referenced package not found in bundle or imports: " + packageName, Project.MSG_WARN); } } } } } private void addZipGroups() { for (int i = 0; i < zipgroups.size(); i++) { FileSet fileset = (FileSet) zipgroups.get(i); FileScanner fs = fileset.getDirectoryScanner(getProject()); String[] files = fs.getIncludedFiles(); File basedir = fs.getBasedir(); for (int j = 0; j < files.length; j++) { ZipFileSet zipfileset = new ZipFileSet(); zipfileset.setSrc(new File(basedir, files[j])); srcFilesets.add(zipfileset); } } } private void addImplicitFileset() { if (baseDir != null) { FileSet fileset = (FileSet) getImplicitFileSet().clone(); fileset.setDir(baseDir); srcFilesets.add(fileset); } } private File getZipFile(FileSet fileset) { if (fileset instanceof ZipFileSet) { ZipFileSet zipFileset = (ZipFileSet) fileset; return zipFileset.getSrc(getProject()); } else { return null; } } private void analyzeClass(ClassParser parser) throws IOException { JavaClass javaClass = parser.parse(); availablePackages.add(javaClass.getPackageName()); String[] interfaces = javaClass.getInterfaceNames(); for (int i = 0; i < interfaces.length; i++) { if("org.osgi.framework.BundleActivator".equals(interfaces[i])) { activatorClasses.add(javaClass.getClassName()); break; } } ConstantPool constantPool = javaClass.getConstantPool(); Constant[] constants = constantPool.getConstantPool(); for (int i = 0; i < constants.length; i++) { Constant constant = constants[i]; if (constant instanceof ConstantClass) { ConstantClass constantClass = (ConstantClass) constant; String referencedClass = constantClass.getBytes(constantPool); if (referencedClass.charAt(0) == '[') { referencedClass = Utility.signatureToString(referencedClass, false); } else { referencedClass = Utility.compactClassName(referencedClass, false); } int lastDotIndex = referencedClass.lastIndexOf('.'); if (lastDotIndex >= 0) { String packageName = referencedClass.substring(0, lastDotIndex); referencedPackages.add(packageName); } } } } private boolean isStandardPackage(String packageName) { for (Iterator i = standardPackagePrefixes.iterator(); i.hasNext();) { String prefix = (String) i.next(); if (packageName.startsWith(prefix)) { return true; } } return false; } private void handleActivator() throws ManifestException { if (activator == ACTIVATOR_NONE) { log("No BundleActivator set", Project.MSG_DEBUG); } else if (activator == ACTIVATOR_AUTO) { switch (activatorClasses.size()) { case 0: { log("No class implementing BundleActivator found", Project.MSG_INFO); break; } case 1: { activator = (String) activatorClasses.iterator().next(); break; } default: { log("More than one class implementing BundleActivator found:", Project.MSG_WARN); for (Iterator i = activatorClasses.iterator(); i.hasNext();) { String activator = (String) i.next(); log(" " + activator, Project.MSG_WARN); } break; } } } if (activator != ACTIVATOR_NONE && activator != ACTIVATOR_AUTO) { log("Bundle-Activator: " + activator, Project.MSG_INFO); generatedManifest.addConfiguredAttribute(createAttribute(BUNDLE_ACTIVATOR_KEY, activator)); } } private void handleClassPath() throws ManifestException { StringBuffer value = new StringBuffer(); boolean rootIncluded = false; if (baseDir != null || classes.size() == 0) { value.append(".,"); rootIncluded = true; } Iterator i = classes.iterator(); while (i.hasNext()) { ZipFileSet zipFileSet = (ZipFileSet) i.next(); String prefix = zipFileSet.getPrefix(getProject()); if (prefix.length() > 0) { value.append(prefix); value.append(','); } else if (!rootIncluded) { value.append(".,"); rootIncluded = true; } } i = libs.iterator(); while (i.hasNext()) { ZipFileSet fileset = (ZipFileSet) i.next(); if (fileset.getSrc(getProject()) == null) { DirectoryScanner ds = fileset.getDirectoryScanner(getProject()); String[] files = ds.getIncludedFiles(); if (files.length != 0) { zipgroups.add(fileset); String prefix = fixPrefix(fileset.getPrefix(getProject())); for (int j = 0; j < files.length; j++) { value.append(prefix.replace('\\', '/')); value.append(files[j].replace('\\', '/')); value.append(','); } } } } if (value.length() > 2) { generatedManifest.addConfiguredAttribute(createAttribute(BUNDLE_CLASS_PATH_KEY, value.substring(0, value.length() - 1))); } } private static String fixPrefix(String prefix) { if (prefix.length() > 0) { char c = prefix.charAt(prefix.length() - 1); if (c != '/' && c != '\\') { prefix = prefix + "/"; } } return prefix; } private void addPackageHeader(String headerName, Map packageMap) throws ManifestException { Iterator i = packageMap.entrySet().iterator(); if (i.hasNext()) { StringBuffer valueBuffer = new StringBuffer(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String name = (String) entry.getKey(); String version = (String) entry.getValue(); valueBuffer.append(name); if (version != null) { valueBuffer.append(";specification-version="); valueBuffer.append(version); } valueBuffer.append(','); } valueBuffer.setLength(valueBuffer.length() - 1); String value = valueBuffer.toString(); generatedManifest.addConfiguredAttribute(createAttribute(headerName, value)); log(headerName + ": " + value, Project.MSG_INFO); } } private static Manifest.Attribute createAttribute(String name, String value) { Manifest.Attribute attribute = new Manifest.Attribute(); attribute.setName(name); attribute.setValue(value); return attribute; } // public methods public void setActivator(String activator) { if (ACTIVATOR_NONE.equalsIgnoreCase(activator)) { this.activator = ACTIVATOR_NONE; } else if (ACTIVATOR_AUTO.equalsIgnoreCase(activator)) { this.activator = ACTIVATOR_AUTO; } else { this.activator = activator; } } public void setPackageAnalysis(String packageAnalysis) { packageAnalysis = packageAnalysis.trim().toLowerCase(); if (PACKAGE_ANALYSIS_NONE.equals(packageAnalysis)) { this.packageAnalysis = PACKAGE_ANALYSIS_NONE; } else if (PACKAGE_ANALYSIS_WARN.equals(packageAnalysis)) { this.packageAnalysis = PACKAGE_ANALYSIS_WARN; } else if (PACKAGE_ANALYSIS_AUTO.equals(packageAnalysis)) { this.packageAnalysis = PACKAGE_ANALYSIS_AUTO; } else { throw new BuildException("Illegal value: " + packageAnalysis); } } public void addConfiguredStandardPackage(OSGiPackage osgiPackage) { String name = osgiPackage.getName(); String prefix = osgiPackage.getPrefix(); if (name != null && prefix == null) { availablePackages.add(name); } else if (prefix != null && name == null) { standardPackagePrefixes.add(prefix); } else { throw new BuildException("StandardPackage must have exactly one of the name and prefix attributes defined"); } } public void addConfiguredImportPackage(OSGiPackage osgiPackage) { String name = osgiPackage.getName(); if (name == null) { throw new BuildException("ImportPackage must have a name"); } else if (osgiPackage.getPrefix() != null) { throw new BuildException("ImportPackage must not have a prefix attribute"); } else { importPackage.put(name, osgiPackage.getVersion()); } } public void addConfiguredExportPackage(OSGiPackage osgiPackage) { String name = osgiPackage.getName(); if (name == null) { throw new BuildException("ExportPackage must have a name"); } else if (osgiPackage.getPrefix() != null) { throw new BuildException("ExportPackage must not have a prefix attribute"); } else { exportPackage.put(name, osgiPackage.getVersion()); } } public void addConfiguredLib(ZipFileSet fileset) { // TODO: handle refid if (fileset.getSrc(getProject()) == null) { addFileset(fileset); libs.add(fileset); } else { addClasses(fileset); } } public void addClasses(ZipFileSet fileset) { super.addZipfileset(fileset); srcFilesets.add(fileset); classes.add(fileset); } // extends Jar public void execute() { try { handleClassPath(); analyze(); handleActivator(); addPackageHeader(IMPORT_PACKAGE_KEY, importPackage); addPackageHeader(EXPORT_PACKAGE_KEY, exportPackage); // TODO: better merge may be needed, currently overwrites pre-existing headers addConfiguredManifest(generatedManifest); } catch (ManifestException me) { throw new BuildException("Error merging manifest headers", me); } super.execute(); } public void setBasedir(File baseDir) { super.setBasedir(baseDir); this.baseDir = baseDir; } public void addZipGroupFileset(FileSet fileset) { super.addZipGroupFileset(fileset); zipgroups.add(fileset); } public void addZipfileset(ZipFileSet fileset) { super.addZipfileset(fileset); } } // Bundle
import java.util.Scanner; import java.io.*; public class HannahBot { public static String[] borrowedItem = new String[10000]; public static String[] borrowedTeam = new String[10000]; public static int borrowedPointer = 0; public static String[] lentItem = new String[10000]; public static int[][] lentLoc = new int[10000][2]; public static String[] lentTeam = new String[10000]; public static int lentPointer = 0; public static String[] borrowedItemBU = new String[10000]; public static String[] borrowedTeamBU = new String[10000]; public static String[] lentItemBU = new String[10000]; public static int[][] lentLocBU = new int[10000][2]; public static String[] lentTeamBU = new String[10000]; public static int[][] results = new int[10000][2]; public static String[] exact = new String[10000]; public static int[] exactLocation = new int[10000]; public static int exactPointer = 0; public static String[] printed = new String[10000]; public static int printedPointer = 1; public static int resultPointer = 0; public static int[] p = new int[7]; public static String[] keywords = new String[10000]; public static int keywordPointer = 0; public static int TLLength = 42; public static int TALength = 20; public static int TBLength = 11; public static int TCLength = 18; public static int TDLength = 25; public static int TELength = 8; public static int CLength = 16; public static int ELength = 23; public static int PLength = 29; public static String[][] ToolBox = new String[42][2]; public static String[][] ToteA = new String[20][2]; public static String[][] ToteB = new String[11][2]; public static String[][] ToteC = new String[18][2]; public static String[][] ToteD = new String[25][2]; public static String[][] ToteE = new String[8][2]; public static String[][] Crate = new String[16][2]; public static String[] TLDesc = new String[42]; public static String[] TADesc = new String[20]; public static String[] TBDesc = new String[11]; public static String[] TCDesc = new String[18]; public static String[] TDDesc = new String[25]; public static String[] TEDesc = new String[8]; public static String[] CDesc = new String[16]; public static String[] Exclusion = new String[23]; public static String[] People = new String[29]; public static boolean askHannah = false; public static boolean debugMode = false; public static boolean ziptie = false; public static boolean adminRestart = true; public static boolean on = true; public static void main(String args[]) throws InterruptedException { initialize(); while( on ) { conductor(); } } public static void initialize() { loadLibrary(); if( !loaded() ) { if(createFile() ) { resetBorrow(); } } loadBorrow(); greet(); } public static boolean createFile() { try { FileWriter fw = new FileWriter("borrow.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw); fw.close(); bw.close(); out.close(); } catch( Exception E ) { System.out.println("Error writing."); } return true; } public static boolean loaded() { boolean tf = false; String fileName = "borrow.txt"; String line = null; try { FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); fileReader.close(); bufferedReader.close(); tf = true; } catch(Exception e) { tf = false; System.out.println("Initial startup detected."); System.out.println("Creating new file."); } return tf; } public static void greet() { System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=[Hannah Bot]=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); System.out.println(); System.out.println(" Hi, I'm HannahBot (v1.9). I can look for things, and tell you what's in our totes and boxes."); System.out.println("Hannah Bot (v1.9) Theoretically(TM) supports description-based queries and all sentence structures."); System.out.println("Hannah Bot (v1.9) Theoretically(TM) can now read and keep track of borrowed items from a file."); System.out.println(); System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=(v1.9)=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"); System.out.println(); System.out.println("How may I help you?"); } public static void conductor() throws InterruptedException { reset(); String input = input(); boolean normal = caser(input); if( normal ) { parse(input); search(); output(); } menu(); } public static void reset() { resultPointer = 0; keywordPointer = 0; for( int f=0; f<printedPointer; f++ ) { printed[f] = ""; } printedPointer = 1; ziptie = false; } public static boolean caser(String input) throws InterruptedException { boolean normal = false; boolean skip = false; boolean ignoreExclaim = false; String data = input.toLowerCase(); if( input.equals("") ) { System.out.println("I'm going to need something more specific."); skip = true; } if( data.contains("bye") ) { shutDown(); skip = true; } if( data.contains("changelog") ) { System.out.println("(v1.0) :: Basic search function for totes."); System.out.println("(v1.1) :: Added some more search functinality."); System.out.println("(v1.2) :: Added ability to list things in totes."); System.out.println("(v1.3) :: Added support for sentence structures."); System.out.println("(v1.4) :: Added Easter Eggs and bug fixes."); System.out.println("(v1.5) :: Incorporated description-based search."); System.out.println("(v1.6) :: Bug fixes. Added some additional commands and Easter Eggs."); System.out.println("(v1.7) :: Improved Search Algorithm. Bug Fixes. Consolidated Memory Arrays."); System.out.println("(v1.8) :: Critical Bug Fix."); System.out.println("(v1.9) :: Added ability to read and keep track of borrowed items from a file."); skip = true; } if( data.contains("help") && !data.contains("find") || data.contains("help") && !data.contains("look") ) { System.out.println("I can look for things by name or by description, theoretically."); System.out.println("I can also list things in the totes."); System.out.println("Say 'flush' to clear the output thingy."); System.out.println("Say 'changelog' to view the changelog."); System.out.println("You can also toggle debug mode by telling me to."); skip = true; } if( data.contains("todo") || data.contains("to-do") ) { System.out.println("1. Borrowed Item Tracking"); System.out.println("2. Memory Modification"); System.out.println("3. Emoji Support"); System.out.println("4. Fix repeat bug"); System.out.println("5. Fix pointer error"); skip = true; } if( data.contains("flush") ) { for( int f=0; f<50; f++ ) { System.out.println(); } skip = true; } if( data.contains("git") ) { System.out.println("Go away, Ryan."); skip = true; } if( data.contains("cls") ) { System.out.println("Cls? What's that? I'm supposed to be based off of a human being, Pranav."); skip = true; } if( data.contains("restore") && data.contains("borrow") ) { restoreBorrow(); System.out.println("I've successfully restored the borrow file."); } if( data.contains("reset") && data.contains("borrow") ) { resetBorrow(); System.out.println("I've cleared all memories of what we've borrowed."); System.out.println("I've saved a backup of it, though, so just let me know if you want to restore it."); skip = true; } else if( data.contains("borrow") || data.contains("lend") || data.contains("lent") ) { data = " " + data + " "; if( (data.contains(" we ") && data.contains("borrow")) || (data.contains(" us ") && data.contains("lent")) ) { borrow("in"); } else if( (data.contains(" we ") && data.contains("lent")) || (data.contains(" us ") && data.contains("borrow")) ) { borrow("out"); } else if( data.contains("borrow") || data.contains("lend") || data.contains("lent") ) { borrow("null"); } skip = true; } if( data.contains("three") || data.contains("3") ) { if( data.contains("law") ) { System.out.println("I'm offended."); skip = true; } } if( data.contains("debug") && data.contains(" on") ) { debugMode = true; skip = true; } else if( data.contains("debug") && data.contains(" off") ) { debugMode = false; skip = true; } else if( data.contains("debug") && data.contains("toggle") ) { debugMode = !debugMode; } if( data.startsWith("hi!") || data.startsWith("hi") || data.startsWith("hi?") || data.startsWith("hello") || data.startsWith("greetings") ) { System.out.println("Hi."); Thread.sleep(500); ignoreExclaim = true; skip = true; } if( data.contains("ziptie") && data.contains("dream") ) { System.out.println("Allow me to refer you to our robot."); } if( data.contains("door") || data.contains("hinge") ) { System.out.println("Really? Again?"); skip = true; } if( data.contains("replacement") && data.contains("hannah") ) { System.out.println("I'm not Hannah's replacement. Hannah is a wonderful and unique human being. I am a computer program."); skip = true; } if( input.endsWith("!") && !ignoreExclaim ) { System.out.println("Hey, no need to yell."); Thread.sleep(500); } if( input.endsWith("!") && data.contains("please") ) { System.out.println("Fine."); Thread.sleep(500); } if( data.contains("backpack") ) { System.out.println("If you're looking for a backpack, I would ask Pranav."); skip = true; } if( !skip ) { boolean checkPerson = false; for( int f=0; f<29; f++ ) { if( data.contains(People[f]) && data.contains("where") ) { checkPerson = true; break; } } if( checkPerson ) { System.out.println("I'm a tote organizer. Go ask Rayna or something."); } else if( data.contains("where") && data.contains("hannah") && askHannah ) { System.out.println("I'm right her- Oh."); Thread.sleep(500); System.out.println("You meant *that* Hannah."); askHannah = true; } else if( data.contains("where") && data.contains("hannah") && !askHannah ) { System.out.println("Haven't you already tried looking for me?"); } else if( data.contains("love") ) { System.out.println("If you're looking for love, you'll have to look elsewhere."); } else if( data.contains("toolbox") ) { listToolBox(); } else if( data.contains("tote a") ) { listToteA(); } else if( data.contains("tote b") ) { listToteB(); } else if( data.contains("tote c") ) { listToteC(); } else if( data.contains("tote d") ) { listToteD(); } else if( data.contains("tote e") ) { listToteE(); } else if( data.contains("crate") ) { listCrate(); } else if( data.contains("inventory") || data.contains("list") || data.contains(" all") || data.contains("everything") ) { listToolBox(); listToteA(); listToteB(); listToteC(); listToteD(); listToteE(); listCrate(); } else { normal = true; if( data.contains("ziptie") || data.contains("zip tie") ) { ziptie = true; } } } return normal; } public static void parse(String input) { String data = input.toLowerCase(); while( data.endsWith(" ") ) { data = data.substring(0,data.length()-1); } if( data.endsWith(".") || data.endsWith("?") || data.endsWith("!") ) { data = data.substring(0,data.length()-1); } while( data.endsWith(" ") ) { data = data.substring(0,data.length()-1); } data = data + " "; while( data.contains(" ") ) { int end = data.indexOf(" "); String keyword = data.substring(0,end); String temp = data.substring(end+1,data.length()); boolean pass = true; for( int f=0; f<23; f++ ) { if(keyword.equals(Exclusion[f])) { pass = false; break; } } if( keyword.length() < 3 ) { pass = false; } if( pass ) { if( debugMode ) { System.out.println(keyword); } keywords[keywordPointer] = keyword; keywordPointer++; } data = temp; } } public static void menu() { System.out.println("How else may I help you?"); } public static void output() { if( resultPointer == 0 ) { System.out.println("Sorry, I couldn't find what you were looking for. Maybe you meant something else?"); } else { System.out.println("Okay, here's what I found:"); } System.out.println(""); if( p[0] > 0 ) { System.out.println("In the Toolbox, we should theoretically have the following items:"); for( int f=0; f<p[0]; f++ ) { if(antiRepeat(ToolBox[results[f][1]][0])) { if( ToolBox[results[f][1]][1] == "0" ) { System.out.println(ToolBox[results[f][1]][0]); } if( ToolBox[results[f][1]][1] != "0" ) { System.out.println("* The " + ToolBox[results[f][1]][0] + " was lent to team " + ToolBox[results[f][1]][1] + "."); } } } System.out.println(""); } if( p[1] > 0 ) { System.out.println("In Tote A, we should theoretically have the following items:"); for( int f=p[0]; f<p[0]+p[1]; f++ ) { if(antiRepeat(ToteA[results[f][1]][0])) { if( ToteA[results[f][1]][1] == "0" ) { System.out.println(ToteA[results[f][1]][0]); } if( ToteA[results[f][1]][1] != "0" ) { System.out.println("* The " + ToteA[results[f][1]][0] + " was lent to team " + ToteA[results[f][1]][1] + "."); } } } System.out.println(""); } if( p[2] > 0 ) { System.out.println("In Tote B, we should theoretically have the following items:"); for( int f=p[0]+p[1]; f<p[0]+p[1]+p[2]; f++ ) { if(antiRepeat(ToteB[results[f][1]][0])) { if( ToteB[results[f][1]][1] == "0" ) { System.out.println(ToteB[results[f][1]][0]); } if( ToteB[results[f][1]][1] != "0" ) { System.out.println("* The " + ToteB[results[f][1]][0] + " was lent to team " + ToteB[results[f][1]][1] + "."); } } } System.out.println(""); } if( p[3] > 0 ) { System.out.println("In Tote C, we should theoretically have the following items:"); for( int f=p[0]+p[1]+p[2]; f<p[0]+p[1]+p[2]+p[3]; f++ ) { if(antiRepeat(ToteC[results[f][1]][0])) { if( ToteC[results[f][1]][1] == "0" ) { System.out.println(ToteC[results[f][1]][0]); } if( ToteC[results[f][1]][1] != "0" ) { System.out.println("* The " + ToteC[results[f][1]][0] + " was lent to team " + ToteC[results[f][1]][1] + "."); } } } System.out.println(""); } if( p[4] > 0 ) { System.out.println("In Tote D, we should theoretically have the following items:"); for( int f=p[0]+p[1]+p[2]+p[3]; f<p[0]+p[1]+p[2]+p[3]+p[4]; f++ ) { if(antiRepeat(ToteD[results[f][1]][0])) { if( ToteD[results[f][1]][1] == "0" ) { System.out.println(ToteD[results[f][1]][0]); } if( ToteD[results[f][1]][1] != "0" ) { System.out.println("* The " + ToteD[results[f][1]][0] + " was lent to team " + ToteD[results[f][1]][1] + "."); } } } System.out.println(""); } if( p[5] > 0 ) { System.out.println("In Tote E, we should theoretically have the following items:"); for( int f=p[0]+p[1]+p[2]+p[3]+p[4]; f<p[0]+p[1]+p[2]+p[3]+p[4]+p[5]; f++ ) { if(antiRepeat(ToteE[results[f][1]][0])) { if( ToteE[results[f][1]][1] == "0" ) { System.out.println(ToteE[results[f][1]][0]); } if( ToteE[results[f][1]][1] != "0" ) { System.out.println("* The " + ToteE[results[f][1]][0] + " was lent to team " + ToteE[results[f][1]][1] + "."); } } } System.out.println(""); } if( p[6] > 0 ) { System.out.println("In the Crate, we should theoretically have the following items:"); for( int f=p[0]+p[1]+p[2]+p[3]+p[4]+p[5]; f<p[0]+p[1]+p[2]+p[3]+p[4]+p[5]+p[6]; f++ ) { if(antiRepeat(Crate[results[f][1]][0])) { if( Crate[results[f][1]][1] == "0" ) { System.out.println(Crate[results[f][1]][0]); } if( ToolBox[results[f][1]][1] != "0" ) { System.out.println("* The " + Crate[results[f][1]][0] + " was lent to team " + Crate[results[f][1]][1] + "."); } } } System.out.println(""); } if( ziptie ) { System.out.println("There's also a whole bunch in Trinity's hair."); } } public static String input() { Scanner sc = new Scanner(System.in); String query = sc.nextLine(); return query; } public static void search() { checkToolBox(); checkToteA(); checkToteB(); checkToteC(); checkToteD(); checkToteE(); checkCrate(); } public static boolean antiRepeat(String check) { boolean b = true; for( int f=0; f<printedPointer; f++ ) { if(check.equals(printed[f])) { b = false; } } if( b ) { printed[printedPointer-1] = check; printedPointer++; } return b; } public static void checkToolBox() { p[0] = 0; for( int f=0; f<41; f++ ) { for( int g=0; g<keywordPointer; g++ ) { if( keywords[g].toLowerCase().contains(TLDesc[f].toLowerCase()) || TLDesc[f].toLowerCase().contains(keywords[g].toLowerCase()) ) { p[0]++; resultPointer++; results[resultPointer-1][0] = 0; results[resultPointer-1][1] = f; } } } } public static void checkToteA() { p[1] = 0; for( int f=0; f<20; f++ ) { for( int g=0; g<keywordPointer; g++ ) { if( keywords[g].toLowerCase().contains(TADesc[f].toLowerCase()) || TADesc[f].toLowerCase().contains(keywords[g].toLowerCase()) ) { p[1]++; resultPointer++; results[resultPointer-1][0] = 1; results[resultPointer-1][1] = f; } } } } public static void checkToteB() { p[2] = 0; for( int f=0; f<11; f++ ) { for( int g=0; g<keywordPointer; g++ ) { if( keywords[g].toLowerCase().contains(TBDesc[f].toLowerCase()) || TBDesc[f].toLowerCase().contains(keywords[g].toLowerCase()) ) { p[2]++; resultPointer++; results[resultPointer-1][0] = 2; results[resultPointer-1][1] = f; } } } } public static void checkToteC() { p[3] = 0; for( int f=0; f<18; f++ ) { for( int g=0; g<keywordPointer; g++ ) { if( keywords[g].toLowerCase().contains(TCDesc[f].toLowerCase()) || TCDesc[f].toLowerCase().contains(keywords[g].toLowerCase()) ) { p[3]++; resultPointer++; results[resultPointer-1][0] = 3; results[resultPointer-1][1] = f; } } } } public static void checkToteD() { p[4] = 0; for( int f=0; f<25; f++ ) { for( int g=0; g<keywordPointer; g++ ) { if( keywords[g].toLowerCase().contains(TDDesc[f].toLowerCase()) || TDDesc[f].toLowerCase().contains(keywords[g].toLowerCase()) ) { p[4]++; resultPointer++; results[resultPointer-1][0] = 4; results[resultPointer-1][1] = f; } } } } public static void checkToteE() { p[5] = 0; for( int f=0; f<8; f++ ) { for( int g=0; g<keywordPointer; g++ ) { if( keywords[g].toLowerCase().contains(TEDesc[f].toLowerCase()) || TEDesc[f].toLowerCase().contains(keywords[g].toLowerCase()) ) { p[5]++; resultPointer++; results[resultPointer-1][0] = 5; results[resultPointer-1][1] = f; } } } } public static void checkCrate() { p[6] = 0; for( int f=0; f<16; f++ ) { for( int g=0; g<keywordPointer; g++ ) { if( keywords[g].toLowerCase().contains(CDesc[f].toLowerCase()) || CDesc[f].toLowerCase().contains(keywords[g].toLowerCase()) ) { p[6]++; resultPointer++; results[resultPointer-1][0] = 6; results[resultPointer-1][1] = f; } } } } public static void borrow(String inout) { boolean check = false; boolean repeat = true; boolean in = false; boolean out = false; if( inout.equals("in") ) { in = true; } if( inout.equals("out") ) { out = true; } if( inout.equals("null") ) { check = true; System.out.println("Do you want to record what we borrowed, or what was borrowed from us?"); } String IO = ""; String Item = ""; String Team = ""; if( check ) { while( repeat ) { String input = input(); String data = input.toLowerCase(); data = " " + data + " "; if( (data.contains(" we ") && data.contains("borrow")) || (data.contains(" us ") && data.contains("lent")) ) { in = true; } if( (data.contains(" we ") && data.contains("lent")) || (data.contains(" us ") && data.contains("borrow")) ) { out = true; } repeat = false; if( in && out ) { System.out.println("You're going to have to pick one or the other."); repeat = true; } } } if( in ) { IO = "B"; repeat = true; while( repeat ) { repeat = false; System.out.println("What item did we borrow?"); Item = input(); repeat = false; if( Item.equals("") ) { System.out.println("I'm going to need something more specific."); repeat = true; } } repeat = true; while( repeat ) { repeat = false; System.out.println("Which team did we borrow from?"); Team = input(); repeat = false; if( Team.equals("") ) { System.out.println("I'm going to need something more specific."); repeat = true; } } } if( out ) { IO = "L"; repeat = true; while( repeat ) { repeat = false; System.out.println("What item did we lend?"); Item = input(); repeat = false; if( Item.equals("") ) { System.out.println("I'm going to need something more specific."); repeat = true; } } repeat = true; while( repeat ) { repeat = false; System.out.println("Which team did we lend to?"); Team = input(); repeat = false; if( Team.equals("") ) { System.out.println("I'm going to need something more specific."); repeat = true; } } } borrowWrite(IO + "~" + Item + "~" + Team + "~"); loadBorrow(); } public static void loadBorrow() { String fileName = "borrow.txt"; String line = null; try { FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { String item = ""; if( line.startsWith(" { String ignore = line; } else if( line.toLowerCase().equals("b") ) { boolean good = true; line = bufferedReader.readLine(); String tempString = line; String tempTeam = "0"; try { line = bufferedReader.readLine(); tempTeam = line; } catch(Exception e) { System.out.println("Warning: Syntax error!"); good = false; break; } if( good ) { borrowedItem[borrowedPointer] = tempString; borrowedTeam[borrowedPointer] = tempTeam; borrowedPointer++; } } else if( line.toLowerCase().equals("l") ) { boolean good = true; line = bufferedReader.readLine(); String tempString = line; String tempTeam = "0"; try { line = bufferedReader.readLine(); tempTeam = line; } catch(Exception e) { System.out.println("Warning: Syntax error!"); good = false; break; } if( good ) { item = tempString.toLowerCase(); int tb = ToolBoxCB(item); int a = ToteACB(item); int b = ToteBCB(item); int c = ToteCCB(item); int d = ToteDCB(item); int e = ToteECB(item); int crate = CrateCB(item); if( tb+a+b+c+d+e+crate != 0 ) { if( tb != 0 ) { lentLoc[lentPointer][0] = 0; lentLoc[lentPointer][1] = tb; ToolBox[tb][1] = tempTeam; } if( a != 0 ) { lentLoc[lentPointer][0] = 1; lentLoc[lentPointer][1] = a; ToteA[a][1] = tempTeam; } if( b != 0 ) { lentLoc[lentPointer][0] = 2; lentLoc[lentPointer][1] = b; ToteB[b][1] = tempTeam; } if( c != 0 ) { lentLoc[lentPointer][0] = 3; lentLoc[lentPointer][1] = c; ToteC[c][1] = tempTeam; } if( d != 0 ) { lentLoc[lentPointer][0] = 4; lentLoc[lentPointer][1] = d; ToteD[d][1] = tempTeam; } if( e != 0 ) { lentLoc[lentPointer][0] = 5; lentLoc[lentPointer][1] = e; ToteE[e][1] = tempTeam; } if( crate != 0 ) { lentLoc[lentPointer][0] = 6; lentLoc[lentPointer][1] = crate; Crate[crate][1] = tempTeam; } lentItem[lentPointer] = tempString; lentTeam[lentPointer] = tempTeam; lentPointer++; } else { System.out.println("I don't think we have a " + item + "."); System.out.println("You may want to check the borrow file, or reset it."); break; } } } } fileReader.close(); bufferedReader.close(); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } } public static void write(String string) { try{ FileWriter fstream = new FileWriter("borrow.txt",true); BufferedWriter fbw = new BufferedWriter(fstream); fbw.write(string); fbw.newLine(); fbw.close(); }catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } public static void borrowWrite(String writer) { int end = writer.indexOf("~"); String BL = writer.substring(0,end); String temp = writer.substring(end+1,writer.length()); end = temp.indexOf("~"); String item = temp.substring(0,end); temp = temp.substring(end+1,temp.length()); end = temp.indexOf("~"); String team = temp.substring(0,end); temp = temp.substring(end+1,temp.length()); write(BL); write(item); write(team); loadBorrow(); } public static void resetBorrow() { write("// adminRestart = false"); write("// This is the file where the borrowed items are stored."); write("// Line 1: B/L (Borrowed/Lent)"); write("// Line 2: Item Name (Exact)"); write("// Line 3: Team No."); borrowedPointer = 0; lentPointer = 0; for( int f=0; f<10000; f++ ) { borrowedItem[f] = ""; borrowedTeam[f] = ""; lentItem[f] = ""; lentLoc[f][0] = 0; lentLoc[f][1] = 0; lentTeam[f] = ""; } } public static void restoreBorrow() { borrowedItem = borrowedItemBU; borrowedTeam = borrowedTeamBU; borrowedPointer = 0; lentItem = lentItemBU; lentLoc = lentLocBU; lentTeam = lentTeamBU; lentPointer = 0; } public static void loadLibrary() { loadToolBox(); loadToteA(); loadToteB(); loadToteC(); loadToteD(); loadToteE(); loadCrate(); loadTLDesc(); loadTADesc(); loadTBDesc(); loadTCDesc(); loadTDDesc(); loadTEDesc(); loadCDesc(); loadExclusion(); loadPeople(); } public static void loadToolBox() { ToolBox[0][0] = "Precision Screwdriver Set"; ToolBox[1][0] = "Goo-gone"; ToolBox[2][0] = "Files"; ToolBox[3][0] = "Erwin Clamps"; ToolBox[4][0] = "Metal Clamps"; ToolBox[5][0] = "Flashlight"; ToolBox[6][0] = "Craftsman's square"; ToolBox[7][0] = "Flathead"; ToolBox[8][0] = "Phillips"; ToolBox[9][0] = "Icepick"; ToolBox[10][0] = "Utility"; ToolBox[11][0] = "Deburring tool"; ToolBox[12][0] = "Paper ruler"; ToolBox[13][0] = "Loctite"; ToolBox[14][0] = "Bent Needlenose (Red & Black, orange)"; ToolBox[15][0] = "Wire Crusher (orange)"; ToolBox[16][0] = "Needlenose (orange)"; ToolBox[17][0] = "Drill Bit row thing"; ToolBox[18][0] = "Big Needlenose (Grey)"; ToolBox[19][0] = "Box Cutter"; ToolBox[20][0] = "Wire Stripper/Crimper"; ToolBox[21][0] = "Snub-Nose Pliers"; ToolBox[22][0] = "Needlenose (green)"; ToolBox[23][0] = "Stab-Stab"; ToolBox[24][0] = "Chain Breaker"; ToolBox[25][0] = "SAE Bit Row"; ToolBox[26][0] = "Snub-Nose Pliers (orange, black-red)"; ToolBox[27][0] = "SAE Hex Keys x2"; ToolBox[28][0] = "Wire Stripper"; ToolBox[29][0] = "Snips"; ToolBox[30][0] = "Blue Vise Grip"; ToolBox[31][0] = "Mallet"; ToolBox[32][0] = "Tiny snips"; ToolBox[33][0] = "Hammer"; ToolBox[34][0] = "Ruler"; ToolBox[35][0] = "Measuring Tape"; ToolBox[36][0] = "Robo-Grip"; ToolBox[37][0] = "Tiny Tape Measure"; ToolBox[38][0] = "Aviation Snips"; ToolBox[39][0] = "Wago"; ToolBox[40][0] = "Scissors"; for( int f=0; f<41; f++ ) { ToolBox[f][1] = "0"; } } public static void loadToteA() { ToteA[0][0] = "Rivet Box"; ToteA[1][0] = "Pneumatics Hardware Box"; ToteA[2][0] = "Zip Tie Box"; ToteA[3][0] = "Encoders"; ToteA[4][0] = "Pressure Tape"; ToteA[5][0] = "Hack Saw"; ToteA[6][0] = "PWM Crimp Tool"; ToteA[7][0] = "Pneumatic Wheels"; ToteA[8][0] = "Grease"; ToteA[9][0] = "craftsman drill bit set"; ToteA[10][0] = "rivet gun"; ToteA[11][0] = "Tape Box"; ToteA[12][0] = "Gorilla Tape"; ToteA[13][0] = "Clear Packing tape"; ToteA[14][0] = "Electrical Tape, Red"; ToteA[15][0] = "Electrical Tape, Black"; ToteA[16][0] = "Painter's Tape, Blue"; ToteA[17][0] = "Crazy glue "; ToteA[18][0] = "Black Rachet Set"; ToteA[19][0] = "Drills + chargers"; for( int f=0; f<20; f++ ) { ToteA[f][1] = "0"; } } public static void loadToteB() { ToteB[0][0] = "Polycord Box (+tread, radio, camera)"; ToteB[1][0] = "Solder Box (+chain)"; ToteB[2][0] = "Vex Pro Box (versas/ringlight/victor)"; ToteB[3][0] = "SAE Tap Set"; ToteB[4][0] = "Spacer Box"; ToteB[5][0] = "Warrior Set"; ToteB[6][0] = "Box End Rachets"; ToteB[7][0] = "Compressed Air"; ToteB[8][0] = "Tap Fluid"; ToteB[9][0] = "Caliper"; ToteB[10][0] = "Blue Rachet Set"; for( int f=0; f<11; f++ ) { ToteB[f][1] = "0"; } } public static void loadToteC() { ToteC[0][0] = "Hardstop (orange)"; ToteC[1][0] = "Gears Stuff Box"; ToteC[2][0] = "Mcmaster box"; ToteC[3][0] = "Red Battery Wire"; ToteC[4][0] = "Black Battery Wire"; ToteC[5][0] = "Pickup hardware bag(small)"; ToteC[6][0] = "Wire box"; ToteC[7][0] = "Victors"; ToteC[8][0] = "Pneumatic Tubing Bag"; ToteC[9][0] = "Versas"; ToteC[10][0] = "Long Pistons"; ToteC[11][0] = "Air Tanks"; ToteC[12][0] = "Random Sheet Metal "; ToteC[13][0] = "Sponsor panels"; ToteC[14][0] = "Breakers"; ToteC[15][0] = "Pneumatic Tubing Blue and Orange"; ToteC[16][0] = "Optical Sensor"; ToteC[17][0] = "Pickup hardware bag(big)"; for( int f=0; f<18; f++ ) { ToteC[f][1] = "0"; } } public static void loadToteD() { ToteD[0][0] = "Pit Bag"; ToteD[1][0] = "White Board"; ToteD[2][0] = "Staple Bag"; ToteD[3][0] = "Staple Gun"; ToteD[4][0] = "Paint brushes+paint"; ToteD[5][0] = "Red Fabric"; ToteD[6][0] = "Blue Fabric"; ToteD[7][0] = "Bumper Bolts + Nuts Bag"; ToteD[8][0] = "Standard"; ToteD[9][0] = "Power Strips "; ToteD[10][0] = "Extension cords"; ToteD[11][0] = "Mutimeter"; ToteD[12][0] = "vise bit"; ToteD[13][0] = "Radio power cord"; ToteD[14][0] = "Ethernet"; ToteD[15][0] = "Ball"; ToteD[16][0] = "Crowbar"; ToteD[17][0] = "Crate Screws(box)"; ToteD[18][0] = "Pool noodle"; ToteD[19][0] = "1x1 tubing"; ToteD[20][0] = "Gorilla Tape"; ToteD[21][0] = "Velcro"; ToteD[22][0] = "Pneumatics plate"; ToteD[23][0] = "2 CIMs Box"; ToteD[24][0] = "4 Dry Erase Markers"; for( int f=0; f<25; f++ ) { ToteD[f][1] = "0"; } } public static void loadToteE() { ToteE[0][0] = "Chain Box"; ToteE[1][0] = "Plates Stuff Box"; ToteE[2][0] = "Clear Screw Box"; ToteE[3][0] = "Mantis hardware bag"; ToteE[4][0] = "Crappy Drill Bit Set"; ToteE[5][0] = "Electrical Stuff box"; ToteE[6][0] = "Anderson Box"; ToteE[7][0] = "Rag Bag"; for( int f=0; f<8; f++ ) { ToteE[f][1] = "0"; } } public static void loadCrate() { Crate[0][0] = "long hex stock (3)"; Crate[1][0] = "standard stand"; Crate[2][0] = "vise"; Crate[3][0] = "tarp "; Crate[4][0] = "white shelves"; Crate[5][0] = "EZ Up"; Crate[6][0] = "robot"; Crate[7][0] = "Bumpers"; Crate[8][0] = "banner"; Crate[9][0] = "Blue Banner"; Crate[10][0] = "sheet metal"; Crate[11][0] = "big shelves"; Crate[12][0] = "Shop vac"; Crate[13][0] = "push cart (1)"; Crate[14][0] = "Orange Safety Kit"; Crate[15][0] = "knee pads"; for( int f=0; f<16; f++ ) { Crate[f][1] = "0"; } } public static void loadExclusion() { Exclusion[0] = "and"; Exclusion[1] = "or"; Exclusion[2] = "where"; Exclusion[3] = "what"; Exclusion[4] = "which"; Exclusion[5] = "i"; Exclusion[6] = "am"; Exclusion[7] = "look"; Exclusion[8] = "search"; Exclusion[9] = "for"; Exclusion[10] = "a"; Exclusion[11] = "the"; Exclusion[12] = "an"; Exclusion[13] = "are"; Exclusion[14] = "is"; Exclusion[15] = "in"; Exclusion[16] = "inside"; Exclusion[17] = "at"; Exclusion[18] = "you"; Exclusion[19] = "find"; Exclusion[20] = "me"; Exclusion[21] = "tell"; Exclusion[22] = "could"; } public static void loadPeople() { People[0] = "justin"; People[1] = "pranav"; People[2] = "aanya"; People[3] = "anya"; People[4] = "thuy"; People[5] = "evan"; People[6] = "rayna"; People[7] = "antoni"; People[8] = "kunal"; People[9] = "canoe"; People[10] = "hayley"; People[11] = "arrington"; People[12] = "tibbs"; People[13] = "jessica"; People[14] = "raymond"; People[15] = "alex"; People[16] = "robert"; People[17] = "nathan"; People[18] = "trinity"; People[19] = "reyna"; People[20] = "rohan"; People[21] = "russel"; People[22] = "matt"; People[23] = "matthew"; People[24] = "ryan"; People[25] = "joey"; People[26] = "kovalik"; People[27] = "joseph"; People[28] = "zain"; } public static void loadTLDesc() { TLDesc[0] = "Precision Screwdrivers Sets screws "; TLDesc[1] = "Goo-gone goo gone removers"; TLDesc[2] = "Files"; TLDesc[3] = "Erwin Clamps"; TLDesc[4] = "Metal Clamps"; TLDesc[5] = "Flashlights"; TLDesc[6] = "Craftsman's square"; TLDesc[7] = "Flathead screwdrivers screws"; TLDesc[8] = "Phillips screwdriver screws"; TLDesc[9] = "Icepicks pokey little"; TLDesc[10] = "Utility utilities"; TLDesc[11] = "Deburring tool "; TLDesc[12] = "Paper rulers measures"; TLDesc[13] = "Loctites lock tight"; TLDesc[14] = "Bent Needlenoses (Red & Black, orange)"; TLDesc[15] = "Wire Crushers (orange)"; TLDesc[16] = "Needlenoses (orange)"; TLDesc[17] = "Drills Bits rows thing"; TLDesc[18] = "Big Needlenoses (Grey)"; TLDesc[19] = "Boxes Cutters scissors knife knives"; TLDesc[20] = "Wires Strippers/Crimpers"; TLDesc[21] = "Snub-Noses Pliers snubs noses"; TLDesc[22] = "Needlenoses (green)"; TLDesc[23] = "Stab-Stab stabs stab"; TLDesc[24] = "Chains Breakers"; TLDesc[25] = "SAE Bits Rows"; TLDesc[26] = "Snub-Nose Pliers (orange, black-red)"; TLDesc[27] = "SAE Hex Keys x2"; TLDesc[28] = "Wires Strippers"; TLDesc[29] = "Snips"; TLDesc[30] = "Blue Vise Grips"; TLDesc[31] = "Mallets hammers"; TLDesc[32] = "Tiny snips"; TLDesc[33] = "Hammers"; TLDesc[34] = "Rulers measures"; TLDesc[35] = "Measuring Tape"; TLDesc[36] = "Robo-Grips"; TLDesc[37] = "Tiny Tape Measures rulers"; TLDesc[38] = "Aviation Snips"; TLDesc[39] = "Wago tools screwdrivers"; TLDesc[40] = "Scissors"; } public static void loadTADesc() { TADesc[0] = "Rivets Boxes"; TADesc[1] = "Pneumatics Hardware Boxes"; TADesc[2] = "Zip Tie Boxes ziptie zipties"; TADesc[3] = "Encoders"; TADesc[4] = "Pressure Tapes"; TADesc[5] = "Hack Saws"; TADesc[6] = "PWM Crimp Tools"; TADesc[7] = "Pneumatic Wheels"; TADesc[8] = "Greases"; TADesc[9] = "craftsman drill bits sets"; TADesc[10] = "rivet guns"; TADesc[11] = "Tape Boxes"; TADesc[12] = "Gorilla Tapes"; TADesc[13] = "Clear Packing tapes"; TADesc[14] = "Electrical Tapes, Red"; TADesc[15] = "Electrical Tapes, Black"; TADesc[16] = "Painter's Tapes, Blue"; TADesc[17] = "Crazy glues"; TADesc[18] = "Black Rachets Sets"; TADesc[19] = "Drills + chargers"; } public static void loadTBDesc() { TBDesc[0] = "Polycords Boxes (+treads, radios, cameras)"; TBDesc[1] = "Solder Boxes (+chains)"; TBDesc[2] = "Vex Pro Boxes (versas/ringlights/victors) vexpros"; TBDesc[3] = "SAE Tap Sets"; TBDesc[4] = "Spacer Boxes"; TBDesc[5] = "Warrior Sets"; TBDesc[6] = "Box End Rachets"; TBDesc[7] = "Compressed Air compress"; TBDesc[8] = "Tap Fluids liquids"; TBDesc[9] = "Calipers"; TBDesc[10] = "Blue Rachets Sets"; } public static void loadTCDesc() { TCDesc[0] = "Hardstops (orange)"; TCDesc[1] = "Gears Stuff Boxes"; TCDesc[2] = "Mcmaster boxes"; TCDesc[3] = "Red Battery batteries Wires electric cables cords"; TCDesc[4] = "Black Battery Wires batteries electric cables cords"; TCDesc[5] = "Pickup hardware bags(small)"; TCDesc[6] = "Wires cables electric cords boxes "; TCDesc[7] = "Victors motors"; TCDesc[8] = "Pneumatics Tubing Bags"; TCDesc[9] = "Versas"; TCDesc[10] = "Long Pistons pneumatics"; TCDesc[11] = "Air Tanks pneumatics"; TCDesc[12] = "Random Sheets Metal scrap"; TCDesc[13] = "Sponsor panels"; TCDesc[14] = "Breakers electric"; TCDesc[15] = "Pneumatics Tubing Blue and Orange"; TCDesc[16] = "Optical Sensors"; TCDesc[17] = "Pickup hardware bags(big)"; } public static void loadTDDesc() { TDDesc[0] = "Pit Bags"; TDDesc[1] = "White Boards"; TDDesc[2] = "Staples Bags"; TDDesc[3] = "Staples Guns"; TDDesc[4] = "Paint brushes+paint"; TDDesc[5] = "Red Fabrics"; TDDesc[6] = "Blue Fabrics"; TDDesc[7] = "Bumpers Bolts + Nuts Bags"; TDDesc[8] = "Standards flags"; TDDesc[9] = "Power Strips electric"; TDDesc[10] = "Extension cords power"; TDDesc[11] = "Multimeters"; TDDesc[12] = "vise bits"; TDDesc[13] = "Radio power cords cables wires"; TDDesc[14] = "Ethernet cables wires"; TDDesc[15] = "Balls"; TDDesc[16] = "Crowbars"; TDDesc[17] = "CDesc Screws(box)"; TDDesc[18] = "Pool noodles"; TDDesc[19] = "1x1 tubing"; TDDesc[20] = "Gorilla Tape"; TDDesc[21] = "Velcro"; TDDesc[22] = "Pneumatics plates"; TDDesc[23] = "2 CIMs Boxes"; TDDesc[24] = "4 Dry Erase Markers"; } public static void loadTEDesc() { TEDesc[0] = "Chain Boxes"; TEDesc[1] = "Plates Stuff Boxes"; TEDesc[2] = "Clear Screw Boxes"; TEDesc[3] = "Mantis hardware bags"; TEDesc[4] = "Crappy Drills Bits Sets"; TEDesc[5] = "Electrical Stuff boxes"; TEDesc[6] = "Anderson Boxes"; TEDesc[7] = "Rags Bags"; } public static void loadCDesc() { CDesc[0] = "long hex stocks (3)"; CDesc[1] = "standard stands"; CDesc[2] = "vises"; CDesc[3] = "tarps"; CDesc[4] = "white shelves"; CDesc[5] = "EZ Ups"; CDesc[6] = "robots"; CDesc[7] = "Bumpers"; CDesc[8] = "banners"; CDesc[9] = "Blue Banners chairmans"; CDesc[10] = "sheets metal"; CDesc[11] = "big shelves"; CDesc[12] = "Shop vacs"; CDesc[13] = "push carts (1)"; CDesc[14] = "Orange Safety Kits"; CDesc[15] = "knee pads"; } public static int ToolBoxCB(String item) { int loc = 0; for( int f=0; f<41; f++ ) { if( item.equals(ToolBox[f][0].toLowerCase()) ) { loc = f; break; } } return loc; } public static int ToteACB(String item) { int loc = 0; for( int f=0; f<20; f++ ) { if( item.equals(ToteA[f][0].toLowerCase()) ) { loc = f; break; } } return loc; } public static int ToteBCB(String item) { int loc = 0; for( int f=0; f<11; f++ ) { if( item.equals(ToteB[f][0].toLowerCase()) ) { loc = f; break; } } return loc; } public static int ToteCCB(String item) { int loc = 0; for( int f=0; f<18; f++ ) { if( item.equals(ToteC[f][0].toLowerCase()) ) { loc = f; break; } } return loc; } public static int ToteDCB(String item) { int loc = 0; for( int f=0; f<25; f++ ) { if( item.equals(ToteD[f][0].toLowerCase()) ) { loc = f; break; } } return loc; } public static int ToteECB(String item) { int loc = 0; for( int f=0; f<8; f++ ) { if( item.equals(ToteE[f][0].toLowerCase()) ) { loc = f; break; } } return loc; } public static int CrateCB(String item) { int loc = 0; for( int f=0; f<16; f++ ) { if( item.equals(Crate[f][0].toLowerCase()) ) { loc = f; break; } } return loc; } public static void listToolBox() { System.out.println("The Toolbox contains the following:"); for( int f=0; f<41; f++ ) { if( ToolBox[f][1] == "0" ) { System.out.println(ToolBox[f][0]); } if( ToolBox[f][1] != "0" ) { System.out.println("The " + ToolBox[f][0] + " was lent to team " + ToolBox[f][1] + "."); } } System.out.println(); } public static void listToteA() { System.out.println("Tote A contains the following:"); for( int f=0; f<20; f++ ) { if( ToteA[f][1] == "0" ) { System.out.println(ToteA[f][0]); } if( ToteA[f][1] != "0" ) { System.out.println("* The " + ToteA[f][0] + " was lent to team " + ToteA[f][1] + "."); } } System.out.println(); } public static void listToteB() { System.out.println("Tote B contains the following:"); for( int f=0; f<11; f++ ) { if( ToteB[f][1] == "0" ) { System.out.println(ToteB[f][0]); } if( ToteB[f][1] != "0" ) { System.out.println("* The " + ToteB[f][0] + " was lent to team " + ToteB[f][1] + "."); } } System.out.println(); } public static void listToteC() { System.out.println("Tote C contains the following:"); for( int f=0; f<18; f++ ) { if( ToteC[f][1] == "0" ) { System.out.println(ToteC[f][0]); } if( ToteC[f][1] != "0" ) { System.out.println("* The " + ToteC[f][0] + " was lent to team " + ToteC[f][1] + "."); } } System.out.println(); } public static void listToteD() { System.out.println("Tote D contains the following:"); for( int f=0; f<25; f++ ) { if( ToteD[f][1] == "0" ) { System.out.println(ToteD[f][0]); } if( ToteD[f][1] != "0" ) { System.out.println("* The " + ToteD[f][0] + " was lent to team " + ToteD[f][1] + "."); } } System.out.println(); } public static void listToteE() { System.out.println("Tote E contains the following:"); for( int f=0; f<8; f++ ) { if( ToteE[f][1] == "0" ) { System.out.println(ToteE[f][0]); } if( ToteE[f][1] != "0" ) { System.out.println("* The " + ToteE[f][0] + " was lent to team " + ToteE[f][1] + "."); } } System.out.println(); } public static void listCrate() { System.out.println("The Crate contains the following:"); for( int f=0; f<16; f++ ) { if( Crate[f][1] == "0" ) { System.out.println(Crate[f][0]); } if( Crate[f][1] != "0" ) { System.out.println("* The " + Crate[f][0] + " was lent to team " + Crate[f][1] + "."); } } System.out.println(); } public static void shutDown() { write("close"); on = false; } }
package main; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; import java.io.File; import java.time.Instant; import controllers.InitialMenuController; import views.InitialMenuView; import stats.StatUpdateListener; import models.Roster; import interceptor.*; public class MainDriver { final static String statFilepath = "resources/stats/"; final static String rosterFilepath = "resources/Rosters/"; final static File resFolder = new File(statFilepath); public static StatUpdateListener statListener = null; public static Instant lastUpdate; public static void main(String [] args){ lastUpdate = Instant.now(); statListener = setupFileMonitor(resFolder, 2000); statListener.attach(Roster.getInstance(statListener)); ServerReplyInterceptor inter = new LoggingInterceptor(); ServerReplyDispatcher dis = new ServerReplyDispatcher(); dis.register(inter); statListener.registerServerReplyDispatcher(dis); InitialMenuView v = new InitialMenuView(); InitialMenuController con = new InitialMenuController(v); } public static StatUpdateListener setupFileMonitor(File folder, int pollingMsecs){ FileAlterationObserver observer = new FileAlterationObserver(folder); FileAlterationMonitor monitor = new FileAlterationMonitor(pollingMsecs); StatUpdateListener listener = new StatUpdateListener(); observer.addListener(listener); monitor.addObserver(observer); try { monitor.start(); } catch (Exception e) { System.out.println("Unexpected problem with file monitor"); e.printStackTrace(); } return listener; } }
public class IPAddress { private String address; public enum Class { A, B, C, Invalid }; public IPAddress(String input) { address = input; } public String toString() { return address; } public String toBinaryString() { String rv = ""; for(String block: address.split("\\.")) { rv += Integer.toBinaryString(Integer.parseInt(block)); } return rv; } public Class getIPClass() { int first_block = Integer.parseInt(address.split("\\.")[0]); if(first_block >= 0 && first_block <= 127) { return Class.A; } else if(first_block > 127 && first_block <= 191) { return Class.B; } else if(first_block > 191 && first_block <= 223) { return Class.C; } else { return Class.Invalid; } } // Note: I am not sure if this is technically called a net address // but for IP Address : 112.245.182.222 // return value will be : 112.0.0.0 // since it is a class A address public IPAddress getNetAddress() { switch (getIPClass()) { case A: return new IPAddress(String.format("%s.0.0.0", address.substring(0,3))); case B: return new IPAddress(String.format("%s.0.0" , address.substring(0,7))); case C: return new IPAddress(String.format("%s.0" , address.substring(0,15))); } return new IPAddress("0.0.0.0"); } }
package com.i906.mpt.prayer; import android.location.Location; import com.i906.mpt.api.prayer.PrayerCode; import com.i906.mpt.location.LocationRepository; import com.i906.mpt.prefs.HiddenPreferences; import com.i906.mpt.prefs.LocationPreferences; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; import javax.inject.Singleton; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.Subject; import timber.log.Timber; /** * @author Noorzaini Ilhami */ @Singleton public class PrayerManager { private final long mLocationDistanceLimit; private final LocationPreferences mLocationPreferences; private final LocationRepository mLocationRepository; private final PrayerBroadcaster mPrayerBroadcaster; private final PrayerDownloader mPrayerDownloader; private Location mLastLocation; private PrayerCode mLastPreferredLocation; private PrayerContext mLastPrayerContext; private Subject<PrayerContext, PrayerContext> mPrayerStream; private AtomicBoolean mIsLoading = new AtomicBoolean(false); private AtomicBoolean mIsError = new AtomicBoolean(false); @Inject public PrayerManager(PrayerDownloader downloader, LocationRepository location, PrayerBroadcaster broadcaster, HiddenPreferences hprefs, LocationPreferences lprefs) { mLocationPreferences = lprefs; mLocationRepository = location; mPrayerBroadcaster = broadcaster; mPrayerDownloader = downloader; mLocationDistanceLimit = hprefs.getLocationDistanceLimit(); } public Observable<PrayerContext> getPrayerContext(final boolean refresh) { checkPrayerStream(); if (isLoading() && !refresh) { return mPrayerStream.asObservable(); } Observable<PrayerContext> data; if (!useAutomaticLocation()) { data = getPreferredPrayerContext(refresh); } else { data = getAutomaticPrayerContext(refresh); } data.subscribe(new Action1<PrayerContext>() { @Override public void call(PrayerContext prayer) { mIsError.set(false); mPrayerStream.onNext(prayer); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { mIsError.set(true); mPrayerStream.onError(throwable); } }); return mPrayerStream.asObservable(); } private Observable<PrayerContext> getAutomaticPrayerContext(boolean refresh) { return mLocationRepository.getLocation(refresh) .doOnSubscribe(new Action0() { @Override public void call() { mIsError.set(false); } }) .subscribeOn(Schedulers.io()) .flatMap(new Func1<Location, Observable<PrayerContext>>() { @Override public Observable<PrayerContext> call(Location location) { mLastLocation = location; if (shouldUpdatePrayerContext(location) && !isLoading()) { return updatePrayerContext(location); } if (mLastPrayerContext != null) { return Observable.just(mLastPrayerContext); } else { return mPrayerStream.asObservable() .first(); } } }); } private Observable<PrayerContext> getPreferredPrayerContext(boolean refresh) { final PrayerCode location = mLocationPreferences.getPreferredLocation(); if (location == null) { return getAutomaticPrayerContext(refresh); } return Observable.just(location.getCode()) .doOnSubscribe(new Action0() { @Override public void call() { mIsError.set(false); } }) .flatMap(new Func1<String, Observable<PrayerContext>>() { @Override public Observable<PrayerContext> call(String code) { if (shouldUpdatePrayerContext(code) && !isLoading()) { mLastPreferredLocation = location; return updatePrayerContext(code); } if (mLastPrayerContext != null) { return Observable.just(mLastPrayerContext); } else { return mPrayerStream.asObservable() .first(); } } }); } private boolean useAutomaticLocation() { return mLocationPreferences.isUsingAutomaticLocation() || !mLocationPreferences.hasPreferredLocation(); } private void checkPrayerStream() { if (mPrayerStream == null || hasError() && !isLoading()) { mPrayerStream = BehaviorSubject.create(); } } private void broadcastPrayerContext(PrayerContext context) { Timber.i("Broadcasting updated prayer context"); mPrayerStream.onNext(context); mPrayerBroadcaster.sendPrayerUpdatedBroadcast(); } private boolean shouldUpdatePrayerContext(String code) { if (mLastPrayerContext == null) { return true; } if (mLastPreferredLocation != null) { if (!mLastPreferredLocation.getCode().equals(code)) { return true; } } return false; } private boolean shouldUpdatePrayerContext(Location location) { if (mLastPrayerContext == null) { return true; } return shouldUpdateLocation(location); } private boolean shouldUpdateLocation(Location location) { float distance = LocationRepository.getDistance(mLastLocation, location); return distance >= mLocationDistanceLimit; } public Observable<PrayerContext> refreshPrayerContext(Location location) { checkPrayerStream(); if (shouldUpdateLocation(location) && !isLoading()) { mLastLocation = location; updatePrayerContext(location) .subscribe(new Action1<PrayerContext>() { @Override public void call(PrayerContext context) { } }, new Action1<Throwable>() { @Override public void call(Throwable e) { } }); } return mPrayerStream.asObservable(); } private Observable<PrayerContext> updatePrayerContext(String code) { Timber.i("Updating preferred prayer context"); return mPrayerDownloader.getPrayerTimes(code) .doOnNext(new Action1<PrayerContext>() { @Override public void call(PrayerContext prayerContext) { mLastPrayerContext = prayerContext; broadcastPrayerContext(prayerContext); } }) .doOnSubscribe(new Action0() { @Override public void call() { mIsLoading.set(true); } }) .doOnTerminate(new Action0() { @Override public void call() { mIsLoading.set(false); } }); } private Observable<PrayerContext> updatePrayerContext(Location location) { Timber.i("Updating prayer context"); return mPrayerDownloader.getPrayerTimes(location) .doOnNext(new Action1<PrayerContext>() { @Override public void call(PrayerContext prayerContext) { mLastPrayerContext = prayerContext; broadcastPrayerContext(prayerContext); } }) .doOnSubscribe(new Action0() { @Override public void call() { mIsLoading.set(true); } }) .doOnTerminate(new Action0() { @Override public void call() { mIsLoading.set(false); } }); } public void notifyPreferenceChanged() { mLastPrayerContext = null; } public boolean hasError() { return mIsError.get(); } public boolean isLoading() { return mIsLoading.get(); } }
package com.liuhc.tools.demo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.liuhc.tools.DateFormatHelper; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String date = DateFormatHelper.getCurrentTime(DateFormatHelper.FORMAT_SECOND); // Toast.makeText(this, date, Toast.LENGTH_SHORT).show(); } }
package com.mikepenz.unsplash.views; import android.animation.ArgbEvaluator; import android.animation.FloatEvaluator; import android.animation.ObjectAnimator; import android.os.Build; import android.view.View; import android.view.ViewPropertyAnimator; import android.view.animation.PathInterpolator; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; @SuppressWarnings("UnnecessaryLocalVariable") public class Utils { public final static int COLOR_ANIMATION_DURATION = 1000; public final static int DEFAULT_DELAY = 0; public static void animateViewColor(View v, int startColor, int endColor) { ObjectAnimator animator = ObjectAnimator.ofObject(v, "backgroundColor", new ArgbEvaluator(), startColor, endColor); if (Build.VERSION.SDK_INT >= 21) { animator.setInterpolator(new PathInterpolator(0.4f, 0f, 1f, 1f)); } animator.setDuration(COLOR_ANIMATION_DURATION); animator.start(); } public static void animateViewElevation(View v, float start, float end) { if (Build.VERSION.SDK_INT >= 21) { ObjectAnimator animator = ObjectAnimator.ofObject(v, "elevation", new FloatEvaluator(), start, end); animator.setDuration(500); animator.start(); } } public static void configuredHideYView(View v) { v.setScaleY(0); v.setPivotY(0); } public static ViewPropertyAnimator hideViewByScaleXY(View v) { return hideViewByScale(v, DEFAULT_DELAY, 0, 0); } public static ViewPropertyAnimator hideViewByScaleY(View v) { return hideViewByScale(v, DEFAULT_DELAY, 1, 0); } public static ViewPropertyAnimator hideViewByScalyInX(View v) { return hideViewByScale(v, DEFAULT_DELAY, 0, 1); } private static ViewPropertyAnimator hideViewByScale(View v, int delay, int x, int y) { ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(delay) .scaleX(x).scaleY(y); return propertyAnimator; } public static ViewPropertyAnimator showViewByScale(View v) { ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(DEFAULT_DELAY) .scaleX(1).scaleY(1); return propertyAnimator; } public static void copyInputStreamToFile(InputStream in, File file) { try { OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } }
package com.smvit.glugmvit; import android.animation.ObjectAnimator; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; public class Tab_fragment_1 extends Fragment { ImageView show,hide; TextView desctext,title_members,members; Button contribute; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frag_0_tab_1, container, false); contribute = (Button) view.findViewById(R.id.contribute); show = (ImageView) view.findViewById(R.id.show); hide = (ImageView) view.findViewById(R.id.hide); desctext=(TextView) view.findViewById(R.id.project_description); title_members=(TextView) view.findViewById(R.id.title_members); members=(TextView) view.findViewById(R.id.members); show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { show.setVisibility(View.INVISIBLE); hide.setVisibility(View.VISIBLE); desctext.setMaxLines(Integer.MAX_VALUE); title_members.setMaxLines(Integer.MAX_VALUE); members.setMaxLines(Integer.MAX_VALUE); } }); hide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hide.setVisibility(View.INVISIBLE); show.setVisibility(View.VISIBLE); desctext.setMaxLines(0); title_members.setMaxLines(0); members.setMaxLines(0); } }); contribute.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*link to login page and ask for sign up if alredy signed in, email the user information to glug mvit organization */ } }); return view; } }
package derpibooru.derpy.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import butterknife.Bind; import butterknife.ButterKnife; import derpibooru.derpy.R; import derpibooru.derpy.data.server.DerpibooruImageDetailed; import derpibooru.derpy.data.server.DerpibooruImageThumb; import derpibooru.derpy.data.server.DerpibooruUser; import derpibooru.derpy.server.QueryHandler; import derpibooru.derpy.server.providers.ImageDetailedProvider; import derpibooru.derpy.ui.fragments.ImageActivityMainFragment; import derpibooru.derpy.ui.fragments.ImageActivityTagFragment; import derpibooru.derpy.ui.fragments.ImageListFragment; public class ImageActivity extends AppCompatActivity { public static final String EXTRAS_TAG_SEARCH_QUERY = "derpibooru.derpy.SearchTagName"; public static final String EXTRAS_IMAGE_DETAILED = "derpibooru.derpy.ImageDetailed"; public static final String EXTRAS_IMAGE_ID = "derpibooru.derpy.ImageId"; @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.toolbarLayout) View toolbarLayout; @Bind(R.id.fragmentLayout) FrameLayout contentLayout; private DerpibooruImageDetailed mImage; @Override protected void onCreate(Bundle savedInstanceState) throws IllegalStateException { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image); ButterKnife.bind(this); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); setFragmentCallbackHandlers(getCurrentFragment()); if ((savedInstanceState != null) && (savedInstanceState.containsKey(EXTRAS_IMAGE_DETAILED))) { mImage = savedInstanceState.getParcelable(EXTRAS_IMAGE_DETAILED); if (getCurrentFragment() instanceof ImageActivityMainFragment) { forceMainFragmentToDisplayDetailedImage(getCurrentFragment()); } } else if (getIntent().hasExtra(EXTRAS_IMAGE_ID)) { fetchDetailedInformation(getIntent().getIntExtra(EXTRAS_IMAGE_ID, 0)); } else if (getIntent().hasExtra(ImageListFragment.EXTRAS_IMAGE_THUMB)) { DerpibooruImageThumb thumb = getIntent().getParcelableExtra(ImageListFragment.EXTRAS_IMAGE_THUMB); displayMainFragment(thumb); fetchDetailedInformation(thumb.getId()); } } private void setFragmentCallbackHandlers(Fragment target) { if (target instanceof ImageActivityMainFragment) { ((ImageActivityMainFragment) target) .setActivityCallbacks(new MainFragmentCallbackHandler()); } else if (target instanceof ImageActivityTagFragment) { ((ImageActivityTagFragment) target) .setActivityCallbacks(new TagFragmentCallbackHandler()); } } /** * If {@link ImageActivityMainFragment} has not created its view yet, it is forced to * skip the placeholder thumb and call {@link ImageActivityMainFragment.ImageActivityMainFragmentHandler#getImage()}. */ private void forceMainFragmentToDisplayDetailedImage(Fragment mainFragment) { mainFragment.getArguments().remove(ImageListFragment.EXTRAS_IMAGE_THUMB); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); if (mImage != null) { savedInstanceState.putParcelable(EXTRAS_IMAGE_DETAILED, mImage); } } @Override public void onBackPressed() { if (getSupportFragmentManager().getBackStackEntryCount() > 0) { for (Fragment fragment : getSupportFragmentManager().getFragments()) { setFragmentCallbackHandlers(fragment); } } if (!getSupportFragmentManager().popBackStackImmediate()) { setActivityResult(); super.onBackPressed(); } else if ((getCurrentFragment() instanceof ImageActivityMainFragment) && (mImage != null)) { ((ImageActivityMainFragment) getCurrentFragment()).resetView(); ((ImageActivityMainFragment) getCurrentFragment()).onDetailedImageFetched(); } } private void setActivityResult() { setResult(RESULT_OK, getActivityResultIntent()); } private void setActivityResult(String tagSearch) { Intent intent = getActivityResultIntent(); intent.putExtra(EXTRAS_TAG_SEARCH_QUERY, tagSearch); setResult(RESULT_OK, intent); } private Intent getActivityResultIntent() { Intent intent = new Intent(); if (mImage != null) { intent.putExtra(ImageListFragment.EXTRAS_IMAGE_THUMB, mImage.getThumb()); } return intent; } private void fetchDetailedInformation(int imageId) { ImageDetailedProvider provider = new ImageDetailedProvider( this, new QueryHandler<DerpibooruImageDetailed>() { @Override public void onQueryExecuted(DerpibooruImageDetailed info) { mImage = info; displayMainFragment(null); } @Override public void onQueryFailed() { /* TODO: handle failed request */ } }); provider.id(imageId).fetch(); } private void displayMainFragment(@Nullable DerpibooruImageThumb placeholderThumb) { if (placeholderThumb != null) { initializeMainFragmentWithPlaceholderThumb(placeholderThumb); } else if (getCurrentFragment() instanceof ImageActivityMainFragment) { /* the main fragment has already been instantiated with a placeholder thumb */ ((ImageActivityMainFragment) getCurrentFragment()) .onDetailedImageFetched(); } else { initializeMainFragmentWithDetailed(); } } private void initializeMainFragmentWithDetailed() { if (getCurrentFragment() instanceof ImageActivityMainFragment) { setFragmentCallbackHandlers(getCurrentFragment()); forceMainFragmentToDisplayDetailedImage(getCurrentFragment()); } else { instantiateMainFragment(null); } } private void initializeMainFragmentWithPlaceholderThumb(DerpibooruImageThumb thumb) { if (!(getCurrentFragment() instanceof ImageActivityMainFragment)) { instantiateMainFragment(thumb); } } private void instantiateMainFragment(@Nullable DerpibooruImageThumb placeholderThumb) { ImageActivityMainFragment mainFragment = new ImageActivityMainFragment(); mainFragment.setActivityCallbacks(new MainFragmentCallbackHandler()); mainFragment.setArguments(getMainFragmentArguments(placeholderThumb)); safelyCommitFragmentTransaction( getSupportFragmentManager() .beginTransaction() .replace(contentLayout.getId(), mainFragment)); } private Bundle getMainFragmentArguments(@Nullable DerpibooruImageThumb thumb) { boolean isUserLoggedIn = ((DerpibooruUser) getIntent().getParcelableExtra(MainActivity.EXTRAS_USER)).isLoggedIn(); Bundle args = new Bundle(); args.putBoolean(ImageActivityMainFragment.EXTRAS_IS_USER_LOGGED_IN, isUserLoggedIn); if (thumb != null) { args.putParcelable(ImageListFragment.EXTRAS_IMAGE_THUMB, thumb); } return args; } @Nullable protected Fragment getCurrentFragment() { return getSupportFragmentManager().findFragmentById(contentLayout.getId()); } private void displayTagFragment(int tagId) { Bundle args = new Bundle(); args.putInt(ImageActivityTagFragment.EXTRAS_TAG_ID, tagId); ImageActivityTagFragment fragment = new ImageActivityTagFragment(); fragment.setActivityCallbacks(new TagFragmentCallbackHandler()); fragment.setArguments(args); safelyCommitFragmentTransaction( getSupportFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.image_activity_tag_enter, R.anim.image_activity_tag_exit, R.anim.image_activity_tag_back_stack_pop_enter, R.anim.image_activity_tag_back_stack_pop_exit) .addToBackStack(null) .replace(contentLayout.getId(), fragment)); } private int safelyCommitFragmentTransaction(FragmentTransaction transaction) { try { return transaction.commit(); } catch (IllegalStateException e) { Log.e("ImageActivity", "safelyCommitFragmentTransaction: failed to commit transaction", e); return -1; } } private class MainFragmentCallbackHandler implements ImageActivityMainFragment.ImageActivityMainFragmentHandler { @Override public boolean isToolbarVisible() { return toolbarLayout.getVisibility() == View.VISIBLE; } @Override public void setToolbarVisible(boolean visible) { toolbarLayout.setVisibility(visible ? View.VISIBLE : View.GONE); } @Override public DerpibooruImageDetailed getImage() { return mImage; } @Override public void setToolbarTitle(String title) { toolbar.setTitle(title); } @Override public void openTagInformation(int tagId) { displayTagFragment(tagId); } } private class TagFragmentCallbackHandler implements ImageActivityTagFragment.ImageActivityTagFragmentHandler { @Override public void onTagSearchRequested(String tagName) { setActivityResult(tagName); ImageActivity.super.finish(); } @Override public void setToolbarTitle(String title) { toolbar.setTitle(title); } } }
package pl.beerlurk.beerlurk; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.List; import de.greenrobot.event.EventBus; import pl.beerlurk.beerlurk.dto.DistancedBeerLocation; import pl.beerlurk.beerlurk.service.BeerApi; import pl.beerlurk.beerlurk.service.BeerService; import pl.beerlurk.beerlurk.service.GeocodeApi; import pl.beerlurk.beerlurk.service.MatrixApi; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; public class MainActivity extends AppCompatActivity { public List<DistancedBeerLocation> data; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.main_list); final TextView emptyView = (TextView) findViewById(R.id.empty_view); emptyView.setText("Try to search for something"); listView.setEmptyView(emptyView); EditText editText = (EditText) findViewById(R.id.edit); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { String search = v.getText().toString().trim(); if (search.length() > 0) { v.setHint("Last search: " + search); v.setText(null); emptyView.setText("Searching..."); doCall(search); return true; } return false; } }); EventBus.getDefault().register(this); } @SuppressWarnings("unused") public void onEvent(ShowOnMapClickEvent event) { Intent intent = new Intent(this, MapActivity.class); intent.putExtra("clicked", event.getDistancedBeerLocation()); intent.putParcelableArrayListExtra("all", new ArrayList<>(data)); startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } private void doCall(String search) { Location myLocation = new Location("my"); myLocation.setLatitude(52.22037939); myLocation.setLongitude(21.0086596); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); RestAdapter googleAdapter = new RestAdapter.Builder() .setEndpoint("https://maps.googleapis.com") .setConverter(new GsonConverter(gson)) .setLogLevel(RestAdapter.LogLevel.FULL) .build(); RestAdapter beerAdapter = new RestAdapter.Builder() .setEndpoint("http://beer-lurk.herokuapp.com") .setConverter(new GsonConverter(gson)) .setLogLevel(RestAdapter.LogLevel.FULL) .build(); MatrixApi matrixApi = googleAdapter.create(MatrixApi.class); GeocodeApi geocodeApi = googleAdapter.create(GeocodeApi.class); BeerApi beerApi = beerAdapter.create(BeerApi.class); new BeerService(beerApi, matrixApi, geocodeApi) .call(search, myLocation) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<List<DistancedBeerLocation>>() { @Override public void call(List<DistancedBeerLocation> distancedBeerLocations) { Log.e("tag", "count: " + distancedBeerLocations.size()); Log.e("tag", distancedBeerLocations + ""); TextView emptyView = (TextView) findViewById(R.id.empty_view); emptyView.setText("Found nothing."); data = distancedBeerLocations; showList(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Log.e("tag", "error", throwable); TextView emptyView = (TextView) findViewById(R.id.empty_view); emptyView.setText("Search failed."); } }); } private void showList() { ListView listView = (ListView) findViewById(R.id.main_list); listView.setAdapter(new MyAdapter(data)); } }
package com.quartzodev.api; import com.quartzodev.api.interfaces.IQuery; import com.quartzodev.data.Book; import junit.framework.Assert; import org.junit.Ignore; import org.junit.Test; @Ignore public class APIServiceTest { @Test public void shouldFindBookByISBNGoogle() { IQuery query = APIService.getInstance().getService(APIService.GOOGLE); Book book = query.getBookByISBN("9781133709077"); Assert.assertNotNull(book); book = query.getBookByISBN("1133709079-"); Assert.assertNull(book); } @Test public void shouldFindBookByISBNGoodreads() { IQuery query = APIService.getInstance().getService(APIService.GOODREADS); Book book = query.getBookByISBN("0061964360"); Assert.assertNotNull(book); book = query.getBookByISBN("1133709079-"); Assert.assertNull(book); } }
/* * BeamPositionFace.java * */ package xal.app.rtbtwizard; import xal.extension.widgets.swing.*; import xal.tools.apputils.EdgeLayout; import xal.tools.messaging.*; import xal.ca.*; import xal.tools.data.*; import java.text.NumberFormat; import java.util.*; import java.io.*; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import xal.extension.smf.application.*; import xal.smf.data.*; import xal.smf.*; import xal.smf.impl.*; import xal.smf.proxy.ElectromagnetPropertyAccessor; import xal.model.*; import xal.model.alg.*; import xal.sim.scenario.*; import xal.model.probe.*; import xal.model.probe.traj.*; import xal.model.xml.*; //import xal.tools.optimizer.*; import xal.tools.beam.Twiss; import xal.extension.widgets.plot.*; import java.text.NumberFormat; import xal.extension.widgets.swing.DecimalField; import xal.tools.apputils.EdgeLayout; import xal.tools.data.*; import xal.tools.xml.XmlDataAdaptor; import xal.tools.beam.*; import java.text.DecimalFormat; import xal.extension.solver.*; //import xal.tools.formula.*; import xal.extension.solver.hint.*; import xal.extension.solver.algorithm.*; import xal.extension.solver.market.*; import xal.extension.solver.solutionjudge.*; import xal.service.pvlogger.sim.PVLoggerDataSource; import xal.extension.widgets.apputils.SimpleProbeEditor; /** * Performs matching to find steerer strengths for desired injection * spot position and angle on the foil. * @author cp3 */ public class BeamSizeFace extends JPanel{ /** ID for serializable version */ private static final long serialVersionUID = 1L; private AcceleratorSeq seq; private Scenario scenario; private EnvelopeProbe probe; private JButton probeeditbutton; private Accelerator accl = new Accelerator(); private DecimalField[] xdat = new DecimalField[5]; private DecimalField[] ydat = new DecimalField[5]; private NumberFormat numFor; private JPanel resultsPanel; private JPanel initPanel; private FunctionGraphsJPanel plotpanel; private JButton solvebutton; private JButton sendtoharpbutton; public JPanel mainPanel; public JTable resultstable; public JTable twisstable; JButton loadbutton; JScrollPane resultsscrollpane; ResultsTableModel resultstablemodel; JScrollPane twissscrollpane; ResultsTableModel twisstablemodel; EdgeLayout layout = new EdgeLayout(); JLabel ws21label = new JLabel("WS20: "); JLabel ws22label = new JLabel("WS21: "); JLabel ws23label = new JLabel("WS23: "); JLabel ws24label = new JLabel("WS24: "); JLabel harplabel = new JLabel("Harp:"); JLabel devicelabel = new JLabel("Device"); JLabel xlabel = new JLabel("X (mm) "); JLabel ylabel = new JLabel("Y (mm) "); JLabel uselabel = new JLabel("Use"); JLabel twisstablelabel = new JLabel("Twiss Matching Results at First Wirescanner"); JLabel resultstablelabel = new JLabel("Beam Size Results"); JCheckBox ws21box = new JCheckBox(); JCheckBox ws22box = new JCheckBox(); JCheckBox ws23box = new JCheckBox(); JCheckBox ws24box = new JCheckBox(); JCheckBox harpbox = new JCheckBox(); Object[][] tabledata = new Object[8][3]; Object[][] twissdata = new Object[3][3]; GridLimits limits = new GridLimits(); //ArrayList xsigmas = new ArrayList(); //ArrayList ysigmas = new ArrayList(); ArrayList<Object> xdatalist = new ArrayList<Object>(); ArrayList<Object> ydatalist = new ArrayList<Object>(); ArrayList<String> namelist = new ArrayList<String>(); ArrayList<String> fullnamelist = new ArrayList<String>(); ArrayList<Object> xfulldatalist = new ArrayList<Object>(); ArrayList<Object> yfulldatalist = new ArrayList<Object>(); GenDocument doc; JComboBox<String> syncstate; String latticestate = "Live"; String[] syncstates = {"Model Live Lattice", "Model PV Logger Lattice"}; JTextField pvloggerfield; JTextField solvertimefield; JLabel usepvlabel; JLabel solvertime; Integer pvloggerid = new Integer(0); double alphaz0, betaz0; double currentenergy = 1e9; double currentI = 1.0; double currentcharge = 0.0; double[] currenttwiss = new double[6]; double windowratio = 0.0; double targetratio = 0.0; double harparea=0.0; int istart=0; DataTable fitsdatabase; HashMap<String, Double> beamarearatios = new HashMap<String, Double>(); HashMap<String, Double> beamwindowratios = new HashMap<String, Double>(); public BeamSizeFace(GenDocument aDocument, JPanel mainpanel) { doc=aDocument; setPreferredSize(new Dimension(950,600)); setLayout(layout); init(); setAction(); addcomponents(); } public void addcomponents(){ layout.setConstraints(mainPanel, 0, 0, 0, 0, EdgeLayout.ALL_SIDES, EdgeLayout.GROW_BOTH); this.add(mainPanel); EdgeLayout newlayout = new EdgeLayout(); mainPanel.setLayout(newlayout); GridLayout initgrid = new GridLayout(6, 4); newlayout.setConstraints(syncstate, 17, 20, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(syncstate); newlayout.setConstraints(usepvlabel, 20, 220, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(usepvlabel); newlayout.setConstraints(pvloggerfield, 20, 310, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(pvloggerfield); initPanel.setLayout(initgrid); initPanel.add(devicelabel); initPanel.add(xlabel); initPanel.add(ylabel); initPanel.add(uselabel); initPanel.add(ws21label); initPanel.add(xdat[0]); initPanel.add(ydat[0]); initPanel.add(ws21box); initPanel.add(ws22label); initPanel.add(xdat[1]); initPanel.add(ydat[1]); initPanel.add(ws22box); initPanel.add(ws23label); initPanel.add(xdat[2]); initPanel.add(ydat[2]); initPanel.add(ws23box); initPanel.add(ws24label); initPanel.add(xdat[3]); initPanel.add(ydat[3]); initPanel.add(ws24box); initPanel.add(harplabel); initPanel.add(xdat[4]); initPanel.add(ydat[4]); initPanel.add(harpbox); newlayout.setConstraints(initPanel, 60, 50, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(initPanel); //GridLayout resultsgrid = new GridLayout(1, 2); //resultsPanel.setLayout(resultsgrid); resultsPanel.add(twisstablelabel); resultsPanel.add(twissscrollpane); resultsPanel.add(resultstablelabel); resultsPanel.add(resultsscrollpane); newlayout.setConstraints(resultsPanel, 0, 470, 200, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(resultsPanel); newlayout.setConstraints(solvertime, 195, 10, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(solvertime); newlayout.setConstraints(solvertimefield, 215, 10, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(solvertimefield); newlayout.setConstraints(probeeditbutton, 205, 150, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(probeeditbutton); newlayout.setConstraints(loadbutton, 105, 335, 150, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(loadbutton); newlayout.setConstraints(solvebutton, 205, 335, 150, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(solvebutton); newlayout.setConstraints(sendtoharpbutton, 305, 590, 150, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(sendtoharpbutton); newlayout.setConstraints(plotpanel, 370, 50, 100, 10, EdgeLayout.LEFT, EdgeLayout.NO_GROWTH); mainPanel.add(plotpanel); } public void init(){ mainPanel = new JPanel(); mainPanel.setPreferredSize(new Dimension(950,600)); resultsPanel = new JPanel(); resultsPanel.setPreferredSize(new Dimension(400,300)); resultsPanel.setBorder(BorderFactory.createTitledBorder("Results")); initPanel = new JPanel(); initPanel.setPreferredSize(new Dimension(280,110)); initPanel.setBorder(BorderFactory.createTitledBorder("Measured RMS Values")); plotpanel = new FunctionGraphsJPanel(); plotpanel.setPreferredSize(new Dimension(800, 230)); plotpanel.setGraphBackGroundColor(Color.WHITE); solvebutton = new JButton("Solve"); sendtoharpbutton = new JButton("Send Results to Harp"); loadbutton = new JButton("Load Fits"); numFor = NumberFormat.getNumberInstance(); numFor.setMinimumFractionDigits(4); accl = doc.getAccelerator(); seq=accl.getSequence("RTBT2"); ws21box.setSelected(true); ws22box.setSelected(true); ws23box.setSelected(true); ws24box.setSelected(true); harpbox.setSelected(true); for(int i = 0; i<5; i++){ xdat[i] = new DecimalField(0.0, 4, numFor); ydat[i] = new DecimalField(0.0, 4, numFor); } usepvlabel = new JLabel("PV Logger ID: "); pvloggerfield = new JTextField(8); solvertime = new JLabel("Solver time (s): "); solvertimefield = new JTextField(8); solvertimefield.setText("60"); syncstate = new JComboBox<String>(syncstates); probeeditbutton = new JButton("Edit Model Probe"); //Set up a few model items IAlgorithm etracker = null; try { etracker = AlgorithmFactory.createEnvTrackerAdapt (seq); } catch ( InstantiationException exception ) { System.err.println( "Instantiation exception creating tracker." ); exception.printStackTrace(); } try { probe=ProbeFactory.getEnvelopeProbe(seq, etracker); currentenergy = probe.getKineticEnergy(); currentI = probe.getBeamCurrent(); //currentcharge = probe.getBeamCharge(); scenario = Scenario.newScenarioFor(seq); scenario.setProbe(probe); scenario.setSynchronizationMode(Scenario.SYNC_MODE_RF_DESIGN); //scenario.resync(); //scenario.run(); } catch(Exception exception){ exception.printStackTrace(); } makeResultsTable(); tabledata[0][0] = new String("RTBT_Diag:WS20"); tabledata[1][0] = new String("RTBT_Diag:WS21"); tabledata[2][0] = new String("RTBT_Diag:WS23"); tabledata[3][0] = new String("RTBT_Diag:WS24"); tabledata[4][0] = new String("RTBT_Diag:Harp30"); tabledata[5][0] = new String("Window"); tabledata[6][0] = new String("Target"); tabledata[7][0] = new String("Target (with scattering)"); resultstablemodel.setTableData(tabledata); makeTwissTable(); twisstablemodel.setValueAt(new String("Alpha"),0,0); twisstablemodel.setValueAt(new String("Beta"),1,0); twisstablemodel.setValueAt(new String("Emit"),2,0); fullnamelist.add("RTBT_Diag:WS20"); fullnamelist.add("RTBT_Diag:WS21"); fullnamelist.add("RTBT_Diag:WS23"); fullnamelist.add("RTBT_Diag:WS24"); fullnamelist.add("RTBT_Diag:Harp30"); /* pvloggerfield.setText("2059640"); xdat[0].setValue(25.02); xdat[1].setValue(18); xdat[2].setValue(25.0); xdat[3].setValue(10.1); xdat[4].setValue(38.0); ydat[0].setValue(18.3); ydat[1].setValue(18.3); ydat[2].setValue(10.2); ydat[3].setValue(20.8); ydat[4].setValue(22); */ } public void setAction(){ solvebutton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ solve(); } }); sendtoharpbutton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ sendtoharp(); } }); loadbutton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ loadFits(); } }); syncstate.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { if(syncstate.getSelectedIndex() == 0){ latticestate="Live"; System.out.println("Using live."); } if(syncstate.getSelectedIndex() == 1){ latticestate="PVLogger"; System.out.println("Using PVlogger."); } } }); probeeditbutton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { SimpleProbeEditor spe = new SimpleProbeEditor(doc.myWindow(), scenario.getProbe()); //scenario.resetProbe(); //spe.createSimpleProbeEditor(scenario.getProbe()); // update the model probe with the one from probe editor //if (spe.probeHasChanged()){ scenario.setProbe(spe.getProbe()); currentenergy=probe.getKineticEnergy(); currentI=probe.getBeamCurrent(); //currentcharge=probe.getBeamCharge(); } }); } public void solve() { xfulldatalist.add(xdat[0].getValue()); yfulldatalist.add(ydat[0].getValue()); xfulldatalist.add(xdat[1].getValue()); yfulldatalist.add(ydat[1].getValue()); xfulldatalist.add(xdat[2].getValue()); yfulldatalist.add(ydat[2].getValue()); xfulldatalist.add(xdat[3].getValue()); yfulldatalist.add(ydat[3].getValue()); xfulldatalist.add(xdat[4].getValue()); yfulldatalist.add(ydat[4].getValue()); xdatalist.clear(); ydatalist.clear(); namelist.clear(); //for(int i=0; i<4; i++){ if(ws21box.isSelected() == true){ namelist.add("RTBT_Diag:WS20"); xdatalist.add(xdat[0].getValue()); ydatalist.add(ydat[0].getValue()); } if(ws22box.isSelected() == true){ namelist.add("RTBT_Diag:WS21"); xdatalist.add(xdat[1].getValue()); ydatalist.add(ydat[1].getValue()); } if(ws23box.isSelected() == true){ namelist.add("RTBT_Diag:WS23"); xdatalist.add(xdat[2].getValue()); ydatalist.add(ydat[2].getValue()); } if(ws24box.isSelected() == true){ namelist.add("RTBT_Diag:WS24"); xdatalist.add(xdat[3].getValue()); ydatalist.add(ydat[3].getValue()); } if(harpbox.isSelected() == true){ namelist.add("RTBT_Diag:Harp30"); xdatalist.add(xdat[4].getValue()); ydatalist.add(ydat[4].getValue()); } if(namelist.get(0) == "RTBT_Diag:WS20") istart=0; if(namelist.get(0) == "RTBT_Diag:WS21") istart=1; if(namelist.get(0) == "RTBT_Diag:WS23") istart=2; if(namelist.get(0) == "RTBT_Diag:WS24") istart=3; if(namelist.get(0) == "RTBT_Diag:Harp30") istart=4; System.out.println("Wires in use: " + namelist); try { if(latticestate.equals("Live")){ scenario = Scenario.newScenarioFor(seq); scenario.setProbe(probe); scenario.setSynchronizationMode(Scenario.SYNC_MODE_LIVE); System.out.println("Loading live machine state."); } if(latticestate.equals("PVLogger")){ String id = pvloggerfield.getText(); pvloggerid = new Integer(Integer.parseInt(id)); scenario = Scenario.newScenarioFor(seq); scenario.setProbe(probe); scenario.setSynchronizationMode(Scenario.SYNC_MODE_DESIGN); System.out.println("Loading PVlogger state."); if(pvloggerid !=0){ PVLoggerDataSource plds = new PVLoggerDataSource(pvloggerid.intValue()); scenario = plds.setModelSource(seq, scenario); } else{ System.out.println("No PV Logger ID Found!"); } } scenario.resync(); scenario.run(); } catch(Exception exception){ exception.printStackTrace(); } String time = solvertimefield.getText(); double solvetime= new Double(Double.parseDouble(time)); EnvelopeTrajectory traj= (EnvelopeTrajectory)probe.getTrajectory(); EnvelopeProbeState state = (EnvelopeProbeState)traj.statesForElement(namelist.get(0))[0]; //EnvelopeProbeState state =(EnvelopeProbeState)traj.statesForElement("RTBT_Diag:WS20")[0]; CovarianceMatrix covarianceMatrix = state.getCovarianceMatrix(); Twiss[] twiss = covarianceMatrix.computeTwiss(); // set up some variables to use in the optimization: // initial guesses double alphax0=twiss[0].getAlpha(); //alphax0 = -2.5; double betax0=twiss[0].getBeta(); //betax0 = 21.; double alphay0=twiss[1].getAlpha(); //alphay0 = 1.; double betay0=twiss[1].getBeta(); //betay0 = 9.; alphaz0 = twiss[2].getAlpha(); betaz0 = twiss[2].getBeta(); //double emitx0 = 20.; //double emity0 = 13.; double emitx0 = twiss[0].getEmittance(); double emity0 = twiss[1].getEmittance(); System.out.println("Starting with ax, bx, ex = " + alphax0 + " " + betax0 + " " + emitx0); System.out.println("Starting with ay, by, ey = " + alphay0 + " " + betay0 + " " + emity0); try{ scenario.setStartNode(namelist.get(0)); //scenario.setStartNode("RTBT_Diag:WS20"); } catch(Exception exception){ exception.printStackTrace(); } Twiss xTwiss = new Twiss(alphax0, betax0, emitx0); Twiss yTwiss = new Twiss(alphay0, betay0, emity0); Twiss zTwiss = new Twiss(alphaz0, betaz0, 11.4e-3); Twiss[] tw = new Twiss[3]; tw[0]=xTwiss; tw[1]=yTwiss; tw[2]=zTwiss; resetProbe(); probe.initFromTwiss(tw); //probe.setPosition(seq.getPosition(seq.getNodeWithId("RTBT_Diag:WS20"))); //probe.setPosition(seq.getPosition(seq.getNodeWithId((String)namelist.get(0)))); ArrayList<Variable> variables = new ArrayList<Variable>(); variables.add(new Variable("alphaX",alphax0, -4., 4.0)); variables.add(new Variable("betaX",betax0, 2, 40)); variables.add(new Variable("alphaY", alphay0, -4., 4.0)); variables.add(new Variable("betaY",betay0, 2, 40)); variables.add(new Variable("emitX",emitx0, 1, 40)); variables.add(new Variable("emitY",emity0, 1, 40)); ArrayList<Objective> objectives = new ArrayList<Objective>(); objectives.add(new TargetObjective( "diff", 0.0 ) ); Evaluator1 evaluator = new Evaluator1( objectives, variables ); Problem problem = new Problem( objectives, variables, evaluator ); problem.addHint(new InitialDelta( 0.1 ) ); Stopper maxSolutionStopper = SolveStopperFactory.minMaxTimeSatisfactionStopper( 1, solvetime, 0.999 ); Solver solver = new Solver(new RandomShrinkSearch(), maxSolutionStopper ); solver.solve( problem ); System.out.println("score is " + solver.getScoreBoard()); Trial best = solver.getScoreBoard().getBestSolution(); // rerun with solution to populate results table calcError(variables, best); updateProbe(variables, best); try{ scenario.run(); } catch(Exception exception){ exception.printStackTrace(); } //Print the final results at the desired locations resetTwissTable(variables, best); resetResultsTable(); resetPlot(variables,best); resetInitProbe(namelist.get(0)); } public double calcError(ArrayList<Variable> vars, Trial trial){ updateProbe(vars, trial); try{ scenario.run(); } catch(Exception exception){ exception.printStackTrace(); } Trajectory<EnvelopeProbeState> traj = probe.createTrajectory(); double error = 0.0; int size = namelist.size(); double rx=0; double ry=0; //System.out.println("namelist is " + namelist); //System.out.println("size is " + size); //System.out.println("first is " + namelist.get(0)); for(int i =0; i<size; i++){ String name = namelist.get(i); //EnvelopeProbeState state = (EnvelopeProbeState)traj.statesForElement("RTBT_Diag:WS21")[0]; EnvelopeProbeState state = (EnvelopeProbeState)traj.statesForElement(namelist.get(i))[0]; CovarianceMatrix covarianceMatrix = state.getCovarianceMatrix(); Twiss[] twiss = covarianceMatrix.computeTwiss(); rx = twiss[0].getEnvelopeRadius(); ry = twiss[1].getEnvelopeRadius(); error += Math.pow( (rx*1000. - ((Double)xdatalist.get(i)).doubleValue()), 2.); error += Math.pow( (ry*1000. - ((Double)ydatalist.get(i)).doubleValue()), 2.); //System.out.println(namelist.get(i) + " " + rx*1000 + " " + xdatalist.get(i)); } error = Math.sqrt(error); return error; } void updateProbe(ArrayList<Variable> vars, Trial trial){ double alphax=0.0; double alphay=0.0; double betax=0.0; double betay=0.0; double emitx=0.0; double emity=0.0; probe = (EnvelopeProbe)scenario.getProbe(); resetProbe(); //probe.setPosition(seq.getPosition(seq.getNodeWithId((String)namelist.get(0)))); Iterator<Variable> itr = vars.iterator(); while(itr.hasNext()){ Variable variable = itr.next(); double value = trial.getTrialPoint().getValue(variable); String name = variable.getName(); if(name.equalsIgnoreCase("alphaX")) alphax = value; if(name.equalsIgnoreCase("alphaY")) alphay = value; if(name.equalsIgnoreCase("betaX")) betax = value; if(name.equalsIgnoreCase("betaY")) betay = value; if(name.equalsIgnoreCase("emitY")) emity = value * 1.e-6; if(name.equalsIgnoreCase("emitX")) emitx = value * 1.e-6; } Twiss xTwiss = new Twiss(alphax, betax, emitx); Twiss yTwiss = new Twiss(alphay, betay, emity); Twiss zTwiss = new Twiss(alphaz0,betaz0, 11.4e-3); Twiss[] tw= new Twiss[3]; tw[0]=xTwiss; tw[1]=yTwiss; tw[2]=zTwiss; probe.initFromTwiss(tw); } void resetProbe(){ probe.reset(); //probe.setPosition(seq.getPosition(seq.getNodeWithId("RTBT_Diag:WS20"))); probe.setKineticEnergy(currentenergy); probe.setBeamCurrent(currentI); //probe.setBeamCharge(currentcharge); } void resetInitProbe(String currentElem){ scenario.setStartElementId("Begin_Of_RTBT2"); probe.reset(); probe.setKineticEnergy(currentenergy); probe.setBeamCurrent(currentI); //probe.setBeamCharge(currentcharge); double[] inittwiss = findTwissAtSeqStart(currentElem); Twiss xTwiss = new Twiss(inittwiss[0], inittwiss[1], inittwiss[2]); Twiss yTwiss = new Twiss(inittwiss[3], inittwiss[4], inittwiss[5]); Twiss zTwiss = new Twiss(alphaz0,betaz0, 11.4e-3); Twiss[] tw= new Twiss[3]; tw[0]=xTwiss; tw[1]=yTwiss; tw[2]=zTwiss; probe.reset(); System.out.println("New init Twiss are = " + xTwiss + " " + yTwiss + " " + zTwiss); probe.initFromTwiss(tw); } double[] findTwissAtSeqStart(String currentElem){ double[] twiss = new double[6]; String refStart = new String("Begin_Of_RTBT2"); try{ scenario.run(); } catch(Exception exception){ exception.printStackTrace(); } PhaseMatrix matRef = (probe).stateResponse(currentElem, refStart); //PhaseMatrix matRef = ((EnvelopeProbe)probe).stateResponse(currentElem, "RTBT_Mag:QH20"); double Rs11 = matRef.getElem(0, 0); double Rs12 = matRef.getElem(0, 1); double Rs16 = matRef.getElem(0, 5); double Rs21 = matRef.getElem(1, 0); double Rs22 = matRef.getElem(1, 1); double Rs26 = matRef.getElem(1, 5); double Rs33 = matRef.getElem(2, 2); double Rs34 = matRef.getElem(2, 3); double Rs36 = matRef.getElem(2, 5); double Rs43 = matRef.getElem(3, 2); double Rs44 = matRef.getElem(3, 3); double Rs46 = matRef.getElem(3, 5); double alphax=currenttwiss[0]; double betax=currenttwiss[1]; double alphay=currenttwiss[3]; double betay=currenttwiss[4]; double gammax=(1+(alphax*alphax))/betax; double gammay=(1+(alphay*alphay))/betay; twiss[0] = -1.*Rs11*Rs21*betax + (Rs11*Rs22 + Rs12*Rs21)*alphax-Rs12*Rs22*gammax; twiss[1] = Rs11*Rs11*betax - 2.*Rs11*Rs12*alphax + Rs12*Rs12*gammax; twiss[2] = currenttwiss[2]; twiss[3] = -1.*Rs33*Rs43*betay + (Rs33*Rs44 + Rs34*Rs43)*alphay - Rs34*Rs44*gammay; twiss[4] = Rs33*Rs33*betay - 2.*Rs33*Rs34*alphay + Rs34*Rs34*gammay; twiss[5] = currenttwiss[5]; return twiss; } public void makeResultsTable(){ String[] colnames = {"Location", "X (mm)", "Y (mm)"}; resultstablemodel = new ResultsTableModel(colnames,8); resultstable = new JTable(resultstablemodel); resultstable.getColumnModel().getColumn(0).setMinWidth(141); resultstable.getColumnModel().getColumn(1).setMinWidth(112); resultstable.getColumnModel().getColumn(2).setMinWidth(112); resultstable.setPreferredScrollableViewportSize(resultstable.getPreferredSize()); resultstable.setRowSelectionAllowed(false); resultstable.setColumnSelectionAllowed(false); resultstable.setCellSelectionEnabled(true); resultsscrollpane = new JScrollPane(resultstable,JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); resultsscrollpane.setColumnHeaderView(resultstable.getTableHeader()); resultstable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); resultsscrollpane.setPreferredSize(new Dimension(365, 145)); } public void makeTwissTable(){ String[] colnames = {"Parameter", "Horizontal", "Vertical"}; twisstablemodel = new ResultsTableModel(colnames,4); twisstable = new JTable(twisstablemodel); twisstable.getColumnModel().getColumn(0).setMinWidth(130); twisstable.getColumnModel().getColumn(1).setMinWidth(115); twisstable.getColumnModel().getColumn(2).setMinWidth(115); twisstable.setPreferredScrollableViewportSize(resultstable.getPreferredSize()); twisstable.setRowSelectionAllowed(false); twisstable.setColumnSelectionAllowed(false); twisstable.setCellSelectionEnabled(true); twissscrollpane = new JScrollPane(twisstable,JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); twissscrollpane.setColumnHeaderView(twisstable.getTableHeader()); twisstable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); twissscrollpane.setPreferredSize(new Dimension(360, 64)); } public void resetTwissTable(ArrayList<Variable> vars, Trial trial){ Iterator<Variable> itr = vars.iterator(); while(itr.hasNext()){ Variable variable = itr.next(); double value = trial.getTrialPoint().getValue(variable); System.out.println("value is " + value); String name = variable.getName(); DecimalFormat decfor = new DecimalFormat("###.000"); if(name.equalsIgnoreCase("alphaX")){ twisstablemodel.setValueAt(new Double(decfor.format(value)),0,1); currenttwiss[0]=value; } if(name.equalsIgnoreCase("alphaY")){ twisstablemodel.setValueAt(new Double(decfor.format(value)),0,2); currenttwiss[3]=value; } if(name.equalsIgnoreCase("betaX")){ twisstablemodel.setValueAt(new Double(decfor.format(value)),1,1); currenttwiss[1]=value; } if(name.equalsIgnoreCase("betaY")){ twisstablemodel.setValueAt(new Double(decfor.format(value)),1,2); currenttwiss[4]=value; } if(name.equalsIgnoreCase("emitY")){ twisstablemodel.setValueAt(new Double(decfor.format(value)),2,2); currenttwiss[5]=value; } if(name.equalsIgnoreCase("emitX")){ twisstablemodel.setValueAt(new Double(decfor.format(value)),2,1); currenttwiss[2]=value; } } twisstablemodel.fireTableDataChanged(); } public void resetResultsTable(){ DecimalFormat decfor = new DecimalFormat("###.000"); int size = fullnamelist.size(); EnvelopeTrajectory traj= (EnvelopeTrajectory)probe.getTrajectory(); EnvelopeProbeState newstate; Twiss[] newtwiss; double rx, ry; for(int i = 0; i<istart; i++){ tabledata[i][1] = new Double(0.0); tabledata[i][2] = new Double(0.0); } for(int i = istart; i<size; i++){ newstate = (EnvelopeProbeState)traj.statesForElement(fullnamelist.get(i))[0]; CovarianceMatrix covarianceMatrix = newstate.getCovarianceMatrix(); newtwiss = covarianceMatrix.computeTwiss(); rx = 1000*newtwiss[0].getEnvelopeRadius(); ry = 1000*newtwiss[1].getEnvelopeRadius(); tabledata[i][1] = new Double(decfor.format(rx)); tabledata[i][2] = new Double(decfor.format(ry)); System.out.println("Horizontal Alpha and Beta for " + fullnamelist.get(i) + " is " + newtwiss[0].getAlpha() + " and " + newtwiss[0].getBeta()); System.out.println("Vertical Alpha and Beta for " + fullnamelist.get(i) + " is " + newtwiss[1].getAlpha() + " and " + newtwiss[1].getBeta()); } harparea=((Double)tabledata[4][1]).doubleValue()*((Double)tabledata[4][2]).doubleValue();; newstate = (EnvelopeProbeState)traj.statesForElement("RTBT_Vac:VIW")[0]; CovarianceMatrix covarianceMatrix = newstate.getCovarianceMatrix(); newtwiss = covarianceMatrix.computeTwiss(); rx = 1000*newtwiss[0].getEnvelopeRadius(); ry = 1000*newtwiss[1].getEnvelopeRadius(); tabledata[5][1] = new Double(decfor.format(rx)); tabledata[5][2] = new Double(decfor.format(ry)); newstate = (EnvelopeProbeState)traj.statesForElement("RTBT:Tgt")[0]; covarianceMatrix = newstate.getCovarianceMatrix(); newtwiss = covarianceMatrix.computeTwiss(); rx = 1000*newtwiss[0].getEnvelopeRadius(); ry = 1000*newtwiss[1].getEnvelopeRadius(); tabledata[6][1] = new Double(decfor.format(rx)); tabledata[6][2] = new Double(decfor.format(ry)); double xtargetwin = Math.sqrt(rx*rx + 11.0*11.0); double ytargetwin = Math.sqrt(ry*ry + 11.0*11.0); tabledata[7][1] = new Double(decfor.format(xtargetwin)); tabledata[7][2] = new Double(decfor.format(ytargetwin)); resultstablemodel.setTableData(tabledata); //Build size ratio HashMap int rows = resultstablemodel.getRowCount(); double xwindowvalue = ((Double)tabledata[5][1]).doubleValue(); double ywindowvalue = ((Double)tabledata[5][2]).doubleValue(); double windowarea = xwindowvalue*ywindowvalue; double xtargetvalue = ((Double)tabledata[7][1]).doubleValue(); double ytargetvalue = ((Double)tabledata[7][2]).doubleValue(); double targetarea = xtargetvalue*ytargetvalue; System.out.println("target area is " + targetarea); for(int i=0; i< rows-2; i++){ String label = (String)resultstablemodel.getValueAt(i,0); double xvalue = ((Double)tabledata[i][1]).doubleValue(); double yvalue = ((Double)tabledata[i][2]).doubleValue(); double area = xvalue*yvalue; double tratio = area/targetarea; double wratio = area/windowarea; //System.out.println("for wire " + label); //System.out.println("xvalue, yvalue, area " + xvalue + " " + yvalue + " " + area); //System.out.println("window area = " + windowarea); //System.out.println("target area = " + targetarea); //System.out.println(" and window ratio is " + wratio); //System.out.println(" and target ratio is " + tratio); beamarearatios.put(new String(label), tratio); beamwindowratios.put(new String(label), wratio); } targetratio = harparea/targetarea; windowratio = harparea/windowarea; System.out.println("targetratio= " + targetratio + " windowratio= " + windowratio); doc.beamarearatios=beamarearatios; doc.windowarearatios=beamwindowratios; doc.xsize = ((Double)tabledata[rows-1][1]).doubleValue(); doc.ysize = ((Double)tabledata[rows-1][2]).doubleValue(); } @SuppressWarnings ("unchecked") //had to suppress becayse valueForKey returns object and does not allow for specific casting private void loadFits(){ fitsdatabase = doc.wireresultsdatabase; //ArrayList tabledata = new ArrayList(); if(fitsdatabase.records().size() == 0){ System.out.println("No data available to load!"); } else{ Collection<GenericRecord> records = fitsdatabase.records(); Iterator<GenericRecord> itr = records.iterator(); while(itr.hasNext()){ //tabledata.clear(); GenericRecord record = itr.next(); String wire = (String)record.valueForKey("wire"); String direction = (String)record.valueForKey("direction"); if(wire.equals("RTBT_Diag:WS20")){ if(direction.equals("H")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); xdat[0].setValue(fitparams[4]); } if(direction.equals("V")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); ydat[0].setValue(fitparams[4]); } } if(wire.equals("RTBT_Diag:WS21")){ if(direction.equals("H")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); xdat[1].setValue(fitparams[4]); } if(direction.equals("V")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); ydat[1].setValue(fitparams[4]); } } if(wire.equals("RTBT_Diag:WS23")){ if(direction.equals("H")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); xdat[2].setValue(fitparams[4]); } if(direction.equals("V")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); ydat[2].setValue(fitparams[4]); } } if(wire.equals("RTBT_Diag:WS24")){ if(direction.equals("H")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); xdat[3].setValue(fitparams[4]); } if(direction.equals("V")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); ydat[3].setValue(fitparams[4]); } } if(wire.equals("RTBT_Diag:Harp30")){ if(direction.equals("H")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); xdat[4].setValue(fitparams[4]); } if(direction.equals("V")){ ArrayList<double[]> results = (ArrayList<double[]>)record.valueForKey("data"); double[] fitparams = results.get(0); ydat[4].setValue(fitparams[4]); } } } } } public void sendtoharp(){ System.out.println("Sending targetratio as " + targetratio); System.out.println("Sending windowratio as " + windowratio); Channel windowch; Channel targetch; windowch = ChannelFactory.defaultFactory().getChannel("RTBT_Diag:Harp30:WindowSizeRatio_Set"); targetch = ChannelFactory.defaultFactory().getChannel("RTBT_Diag:Harp30:TargetSizeRatio_Set"); windowch.connectAndWait(); targetch.connectAndWait(); try { windowch.putVal(windowratio); targetch.putVal(targetratio); System.out.println("Sending targetratio as " + targetratio); System.out.println("Sending windowratio as " + windowratio); Channel.flushIO(); } catch (ConnectionException e){ System.err.println("Unable to connect to channel access."); } catch (PutException e){ System.err.println("Unable to set process variables."); } } public void resetPlot(ArrayList<Variable> vars, Trial trial){ plotpanel.removeAllGraphData(); BasicGraphData hgraphdata = new BasicGraphData(); BasicGraphData vgraphdata = new BasicGraphData(); BasicGraphData xgraphdata = new BasicGraphData(); BasicGraphData ygraphdata = new BasicGraphData(); ArrayList<Double> sdata = new ArrayList<Double>(); ArrayList<Double> hdata = new ArrayList<Double>(); ArrayList<Double> vdata = new ArrayList<Double>(); //probe.reset(); resetProbe(); //scenario.setStartElementId("RTBT_Diag:WS20"); scenario.setStartElementId(namelist.get(0)); try{ scenario.resync(); scenario.run(); } catch(Exception exception){ exception.printStackTrace(); } //probe.reset(); Trajectory<EnvelopeProbeState> traj = probe.createTrajectory(); //System.out.println("trajectory is = " + traj); Iterator<EnvelopeProbeState> iterState= traj.stateIterator(); while(iterState.hasNext()){ EnvelopeProbeState state= (EnvelopeProbeState)iterState.next(); sdata.add(state.getPosition()); CovarianceMatrix covarianceMatrix = state.getCovarianceMatrix(); Twiss[] twiss = covarianceMatrix.computeTwiss(); double rx = 1000.0*twiss[0].getEnvelopeRadius(); double ry = 1000.0*twiss[1].getEnvelopeRadius(); hdata.add(rx); vdata.add(ry); } int size = sdata.size() - 1; double[] s = new double[size]; double[] x = new double[size]; double[] y = new double[size]; for(int i=0; i<size; i++){ s[i]=(sdata.get(i)).doubleValue(); x[i]=(hdata.get(i)).doubleValue(); y[i]=(vdata.get(i)).doubleValue(); } hgraphdata.addPoint(s, x); hgraphdata.setDrawPointsOn(false); hgraphdata.setDrawLinesOn(true); hgraphdata.setGraphProperty("Legend", new String("Horizontal")); hgraphdata.setGraphColor(Color.RED); vgraphdata.addPoint(s, y); vgraphdata.setDrawPointsOn(false); vgraphdata.setDrawLinesOn(true); vgraphdata.setGraphProperty("Legend", new String("Vertical")); vgraphdata.setGraphColor(Color.BLUE); //limits.setSmartLimits(); //limits.setXmax(14.0); plotpanel.setExternalGL(limits); plotpanel.addGraphData(hgraphdata); plotpanel.addGraphData(vgraphdata); int datasize = namelist.size(); //int size = namelist.size(); double[] srdata = new double[datasize]; double[] xrdata = new double[datasize]; double[] yrdata = new double[datasize]; //traj= (EnvelopeTrajectory)probe.getTrajectory(); EnvelopeProbeState newstate; Twiss[] newtwiss; double rx, ry; for(int i =0; i<datasize; i++){ newstate = (EnvelopeProbeState)traj.statesForElement(namelist.get(i))[0]; srdata[i]=newstate.getPosition(); xrdata[i]=((Double)xdatalist.get(i)).doubleValue(); yrdata[i]=((Double)ydatalist.get(i)).doubleValue(); System.out.println("For " + namelist.get(i) + "pos is " + newstate.getPosition()); } xgraphdata.addPoint(srdata, xrdata); xgraphdata.setDrawPointsOn(true); xgraphdata.setDrawLinesOn(false); xgraphdata.setGraphColor(Color.RED); ygraphdata.addPoint(srdata, yrdata); ygraphdata.setDrawPointsOn(true); ygraphdata.setDrawLinesOn(false); ygraphdata.setGraphColor(Color.BLUE); plotpanel.addGraphData(xgraphdata); plotpanel.addGraphData(ygraphdata); limits.setSmartLimits(); limits.setXmin(srdata[0] - 2.0); plotpanel.setExternalGL(limits); } //Evaluates beam properties for a trial point class Evaluator1 implements Evaluator{ protected ArrayList<Objective> _objectives; protected ArrayList<Variable> _variables; public Evaluator1( final ArrayList<Objective> objectives, final ArrayList<Variable> variables ) { _objectives = objectives; _variables = variables; } public void evaluate(final Trial trial){ double error =0.0; Iterator<Objective> itr = _objectives.iterator(); while(itr.hasNext()){ TargetObjective objective = (TargetObjective)itr.next(); error = calcError(_variables, trial); trial.setScore(objective, error); } } } // objective class for solver. class TargetObjective extends Objective{ protected final double _target; public TargetObjective(final String name, final double target){ super(name); _target=target; } public double satisfaction(double value){ double error = _target - value; return 1.0/(1+error*error); } } }
//package libManGUI.LibManGUI; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** LibManGUI implements Java Swing applications to provide the user with a simple library management program which can keep track of books and whom has rented them. @author Stefan Knott */ public class LibManGUI extends JFrame { private static final long serialVersionUID = 1L; private JFrame mainFrame; private JLabel statusLabel; private JPanel controlPanel, addPanel, searchPanel, chkOutPanel, rmvPanel; private JButton addButton, addButton2, searchButton, searchButton2, chkOutButton, chkOutButton2, rmvButton, rmvButton2; private JTextField addTxt, searchTxt, bkTxt, rentTxt, rmvTxt; ///Default Constructor public LibManGUI() { new libManager(); libManager.readInHandler(); prepareGUI(); } ///Where the GUI is ran from public static void main(String[] args) { LibManGUI gui = new LibManGUI(); gui.runGUI(); } private void setControlPanelComponents() { statusLabel = new JLabel("Welcome to Your Library!",JLabel.CENTER); statusLabel.setBounds(40, 275, 300, 50); addButton = new JButton("Add"); rmvButton = new JButton("Remove"); searchButton = new JButton("Search"); chkOutButton = new JButton("Checkout"); controlPanel.setLayout(null); controlPanel.setOpaque(true); addButton.setBounds(250, 75, 115, 30); rmvButton.setBounds(250, 110, 115, 30); searchButton.setBounds(250, 145, 115, 30); chkOutButton.setBounds(250, 180, 115, 30); try{ BufferedImage mainIcon = ImageIO.read(new File("bookworm.jpg")); JLabel picLabel = new JLabel(new ImageIcon(mainIcon)); picLabel.setBounds(50, 75, 150, 150); controlPanel.add(picLabel); }catch(IOException e){} controlPanel.add(addButton); controlPanel.add(rmvButton); controlPanel.add(searchButton); controlPanel.add(chkOutButton); controlPanel.add(statusLabel); controlPanel.setBackground(Color.WHITE); } private void addPicture(JPanel panel) { try{ BufferedImage bookworm = ImageIO.read(new File("bookworm21.gif")); JLabel wormLabel = new JLabel(new ImageIcon(bookworm)); wormLabel.setBounds(50, 265, 150, 67); panel.add(wormLabel); }catch(IOException e){} } private void setAddPanelComponents() { addPanel.setLayout(null); addPanel.setOpaque(true); JLabel addLabel = new JLabel("Book title:"); addButton2 = new JButton("Add"); addTxt = new JTextField(10); addPicture(addPanel); addLabel.setBounds(55, 105, 115, 30); addButton2.setBounds(250, 105, 115, 30); addTxt.setBounds(130, 105, 115, 30); addPanel.add(addLabel); addPanel.add(addButton2); addPanel.add(addTxt); } private void setRmvPanelComponents() { rmvPanel.setLayout(null); rmvPanel.setOpaque(true); rmvButton2 = new JButton("Remove"); rmvTxt = new JTextField(10); JLabel rmvLabel = new JLabel("Book title: "); rmvPanel.add(rmvButton2); rmvPanel.add(rmvTxt); rmvPanel.add(rmvLabel); addPicture(rmvPanel); rmvLabel.setBounds(55, 105, 115, 30); rmvButton2.setBounds(250, 105, 115, 30); rmvTxt.setBounds(130, 105, 115, 30); } private void setSearchPanelComponents() { searchPanel.setLayout(null); searchPanel.setOpaque(true); searchButton2 = new JButton("Search"); searchTxt = new JTextField(10); JLabel searchLabel = new JLabel("Book title:"); searchPanel.add(searchButton2); searchPanel.add(searchTxt); searchPanel.add(searchLabel); addPicture(searchPanel); searchLabel.setBounds(55, 105, 115, 30); searchButton2.setBounds(250, 105, 115, 30); searchTxt.setBounds(130, 105, 115, 30); } private void setChkOutPanelComponents() { chkOutPanel.setLayout(null); chkOutPanel.setOpaque(true); chkOutButton2 = new JButton("Check Out"); bkTxt = new JTextField(10); rentTxt = new JTextField(10); JLabel bookLabel = new JLabel("Book title:"); JLabel renterLabel = new JLabel("Renter:"); chkOutPanel.add(chkOutButton2); chkOutPanel.add(bkTxt); chkOutPanel.add(rentTxt); chkOutPanel.add(bookLabel); chkOutPanel.add(renterLabel); addPicture(chkOutPanel); bookLabel.setBounds(55, 100, 115, 30); renterLabel.setBounds(75, 135, 115, 30); chkOutButton2.setBounds(250, 135, 115, 30); bkTxt.setBounds(130, 100, 115, 30); rentTxt.setBounds(130, 135, 115, 30); } /**Method prepare the layout for the GUI's panels which are used for adding, searching and checking out. */ private void prepareGUI() { controlPanel = new JPanel(); addPanel = new JPanel(); rmvPanel = new JPanel(); searchPanel = new JPanel(); chkOutPanel = new JPanel(); mainFrame = new JFrame("Library Manager"); mainFrame.setSize(400, 350); mainFrame.getContentPane().setBackground(new Color(255,255, 255)); mainFrame.setResizable(false); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ libManager.writeToFileHandler(); System.exit(0); } }); setControlPanelComponents(); setAddPanelComponents(); setSearchPanelComponents(); setChkOutPanelComponents(); setRmvPanelComponents(); mainFrame.add(controlPanel); mainFrame.setVisible(true); } /**Method used to set the control of the mainFrame @param rmv JPanel to be removed from mainFrame @param set JPanel to be set to MainFrame */ private void resetPane(JPanel rmv, JPanel set) { mainFrame.remove(rmv); mainFrame.setContentPane(set); mainFrame.validate(); mainFrame.repaint(); mainFrame.getContentPane().setBackground(new Color(255, 255, 255)); statusLabel.setSize(200, 50); statusLabel.setBounds(50, 275, 300, 50); } /**Method used to maintain the control and output for add operations. */ private void addPanel() { addButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String addBk = new String(); addBk = addTxt.getText().trim(); if(addBk.equals("")) {} else{ String report = libManager.addHandler(addBk); if(report.equals("Error")){} else{ statusLabel.setText(addBk + " was added to the library"); } } resetPane(addPanel, controlPanel); mainFrame.getContentPane().setBackground(new Color(255, 255, 255)); for(ActionListener al : addButton2.getActionListeners()) { addButton2.removeActionListener(al); } } }); } private void rmvPanel() { rmvButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String rmvBk = new String(); rmvBk = rmvTxt.getText().trim(); if(rmvBk.equals("")) {} else{ String report = libManager.rmvHandler(rmvBk); if(report.equals("Error")){} else{ statusLabel.setText(rmvBk + " was removed from the library"); } } resetPane(addPanel, controlPanel); mainFrame.getContentPane().setBackground(new Color(255, 255, 255)); for(ActionListener al : addButton2.getActionListeners()) { addButton2.removeActionListener(al); } } }); } /**Method used to maintain the control and output for search operations. */ private void searchPanel() { searchButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String searchItem = searchTxt.getText().trim(); if(searchItem.equals("")) {} else { String report = libManager.searchHandler(searchItem); if(report.equals("Error")) {} else { statusLabel.setText("Book info: " + report); } } resetPane(searchPanel, controlPanel); for(ActionListener al : searchButton2.getActionListeners()) { searchButton2.removeActionListener(al); } } }); return; } /**Method used to maintain the control and output for checkout operations. */ private void chkOutPanel() { chkOutButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String bk = bkTxt.getText().trim(); String renter = rentTxt.getText().trim(); if(bk.equals("") || renter.equals("")) {} else { String report = libManager.chkOutHandler(bk, renter); if(report.equals("Error")) {} else { statusLabel.setText("Book: " + bk + " is now checked out by " + renter); } } resetPane(chkOutPanel, controlPanel); } }); } /**Method used to maintain control of the GUI from the control panel */ private void runGUI() { addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { resetPane(controlPanel, addPanel); addPanel(); } }); searchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { resetPane(controlPanel, searchPanel); searchPanel(); } }); chkOutButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { resetPane(controlPanel, chkOutPanel); chkOutPanel(); } }); rmvButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { resetPane(controlPanel, rmvPanel); rmvPanel(); } }); controlPanel.add(addButton); controlPanel.add(rmvButton); controlPanel.add(searchButton); controlPanel.add(chkOutButton); mainFrame.setVisible(true); } }
package com.mill_e.ustwo; import android.app.ListFragment; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Fragment to display messaging between two users. */ public class MessagingFragment extends ListFragment{ private String _userPartner; private MessageArrayAdapter _arrayAdapter; private boolean _isViewable = false; private final HashMap<String, Long> _backLog = new HashMap<String, Long>(); //TODO: Add "extras" to messaging, open a popupwindow @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { UsTwo.ACTIVE_FRAGMENT = 0; View v = inflater.inflate(R.layout.fragment_messaging_view, container, false); _userPartner = "Kelsey"; v.findViewById(R.id.send_button).setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View view) { sendMessage(view); } }); /*v.findViewById(R.id.button_messaging_extras).setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View view) { simulateReceipt(view); } });*/ _isViewable = true; return v; } private void updateAdapter(Context p_context){ _arrayAdapter = new MessageArrayAdapter(p_context, R.layout.message_layout_sent, ((UsTwo)getActivity()).getService().getMessagesModel()); super.setListAdapter(_arrayAdapter); } private void refreshMessages(){ ((MessageArrayAdapter)super.getListView().getAdapter()).notifyDataSetChanged(); } private void debuggingMessages(View view){ EditText box = ((EditText)getView().findViewById(R.id.edittext_message)); box.setText("Message1"); sendMessage(view); box.setText("Message2"); simulateReceipt(view); box.setText("Message1"); sendMessage(view); box.setText("Message2"); simulateReceipt(view); box.setText("Message1"); sendMessage(view); box.setText("Message2"); simulateReceipt(view); box.setText("Message1"); sendMessage(view); box.setText("Message2"); simulateReceipt(view); box.setText("Message1"); sendMessage(view); box.setText("Message2"); simulateReceipt(view); box.setText("Message1"); sendMessage(view); box.setText("Message2"); simulateReceipt(view); } /** * Sends the current contents of the message EditText as a Message object to the other user. * @param view Context view */ public void sendMessage(View view){ EditText box = ((EditText)getView().findViewById(R.id.edittext_message)); String text = box.getText().toString(); long time = System.currentTimeMillis(); try { UsTwoService service = ((UsTwo)getActivity()).getService(); if (_backLog.size() > 0){ Iterator it = _backLog.entrySet().iterator(); while (it.hasNext()){ Map.Entry entry = (Map.Entry) it.next(); service.addMessage(((String)entry.getKey()), ((Long)entry.getValue()).longValue()); } } service.addMessage(text, time); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e2){ _backLog.put(text, time); } box.setText(R.string.empty); } //defunct for now, service can't send message not from current user private void simulateReceipt(View view){ EditText box = ((EditText)getView().findViewById(R.id.edittext_message)); try { ((UsTwo)getActivity()).getService().addMessage(box.getText().toString(), System.currentTimeMillis()); } catch (IOException e) { e.printStackTrace(); } box.setText(R.string.empty); } @Override public void onViewCreated(View view, Bundle savedInstanceState){ Messages messages; UsTwoService serviceRef = ((UsTwo)getActivity()).getService(); if (serviceRef != null) messages = serviceRef.getMessagesModel(); else messages = new Messages(); _arrayAdapter = new MessageArrayAdapter(getActivity(), R.layout.message_layout_sent, messages); super.setListAdapter(_arrayAdapter); refreshMessages(); } }
package net.acomputerdog.BlazeLoader.main; /** * Contains methods for obtaining information about the installed version of BlazeLoader. * -MUST remain backward compatible!- */ public final class Version { private static final boolean isOBF = isGameOBF(); /** * Gets the global version of BlazeLoader. A change here will RESET the status of the other two update counters. * Mods must check this value first before determining if the version of BL is correct. * Generally a change here is either a Minecraft update or a large restructuring. * * @return Return the global version of BlazeLoader. */ public static int getGlobalVersion() { return 2; } /** * Gets the version of the API features of BlazeLoader. Incremented with changes to API features. * Changes here may affect mods. * * @return Get the version of the API features of BlazeLoader */ public static int getApiVersion() { return 8; } /** * Gets the version of the internal features of BlazeLoader. * Mods that only use API features should be unaffected by changes here. * * @return Return an int representing the version of BL's internal components. */ public static int getInternalVersion() { return 9; } /** * Gets the version of BlazeLoader as a string formatted for display. Example return: "0.1.234" * * @return Returns the version of BlazeLoader as a String formatted for display. */ public static String getStringVersion() { return getGlobalVersion() + "." + getApiVersion() + "." + getInternalVersion(); } /** * Gets the version of Minecraft that is running. * * @return Returns a String representing the version of Minecraft, ex. "1.6.4". */ public static String getMinecraftVersion() { return "1.7.2"; } public static boolean isGameObfuscated() { return isOBF; } private static boolean isGameOBF() { try { Class.forName("net.minecraft.client.Minecraft"); return false; } catch (Exception ignored) { return true; } } }
import java.util.Random; public class ANN { private Random random = new Random(); private int L; private double[][][] neuralNetWeights; private double[][] neuralNetBias; private double[][] neuralNetActivation; private double[][] neuralNetZ; private double[][] error; private double weightsLearningRate = .75; private double biasLearningRate = .75; int trialCount = 0; /** * Create an artificial neural network * * @param inputNodesNum, hiddenNodesNum, outputNodesNum */ public ANN(int inputNodesNum, int[] hiddenNodesNum, int outputNodesNum) { L = hiddenNodesNum.length+2; neuralNetWeights = new double[L][][]; neuralNetBias = new double[L][]; neuralNetActivation = new double[L][]; neuralNetZ = new double[L][]; error = new double[L][]; neuralNetWeights[0] = new double[inputNodesNum][1]; neuralNetBias[0] = new double[inputNodesNum]; neuralNetActivation[0] = new double[inputNodesNum]; neuralNetZ[0] = new double[inputNodesNum]; error[0] = new double[inputNodesNum]; neuralNetWeights[1] = new double[hiddenNodesNum[0]][inputNodesNum]; neuralNetBias[1] = new double[hiddenNodesNum[0]]; neuralNetActivation[1] = new double[hiddenNodesNum[0]]; neuralNetZ[1] = new double[hiddenNodesNum[0]]; error[1] = new double[hiddenNodesNum[0]]; for(int i = 1; i < L - 2; i++){ neuralNetWeights[i+1] = new double[hiddenNodesNum[i]][hiddenNodesNum[i - 1]]; neuralNetBias[i+1] = new double[hiddenNodesNum[i]]; neuralNetActivation[i+1] = new double[hiddenNodesNum[i]]; neuralNetZ[i+1] = new double[hiddenNodesNum[i]]; error[i+1] = new double[hiddenNodesNum[i]]; } neuralNetWeights[L - 1] = new double[outputNodesNum][hiddenNodesNum[hiddenNodesNum.length-1]]; neuralNetBias[L - 1] = new double[outputNodesNum]; neuralNetActivation[L - 1] = new double[outputNodesNum]; neuralNetZ[L - 1] = new double[outputNodesNum]; error[L - 1] = new double[outputNodesNum]; init(); } /** * Initializes weights and biases of the neurons */ public void init(){ for(int i = 0; i < neuralNetWeights.length; i++){ for(int j = 0; j < neuralNetWeights[i].length; j++){ if(i == 0|| i == neuralNetWeights.length-1) neuralNetBias[0][j] = 0; else neuralNetBias[i][j] = random.nextGaussian(); for(int k = 0; k < neuralNetWeights[i][j].length; k++){ if(i == 0) neuralNetWeights[i][j][k] = 1; else neuralNetWeights[i][j][k] = random.nextGaussian() * 1.0/Math.sqrt(neuralNetWeights[i].length); } } } } /** * Pass an array of matrixes with labels to train a NN * Returns the average final error, average saturation and final activation signals * * @param values * @param labels * @return */ public double[] train(double[][] values, double[][] labels){ double[] settings = new double[2 + labels[0].length]; for(int i = 0; i < values.length; i ++){ System.out.println(test(values[i], labels[i])[0]); } double averageLastError = 0; double averageSaturation = 0; for(int i = 0; i < labels[0].length; i++){ averageLastError += Math.abs(labels[labels.length - 1][i] - neuralNetActivation[L-1][i]); averageSaturation += Math.pow(Math.abs(labels[labels.length - 1][i] - .5),2) * 2; settings[i+2] = neuralNetActivation[L-1][i]; } settings[0] = averageLastError/labels[0].length; settings[1] = averageSaturation; return settings; } /** * Run a single trial through the ANN * * @param in * @param out */ public double[] test(double[] values, double[] labels){ double[] settings = new double[2 + labels.length]; feedForward(values); backPropogate(labels); trialCount++; double averageLastError = 0; double averageSaturation = 0; for(int i = 0; i < labels.length; i++){ averageLastError += Math.abs(labels[i] - neuralNetActivation[L-1][i]); averageSaturation += Math.pow(Math.abs(labels[i] - .5),2) * 2; settings[i+2] = neuralNetActivation[L-1][i]; } settings[0] = averageLastError/labels.length; settings[1] = averageSaturation; return settings; } /** * Helper method that does the feed forward * * @param inputField */ private void feedForward(double[] inputField){ for(int i = 0; i < inputField.length; i++){ neuralNetActivation[0][i] = inputField[i]; } for(int i = 1; (i < L); i++){ calculateZ(i); calculateActivation(i); } } /** * Helper function to do the back propagation * * @param y */ private void backPropogate(double[] y){ calculateErrorL(y); calculateErrorl(); updateNet(); } /** * Intermediary used in a few calculations * * @param layer */ private void calculateZ(int layer){ for(int j = 0; j < neuralNetWeights[layer].length; j++){ neuralNetZ[layer][j] = 0; for(int k = 0; k < neuralNetWeights[layer][j].length; k++){ neuralNetZ[layer][j] += neuralNetWeights[layer][j][k] * neuralNetActivation[layer - 1][k]; } neuralNetZ[layer][j] += neuralNetBias[layer][j]; } } /** * Activation calculation * * @param layer */ private void calculateActivation(int layer){ neuralNetActivation[layer] = sigmoid(neuralNetZ[layer]); } /** * Activation Function * * @param x * @return f(x) */ private double[] sigmoid(double[] x){ double[] out = new double[x.length]; for(int i = 0; i < x.length; i++) out[i] = 1.0/(1.0 + Math.pow(Math.E,-x[i])); return out; } /** * Derivative of Activation function * * @param x * @return f'(x) */ private double[] sigmoidPrime(double[] x){ double[] out = new double[x.length]; for(int i = 0; i < x.length; i++) out[i] = Math.pow(Math.E, x[i])/Math.pow((Math.pow(Math.E, x[i])+1),2); return out; } /** * Error calculation for output nodes * * @param y */ private void calculateErrorL(double[] y){ error[L - 1] = hadamarProduct(costGradient(L - 1, y),sigmoidPrime(neuralNetZ[L - 1])); } /** * Error calculation for non-output nodes */ private void calculateErrorl(){ for(int i = L - 2; i >= 0; i error[i] = hadamarProduct(arrayProduct(transpose(neuralNetWeights[i + 1]),error[i+1]),sigmoidPrime(neuralNetZ[i])); } } /** * Updates the weights and and bias via their gradients */ private void updateNet(){ for(int i = 1; i < neuralNetWeights.length; i++){ for(int j = 0; j < neuralNetWeights[i].length; j++){ neuralNetBias[i][j] = neuralNetBias[i][j] - biasLearningRate * biasGradient(i,j); for(int k = 0; k < neuralNetWeights[i][j].length; k++){ neuralNetWeights[i][j][k] = neuralNetWeights[i][j][k] - weightsLearningRate * weightGradient(i,j,k); } } } } /** * helper function for bias gradient * * @param l * @param j * @return gradient */ private double biasGradient(int l, int j){ if( l == neuralNetWeights.length-1) return 0; return error[l][j]; } /** * Helper function for weight gradient * * @param l * @param j * @param k * @return gradient */ private double weightGradient(int l, int j, int k){ if(l == 1|| l == 0) return 1; return neuralNetActivation[l - 1][k] * error[l][j]; } /** * Calculates Cost Gradient * * @param layer * @param y * @return cost gradient */ private double[] costGradient(int layer, double[] y){ double out[] = new double[y.length]; for(int i = 0; i < y.length; i++){ out[i] = neuralNetActivation[layer][i] - y[i]; } return out; } /** * Hadamar Product * * @param first * @param second * @return double[] of Hadamar Product */ private double[] hadamarProduct(double[] first, double[] second){ double[] out = new double[first.length]; for(int i = 0; i < out.length; i++){ out[i] = first[i] * second[i]; } return out; } /** * Matrix transpose * * @param a * @return the transpose */ private double[][] transpose(double[][] a){ double[][] out = new double[a[0].length][a.length]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { double temp = a[i][j]; out[j][i] = temp; } } return out; } /** * Matrix multiplication method * * @param first * @param second * @return A * B */ private double[] arrayProduct(double[][] first, double[] second){ double out[] = new double[first.length]; for(int i = 0; i < first.length; i++){ double sum = 0; for(int k = 0; k < second.length; k++){ sum += first[i][k] * second[k]; } out[i] = sum; } return out; } /** * Prints weights * * @return weights */ public String toStringWeights(){ String out = ""; for(int i = 0; i < neuralNetWeights.length; i++){ for(int j = 0; j < neuralNetWeights[i].length; j++){ for(int k = 0; k < neuralNetWeights[i][j].length; k++){ out += neuralNetWeights[i][j][k] + " "; } out += "\n"; } out += "\n"; } return out; } /** * Prints bias * * @return bias */ public String toStringBias(){ String out = ""; for(int i = 0; i < neuralNetBias.length; i++){ for(int j = 0; j < neuralNetBias[i].length; j++){ out += neuralNetBias[i][j] + " "; out += "\n"; } out += "\n"; } return out; } /** * Prints Activation Values * * @return Activation Values */ public String toStringActivationFunction(){ String out = ""; for(int i = 0; i < neuralNetActivation.length; i++){ for(int j = 0; j < neuralNetActivation[i].length; j++){ out += neuralNetActivation[i][j] + " "; out += "\n"; } out += "\n"; } return out; } /** * Prints Z * * @return Z */ public String toStringZ(){ String out = ""; for(int i = 0; i < neuralNetZ.length; i++){ for(int j = 0; j < neuralNetZ[i].length; j++){ out += neuralNetZ[i][j] + " "; out += "\n"; } out += "\n"; } return out; } /** * @return the weightsLearningRate */ public double getWeightsLearningRate() { return weightsLearningRate; } /** * @param weightsLearningRate the weightsLearningRate to set */ public void setWeightsLearningRate(double weightsLearningRate) { this.weightsLearningRate = weightsLearningRate; } /** * @return the biasLearningRate */ public double getBiasLearningRate() { return biasLearningRate; } /** * @param biasLearningRate the biasLearningRate to set */ public void setBiasLearningRate(double biasLearningRate) { this.biasLearningRate = biasLearningRate; } }
import javafx.animation.*; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.TilePane; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.PathElement; import javafx.stage.Stage; import javafx.util.Duration; public class SudokuGUI extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Sudoku solver"); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("Icon.png"))); BorderPane root = new BorderPane(); root.setOpacity(0); //Sudoku grid TilePane sudokuGrid = new TilePane(); sudokuGrid.setPrefColumns(3); sudokuGrid.setPrefRows(3); sudokuGrid.setPadding(new Insets(6, 0, 6, 0)); sudokuGrid.setHgap(3); sudokuGrid.setVgap(3); sudokuGrid.setAlignment(Pos.CENTER); sudokuGrid.setTileAlignment(Pos.CENTER); sudokuGrid.setStyle("-fx-background-color: #DADADF"); for(int index = 0; index < 9; index++) { createSquare(sudokuGrid, index); } root.setTop(sudokuGrid); //Button to solve sudoku Button buttonSolve = new Button(); buttonSolve.setText("Solve"); buttonSolve.setStyle("-fx-font: 18 segoiui;"); buttonSolve.setPrefSize(120, 40); buttonSolve.setOnAction(event -> { int[][] ret = new int[9][9]; for(Node pane:sudokuGrid.getChildren()){ for(Node field:((TilePane) pane).getChildren()) { int row = ((SudokuTextField) field).getRowPosition(); int col = ((SudokuTextField) field).getColumnPosition(); String string = ((SudokuTextField) field).getText(); if(string.length() == 0) ret[row][col] = 0; else ret[row][col] = Integer.parseInt(string); } } SudokuSolver solver = new SudokuSolver(ret); ret = solver.solve(); int index = 0; for(Node pane:sudokuGrid.getChildren()){ for(Node field:((TilePane) pane).getChildren()){ SudokuTextField sudokuField = (SudokuTextField) field; int row = sudokuField.getRowPosition(); int col = sudokuField.getColumnPosition(); if(ret[row][col] == -1) { field.setStyle("-fx-control-inner-background: #FF4545; -fx-font: 22 segoiui;"); } else if(ret[row][col] == 0) { sudokuField.setText(""); } else { sudokuField.setText(Integer.toString(ret[row][col])); sudokuField.setFieldStyle(index); } } index++; } }); //Button to clear the grid Button buttonClear = new Button(); buttonClear.setText("Clear"); buttonClear.setStyle("-fx-font: 18 segoiui;"); buttonClear.setPrefSize(120, 40); buttonClear.setOnAction(event -> { int index = 0; for(Node pane:sudokuGrid.getChildren()){ for(Node field:((TilePane) pane).getChildren()){ ((SudokuTextField) field).setText(""); ((SudokuTextField) field).setFieldStyle(index); } index++; } }); //Horizontal box that contains buttons HBox controls = new HBox(); controls.setPadding(new Insets(4, 4, 4, 4)); controls.setSpacing(20); controls.setAlignment(Pos.CENTER); controls.getChildren().addAll(buttonSolve, buttonClear); root.setCenter(controls); primaryStage.setResizable(false); primaryStage.setScene(new Scene(root)); //SudokuGrid animation FadeTransition ft = new FadeTransition(new Duration(500), root); ParallelTransition pt = new ParallelTransition(ft); ft.setFromValue(0); ft.setToValue(1); primaryStage.show(); pt.play(); } private void createSquare(TilePane sudokuGrid, int index) { //3x3 subsquare TilePane pane = new TilePane(); pane.setPrefRows(3); pane.setPrefColumns(3); pane.setVgap(index % 2 == 0 ? 3 : 4); pane.setHgap(index % 2 == 0 ? 3 : 4); pane.setAlignment(Pos.CENTER); pane.setPadding(new Insets(1, 1, 1, 1)); //Fill the square and map tiles to their coordinates for(int i = 0; i < 9; i++) { //Determine the tile's position in the sudoku grid int fieldNumber = (index % 3) * 3 + (index / 3) * 27 + (i / 3) * 9 + i % 3 + 1; int row = (fieldNumber - 1) / 9; int col = (fieldNumber - 1) % 9; //Formatting SudokuTextField field = new SudokuTextField(row, col); field.setPrefSize(index % 2 == 0 ? 45 : 43, index % 2 == 0 ? 40 : 39); field.setAlignment(Pos.CENTER); field.setPadding(new Insets(0, 0, 0, 0)); //Styling field.setFieldStyle(index); //Animations ScaleTransition scaleUp = new ScaleTransition(new Duration(200), field); scaleUp.setFromX(1); scaleUp.setFromY(1); scaleUp.setToX(1.05); scaleUp.setToY(1.05); ScaleTransition scaleDown = new ScaleTransition(new Duration(200), field); scaleDown.setFromX(1.05); scaleDown.setFromY(1.05); scaleDown.setToX(1); scaleDown.setToY(1); //Play animation on focus field.focusedProperty().addListener(event -> { if(field.focusedProperty().getValue()) { scaleUp.play(); } else { scaleDown.play(); } }); //Focus on mouse over field.setOnMouseEntered(event -> field.requestFocus()); pane.getChildren().add(field); } sudokuGrid.getChildren().add(pane); } /** * TextField with limited maximum length that only accepts number 1-9 and holds its coordinates in the sudoku grid */ private class SudokuTextField extends TextField { private final int length; private int compare; private final int rowPosition; private final int columnPosition; private SudokuTextField(int row, int col) { super(); this.length = 1; rowPosition = row; columnPosition = col; } //Ensures that only numbers can be entered by the user public void replaceText(int start, int end, String text) { if(text.length() == 0) super.replaceText(start, end, text); compare = getText().length() - (end - start) + text.length(); if(compare <= length || start != end) { try { if(Integer.parseInt(text) > 0) super.replaceText(start, end, text); } catch (Exception ignored) { } } } //Ensures that only numbers can be entered by the user public void replaceSelection(String text) { if(text.length() == 0) super.replaceSelection(text); compare = getText().length() + text.length(); if(compare <= length ) try { if(Integer.parseInt(text) > 0) super.replaceSelection(text); } catch (Exception ignored) { } } //Styling public void setFieldStyle(int index) { if(index % 2 == 0) this.setStyle("-fx-control-inner-background: #ff7f50; -fx-font: 22 segoiui;"); else this.setStyle("-fx-font: 22 segoiui;"); } public int getRowPosition() { return rowPosition; } public int getColumnPosition() { return columnPosition; } } }
import java.util.*; /** * Given a collection of intervals, merge all overlapping intervals. * * For example, * Given [1,3],[2,6],[8,10],[15,18], * return [1,6],[8,10],[15,18]. * * Tags: Array, Sort */ class MergeIntervals { public static void main(String[] args) { } /** * Sort and merge, O(nlogn) * Sort the intervals according to their start value * Go through the intervals and update last interval * If last interval in result overlap with current interval * Remove last interval and add new interval with updated end value * Which is the bigger of last.end and i.end */ public List<Interval> merge(List<Interval> intervals) { List<Interval> res = new ArrayList<Interval>(); if (intervals == null || intervals.size() == 0) return res; Collections.sort(intervals, new MyComparator()); for (Interval i : intervals) { if (res.isEmpty()) res.add(i); // first interval else { Interval last = res.get(res.size() - 1); // get last interval if (last.end >= i.start) { // overlap res.remove(last); res.add(new Interval(last.start, Math.max(last.end, i.end))); // extend end } else res.add(i); //no overlap } } return res; } /** * Comparator for interval * Sort according to start date */ class MyComparator implements Comparator<Interval> { @Override public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } } public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } }
package VASSAL.counters; import VASSAL.build.GameModule; import VASSAL.build.module.GameState; import VASSAL.build.module.documentation.HelpFile; import VASSAL.command.ChangeTracker; import VASSAL.command.Command; import VASSAL.command.NullCommand; import VASSAL.configure.StringConfigurer; import VASSAL.i18n.TranslatablePiece; import VASSAL.tools.SequenceEncoder; import javax.swing.KeyStroke; import java.awt.Component; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP0; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP1; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP2; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP3; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP4; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP5; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP6; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP7; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP8; import static VASSAL.counters.MatCargo.CURRENT_MAT_PROP9; /** * Designates the piece as a "Mat" on which other pieces ("Cargo") can be placed. */ public class Mat extends Decorator implements TranslatablePiece { public static final String ID = "mat;"; // NON-NLS public static final String MAT_NAME = "MatName"; //NON-NLS public static final String MAT_ID = "MatID"; //NON-NLS public static final String MAT_CONTENTS = "MatContents"; //NON-NLS public static final String MAT_NUM_CARGO = "MatNumCargo"; //NON-NLS protected String matName; protected String desc; protected List<GamePiece> contents = new ArrayList<>(); public Mat() { this(ID + "Mat;;", null); //NON-NLS } public Mat(String name) { this (ID + name + ";;", null); } public Mat(String type, GamePiece inner) { mySetType(type); setInner(inner); } @Override public void mySetType(String type) { type = type.substring(ID.length()); final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';'); matName = st.nextToken(); desc = st.nextToken(); } @Override public String myGetType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(matName).append(desc); return ID + se.getValue(); } @Override protected KeyCommand[] myGetKeyCommands() { return KeyCommand.NONE; } @Override public String myGetState() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(contents.size()); for (final GamePiece p : contents) { se.append(p.getId()); } return se.getValue(); } @Override public Command myKeyEvent(KeyStroke stroke) { return null; } public List<GamePiece> getContents() { return new ArrayList<>(contents); } public List<Point> getOffsets(int x, int y) { final List<Point> offsets = new ArrayList<>(); for (final GamePiece piece : getContents()) { final Point pt = piece.getPosition(); pt.x -= x; pt.y -= y; offsets.add(pt); } return offsets; } @Override public void mySetState(String newState) { contents.clear(); final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(newState, ';'); final int num = st.nextInt(0); final GameState gs = GameModule.getGameModule().getGameState(); for (int i = 0; i < num; i++) { final GamePiece piece = gs.getPieceForId(st.nextToken()); if (piece != null) { //BR// getPieceForId can return null. contents.add(piece); } } GameModule.getGameModule().setMatSupport(true); } /** * @param p a particular gamepiece, presumably with a MatCargo trait * @return true if the given piece is on our list of contained cargo */ public boolean hasCargo(GamePiece p) { return contents.contains(p); } /** * Adds a piece of cargo to this mat * @param p game piece to add */ public void addCargo(GamePiece p) { if (!(p instanceof Decorator) || hasCargo(p)) { return; } contents.add(p); final GamePiece cargo = Decorator.getDecorator(Decorator.getOutermost(p), MatCargo.class); if (cargo != null) { ((MatCargo)cargo).setMat(Decorator.getOutermost(this)); } } /** * Adds a piece of cargo and returns a command to duplicate the operation on another client * @param p piece of cargo to add * @return Command that adds the cargo to this mat (and removes it from any other mat it was on) */ public Command makeAddCargoCommand(GamePiece p) { final ChangeTracker ct = new ChangeTracker(this); final ChangeTracker ct2 = new ChangeTracker(p); ChangeTracker ct3 = null; if ((p instanceof Decorator) && !hasCargo(p)) { final GamePiece cargo = Decorator.getDecorator(Decorator.getOutermost(p), MatCargo.class); if (cargo != null) { final GamePiece mt = ((MatCargo)cargo).getMat(); if ((mt != null) && (mt != Decorator.getOutermost(this))) { ct3 = new ChangeTracker(mt); final Mat mat = (Mat)Decorator.getDecorator(mt, Mat.class); mat.removeCargo(p); } } } addCargo(p); Command c = ct.getChangeCommand().append(ct2.getChangeCommand()); if (ct3 != null) { c = c.append(ct3.getChangeCommand()); } return c; } /** * Removes a MatCargo piece from our list of cargo. Does NOT clear MatCargo's reference to this mat - must be done separately. * @param p Cargo to remove */ public void removeCargo(GamePiece p) { if ((p instanceof Decorator) && hasCargo(p)) { contents.remove(p); } } /** * Removes a MatCargo piece from our list of cargo, and returns a Command to duplicate the changes on another client * @param p GamePiece with a MatCargo trait, to be removed * @return Command to remove the piece */ public Command makeRemoveCargoCommand(GamePiece p) { final ChangeTracker ct = new ChangeTracker(this); final ChangeTracker ct2 = new ChangeTracker(p); removeCargo(p); return ct.getChangeCommand().append(ct2.getChangeCommand()); } /** * Remove all cargo from this Mat, and returns a Command to duplicate the changes on another client * @return Command to remove all cargo */ public Command makeRemoveAllCargoCommand() { Command c = new NullCommand(); for (final GamePiece p : getContents()) { c = c.append(makeRemoveCargoCommand(p)); } return c; } @Override public Rectangle boundingBox() { return piece.boundingBox(); } @Override public void draw(Graphics g, int x, int y, Component obs, double zoom) { piece.draw(g, x, y, obs, zoom); } @Override public String getName() { return piece.getName(); } @Override public Shape getShape() { return piece.getShape(); } @Override public PieceEditor getEditor() { return new Ed(this); } @Override public String getDescription() { return buildDescription("Editor.Mat.trait_description", matName, desc); } @Override public Object getProperty(Object key) { if (MAT_NAME.equals(key)) { return matName; } if (MAT_ID.equals(key)) { return matName + "_" + getProperty(BasicPiece.PIECE_UID); } else if (MAT_CONTENTS.equals(key)) { return new ArrayList<>(contents); } else if (MAT_NUM_CARGO.equals(key)) { return String.valueOf(contents.size()); } else if (Properties.NO_STACK.equals(key)) { // Mats can't stack return Boolean.TRUE; } return super.getProperty(key); } @Override public Object getLocalizedProperty(Object key) { if (MAT_NAME.equals(key)) { return matName; } if (MAT_ID.equals(key)) { return matName + "_" + getProperty(BasicPiece.PIECE_UID); } else if (MAT_NUM_CARGO.equals(key)) { return String.valueOf(contents.size()); } else if (Properties.NO_STACK.equals(key)) { // Mats can't stack return Boolean.TRUE; } return super.getLocalizedProperty(key); } @Override public void setProperty(Object key, Object value) { if (MAT_NAME.equals(key)) { matName = (String) value; return; } super.setProperty(key, value); } @Override public boolean testEquals(Object o) { if (! (o instanceof Mat)) return false; final Mat c = (Mat) o; if (!Objects.equals(matName, c.matName)) { return false; } return Objects.equals(desc, c.desc); } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("Mat.html"); // NON-NLS } /** * Return Property names exposed by this trait */ @Override public List<String> getPropertyNames() { return Arrays.asList(MAT_NAME, MAT_ID, MAT_NUM_CARGO, CURRENT_MAT_PROP0, CURRENT_MAT_PROP1, CURRENT_MAT_PROP2, CURRENT_MAT_PROP3, CURRENT_MAT_PROP4, CURRENT_MAT_PROP5, CURRENT_MAT_PROP6, CURRENT_MAT_PROP7, CURRENT_MAT_PROP8, CURRENT_MAT_PROP9); } public static class Ed implements PieceEditor { private final StringConfigurer matNameInput; private final StringConfigurer descInput; private final TraitConfigPanel controls; public Ed(Mat p) { controls = new TraitConfigPanel(); matNameInput = new StringConfigurer(p.matName); matNameInput.setHintKey("Editor.Mat.name_hint"); controls.add("Editor.Mat.name_label", matNameInput); descInput = new StringConfigurer(p.desc); descInput.setHintKey("Editor.description_hint"); controls.add("Editor.description_label", descInput); } @Override public Component getControls() { return controls; } @Override public String getType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(matNameInput.getValueString()); se.append(descInput.getValueString()); return ID + se.getValue(); } @Override public String getState() { return ""; } } }
package ru.job4j.array; /** * Class BubbleSort to sort array. * @author vivanov * @version 1 * @since 19.03.2017 */ public class BubbleSort { /** * @param array - array to sort. * @return sorted array */ public int[] sort(int[] array) { int temp = 0; int arrLen = array.length; boolean isGreat = false; for (int i = 0; i < arrLen - 1; i++) { for (int j = 0; j < arrLen - i - 1; j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; isGreat = true; } for (int arr : array) { System.out.print(arr + ", "); } System.out.println(); } if (!isGreat) { break; } } return array; } }
package ru.skilanov.square; /** * Square finds function ax^2+bx+c. */ public class Square { /** * @param a first number. * @param b second number. * @param c third number. */ public int a; public int b; public int c; public Square(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } /** * Calculate function ax^2+bx+c with set parameters. */ public float calculate(int x) { return (float) (a * Math.pow(x, 2) + b * x + c); } /** * Show result. */ public void show(int start, int finish, int step) { Square square = new Square(2, 3, 4); for (int index = start; index <= finish; index+=step) { System.out.println(square.calculate(index)); } } }
package io.warp10.worf; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map.Entry; import java.util.Properties; import com.google.common.base.Preconditions; import io.warp10.WarpConfig; import io.warp10.continuum.Configuration; import io.warp10.crypto.CryptoUtils; import io.warp10.crypto.KeyStore; import io.warp10.crypto.OSSKeyStore; import io.warp10.crypto.UnsecureKeyStore; import io.warp10.script.MemoryWarpScriptStack; import io.warp10.script.StackUtils; import io.warp10.script.WarpScriptLib; import io.warp10.script.ext.token.TokenWarpScriptExtension; import io.warp10.standalone.Warp; public class TokenGen { public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: TokenGen config in out"); System.exit(-1); } String config = args[0]; WarpConfig.setProperties(config); Properties properties = WarpConfig.getProperties(); KeyStore keystore; if (properties.containsKey(Configuration.OSS_MASTER_KEY)) { keystore = new OSSKeyStore(properties.getProperty(Configuration.OSS_MASTER_KEY)); } else { keystore = new UnsecureKeyStore(); } // Decode generic keys // We do that first so those keys do not have precedence over the specific // keys. for (Entry<Object,Object> entry: properties.entrySet()) { if (entry.getKey().toString().startsWith(Configuration.WARP_KEY_PREFIX)) { byte[] key = keystore.decodeKey(entry.getValue().toString()); if (null == key) { throw new RuntimeException("Unable to decode key '" + entry.getKey() + "'."); } keystore.setKey(entry.getKey().toString().substring(Configuration.WARP_KEY_PREFIX.length()), key); } } Warp.extractKeys(keystore, properties); keystore.setKey(KeyStore.SIPHASH_CLASS, keystore.decodeKey(properties.getProperty(Configuration.WARP_HASH_CLASS))); Preconditions.checkArgument(16 == keystore.getKey(KeyStore.SIPHASH_CLASS).length, Configuration.WARP_HASH_CLASS + " MUST be 128 bits long."); keystore.setKey(KeyStore.SIPHASH_LABELS, keystore.decodeKey(properties.getProperty(Configuration.WARP_HASH_LABELS))); Preconditions.checkArgument(16 == keystore.getKey(KeyStore.SIPHASH_LABELS).length, Configuration.WARP_HASH_LABELS + " MUST be 128 bits long."); // Generate secondary keys. We use the ones' complement of the primary keys keystore.setKey(KeyStore.SIPHASH_CLASS_SECONDARY, CryptoUtils.invert(keystore.getKey(KeyStore.SIPHASH_CLASS))); keystore.setKey(KeyStore.SIPHASH_LABELS_SECONDARY, CryptoUtils.invert(keystore.getKey(KeyStore.SIPHASH_LABELS))); keystore.setKey(KeyStore.SIPHASH_INDEX, keystore.decodeKey(properties.getProperty(Configuration.CONTINUUM_HASH_INDEX))); Preconditions.checkArgument(16 == keystore.getKey(KeyStore.SIPHASH_INDEX).length, Configuration.CONTINUUM_HASH_INDEX + " MUST be 128 bits long."); keystore.setKey(KeyStore.SIPHASH_TOKEN, keystore.decodeKey(properties.getProperty(Configuration.WARP_HASH_TOKEN))); Preconditions.checkArgument(16 == keystore.getKey(KeyStore.SIPHASH_TOKEN).length, Configuration.WARP_HASH_TOKEN + " MUST be 128 bits long."); keystore.setKey(KeyStore.SIPHASH_APPID, keystore.decodeKey(properties.getProperty(Configuration.WARP_HASH_APP))); Preconditions.checkArgument(16 == keystore.getKey(KeyStore.SIPHASH_APPID).length, Configuration.WARP_HASH_APP + " MUST be 128 bits long."); keystore.setKey(KeyStore.AES_TOKEN, keystore.decodeKey(properties.getProperty(Configuration.WARP_AES_TOKEN))); Preconditions.checkArgument((16 == keystore.getKey(KeyStore.AES_TOKEN).length) || (24 == keystore.getKey(KeyStore.AES_TOKEN).length) || (32 == keystore.getKey(KeyStore.AES_TOKEN).length), Configuration.WARP_AES_TOKEN + " MUST be 128, 192 or 256 bits long."); keystore.setKey(KeyStore.AES_SECURESCRIPTS, keystore.decodeKey(properties.getProperty(Configuration.WARP_AES_SCRIPTS))); Preconditions.checkArgument((16 == keystore.getKey(KeyStore.AES_SECURESCRIPTS).length) || (24 == keystore.getKey(KeyStore.AES_SECURESCRIPTS).length) || (32 == keystore.getKey(KeyStore.AES_SECURESCRIPTS).length), Configuration.WARP_AES_SCRIPTS + " MUST be 128, 192 or 256 bits long."); if (properties.containsKey(Configuration.WARP_AES_METASETS)) { keystore.setKey(KeyStore.AES_METASETS, keystore.decodeKey(properties.getProperty(Configuration.WARP_AES_METASETS))); Preconditions.checkArgument((16 == keystore.getKey(KeyStore.AES_METASETS).length) || (24 == keystore.getKey(KeyStore.AES_METASETS).length) || (32 == keystore.getKey(KeyStore.AES_METASETS).length), Configuration.WARP_AES_METASETS + " MUST be 128, 192 or 256 bits long."); } if (null != properties.getProperty(Configuration.WARP_AES_LOGGING, Configuration.WARP_DEFAULT_AES_LOGGING)) { keystore.setKey(KeyStore.AES_LOGGING, keystore.decodeKey(properties.getProperty(Configuration.WARP_AES_LOGGING, Configuration.WARP_DEFAULT_AES_LOGGING))); Preconditions.checkArgument((16 == keystore.getKey(KeyStore.AES_LOGGING).length) || (24 == keystore.getKey(KeyStore.AES_LOGGING).length) || (32 == keystore.getKey(KeyStore.AES_LOGGING).length), Configuration.WARP_AES_LOGGING + " MUST be 128, 192 or 256 bits long."); } keystore.forget(); TokenWarpScriptExtension ext = new TokenWarpScriptExtension(keystore); WarpScriptLib.register(ext); PrintWriter pw = new PrintWriter(System.out); if (args.length > 2) { if (!"-".equals(args[2])) { pw = new PrintWriter(new FileWriter(args[2])); } } MemoryWarpScriptStack stack = new MemoryWarpScriptStack(null, null, WarpConfig.getProperties()); stack.maxLimits(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; InputStream in = null; if ("-".equals(args[1])) { in = System.in; } else { in = new FileInputStream(args[1]); } while(true) { int len = in.read(buf); if (len <= 0) { break; } baos.write(buf, 0, len); } in.close(); String script = new String(baos.toByteArray(), "UTF-8"); stack.execMulti(script); StackUtils.toJSON(pw, stack); pw.flush(); pw.close(); } }
package org.spine3.base; import com.google.common.escape.Escaper; import com.google.common.escape.Escapers; import java.util.AbstractMap; import java.util.Map; import java.util.regex.Pattern; import static com.google.common.collect.Maps.newHashMap; import static org.spine3.util.Exceptions.newIllegalArgumentException; /** * The stringifier for the {@code Map} classes. * * <p>The stringifier for the type of the elements in the map * should be registered in the {@code StringifierRegistry} class * for the correct usage of {@code MapStringifier}. * * <h3>Example</h3> * * {@code * // The registration of the stringifier. * final Type type = Types.mapTypeOf(String.class, Long.class); * StringifierRegistry.getInstance().register(stringifier, type); * * // Obtain already registered `MapStringifier`. * final Stringifier<Map<String, Long>> mapStringifier = StringifierRegistry.getInstance() * .getStringifier(type); * * // Convert to string. * final Map<String, Long> mapToConvert = newHashMap(); * mapToConvert.put("first", 1); * mapToConvert.put("second", 2); * * // The result is: \"first\":\"1\",\"second\":\"2\". * final String convertedString = mapStringifier.toString(mapToConvert); * * * // Convert from string. * final String stringToConvert = ... * final Map<String, Long> convertedMap = mapStringifier.fromString(stringToConvert); * } * * @param <K> the type of the keys in the map * @param <V> the type of the values in the map */ class MapStringifier<K, V> extends Stringifier<Map<K, V>> { private static final char DEFAULT_ELEMENT_DELIMITER = ','; private static final char KEY_VALUE_DELIMITER = ':'; private static final char QUOTE = '"'; /** * The delimiter for the passed elements in the {@code String} representation, * {@code DEFAULT_ELEMENT_DELIMITER} by default. */ private final char delimiter; private final Class<K> keyClass; private final Class<V> valueClass; private final String bucketPattern; private final String keyValuePattern; private final Escaper escaper; /** * Creates a {@code MapStringifier}. * * <p>The {@code DEFAULT_ELEMENT_DELIMITER} is used for key-value * separation in {@code String} representation of the {@code Map}. * * @param keyClass the class of the key elements * @param valueClass the class of the value elements */ MapStringifier(Class<K> keyClass, Class<V> valueClass) { super(); this.keyClass = keyClass; this.valueClass = valueClass; this.delimiter = DEFAULT_ELEMENT_DELIMITER; escaper = createEscaper(delimiter); bucketPattern = createBucketPattern(delimiter); keyValuePattern = createKeyValuePattern(); } /** * Creates a {@code MapStringifier}. * * <p>The specified delimiter is used for key-value separation * in {@code String} representation of the {@code Map}. * * @param keyClass the class of the key elements * @param valueClass the class of the value elements * @param delimiter the delimiter for the passed elements via string */ MapStringifier(Class<K> keyClass, Class<V> valueClass, char delimiter) { super(); this.keyClass = keyClass; this.valueClass = valueClass; this.delimiter = delimiter; escaper = createEscaper(delimiter); bucketPattern = createBucketPattern(delimiter); keyValuePattern = createKeyValuePattern(); } private static String createBucketPattern(char delimiter) { return Pattern.compile("(?<!\\\\)\\\\\\" + delimiter) .pattern(); } private static String createKeyValuePattern() { return Pattern.compile("(?<!\\\\)\\\\" + KEY_VALUE_DELIMITER) .pattern(); } @Override protected String toString(Map<K, V> obj) { final StringBuilder stringBuilder = new StringBuilder(0); for (Map.Entry<K, V> entry : obj.entrySet()) { stringBuilder.append(QUOTE) .append(entry.getKey()) .append(QUOTE) .append(KEY_VALUE_DELIMITER) .append(QUOTE) .append(entry.getValue()) .append(QUOTE) .append(delimiter); } final int length = stringBuilder.length(); final String result = stringBuilder.substring(0, length - 1); return result; } @Override protected Map<K, V> fromString(String s) { final String escapedString = escaper.escape(s); final String[] buckets = escapedString.split(bucketPattern); final Map<K, V> resultMap = newHashMap(); for (String bucket : buckets) { final Map.Entry<K, V> convertedBucket = convert(bucket); resultMap.put(convertedBucket.getKey(), convertedBucket.getValue()); } return resultMap; } private Map.Entry<K, V> convert(String bucketToConvert) { final String[] keyValue = bucketToConvert.split(keyValuePattern); checkKeyValue(keyValue); final String key = unquote(keyValue[0]); final String value = unquote(keyValue[1]); try { final K convertedKey = convert(keyClass, key); final V convertedValue = convert(valueClass, value); final Map.Entry<K, V> convertedBucket = new AbstractMap.SimpleEntry<>(convertedKey, convertedValue); return convertedBucket; } catch (Throwable e) { throw newIllegalArgumentException("The exception is occurred during the conversion", e); } } @SuppressWarnings("unchecked") // It is safe because the type is checked before the cast. private static <I> I convert(Class<I> elementClass, String elementToConvert) { if (isString(elementClass)) { return (I) elementToConvert; } final I convertedValue = Stringifiers.fromString(elementToConvert, elementClass); return convertedValue; } private static void checkKeyValue(String[] keyValue) { if (keyValue.length != 2 || !isQuotedKeyValue(keyValue)) { final String exMessage = "Illegal key-value format. The key-value should be quoted " + "and separated with the `" + KEY_VALUE_DELIMITER + "` character."; throw newIllegalArgumentException(exMessage); } } private static boolean isString(Class<?> aClass) { return String.class.equals(aClass); } private static String unquote(String value) { final String unquotedValue = Pattern.compile("\\\\") .matcher(value.substring(2, value.length() - 2)) .replaceAll(""); return unquotedValue; } private static boolean isQuotedKeyValue(String[] keyValue) { final String key = keyValue[0]; final String value = keyValue[1]; final int keyLength = key.length(); final int valueLength = value.length(); if (keyLength < 2 || valueLength < 2) { return false; } final boolean result = isQuote(key.charAt(1)) && isQuote(key.charAt(keyLength - 1)) && isQuote(value.charAt(1)) && isQuote(value.charAt(valueLength - 1)); return result; } private static boolean isQuote(char character) { return character == QUOTE; } private static Escaper createEscaper(char charToEscape) { final String escapedChar = "\\" + charToEscape; final Escaper result = Escapers.builder() .addEscape('\"', "\\\"") .addEscape(':', "\\:") .addEscape(charToEscape, escapedChar) .build(); return result; } }
package org.jetel.component; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.Defaults; import org.jetel.data.ExternalSortDataRecord; import org.jetel.data.ISortDataRecord; import org.jetel.exception.AttributeNotFoundException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.JetelException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.graph.runtime.tracker.ComponentTokenTracker; import org.jetel.graph.runtime.tracker.CopyComponentTokenTracker; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.SynchronizeUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.property.ComponentXMLAttributes; import org.w3c.dom.Element; /** * <h3>Sort Component</h3> * * <!-- Sorts the incoming records based on specified key --> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>Sort</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>Sorts the incoming records based on specified key.<br> * The key is name (or combination of names) of field(s) from input record. * The sort order is either Ascending (default) or Descending.<br> * In case there is not enough room in internal sort buffer, it performs * external sorting - thus any number of internal records can be sorted.</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>[0]- input records</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>At least one connected output port.</td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td></td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"EXT_SORT"</td></tr> * <tr><td><b>id</b></td><td>component identification</td> * <tr><td><b>sortKey</b></td><td>field names separated by :;| {colon, semicolon, pipe}</td> * <tr><td><b>sortOrder</b><br><i>optional</i></td><td>one of "Ascending|Descending" {the fist letter is sufficient, if not defined, then Ascending}</td> * <tr><td><b>numberOfTapes</b><br><i>optional</i></td><td>even number greater than 2 - denotes how many tapes (temporary files) will be used when external sorting data. * <i>Default is 6 tapes.</i></td> * <!--tr><td><b>sorterInitialCapacity</b><br><i>optional</i></td><td>the initial capacity of internal sorter used for in-memory sorting records. If the * system has plenty of memory, specify high number here (5000 or more). If the system is short on memory, use low number (100).<br> * The final capacity is based on following formula:<br><code>sorter_initial_capacity * (1 - grow_factor^max_num_collections)/(1 - grow_factor)</code><br> * where:<br><code>grow_factor=1.6<br>max_num_collections=8<br>sorterInitialCapacity=2000<br></code><br>With the parameters above, the default total capacity roughly is <b>140000</b> records. The * total capacity is approximately <code>69,91 * sorterInitialCapacity</code>.<br><br> * Following tables shows Total Capacities of internal buffer for various Initial Capacity values: * <table border="1"> * <tr><th>Initial Capacity</th><th>Total Capacity</th></tr> * <tr><td>10</td><td>1000</td></tr> * <tr><td>100</td><td>7000</td></tr> * <tr><td>1000</td><td>70000</td></tr> * <tr><td>2000</td><td>140000</td></tr> * <tr><td>5000</td><td>350000</td></tr> * <tr><td>10000</td><td>700000</td></tr> * <tr><td>20000</td><td>1399000</td></tr> * <tr><td>50000</td><td>3496000</td></tr> * </table> * </tr--> * <tr><td><b>bufferCapacity</b><br><i>optional</i></td><td>What is the maximum number of records * which are sorted in-memory. If number of records exceed this size, external sorting is performed.</td></tr> * <tr><td><b>tmpDirs</b><br><i>optional</i></td><td>Semicolon (;) delimited list of directories which should be * used for creating tape files - used when external sorting is performed. Default value is equal to Java's <code>java.io.tmpdir</code> system property.</td></tr> * </table> * * <h4>Example:</h4> * <pre>&lt;Node id="SORT_CUSTOMER" type="EXT_SORT" sortKey="Name:Address" sortOrder="A"/&gt;</pre> * * @author dpavlis * @since April 4, 2002 */ public class ExtSort extends Node { private static final String XML_NUMBEROFTAPES_ATTRIBUTE = "numberOfTapes"; private static final String XML_SORTERINITIALCAPACITY_ATTRIBUTE = "sorterInitialCapacity"; private static final String XML_SORTORDER_ATTRIBUTE = "sortOrder"; private static final String XML_SORTKEY_ATTRIBUTE = "sortKey"; private static final String XML_BUFFER_CAPACITY_ATTRIBUTE = "bufferCapacity"; private static final String XML_LOCALE_ATTRIBUTE = "locale"; private static final String XML_CASE_SENSITIVE_ATTRIBUTE = "caseSensitive"; /** Description of the Field */ public final static String COMPONENT_TYPE = "EXT_SORT"; private final static int READ_FROM_PORT = 0; private ISortDataRecord sorter; // private SortOrder sortOrderAscending; private boolean[] sortOrderings; private String[] sortKeysNames; /* * case sensitive sorting of string fields? */ boolean caseSensitive = true; private InputPort inPort; private DataRecord inRecord; private int internalBufferCapacity; private int numberOfTapes; private CloverBuffer recordBuffer; private String localeStr; private final static int DEFAULT_NUMBER_OF_TAPES = 6; private static final String KEY_FIELDS_ORDERING_1ST_DELIMETER = "("; private static final String KEY_FIELDS_ORDERING_2ND_DELIMETER = ")"; static Log logger = LogFactory.getLog(ExtSort.class); /** * Constructor for the Sort object * * @param id * Description of the Parameter * @param sortKeysNames * Description of the Parameter * @param sortOrder * Description of the Parameter */ public ExtSort(String id, String[] sortKeys, boolean oldAscendingOrder) { super(id); this.sortKeysNames = sortKeys; this.sortOrderings = new boolean[sortKeysNames.length]; Arrays.fill(sortOrderings, oldAscendingOrder); Pattern pat = Pattern.compile("^(.*)\\((.*)\\)$"); for (int i = 0; i < sortKeys.length; i++) { Matcher matcher = pat.matcher(sortKeys[i]); if (matcher.find()) { String keyPart = sortKeys[i].substring(matcher.start(1), matcher.end(1)); if (matcher.groupCount() > 1) { sortOrderings[i] = (sortKeys[i].substring(matcher.start(2), matcher.end(2))).matches("^[Aa].*"); } sortKeys[i] = keyPart; } } this.numberOfTapes = DEFAULT_NUMBER_OF_TAPES; internalBufferCapacity=-1; } /** * Constructor for the Sort object * * @param id * Description of the Parameter * @param sortKeysNames * Description of the Parameter */ /* public ExtSort(String id, String[] sortKeys) { this(id, sortKeys);//, new SortOrder(new boolean[] { DEFAULT_ASCENDING_SORT_ORDER })); }*/ @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); if (firstRun()) {//a phase-dependent part of initialization //all necessary elements have been initialized in init() } else { sorter.reset(); } } @Override public Result execute() throws Exception { inPort = getInputPort(READ_FROM_PORT); inRecord = DataRecordFactory.newRecord(inPort.getMetadata()); inRecord.init(); DataRecord tmpRecord = inRecord; while (tmpRecord != null && runIt) { tmpRecord = inPort.readRecord(inRecord); if (tmpRecord != null) { sorter.put(inRecord); } SynchronizeUtils.cloverYield(); } try { sorter.sort(); } catch (InterruptedException ex) { throw ex; } catch (Exception ex) { throw new JetelException("Error when sorting", ex); } while (sorter.get(recordBuffer) && runIt) { writeRecordBroadcastDirect(recordBuffer); recordBuffer.clear(); } broadcastEOF(); return runIt ? Result.FINISHED_OK : Result.ABORTED; } @Override public void postExecute() throws ComponentNotReadyException { super.postExecute(); sorter.postExecute(); } /** * Description of the Method * * @exception ComponentNotReadyException * Description of the Exception * @since April 4, 2002 */ @Override public void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); try { // create sorter sorter = new ExternalSortDataRecord(getInputPort(READ_FROM_PORT).getMetadata(), sortKeysNames, sortOrderings, internalBufferCapacity, DEFAULT_NUMBER_OF_TAPES, localeStr, caseSensitive); } catch (Exception e) { throw new ComponentNotReadyException(e); } recordBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE); } @Override public void free() { if(!isInitialized()) return; super.free(); if (sorter != null) { try { sorter.free(); } catch (InterruptedException e) { //DO NOTHING } } } /** * What is the capacity of internal buffer used for * in-memory sorting. * * @param size buffer capacity */ public void setBufferCapacity(int size){ internalBufferCapacity = size; } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @throws AttributeNotFoundException * @since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException, AttributeNotFoundException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); ExtSort sort; boolean oldAscendingOrder; if (xattribs.exists(XML_SORTORDER_ATTRIBUTE)) { // this is for backwards compatibility oldAscendingOrder = xattribs.getString(XML_SORTORDER_ATTRIBUTE) .matches("^[Aa].*"); } else oldAscendingOrder = true; sort = new ExtSort(xattribs.getString(XML_ID_ATTRIBUTE), xattribs.getString( XML_SORTKEY_ATTRIBUTE).split( Defaults.Component.KEY_FIELDS_DELIMITER_REGEX), oldAscendingOrder); if (xattribs.exists(XML_SORTORDER_ATTRIBUTE)) { sort.setSortOrders(xattribs.getString(XML_SORTORDER_ATTRIBUTE), sort.getSortKeyCount()); } if (xattribs.exists(XML_SORTERINITIALCAPACITY_ATTRIBUTE)){ //only for backward compatibility sort.setBufferCapacity(xattribs.getInteger(XML_SORTERINITIALCAPACITY_ATTRIBUTE)); } if (xattribs.exists(XML_NUMBEROFTAPES_ATTRIBUTE)){ sort.setNumberOfTapes(xattribs.getInteger(XML_NUMBEROFTAPES_ATTRIBUTE)); } if (xattribs.exists(XML_BUFFER_CAPACITY_ATTRIBUTE)){ sort.setBufferCapacity(xattribs.getInteger(XML_BUFFER_CAPACITY_ATTRIBUTE)); } if (xattribs.exists(XML_LOCALE_ATTRIBUTE)) { sort.setLocaleStr(xattribs.getString(XML_LOCALE_ATTRIBUTE)); } if (xattribs.exists(XML_CASE_SENSITIVE_ATTRIBUTE)) { sort.setCaseSensitive(xattribs.getBoolean(XML_CASE_SENSITIVE_ATTRIBUTE)); } return sort; } private int getSortKeyCount() { return sortKeysNames.length; } private void setSortOrders(String string, int minLength) { String[] tmp = string.split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); sortOrderings = new boolean[Math.max(tmp.length, minLength)]; boolean lastValue = true; for (int i = 0 ; i < tmp.length ; i++) { lastValue = sortOrderings[i] = tmp[i].matches("^[Aa].*"); } for (int i = tmp.length; i < minLength; i++) { sortOrderings[i] = lastValue; } } /** * Description of the Method * * @return Description of the Return Value */ @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if(!checkInputPorts(status, 1, 1) || !checkOutputPorts(status, 1, Integer.MAX_VALUE)) { return status; } checkMetadata(status, getInMetadata(), getOutMetadata()); DataRecordMetadata inMetadata = getInputPort(READ_FROM_PORT).getMetadata(); for (int i = 0; i < sortKeysNames.length; i++) { if (inMetadata.getFieldPosition(sortKeysNames[i]) < 0) { status.add("Key field '" + sortKeysNames[i] + "' does not exist in input metadata", Severity.ERROR, this, Priority.NORMAL, XML_SORTKEY_ATTRIBUTE); } } // try { // init(); // } catch (ComponentNotReadyException e) { // ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); // if(!StringUtils.isEmpty(e.getAttributeName())) { // problem.setAttributeName(e.getAttributeName()); // status.add(problem); // } finally { // free(); return status; } private int getNumberOfTapes() { return numberOfTapes; } private void setNumberOfTapes(int numberOfTapes) { this.numberOfTapes = numberOfTapes; } public String getLocaleStr() { return localeStr; } public void setLocaleStr(String localeStr) { this.localeStr = localeStr; } public boolean isCaseSensitive() { return caseSensitive; } public void setCaseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; } @Override protected ComponentTokenTracker createComponentTokenTracker() { return new CopyComponentTokenTracker(this); } }
package us.myles.ViaVersion; import lombok.Builder; import us.myles.ViaVersion.api.Via; import us.myles.ViaVersion.api.data.UserConnection; import us.myles.ViaVersion.api.platform.ViaInjector; import us.myles.ViaVersion.api.platform.ViaPlatform; import us.myles.ViaVersion.api.platform.ViaPlatformLoader; import us.myles.ViaVersion.api.platform.providers.ViaProviders; import us.myles.ViaVersion.api.protocol.ProtocolRegistry; import us.myles.ViaVersion.api.protocol.ProtocolVersion; import us.myles.ViaVersion.commands.ViaCommandHandler; import us.myles.ViaVersion.protocols.protocol1_13to1_12_2.TabCompleteThread; import us.myles.ViaVersion.protocols.protocol1_9to1_8.ViaIdleThread; import us.myles.ViaVersion.update.UpdateUtil; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; public class ViaManager { private final ViaPlatform<?> platform; private final ViaProviders providers = new ViaProviders(); // Internals private final ViaInjector injector; private final ViaCommandHandler commandHandler; private final ViaPlatformLoader loader; private final Set<String> subPlatforms = new HashSet<>(); private boolean debug; @Builder public ViaManager(ViaPlatform<?> platform, ViaInjector injector, ViaCommandHandler commandHandler, ViaPlatformLoader loader) { this.platform = platform; this.injector = injector; this.commandHandler = commandHandler; this.loader = loader; } public void init() { if (System.getProperty("ViaVersion") != null) { // Reload? platform.onReload(); } // Check for updates if (platform.getConf().isCheckForUpdates()) UpdateUtil.sendUpdateMessage(); // Force class load ProtocolRegistry.init(); // Inject try { injector.inject(); } catch (Exception e) { platform.getLogger().severe("ViaVersion failed to inject:"); e.printStackTrace(); return; } // Mark as injected System.setProperty("ViaVersion", platform.getPluginVersion()); // If successful platform.runSync(this::onServerLoaded); } public void onServerLoaded() { // Load Server Protocol try { ProtocolRegistry.SERVER_PROTOCOL = injector.getServerProtocolVersion(); } catch (Exception e) { platform.getLogger().severe("ViaVersion failed to get the server protocol!"); e.printStackTrace(); } // Check if there are any pipes to this version if (ProtocolRegistry.SERVER_PROTOCOL != -1) { platform.getLogger().info("ViaVersion detected server version: " + ProtocolVersion.getProtocol(ProtocolRegistry.SERVER_PROTOCOL)); if (!ProtocolRegistry.isWorkingPipe()) { platform.getLogger().warning("ViaVersion does not have any compatible versions for this server version, please read our resource page carefully."); } } // Load Listeners / Tasks ProtocolRegistry.onServerLoaded(); // Load Platform loader.load(); // Common tasks if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_9.getId()) { if (Via.getConfig().isSimulatePlayerTick()) { Via.getPlatform().runRepeatingSync(new ViaIdleThread(), 1L); } } if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_13.getId()) { if (Via.getConfig().get1_13TabCompleteDelay() > 0) { Via.getPlatform().runRepeatingSync(new TabCompleteThread(), 1L); } } // Refresh Versions ProtocolRegistry.refreshVersions(); } public void destroy() { // Uninject platform.getLogger().info("ViaVersion is disabling, if this is a reload and you experience issues consider rebooting."); try { injector.uninject(); } catch (Exception e) { platform.getLogger().severe("ViaVersion failed to uninject:"); e.printStackTrace(); } // Unload loader.unload(); } public Set<UserConnection> getConnections() { return platform.getConnectionManager().getConnections(); } /** * @deprecated use getConnectedClients() */ @Deprecated public Map<UUID, UserConnection> getPortedPlayers() { return getConnectedClients(); } public Map<UUID, UserConnection> getConnectedClients() { return platform.getConnectionManager().getConnectedClients(); } public boolean isClientConnected(UUID player) { return platform.getConnectionManager().isClientConnected(player); } public void handleLoginSuccess(UserConnection info) { platform.getConnectionManager().onLoginSuccess(info); } public void handleDisconnect(UUID id) { UserConnection connection = getConnection(id); if (connection != null) { handleDisconnect(connection); } } public void handleDisconnect(UserConnection info) { platform.getConnectionManager().onDisconnect(info); } public ViaPlatform<?> getPlatform() { return platform; } public ViaProviders getProviders() { return providers; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public ViaInjector getInjector() { return injector; } public ViaCommandHandler getCommandHandler() { return commandHandler; } public ViaPlatformLoader getLoader() { return loader; } /** * Returns a mutable set of self-added subplatform version strings. * This set is expanded by the subplatform itself (e.g. ViaBackwards), and may not contain all running ones. * * @return mutable set of subplatform versions */ public Set<String> getSubPlatforms() { return subPlatforms; } public UserConnection getConnection(UUID playerUUID) { return platform.getConnectionManager().getConnectedClient(playerUUID); } }
package org.neo4j.graphdb; /** * Defines relationship directions used when getting relationships from a * node or when creating traversers. * <p> * A relationship has a direction from a node's point of view. If a node is * the start node of a relationship it will be an {@link #OUTGOING} * relationship from that node's point of view. If a node is the end node of * a relationship it will be an {@link #INCOMING} relationship from that * node's point of view. The {@link #BOTH} direction is used when direction * is of no imporance, such as "give me all" or "traverse all" relationships * that are either {@link #OUTGOING} or {@link #INCOMING}. */ public enum Direction { /** * Defines outgoing relationships. */ OUTGOING, /** * Defines incoming relationships. */ INCOMING, /** * Defines both incoming and outgoing relationships. */ BOTH; /** * Reverses the direction returning {@link #INCOMING} if this equals * {@link #OUTGOING}, {@link #OUTGOING} if this equals {@link #INCOMING} or * {@link #BOTH} if this equals {@link #BOTH}. * * @return The reversed direction. */ public Direction reverse() { switch ( this ) { case OUTGOING: return INCOMING; case INCOMING: return OUTGOING; case BOTH: return BOTH; default: throw new IllegalStateException( "Unknown Direction " + "enum: " + this ); } } }
package hudson.maven; import hudson.FilePath.FileCallable; import hudson.maven.reporters.MavenMailer; import hudson.model.AbstractBuild; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Hudson; import hudson.model.Result; import hudson.remoting.VirtualChannel; import hudson.util.IOException2; import org.apache.maven.embedder.MavenEmbedderException; import org.apache.maven.model.CiManagement; import org.apache.maven.model.Notifier; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * {@link Build} for {@link MavenModuleSet}. * * <p> * A "build" of {@link MavenModuleSet} consists of: * * <ol> * <li>Update the workspace. * <li>Parse POMs * <li>Trigger module builds. * </ol> * * This object remembers the changelog and what {@link MavenBuild}s are done * on this. * * @author Kohsuke Kawaguchi */ public final class MavenModuleSetBuild extends AbstractBuild<MavenModuleSet,MavenModuleSetBuild> { public MavenModuleSetBuild(MavenModuleSet job) throws IOException { super(job); } MavenModuleSetBuild(MavenModuleSet project, File buildDir) throws IOException { super(project, buildDir); } /** * Displays the combined status of all modules. */ @Override public Result getResult() { Result r = super.getResult(); for (List<MavenBuild> list : getModuleBuilds().values()) for (MavenBuild build : list) { Result br = build.getResult(); if(br!=null) r = r.combine(br); } return r; } /** * Computes the module builds that correspond to this build. * <p> * A module may be built multiple times (by the user action), * so the value is a list. */ public Map<MavenModule,List<MavenBuild>> getModuleBuilds() { Collection<MavenModule> mods = getParent().getModules(); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE; // preserve the order by using LinkedHashMap Map<MavenModule,List<MavenBuild>> r = new LinkedHashMap<MavenModule,List<MavenBuild>>(mods.size()); for (MavenModule m : mods) { List<MavenBuild> builds = new ArrayList<MavenBuild>(); MavenBuild b = m.getNearestBuild(number); while(b!=null && b.getNumber()<end) { builds.add(b); b = b.getNextBuild(); } r.put(m,builds); } return r; } /** * Finds {@link Action}s from all the module builds that belong to this * {@link MavenModuleSetBuild}. One action per one {@link MavenModule}, * and newer ones take precedence over older ones. */ public <T extends Action> List<T> findModuleBuildActions(Class<T> action) { Collection<MavenModule> mods = getParent().getModules(); List<T> r = new ArrayList<T>(mods.size()); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber()-1 : Integer.MAX_VALUE; for (MavenModule m : mods) { MavenBuild b = m.getNearestOldBuild(end); while(b!=null && b.getNumber()>=number) { T a = b.getAction(action); if(a!=null) { r.add(a); break; } b = b.getPreviousBuild(); } } return r; } public void run() { run(new RunnerImpl()); } /** * Called when a module build that corresponds to this module set build * has completed. */ /*package*/ void notifyModuleBuild(MavenBuild newBuild) { try { // update module set build number getParent().updateNextBuildNumber(); // update actions Map<MavenModule, List<MavenBuild>> moduleBuilds = getModuleBuilds(); // actions need to be replaced atomically especially // given that two builds might complete simultaneously. synchronized(this) { boolean modified = false; List<Action> actions = getActions(); Set<Class<? extends AggregatableAction>> individuals = new HashSet<Class<? extends AggregatableAction>>(); for (Action a : actions) { if(a instanceof MavenAggregatedReport) { MavenAggregatedReport mar = (MavenAggregatedReport) a; mar.update(moduleBuilds,newBuild); individuals.add(mar.getIndividualActionType()); modified = true; } } // see if the new build has any new aggregatable action that we haven't seen. for (Action a : newBuild.getActions()) { if (a instanceof AggregatableAction) { AggregatableAction aa = (AggregatableAction) a; if(individuals.add(aa.getClass())) { // new AggregatableAction actions.add(aa.createAggregatedAction(this,moduleBuilds)); modified = true; } } } if(modified) { save(); getProject().updateTransientActions(); } } } catch (IOException e) { LOGGER.log(Level.WARNING,"Failed to update "+this,e); } } /** * The sole job of the {@link MavenModuleSet} build is to update SCM * and triggers module builds. */ private class RunnerImpl extends AbstractRunner { protected Result doRun(final BuildListener listener) throws Exception { try { listener.getLogger().println("Parsing POMs"); List<PomInfo> poms = project.getModuleRoot().act(new PomParser(listener,project.getRootPOM())); // update the module list Map<ModuleName,MavenModule> modules = project.modules; synchronized(modules) { Map<ModuleName,MavenModule> old = new HashMap<ModuleName, MavenModule>(modules); modules.clear(); project.reconfigure(poms.get(0)); for (PomInfo pom : poms) { MavenModule mm = old.get(pom.name); if(mm!=null) {// found an existing matching module mm.reconfigure(pom); modules.put(pom.name,mm); } else {// this looks like a new module listener.getLogger().println("Discovered a new module "+pom.name+" "+pom.displayName); mm = new MavenModule(project,pom,getNumber()); modules.put(mm.getModuleName(),mm); } mm.save(); } // remaining modules are no longer active. old.keySet().removeAll(modules.keySet()); for (MavenModule om : old.values()) om.disable(); modules.putAll(old); } // we might have added new modules Hudson.getInstance().rebuildDependencyGraph(); // module builds must start with this build's number for (MavenModule m : modules.values()) m.updateNextBuildNumber(getNumber()); // start the build listener.getLogger().println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(); return null; } catch (AbortException e) { // error should have been already reported. return Result.FAILURE; } catch (IOException e) { e.printStackTrace(listener.error("Failed to parse POMs")); return Result.FAILURE; } catch (InterruptedException e) { e.printStackTrace(listener.error("Aborted")); return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report thus to users@hudson.dev.java.net")); throw e; } } public void post(BuildListener listener) { } } private final class PomParser implements FileCallable<List<PomInfo>> { private final BuildListener listener; private final String rootPOM; public PomParser(BuildListener listener, String rootPOM) { this.listener = listener; this.rootPOM = rootPOM; } /** * Computes the path of {@link #rootPOM}. * * Returns "abc" if rootPOM="abc/pom.xml" * If rootPOM="pom.xml", this method returns "". */ private String getRootPath() { int idx = Math.max(rootPOM.lastIndexOf('/'), rootPOM.lastIndexOf('\\')); if(idx==-1) return ""; return rootPOM.substring(0,idx); } public List<PomInfo> invoke(File ws, VirtualChannel channel) throws IOException { File pom = new File(ws,rootPOM); if(!pom.exists()) { listener.getLogger().println("No such file "+pom); listener.getLogger().println("Perhaps you need to specify the correct POM file path in the project configuration?"); throw new AbortException(); } try { MavenEmbedder embedder = MavenUtil.createEmbedder(listener); MavenProject mp = embedder.readProject(pom); Map<MavenProject,String> relPath = new HashMap<MavenProject,String>(); MavenUtil.resolveModules(embedder,mp,getRootPath(),relPath,listener); List<PomInfo> infos = new ArrayList<PomInfo>(); toPomInfo(mp,null,relPath,infos); for (PomInfo pi : infos) pi.cutCycle(); CiManagement ciMgmt = mp.getCiManagement(); if ((ciMgmt != null) && (ciMgmt.getSystem().equals("hudson"))) { Notifier mailNotifier = null; for (Object n : ciMgmt.getNotifiers()) { Notifier notifier = (Notifier) n; if (notifier.getType().equals("mail")) { mailNotifier = notifier; } } if (mailNotifier != null) { MavenReporter reporter = project.getRootModule().getParent().getReporters().get(MavenMailer.DescriptorImpl.DESCRIPTOR); if (reporter != null) { MavenMailer mailer = (MavenMailer) reporter; mailer.dontNotifyEveryUnstableBuild = !mailNotifier.isSendOnFailure(); String recipients = mailNotifier.getConfiguration().getProperty("recipients"); if (recipients != null) { mailer.recipients = recipients; } } } } embedder.stop(); return infos; } catch (MavenEmbedderException e) { // TODO: better error handling needed throw new IOException2(e); } catch (ProjectBuildingException e) { throw new IOException2(e); } } private void toPomInfo(MavenProject mp, PomInfo parent, Map<MavenProject,String> relPath, List<PomInfo> infos) { PomInfo pi = new PomInfo(mp, parent, relPath.get(mp)); infos.add(pi); for (MavenProject child : (List<MavenProject>)mp.getCollectedProjects()) toPomInfo(child,pi,relPath,infos); } private static final long serialVersionUID = 1L; } private static final Logger LOGGER = Logger.getLogger(MavenModuleSetBuild.class.getName()); }
package io.bitsquare.locale; import io.bitsquare.user.Preferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.Collectors; public class CurrencyUtil { private static final Logger log = LoggerFactory.getLogger(CurrencyUtil.class); private static final List<FiatCurrency> allSortedFiatCurrencies = createAllSortedFiatCurrenciesList(); private static List<FiatCurrency> createAllSortedFiatCurrenciesList() { Set<FiatCurrency> set = CountryUtil.getAllCountries().stream() .map(country -> getCurrencyByCountryCode(country.code)) .collect(Collectors.toSet()); List<FiatCurrency> list = new ArrayList<>(set); list.sort(TradeCurrency::compareTo); return list; } public static List<FiatCurrency> getAllSortedFiatCurrencies() { return allSortedFiatCurrencies; } public static List<FiatCurrency> getAllMainFiatCurrencies() { List<FiatCurrency> list = new ArrayList<>(); // Top traded currencies list.add(new FiatCurrency("USD")); list.add(new FiatCurrency("EUR")); list.add(new FiatCurrency("GBP")); list.add(new FiatCurrency("CAD")); list.add(new FiatCurrency("AUD")); list.add(new FiatCurrency("RUB")); list.add(new FiatCurrency("INR")); TradeCurrency defaultTradeCurrency = getDefaultTradeCurrency(); FiatCurrency defaultFiatCurrency = defaultTradeCurrency instanceof FiatCurrency ? (FiatCurrency) defaultTradeCurrency : null; if (defaultFiatCurrency != null && list.contains(defaultFiatCurrency)) { list.remove(defaultTradeCurrency); list.add(0, defaultFiatCurrency); } return list; } private static final List<CryptoCurrency> allSortedCryptoCurrencies = createAllSortedCryptoCurrenciesList(); public static List<CryptoCurrency> getAllSortedCryptoCurrencies() { return allSortedCryptoCurrencies; } public static List<CryptoCurrency> getMainCryptoCurrencies() { final List<CryptoCurrency> result = new ArrayList<>(); result.add(new CryptoCurrency("ETH", "Ethereum")); result.add(new CryptoCurrency("LTC", "Litecoin")); result.add(new CryptoCurrency("NMC", "Namecoin")); result.add(new CryptoCurrency("DASH", "Dash")); result.add(new CryptoCurrency("NBT", "NuBits")); result.add(new CryptoCurrency("DOGE", "Dogecoin")); result.add(new CryptoCurrency("NXT", "Nxt")); result.add(new CryptoCurrency("BTS", "BitShares")); return result; } public static List<CryptoCurrency> createAllSortedCryptoCurrenciesList() { final List<CryptoCurrency> result = new ArrayList<>(); result.add(new CryptoCurrency("ETH", "Ethereum")); result.add(new CryptoCurrency("LTC", "Litecoin")); result.add(new CryptoCurrency("NMC", "Namecoin")); result.add(new CryptoCurrency("DASH", "Dash")); result.add(new CryptoCurrency("NBT", "NuBits")); result.add(new CryptoCurrency("NSR", "NuShares")); result.add(new CryptoCurrency("PPC", "Peercoin")); result.add(new CryptoCurrency("XPM", "Primecoin")); result.add(new CryptoCurrency("FAIR", "FairCoin")); result.add(new CryptoCurrency("SC", "Siacoin")); result.add(new CryptoCurrency("SJCX", "StorjcoinX")); result.add(new CryptoCurrency("GEMZ", "Gemz")); result.add(new CryptoCurrency("DOGE", "Dogecoin")); result.add(new CryptoCurrency("BLK", "Blackcoin")); result.add(new CryptoCurrency("FCT", "Factom")); result.add(new CryptoCurrency("NXT", "Nxt")); result.add(new CryptoCurrency("BTS", "BitShares")); result.add(new CryptoCurrency("XCP", "Counterparty")); result.add(new CryptoCurrency("XRP", "Ripple")); // Unfortunately we cannot support CryptoNote coins yet as there is no way to proof the transaction. Payment ID helps only locate the tx but the // arbitrator cannot see if the receiving key matches the receivers address. They might add support for exposing the tx key, but that is not // implemented yet. To use the view key (also not available in GUI wallets) would reveal the complete wallet history for incoming payments, which is // not acceptable from privacy point of view. // result.add(new CryptoCurrency("XMR", "Monero")); // result.add(new CryptoCurrency("BCN", "Bytecoin")); return result; } /** * @return Sorted list of SEPA currencies with EUR as first item */ private static Set<TradeCurrency> getSortedSEPACurrencyCodes() { return CountryUtil.getAllSepaCountries().stream() .map(country -> getCurrencyByCountryCode(country.code)) .collect(Collectors.toSet()); } // At OKPay you can exchange internally those currencies public static List<TradeCurrency> getAllOKPayCurrencies() { return new ArrayList<>(Arrays.asList( new FiatCurrency("EUR"), new FiatCurrency("USD"), new FiatCurrency("GBP"), new FiatCurrency("CHF"), new FiatCurrency("RUB"), new FiatCurrency("PLN"), new FiatCurrency("JPY"), new FiatCurrency("CAD"), new FiatCurrency("AUD"), new FiatCurrency("CZK"), new FiatCurrency("NOK"), new FiatCurrency("SEK"), new FiatCurrency("DKK"), new FiatCurrency("HRK"), new FiatCurrency("HUF"), new FiatCurrency("NZD"), new FiatCurrency("RON"), new FiatCurrency("TRY"), new FiatCurrency("ZAR"), new FiatCurrency("HKD"), new FiatCurrency("CNY") )); } public static boolean isFiatCurrency(String currencyCode) { return !(isCryptoCurrency(currencyCode)) && Currency.getInstance(currencyCode) != null; } @SuppressWarnings("WeakerAccess") public static boolean isCryptoCurrency(String currencyCode) { return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny().isPresent(); } public static Optional<CryptoCurrency> getCryptoCurrency(String currencyCode) { return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny(); } public static boolean isCryptoNoteCoin(String currencyCode) { return currencyCode.equals("XMR") || currencyCode.equals("BCN"); } public static FiatCurrency getCurrencyByCountryCode(String countryCode) { return new FiatCurrency(Currency.getInstance(new Locale(LanguageUtil.getDefaultLanguage(), countryCode)).getCurrencyCode()); } public static String getNameByCode(String currencyCode) { try { return Currency.getInstance(currencyCode).getDisplayName(Preferences.getDefaultLocale()); } catch (Throwable t) { // Seems that it is a cryptocurrency return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findFirst().get().getName(); } } public static TradeCurrency getDefaultTradeCurrency() { return Preferences.getDefaultTradeCurrency(); } }
package lucee.runtime.type; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import lucee.commons.collection.MapFactory; import lucee.runtime.PageContext; import lucee.runtime.dump.DumpData; import lucee.runtime.dump.DumpProperties; import lucee.runtime.dump.DumpTable; import lucee.runtime.dump.DumpUtil; import lucee.runtime.dump.SimpleDumpData; import lucee.runtime.exp.ExpressionException; import lucee.runtime.exp.PageException; import lucee.runtime.op.Duplicator; import lucee.runtime.op.ThreadLocalDuplication; import lucee.runtime.type.dt.DateTime; import lucee.runtime.type.it.EntryIterator; import lucee.runtime.type.it.StringIterator; import lucee.runtime.type.util.StructSupport; import lucee.runtime.type.util.StructUtil; /** * CFML data type struct */ public final class StructImplKey extends StructSupport implements Struct { public static final int TYPE_WEAKED = 0; public static final int TYPE_LINKED = 1; public static final int TYPE_SYNC = 2; public static final int TYPE_REGULAR = 3; private Map<Collection.Key, Object> _map; // private static int scount=0; // private static int kcount=0; /** * default constructor */ public StructImplKey() { _map = new HashMap<Collection.Key, Object>(); } /** * This implementation spares its clients from the unspecified, generally chaotic ordering provided * by normally Struct , without incurring the increased cost associated with TreeMap. It can be used * to produce a copy of a map that has the same order as the original * * @param doubleLinked */ public StructImplKey(int type) { if (type == TYPE_LINKED) _map = new LinkedHashMap<Collection.Key, Object>(); else if (type == TYPE_WEAKED) _map = new java.util.WeakHashMap<Collection.Key, Object>(); else if (type == TYPE_SYNC) _map = MapFactory.<Collection.Key, Object>getConcurrentMap(); else _map = new HashMap<Collection.Key, Object>(); } @Override public final Object get(Collection.Key key, Object defaultValue) { Object rtn = _map.get(key); if (rtn != null) return rtn; return defaultValue; } @Override public final Object get(PageContext pc, Collection.Key key, Object defaultValue) { Object rtn = _map.get(key); if (rtn != null) return rtn; return defaultValue; } @Override public final Object get(Collection.Key key) throws PageException {// print.out("k:"+(kcount++)); Object rtn = _map.get(key); if (rtn != null) return rtn; throw invalidKey(key.getString()); } @Override public final Object get(PageContext pc, Collection.Key key) throws PageException {// print.out("k:"+(kcount++)); Object rtn = _map.get(key); if (rtn != null) return rtn; throw invalidKey(key.getString()); } /** * @see lucee.runtime.type.Collection#set(lucee.runtime.type.Collection.Key, java.lang.Object) */ @Override public Object set(Collection.Key key, Object value) throws PageException { _map.put(key, value); return value; } /** * @see lucee.runtime.type.Collection#setEL(lucee.runtime.type.Collection.Key, java.lang.Object) */ @Override public Object setEL(Collection.Key key, Object value) { _map.put(key, value); return value; } /** * @see lucee.runtime.type.Collection#size() */ @Override public int size() { return _map.size(); } @Override public Collection.Key[] keys() {// print.out("keys"); Iterator<Key> it = keyIterator(); Collection.Key[] keys = new Collection.Key[size()]; int count = 0; while (it.hasNext()) { keys[count++] = it.next(); } return keys; } /** * @see lucee.runtime.type.Collection#remove(lucee.runtime.type.Collection.Key) */ @Override public Object remove(Collection.Key key) throws PageException { Object obj = _map.remove(key); if (obj == null) throw new ExpressionException("Cannot remove key [" + key.getString() + "] from struct, the key doesn't exist"); return obj; } @Override public Object removeEL(Collection.Key key) { return _map.remove(key); } /** * @see lucee.runtime.type.Collection#clear() */ @Override public void clear() { _map.clear(); } /** * * @see lucee.runtime.dump.Dumpable#toDumpData(lucee.runtime.PageContext, int) */ @Override public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) { Iterator it = _map.keySet().iterator(); DumpTable table = new DumpTable("struct", "#9999ff", "#ccccff", "#000000"); table.setTitle("Struct"); maxlevel int maxkeys = dp.getMaxKeys(); int index = 0; while (it.hasNext()) { Object key = it.next(); if (DumpUtil.keyValid(dp, maxlevel, key.toString())) { if (maxkeys <= index++) break; table.appendRow(1, new SimpleDumpData(key.toString()), DumpUtil.toDumpData(_map.get(key), pageContext, maxlevel, dp)); } } return table; } /** * throw exception for invalid key * * @param key Invalid key * @return returns an invalid key Exception */ protected ExpressionException invalidKey(String key) { return new ExpressionException("Key [" + key + "] doesn't exist in struct"); } /** * @see lucee.runtime.type.Collection#duplicate(boolean) */ @Override public Collection duplicate(boolean deepCopy) { Struct sct = new StructImplKey(); copy(this, sct, deepCopy); return sct; } public static void copy(Struct src, Struct trg, boolean deepCopy) { boolean inside = ThreadLocalDuplication.set(src, trg); try { Iterator<Entry<Key, Object>> it = src.entryIterator(); Entry<Key, Object> e; while (it.hasNext()) { e = it.next(); if (!deepCopy) trg.setEL(e.getKey(), e.getValue()); else trg.setEL(e.getKey(), Duplicator.duplicate(e.getValue(), deepCopy)); } } finally { if (!inside) ThreadLocalDuplication.reset(); } } @Override public Iterator<Collection.Key> keyIterator() { return _map.keySet().iterator(); } @Override public Iterator<String> keysAsStringIterator() { return new StringIterator(keys()); } @Override public Iterator<Entry<Key, Object>> entryIterator() { return new EntryIterator(this, keys()); } /** * @see lucee.runtime.type.Iteratorable#iterator() */ @Override public Iterator valueIterator() { return _map.values().iterator(); } @Override public final boolean containsKey(Collection.Key key) { return _map.containsKey(key); } @Override public final boolean containsKey(PageContext pc, Collection.Key key) { return _map.containsKey(key); } /** * @see lucee.runtime.op.Castable#castToString() */ @Override public String castToString() throws ExpressionException { throw new ExpressionException("Cannot cast [Struct] to String", "Use Built-In-Function \"serialize(Struct):String\" to create a String from Struct"); } /** * @see lucee.runtime.type.util.StructSupport#castToString(java.lang.String) */ @Override public String castToString(String defaultValue) { return defaultValue; } /** * @see lucee.runtime.op.Castable#castToBooleanValue() */ @Override public boolean castToBooleanValue() throws ExpressionException { throw new ExpressionException("Cannot cast [Struct] to a boolean value"); } /** * @see lucee.runtime.op.Castable#castToBoolean(java.lang.Boolean) */ @Override public Boolean castToBoolean(Boolean defaultValue) { return defaultValue; } /** * @see lucee.runtime.op.Castable#castToDoubleValue() */ @Override public double castToDoubleValue() throws ExpressionException { throw new ExpressionException("Cannot cast [Struct] to a numeric value"); } /** * @see lucee.runtime.op.Castable#castToDoubleValue(double) */ @Override public double castToDoubleValue(double defaultValue) { return defaultValue; } /** * @see lucee.runtime.op.Castable#castToDateTime() */ @Override public DateTime castToDateTime() throws ExpressionException { throw new ExpressionException("Cannot cast [Struct] to a Date"); } /** * @see lucee.runtime.op.Castable#castToDateTime(lucee.runtime.type.dt.DateTime) */ @Override public DateTime castToDateTime(DateTime defaultValue) { return defaultValue; } /** * @see lucee.runtime.op.Castable#compare(boolean) */ @Override public int compareTo(boolean b) throws ExpressionException { throw new ExpressionException("Cannot compare a [Struct] with a boolean value"); } /** * @see lucee.runtime.op.Castable#compareTo(lucee.runtime.type.dt.DateTime) */ @Override public int compareTo(DateTime dt) throws PageException { throw new ExpressionException("Cannot compare a [Struct] with a DateTime Object"); } /** * @see lucee.runtime.op.Castable#compareTo(double) */ @Override public int compareTo(double d) throws PageException { throw new ExpressionException("Cannot compare a [Struct] with a numeric value"); } /** * @see lucee.runtime.op.Castable#compareTo(java.lang.String) */ @Override public int compareTo(String str) throws PageException { throw new ExpressionException("Cannot compare a [Struct] with a String"); } @Override public boolean containsValue(Object value) { return _map.containsValue(value); } @Override public java.util.Collection values() { return _map.values(); } @Override public int getType() { return StructUtil.getType(_map); } }
package org.javarosa.core.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class StreamsUtil { /** * Write everything from input stream to output stream, byte by byte then * close the streams */ @SuppressWarnings("unused") public static void writeFromInputToOutput(InputStream in, OutputStream out, long[] tally) throws InputIOException, OutputIOException { //TODO: God this is naive int val; try { val = in.read(); } catch (IOException e) { throw new StreamsUtil().new InputIOException(e); } while (val != -1) { try { out.write(val); } catch (IOException e) { throw new StreamsUtil().new OutputIOException(e); } incr(tally); try { val = in.read(); } catch (IOException e) { throw new StreamsUtil().new InputIOException(e); } } } public static void writeFromInputToOutputSpecific(InputStream in, OutputStream out) throws InputIOException, OutputIOException { writeFromInputToOutput(in, out, null); } public static void writeFromInputToOutput(InputStream in, OutputStream out) throws IOException { try { writeFromInputToOutput(in, out, null); } catch (InputIOException e) { throw e.internal; } catch (OutputIOException e) { throw e.internal; } } private static final int CHUNK_SIZE = 2048; /** * Write the byte array to the output stream */ public static void writeToOutput(byte[] bytes, OutputStream out, long[] tally) throws IOException { int offset = 0; int remain = bytes.length; while (remain > 0) { int toRead = (remain < CHUNK_SIZE) ? remain : CHUNK_SIZE; out.write(bytes, offset, toRead); remain -= toRead; offset += toRead; if (tally != null) { tally[0] += toRead; } } } @SuppressWarnings("unused") public static void writeToOutput(byte[] bytes, OutputStream out) throws IOException { writeToOutput(bytes, out, null); } private static void incr(long[] tally) { if (tally != null) { tally[0]++; } } //Unify the functional aspects here private abstract class DirectionalIOException extends IOException { final IOException internal; public DirectionalIOException(IOException internal) { super(internal.getMessage()); this.internal = internal; } public IOException getWrapped() { return internal; } public void printStackTrace() { internal.printStackTrace(); } //TODO: Override all common methodss } public class InputIOException extends DirectionalIOException { public InputIOException(IOException internal) { super(internal); } } public class OutputIOException extends DirectionalIOException { public OutputIOException(IOException internal) { super(internal); } } }
package org.kohsuke.stapler; import org.apache.commons.beanutils.Converter; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public final class AcceptHeader { private final List<Atom> atoms = new ArrayList<Atom>(); private final String ranges; * something like "text/*;q=0.5,*; q=0.1" */ public AcceptHeader(String ranges) { this.ranges = ranges; for (String r : StringUtils.split(ranges, ',')) atoms.add(new Atom(r)); } /** * Media range plus parameters and extensions */ protected static class Atom { private final String major; private final String minor; private final Map<String, String> params = new HashMap<String, String>(); private final float q; @Override public String toString() { StringBuilder s = new StringBuilder(major +'/'+ minor); for (String k : params.keySet()) s.append(";").append(k).append("=").append(params.get(k)); return s.toString(); } * Parses a string like 'application/*;q=0.5' into a typed object. */ protected Atom(String range) { String[] parts = StringUtils.split(range, ";"); for (int i = 1; i < parts.length; ++i) { String p = parts[i]; String[] subParts = StringUtils.split(p, '='); if (subParts.length == 2) params.put(subParts[0].trim(), subParts[1].trim()); } String fullType = parts[0].trim(); // Java URLConnection class sends an Accept header that includes a if (fullType.equals("*")) fullType = "*/*"; String[] types = StringUtils.split(fullType, "/"); major = types[0].trim(); minor = types[1].trim(); float q = NumberUtils.toFloat(params.get("q"), 1); if (q < 0 || q > 1) q = 1; this.q = q; params.remove("q"); // normalize this away as this gets in the fitting } * than "text/*", which still fits better than "* /*" */ private int fit(Atom that) { if (!wildcardMatch(that.major, this.major) || !wildcardMatch(that.minor, this.minor)) return -1; int fitness; fitness = (this.major.equals(that.major)) ? 10000 : 0; fitness += (this.minor.equals(that.minor)) ? 1000 : 0; // parameter matches increase score for (String k : that.params.keySet()) { if (that.params.get(k).equals(this.params.get(k))) { fitness++; } } return fitness; } } private static boolean wildcardMatch(String a, String b) { return a.equals(b) || a.equals("*") || b.equals("*"); } /** * Given a MIME type, find the entry from this Accept header that fits the best. * * @param mimeType */ protected @Nullable Atom match(String mimeType) { Atom target = new Atom(mimeType); int bestFitness = -1; Atom best = null; for (Atom a : atoms) { int f = a.fit(target); if (f>bestFitness) { best = a; bestFitness = f; } } return best; } * new AcceptHeader("image/*;q=0.5, image/png;q=1").select("text/plain","text/xml") => null * }</pre> * * @return null if none of the choices in {@code supported} is acceptable to the client. */ public String select(Iterable<String> supported) { float bestQ = 0; String best = null; for (String s : supported) { Atom a = match(s); if (a!= null && a.q > bestQ) { bestQ = a.q; best = s; } } if (best==null) throw HttpResponses.error(HttpServletResponse.SC_NOT_ACCEPTABLE, "Requested MIME types '" + ranges + "' didn't match any of the available options "+supported); return best; } public String select(String... supported) { return select(Arrays.asList(supported)); } @Override public String toString() { return super.toString()+"["+ranges+"]"; } // this performs databinding for @Header parameter injection public static class StaplerConverterImpl implements Converter { public Object convert(Class type, Object value) { return new AcceptHeader(value.toString()); } } }
package net.meeusen.crypto; import java.util.Arrays; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.DerivationParameters; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.generators.KDFCounterBytesGenerator; import org.bouncycastle.crypto.macs.CMac; import org.bouncycastle.crypto.params.KDFCounterParameters; import net.meeusen.util.ByteString; public class Nist800_108Test { final static int bitsPerByte = 8; public static void main(String[] args) { Nist800_108Test someNistTestVectors[] = new Nist800_108Test[] { new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.BEFORE_FIXED, RLen.R_8_BITS, 128, "dff1e50ac0b69dc40f1051d46c2b069c", "c16e6e02c5a3dcc8d78b9ac1306877761310455b4e41469951d9e6c2245a064b33fd8c3b01203a7824485bf0a64060c4648b707d2607935699316ea5", "8be8f0869b3c0ba97b71863d1b9f7813"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.BEFORE_FIXED, RLen.R_8_BITS, 128, "e4d94da336fada7c0ee4a9591dd0327a", "538fefb2eeb7c50c84bf603a7beddff4bba049f0052c45f13c56e9ae5944eb22d677f280e5a29c588cf40c7c57f7767aad3d595069fb40d02c01f866", "268a1d44ba5a5b1a28b9a611c76671f7"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.BEFORE_FIXED, RLen.R_16_BITS, 128, "30ec5f6fa1def33cff008178c4454211", "c95e7b1d4f2570259abfc05bb00730f0284c3bb9a61d07259848a1cb57c81d8a6c3382c500bf801dfc8f70726b082cf4c3fa34386c1e7bf0e5471438", "00018fff9574994f5c4457f461c7a67e"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.BEFORE_FIXED, RLen.R_24_BITS, 128, "ca1cf43e5ccd512cc719a2f9de41734c", "e3884ac963196f02ddd09fc04c20c88b60faa775b5ef6feb1faf8c5e098b5210e2b4e45d62cc0bf907fd68022ee7b15631b5c8daf903d99642c5b831", "1cb2b12326cc5ec1eba248167f0efd58"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.BEFORE_FIXED, RLen.R_24_BITS, 320, "26fa0e32e7e08f9b157ebae9f579710f", "ceab805efbe0c50a8aef62e59d95e7a54daa74ed86aa9b1ae8abf68b985b5af4b0ee150e83e6c063b59c7bf813ede9826af149237aed85b415898fa8", "f1d9138afcc3db6001eb54c4da567a5db3659fc0ed48e664a0408946bcee0742127c17cabf348c7a"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.BEFORE_FIXED, RLen.R_32_BITS, 128, "c10b152e8c97b77e18704e0f0bd38305", "98cd4cbbbebe15d17dc86e6dbad800a2dcbd64f7c7ad0e78e9cf94ffdba89d03e97eadf6c4f7b806caf52aa38f09d0eb71d71f497bcc6906b48d36c4", "26faf61908ad9ee881b8305c221db53f"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.AFTER_FIXED, RLen.R_8_BITS, 128, "e61a51e1633e7d0de704dcebbd8f962f", "5eef88f8cb188e63e08e23c957ee424a3345da88400c567548b57693931a847501f8e1bce1c37a09ef8c6e2ad553dd0f603b52cc6d4e4cbb76eb6c8f", "63a5647d0fe69d21fc420b1a8ce34cc1"), new Nist800_108Test(Prf.CMAC_AES192, CtrLocation.BEFORE_FIXED, RLen.R_8_BITS, 128, "53d1705caab7b06886e2dbb53eea349aa7419a034e2d92b9", "b120f7ce30235784664deae3c40723ca0539b4521b9aece43501366cc5df1d9ea163c602702d0974665277c8a7f6a057733d66f928eb7548cf43e374", "eae32661a323f6d06d0116bb739bd76a"), new Nist800_108Test(Prf.CMAC_AES192, CtrLocation.BEFORE_FIXED, RLen.R_24_BITS, 128, "f7c1e0682a12f1f17d23dc8af5c463b8aa28f87ed82fad22", "890ec4966a8ac3fd635bd264a4c726c87341611c6e282766b7ffe621080d0c00ac9cf8e2784a80166303505f820b2a309e9c3a463d2e3fd4814e3af5", "a71b0cbe30331fdbb63f8d51249ae50b"), new Nist800_108Test(Prf.CMAC_AES256, CtrLocation.BEFORE_FIXED, RLen.R_8_BITS, 128, "aeb7201d055f754212b3e497bd0b25789a49e51da9f363df414a0f80e6f4e42c", "11ec30761780d4c44acb1f26ca1eb770f87c0e74505e15b7e456b019ce0c38103c4d14afa1de71d340db51410596627512cf199fffa20ef8c5f4841e", "2a9e2fe078bd4f5d3076d14d46f39fb2"), new Nist800_108Test(Prf.CMAC_AES256, CtrLocation.BEFORE_FIXED, RLen.R_16_BITS, 128, "4df60800bf8e2f6055c5ad6be43ee3deb54e2a445bc88a576e111b9f7f66756f", "962adcaf12764c87dad298dbd9ae234b1ff37fed24baee0649562d466a80c0dcf0a65f04fe5b477fd00db6767199fa4d1b26c68158c8e656e740ab4d", "eca99d4894cdda31fe355b82059a845c"), new Nist800_108Test(Prf.CMAC_AES256, CtrLocation.AFTER_FIXED, RLen.R_32_BITS, 320, "a487f6ae25608d71b98bd7f7973fa68871b91fb59f703a2e4684d3b98c4309fe", "b353d8e8558b52023882646d9271e245ea5c3684806d726858227dbae641385f4dd122907abb9005f59584f7bf859e0f19a99f52b2f15fffbed3499f", "9820f408e23d1c05638e36540e18832659691471bf215e68f535d66e6b482362902fcdda1818a01f"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.MIDDLE_FIXED, RLen.R_8_BITS, 128, "b6e04abd1651f8794d4326f4c684e631", "93612f7256c46a3d856d3e951e32dbf15fe11159d0b389ad38d603850fee6d18d22031435ed36ee20da76745fbea4b10fe1e", "99322aae605a5f01e32b", "dcb1db87a68762c6b3354779fa590bef"), new Nist800_108Test(Prf.CMAC_AES128, CtrLocation.MIDDLE_FIXED, RLen.R_32_BITS, 128, "90e33a1e76adedcabd2214326be71abf", "3d2f38c571575807eecd0ec9e3fd860fb605f0b17139ce01904abba7ae688a50e620341787f69f00b872343f42b18c979f6f", "8885034123cb45e27440", "9e2156cd13e079c1e6c6379f9a55f433"), }; System.out.println("Running " + someNistTestVectors.length + " NIST test vectors."); int testCounter = 0; for ( Nist800_108Test t : someNistTestVectors ) { System.out.print(testCounter + ":" + t + ": "); boolean hasPassed = t.checkTestVector(); if ( ! hasPassed ) { System.out.println("ERROR."); } else { System.out.println("OK."); } testCounter++; } System.out.println("DONE running NIST test vectors."); System.out.println("Some other tests."); byte[] Ki256_allzeros = new byte[256/bitsPerByte]; String label = "I am deriving a key"; //String label = "CRYPTO STORAGE HW Crypto Derived key SYMR"; String context ="To verify the kdf working"; //String context = "CRYPTO STORAGE HW Crypto key derived from SHK SYMR"; ByteString zeroByte = new ByteString("00"); ByteString labelBytes = new ByteString( label.getBytes() ); ByteString contextBytes = new ByteString( context.getBytes() ); byte[] expectedKo = new ByteString ("132540A1EA6D871254D50521485544CB8286E798D1A2E1DD52EBEB97780CDAE9").getBytes(); ByteString encodedLength = new ByteString("00000100"); // note: must match outputSize, currently hardcoded. /* NIST spec: K(i) := PRF (KI, [i]2 || Label || 0x00 || Context || [L]2) * where [i]2 is added by BC KDFCounterBytesGenerator class. */ byte[] fixedInputData = ByteString.concat(new ByteString[]{labelBytes, zeroByte, contextBytes, encodedLength}).getBytes(); Nist800_108Test othertest = new Nist800_108Test(Prf.CMAC_AES256, CtrLocation.BEFORE_FIXED, RLen.R_32_BITS, 256, Ki256_allzeros, fixedInputData, null, expectedKo); boolean result = othertest.checkTestVector(); System.out.println("result: "+ result); } private enum Prf { CMAC_AES128, CMAC_AES256, CMAC_AES192, ; public String toString() { switch (this) { case CMAC_AES128: return "CMAC_AES128"; case CMAC_AES192: return "CMAC_AES192"; case CMAC_AES256: return "CMAC_AES256"; default: throw new IllegalArgumentException(); } } } private enum CtrLocation { BEFORE_FIXED, MIDDLE_FIXED, AFTER_FIXED; public String toString() { switch (this) { case BEFORE_FIXED: return "BEFORE_FIXED"; case MIDDLE_FIXED: return "MIDDLE_FIXED"; case AFTER_FIXED: return "AFTER_FIXED"; default: throw new IllegalArgumentException(); } } } private enum RLen { R_8_BITS, R_16_BITS, R_24_BITS, R_32_BITS ; public String toString() { switch (this) { case R_8_BITS: return "R_8_BITS"; case R_16_BITS: return "R_16_BITS"; case R_24_BITS: return "R_24_BITS"; case R_32_BITS: return "R_32_BITS"; default: throw new IllegalArgumentException(); } } } private Prf prf; private CtrLocation ctrloc; /* r : An integer, smaller or equal to 32, whose value is the length of the binary representation of the counter i when i is an input in counter mode or (optionally) in feedback mode and double-pipeline iteration mode of each iteration of the PRF. */ private RLen rValue; private int L_outputbits; private byte[] inputkey; private byte[] fixedInDataBefore; private byte[] fixedInDataAfter; private byte[] expectedoutput; /** * Constructor with * a) TWO fixed data inputs (before/after counter) * b) byte[] for ki/fixed data/ko * */ public Nist800_108Test(Prf prf, CtrLocation ctrloc, RLen rEnum, int nrOutputBits, byte[] ki, byte[] fixedinputBefore, byte[] fixedinputAfter, byte[] ko) { this.prf = prf; this.ctrloc = ctrloc; this.rValue = rEnum; this.L_outputbits = nrOutputBits; this.inputkey = ki.clone(); this.fixedInDataBefore = fixedinputBefore.clone(); if ( fixedinputAfter != null ) this.fixedInDataAfter = fixedinputAfter.clone(); this.expectedoutput = ko.clone(); // some checks int nrOutputBytes = this.L_outputbits/bitsPerByte; if ( nrOutputBytes != this.expectedoutput.length ) { throw new Error("Error, L value must be equal to given output key size."); } } /** * Constructor with * a) TWO fixed data inputs (before/after counter) * b) String for ki/fixed data/ko. * */ public Nist800_108Test(Prf prf, CtrLocation ctrloc, RLen rEnum, int nrOutputBits, String ki, String fixedinputBefore, String fixedinputAfter, String ko) { this(prf,ctrloc, rEnum, nrOutputBits, new ByteString(ki).getBytes(), new ByteString(fixedinputBefore).getBytes(), new ByteString(fixedinputAfter).getBytes(), new ByteString(ko).getBytes()); } /** * Constructor with * a) ONE fixed data input * b) String for ki/fixed data/ko. * */ public Nist800_108Test(Prf prf, CtrLocation ctrloc, RLen rEnum, int nrOutputBits, String ki, String fixedinput, String ko) { this( prf, ctrloc, rEnum, nrOutputBits, ki, fixedinput, null, ko); } /** * summarize some KDF params in a string * */ public String toString() { return this.prf.toString() +" "+ this.ctrloc +" "+ this.rValue; } /** * Do a KDF, and compare with expected output. * */ boolean checkTestVector() { int inKeyLenBits = this.inputkey.length*bitsPerByte; switch (this.prf) { case CMAC_AES128: if (inKeyLenBits!=128) throw new Error(); break; case CMAC_AES192: if (inKeyLenBits!=192) throw new Error(); break; case CMAC_AES256:if (inKeyLenBits!=256) throw new Error(); break; } int rbits=0; switch(this.rValue) { case R_8_BITS: rbits=8;break; case R_16_BITS: rbits=16;break; case R_24_BITS: rbits=24;break; case R_32_BITS: rbits=32;break; } DerivationParameters myparams =null; switch(this.ctrloc) { case BEFORE_FIXED: myparams = new KDFCounterParameters(this.inputkey, null, this.fixedInDataBefore, rbits); break; case MIDDLE_FIXED: myparams = new KDFCounterParameters(this.inputkey, this.fixedInDataBefore,this.fixedInDataAfter, rbits); break; case AFTER_FIXED: myparams = new KDFCounterParameters(this.inputkey, this.fixedInDataBefore,null, rbits); break; } BlockCipher underlyingCipher = new AESEngine(); Mac aesCbcMac = new CMac(underlyingCipher); KDFCounterBytesGenerator mygen = new KDFCounterBytesGenerator(aesCbcMac); mygen.init(myparams); byte[] KO = new byte[this.L_outputbits/bitsPerByte]; int offset=0; mygen.generateBytes(KO, offset, KO.length); return Arrays.equals(KO, expectedoutput); } }
package com.cv4j.core.filters; import com.cv4j.core.datamodel.ColorProcessor; import com.cv4j.core.datamodel.ImageProcessor; public abstract class BaseFilter implements CommonFilter { protected int width; protected int height; protected byte[] R; protected byte[] G; protected byte[] B; @Override public ImageProcessor filter(ImageProcessor src) { if (src == null) return null; if (!(src instanceof ColorProcessor)) return src; width = src.getWidth(); height = src.getHeight(); R = ((ColorProcessor)src).getRed(); G = ((ColorProcessor)src).getGreen(); B = ((ColorProcessor)src).getBlue(); return doFilter(src); } public abstract ImageProcessor doFilter(ImageProcessor src); }
package demo.mantle; public class TestTool implements java.util.spi.ToolProvider { @Override public String name() { return "test(demo.mantle)"; } @Override public int run(java.io.PrintWriter out, java.io.PrintWriter err, String... args) { try { checkMantle(); return 0; } catch (Throwable throwable) { throwable.printStackTrace(err); return 1; } } private static void checkMantle() { var mantle = new Mantle(); var type = mantle.core.getClass(); if (!type.getSimpleName().equals("PublicCore")) { throw new AssertionError("Expected PublicCore, but got: " + type); } } }
package com.stanfy.images; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.regex.Pattern; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.TextView; import com.stanfy.DebugFlags; import com.stanfy.images.model.CachedImage; import com.stanfy.views.ImagesLoadListenerProvider; import com.stanfy.views.LoadableImageView; import com.stanfy.views.LoadableTextView; import com.stanfy.views.utils.AppUtils; public class ImagesManager<T extends CachedImage> { /** Logging tag. */ private static final String TAG = "ImagesManager"; /** Pattern to cut the images sources from HTML. */ protected static final Pattern IMG_URL_PATTERN = Pattern.compile("<img.*?src=\"(.*?)\".*?>"); /** Debug flag. */ private static final boolean DEBUG_IO = DebugFlags.DEBUG_IO; /** Debug flag. */ private static final boolean DEBUG = DebugFlags.DEBUG_IMAGES; /** Empty drawable. */ protected static final ColorDrawable EMPTY_DRAWABLE = new ColorDrawable(0xeeeeee); /** Memory cache. */ private ImageMemoryCache memCache; /** Buffers pool. */ private final BuffersPool buffersPool = new BuffersPool(new int[][] { {4, BuffersPool.DEFAULT_SIZE_FOR_IMAGES} }); /** Resources. */ private final Resources resources; /** Target density from source. */ private int sourceDensity = 0; /** Images format. */ private Bitmap.Config imagesFormat = Bitmap.Config.RGB_565; /** Current loads. */ private final ConcurrentHashMap<String, ImageLoader<T>> currentLoads = new ConcurrentHashMap<String, ImageLoader<T>>(Threading.imagesWorkersCount); /** Hidden constructor. */ public ImagesManager(final Resources resources) { this.resources = resources; } /** @param memCache the memCache to set */ public void setMemCache(final ImageMemoryCache memCache) { this.memCache = memCache; } /** @param imagesFormat the imagesFormat to set */ public void setImagesFormat(final Bitmap.Config imagesFormat) { this.imagesFormat = imagesFormat; } /** @param sourceDensity the sourceDensity to set */ public void setSourceDensity(final int sourceDensity) { this.sourceDensity = sourceDensity; } /** * Ensure that all the images are loaded. Not loaded images will be downloaded in this thread. * @param imagesDao images DAO * @param downloader downloader instance * @param context context instance * @param images images collection */ public void ensureImages(final ImagesDAO<T> imagesDao, final Downloader downloader, final Context context, final List<T> images) { final File imagesDir = getImageDir(context); for (final T image : images) { if (image.isLoaded() && new File(imagesDir, image.getPath()).exists()) { continue; } try { makeImageLocal(imagesDao, context, image, downloader); } catch (final IOException e) { if (DEBUG_IO) { Log.e(TAG, "IO error for " + image.getUrl() + ": " + e.getMessage()); } } } } /** * Clear the cached entities. * @param context context instance * @param path image file system path * @param url image URL * @return size of the deleted file */ public long clearCache(final Context context, final String path, final String url) { memCache.remove(url, false); long size = 0; if (path != null) { final File f = new File(getImageDir(context), path); size = f.length(); delete(f); } return size; } /** * Flush resources. */ public void flush() { memCache.clear(false); buffersPool.flush(); } /** * Populate the requested image to the specified view. Called from the GUI thread. * @param view view instance * @param url image URL * @param imagesDAO images DAO * @param downloader downloader instance */ public void populateImage(final View view, final String url, final ImagesManagerContext<T> imagesContext) { final Object tag = view.getTag(); ImageHolder imageHolder = null; if (tag == null) { imageHolder = createImageHolder(view); view.setTag(imageHolder); } else { if (!(tag instanceof ImageHolder)) { throw new IllegalStateException("View already has a tag " + tag); } imageHolder = (ImageHolder)tag; } populateImage(imageHolder, url, imagesContext); } /** * Cancel image loading for a view. * @param view view that hold an image */ public void cancelImageLoading(final View view) { final Object tag = view.getTag(); if (tag != null && tag instanceof ImageHolder) { cancelImageLoading((ImageHolder)tag); } } /** * Cancel image loading for a holder. * @param holder image holder instance */ public void cancelImageLoading(final ImageHolder holder) { holder.cancelLoader(); } protected ImageHolder createImageHolder(final View view) { if (view instanceof LoadableImageView) { return new LoadableImageViewHolder((LoadableImageView)view); } if (view instanceof ImageView) { return new ImageViewHolder((ImageView)view); } if (view instanceof CompoundButton) { return new CompoundButtonHolder((CompoundButton)view); } if (view instanceof TextView) { return new TextViewHolder((TextView)view); } return null; } /** * @param url image URL * @return true if image is cached in memory */ public boolean isMemCached(final String url) { return memCache.contains(url); } /** * @param url image URL * @param view that contains an image holder * @return image bitmap from memory cache */ public Drawable getMemCached(final String url, final View view) { final Object tag = view.getTag(); if (tag == null || !(tag instanceof ImageHolder)) { return null; } final Drawable res = getFromMemCache(url, (ImageHolder)tag); if (res == null) { return null; } return decorateDrawable((ImageHolder)tag, res); } public void populateImage(final ImageHolder imageHolder, final String url, final ImagesManagerContext<T> imagesContext) { if (DEBUG) { Log.d(TAG, "Process url" + url); } if (TextUtils.isEmpty(url)) { setLoadingImage(imageHolder); return; } imageHolder.cancelLoader(); final Drawable memCached = getFromMemCache(url, imageHolder); if (memCached != null) { imageHolder.start(null, url); setImage(imageHolder, memCached, false); imageHolder.finish(url, memCached); return; } if (DEBUG) { Log.d(TAG, "Set loading for " + url); } setLoadingImage(imageHolder); imageHolder.currentUrl = url; // we are in GUI thread startImageLoaderTask(imageHolder, imagesContext); } private void setLoadingImage(final ImageHolder holder) { if (!holder.skipLoadingImage()) { final Drawable d = !holder.isDynamicSize() ? getLoadingDrawable(holder) : null; setImage(holder, d, true); } } /** * @param image image to process * @return local file system path to that image */ public String setCachedImagePath(final T image) { if (image.getPath() != null) { return image.getPath(); } final long id = image.getId(); final String path = AppUtils.buildFilePathById(id, "image-" + id); image.setPath(path); return path; } /** * @return an executor for image tasks */ protected Executor getImageTaskExecutor() { return Threading.getImageTasksExecutor(); } /** * @param context context * @return a drawable to display while the image is loading */ protected Drawable getLoadingDrawable(final ImageHolder holder) { final Drawable d = holder.getLoadingImage(); return d != null ? d : EMPTY_DRAWABLE; } /** * @param context context instance * @param drawable resulting drawable * @return decorated drawable */ protected Drawable decorateDrawable(final ImageHolder holder, final Drawable drawable) { return drawable; } /** * @param imageView image view instance * @param drawable incoming drawable * @param preloader preloading image flag */ protected final void setImage(final ImageHolder imageHolder, final Drawable drawable, final boolean preloader) { final Drawable d = decorateDrawable(imageHolder, drawable); if (preloader) { imageHolder.setLoadingImage(d); } else { imageHolder.setImage(d); } synchronized (imageHolder) { imageHolder.reset(); } } /** * @param url image URL * @return cached drawable */ protected Drawable getFromMemCache(final String url, final ImageHolder holder) { synchronized (holder) { if (holder.currentUrl != null && !holder.currentUrl.equals(url)) { return null; } } final Bitmap map = memCache.getElement(url); if (map == null) { return null; } final BitmapDrawable result = new BitmapDrawable(holder.context.getResources(), map); final int gap = 5; return holder.isDynamicSize() || holder.skipScaleBeforeCache() || Math.abs(holder.getRequiredWidth() - result.getIntrinsicWidth()) < gap || Math.abs(holder.getRequiredHeight() - result.getIntrinsicHeight()) < gap ? result : null; } /** * @param imageHolder image holder to process * @param imagesDAO images DAO * @param downloader downloader instance * @return loader task instance */ protected void startImageLoaderTask(final ImageHolder imageHolder, final ImagesManagerContext<T> imagesContext) { final String key = imageHolder.getLoaderKey(); if (DEBUG) { Log.d(TAG, "Key " + key); } ImageLoader<T> loader = currentLoads.get(key); if (loader != null) { final boolean added = loader.addTarget(imageHolder); if (!added) { loader = null; } } if (loader == null) { if (DEBUG) { Log.d(TAG, "Start a new task"); } loader = new ImageLoader<T>(imageHolder.currentUrl, key, imagesContext); final boolean added = loader.addTarget(imageHolder); if (!added) { throw new IllegalStateException("Cannot add target to the new loader"); } currentLoads.put(key, loader); final Executor executor = getImageTaskExecutor(); executor.execute(loader.future); } else if (DEBUG) { Log.d(TAG, "Joined to the existing task"); } } /** * @param context context instance * @return base dir to save images */ public File getImageDir(final Context context) { final String eState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(eState)) { return AppUtils.getSdkDependentUtils().getExternalCacheDir(context); } return context.getCacheDir(); } private static void delete(final File file) { if (!file.exists()) { return; } final File parent = file.getParentFile(); if (file.delete()) { delete(parent); } } protected void makeImageLocal(final ImagesDAO<T> imagesDao, final Context context, final T image, final Downloader downloader) throws IOException { final String path = setCachedImagePath(image); final File f = new File(getImageDir(context), path); final File parent = f.getParentFile(); parent.mkdirs(); if (!parent.exists()) { Log.e(TAG, "Directories not created for " + f.getParent() + ". Local image won't be saved."); return; } final InputStream in = new PoolableBufferedInputStream(downloader.download(image.getUrl()), BuffersPool.DEFAULT_SIZE_FOR_IMAGES, buffersPool); final FileOutputStream out = new FileOutputStream(f); final byte[] buffer = buffersPool.get(BuffersPool.DEFAULT_SIZE_FOR_IMAGES); if (buffer == null) { return; } int cnt; try { do { cnt = in.read(buffer); if (cnt != -1) { out.write(buffer, 0, cnt); } } while (cnt != -1); } finally { in.close(); out.close(); buffersPool.release(buffer); } image.setLoaded(true); final long time = System.currentTimeMillis(); image.setTimestamp(time); image.setUsageTimestamp(time); imagesDao.updateImage(image); } protected void memCacheImage(final String url, final Drawable d) { if (d instanceof BitmapDrawable) { if (DEBUG) { Log.d(TAG, "Memcache for " + url); } memCache.putElement(url, ((BitmapDrawable)d).getBitmap()); } } protected Drawable readLocal(final T cachedImage, final Context context, final ImageHolder holder) throws IOException { final File file = new File(getImageDir(context), cachedImage.getPath()); if (!file.exists()) { if (DEBUG_IO) { Log.w(TAG, "Local file " + file.getAbsolutePath() + "does not exist."); } return null; } final BitmapFactory.Options options = new BitmapFactory.Options(); if (holder.useSampling() && !holder.isDynamicSize()) { options.inSampleSize = resolveSampleFactor(new FileInputStream(file), holder.getRequiredWidth(), holder.getRequiredHeight()); } final Drawable d = decodeStream(new FileInputStream(file), options); return d; } private InputStream prepareImageOptionsAndInput(final InputStream is, final BitmapFactory.Options options) { final BuffersPool bp = buffersPool; final int bCapacity = BuffersPool.DEFAULT_SIZE_FOR_IMAGES; InputStream src = new FlushedInputStream(is); if (!src.markSupported()) { src = new PoolableBufferedInputStream(src, bCapacity, bp); } final BitmapFactory.Options opts = options != null ? options : new BitmapFactory.Options(); opts.inTempStorage = bp.get(bCapacity); opts.inPreferredConfig = imagesFormat; opts.inDensity = sourceDensity; return src; } private void onImageDecodeFinish(final InputStream src, final BitmapFactory.Options opts) throws IOException { buffersPool.release(opts.inTempStorage); src.close(); } static int nearestPowerOf2(final int value) { if (value <= 0) { return -1; } int result = -1, x = value; while (x > 0) { ++result; x >>>= 1; } return 1 << result; } protected int resolveSampleFactor(final InputStream is, final int width, final int height) throws IOException { final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; final InputStream src = prepareImageOptionsAndInput(is, opts); int result = 1; try { BitmapFactory.decodeResourceStream(null, null, src, null, opts); final int inW = opts.outWidth, inH = opts.outHeight; if (inW > width || inH > height) { final int factor = inW > inH ? inW / width : inH / height; if (factor > 1) { result = factor; final int p = nearestPowerOf2(factor); final int maxDistance = 3; if (result - p < maxDistance) { result = p; } if (DEBUG) { Log.d(TAG, "Sampling: factor=" + factor + ", p=" + p + ", result=" + result); } } } } finally { // recycle onImageDecodeFinish(src, opts); } return result; } protected Drawable decodeStream(final InputStream is, final BitmapFactory.Options options) throws IOException { final BitmapFactory.Options opts = options != null ? options : new BitmapFactory.Options(); final InputStream src = prepareImageOptionsAndInput(is, opts); try { final Bitmap bm = BitmapFactory.decodeResourceStream(null, null, src, null, opts); final Drawable res = bm != null ? new BitmapDrawable(resources, bm) : null; if (DEBUG) { Log.d(TAG, "Image decoded: " + opts.outWidth + "x" + opts.outHeight + ", res=" + res); } return res; } catch (final OutOfMemoryError e) { // I know, it's bad to catch error but files can be VERY big! return null; } finally { // recycle onImageDecodeFinish(src, opts); } } protected static class ImageLoader<T extends CachedImage> implements Callable<Void> { /** Image URL. */ private final String url; /** Loader key. */ private final String key; /** Images manager. */ private final ImagesManager<T> imagesManager; /** Images DAO. */ private final ImagesDAO<T> imagesDAO; /** Downloader. */ private final Downloader downloader; /** Future task instance. */ final FutureTask<Void> future; /** Targets. */ private final ArrayList<ImageHolder> targets = new ArrayList<ImageHolder>(); /** Main GUI view. */ private ImageHolder mainTarget; /** Result drawable. */ private Drawable resultDrawable; /** Resolved result flag. */ private boolean resultResolved = false, started = false; public ImageLoader(final String url, final String key, final ImagesManagerContext<T> imagesContext) { this.url = url; this.key = key; this.imagesManager = imagesContext.getImagesManager(); this.downloader = imagesContext.getDownloader(); this.imagesDAO = imagesContext.getImagesDAO(); this.future = new FutureTask<Void>(this); } /** Called from UI thread. */ public boolean addTarget(final ImageHolder imageHolder) { if (future.isCancelled()) { return false; } // we should start a new task if (!future.isDone()) { // normal case synchronized (this) { if (started) { imageHolder.start(this, url); } if (resultResolved) { imagesManager.setImage(imageHolder, resultDrawable, false); imageHolder.finish(url, resultDrawable); } else { imageHolder.currentLoader = this; targets.add(imageHolder); if (mainTarget == null) { mainTarget = imageHolder; } } } } else { // we finished imagesManager.setImage(imageHolder, resultDrawable, false); } return true; } public void removeTarget(final ImageHolder imageHolder) { imageHolder.cancel(url); synchronized (this) { targets.remove(imageHolder); if (targets.isEmpty()) { future.cancel(true); } } } protected void safeImageSet(final T cachedImage, final Drawable source) { final Drawable d; synchronized (this) { resultResolved = true; if (source == null) { return; } d = memCacheImage(source); resultDrawable = d; } final String url = this.url; mainTarget.post(new Runnable() { @Override public void run() { final ArrayList<ImageHolder> targets = ImageLoader.this.targets; final int count = targets.size(); for (int i = 0; i < count; i++) { final ImageHolder imageHolder = targets.get(i); if (DEBUG) { Log.d(TAG, "Try to set " + imageHolder + " - " + url); } synchronized (imageHolder) { final String currentUrl = imageHolder.currentUrl; if (currentUrl != null && currentUrl.equals(url)) { imagesManager.setImage(imageHolder, d, false); } else { if (DEBUG) { Log.d(TAG, "Skip set for " + imageHolder); } } } } } }); } protected Drawable setLocalImage(final T cachedImage) throws IOException { final Context x = mainTarget.context; if (x == null) { throw new IOException("Context is null"); } final Drawable d = imagesManager.readLocal(cachedImage, x, mainTarget); if (d != null) { imagesDAO.updateUsageTimestamp(cachedImage); } safeImageSet(cachedImage, d); return d; } protected Drawable setRemoteImage(final T cachedImage) throws IOException { if (!url.startsWith("http")) { return null; } final Context x = mainTarget.context; if (x == null) { throw new IOException("Context is null"); } cachedImage.setType(mainTarget.getImageType()); imagesManager.makeImageLocal(imagesDAO, x, cachedImage, downloader); return setLocalImage(cachedImage); } private BitmapDrawable prepare(final BitmapDrawable bd) { int dstW = mainTarget.getRequiredWidth(), dstH = mainTarget.getRequiredHeight(); if (dstW <= 0 || dstH <= 0 || mainTarget.skipScaleBeforeCache()) { if (DEBUG) { Log.d(TAG, "Skip scaling for " + mainTarget + " skip flag: " + mainTarget.skipScaleBeforeCache()); } return bd; } final Bitmap map = bd.getBitmap(); final int w = bd.getIntrinsicWidth(), h = bd.getIntrinsicHeight(); if (w <= dstW && h <= dstH) { return bd; } final double ratio = (double)w / h; if (w > h) { dstH = (int)(dstW / ratio); } else { dstW = (int)(dstH * ratio); } if (dstW <= 0 || dstH <= 0) { return bd; } final Bitmap scaled = Bitmap.createScaledBitmap(map, dstW, dstH, true); return new BitmapDrawable(scaled); } private Drawable memCacheImage(final Drawable d) { Drawable result = d; if (d instanceof BitmapDrawable) { final BitmapDrawable bmd = (BitmapDrawable)d; result = prepare(bmd); if (result != bmd) { bmd.getBitmap().recycle(); } } imagesManager.memCacheImage(url, result); return result; } private void start() { synchronized (this) { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final String url = this.url; for (int i = 0; i < count; i++) { targets.get(i).start(this, url); } started = true; } } private void finish() { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final Drawable d = this.resultDrawable; for (int i = 0; i < count; i++) { targets.get(i).finish(url, d); } } private void cancel() { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final String url = this.url; for (int i = 0; i < count; i++) { targets.get(i).cancel(url); } } private void error(final Throwable e) { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final String url = this.url; for (int i = 0; i < count; i++) { targets.get(i).error(url, e); } } @Override public Void call() { if (DEBUG) { Log.d(TAG, "Start image task"); } final String url = this.url; try { start(); T cachedImage = imagesDAO.getCachedImage(url); if (cachedImage == null) { cachedImage = imagesDAO.createCachedImage(url); if (cachedImage == null) { Log.w(TAG, "Cached image info was not created for " + url); return null; } } Drawable d = null; if (cachedImage.isLoaded()) { if (Thread.interrupted()) { cancel(); return null; } d = setLocalImage(cachedImage); if (DEBUG) { Log.d(TAG, "Image " + cachedImage.getId() + "-local"); } } if (d == null) { if (Thread.interrupted()) { cancel(); return null; } d = setRemoteImage(cachedImage); if (DEBUG) { Log.d(TAG, "Image " + cachedImage.getId() + "-remote"); } } if (d == null) { Log.w(TAG, "Image " + cachedImage.getUrl() + " is not resolved"); } finish(); } catch (final MalformedURLException e) { Log.e(TAG, "Bad URL: " + url + ". Loading canceled.", e); error(e); } catch (final IOException e) { if (DEBUG_IO) { Log.e(TAG, "IO error for " + url + ": " + e.getMessage()); } error(e); } catch (final Exception e) { Log.e(TAG, "Cannot load image " + url, e); error(e); } finally { final boolean removed = imagesManager.currentLoads.remove(key, this); if (!removed && DEBUG) { Log.w(TAG, "Incorrect loader in currents for " + key); } } return null; } } static class FlushedInputStream extends FilterInputStream { public FlushedInputStream(final InputStream inputStream) { super(inputStream); } @Override public long skip(final long n) throws IOException { long totalBytesSkipped = 0L; final InputStream in = this.in; while (totalBytesSkipped < n) { long bytesSkipped = in.skip(n - totalBytesSkipped); if (bytesSkipped == 0L) { final int b = read(); if (b < 0) { break; // we reached EOF } else { bytesSkipped = 1; // we read one byte } } totalBytesSkipped += bytesSkipped; } return totalBytesSkipped; } } public abstract static class ImageHolder { /** Context instance. */ Context context; /** Current image URL. Set this field from the GUI thread only! */ String currentUrl; /** Listener. */ ImagesLoadListener listener; /** Current loader. */ ImageLoader<?> currentLoader; /** Loader key. */ private String loaderKey; /** @param context context instance */ public ImageHolder(final Context context) { this.context = context; reset(); } /* access */ /** @param listener the listener to set */ public final void setListener(final ImagesLoadListener listener) { this.listener = listener; } /** @return the context */ public Context getContext() { return context; } /* actions */ void reset() { currentUrl = null; loaderKey = null; } public void touch() { } public abstract void setImage(final Drawable d); public void setLoadingImage(final Drawable d) { setImage(d); } public abstract void post(final Runnable r); public void destroy() { context = null; } final void cancelLoader() { final String url = currentUrl; if (DEBUG) { Log.d(TAG, "Cancel " + url); } if (url != null) { final ImageLoader<?> loader = this.currentLoader; if (loader != null) { loader.removeTarget(this); } } } final void start(final ImageLoader<?> loader, final String url) { this.currentLoader = loader; if (listener != null) { listener.onLoadStart(this, url); } } final void finish(final String url, final Drawable drawable) { this.currentLoader = null; if (listener != null) { listener.onLoadFinished(this, url, drawable); } } final void error(final String url, final Throwable exception) { this.currentLoader = null; if (listener != null) { listener.onLoadError(this, url, exception); } } final void cancel(final String url) { this.currentLoader = null; if (listener != null) { listener.onLoadCancel(this, url); } } /* parameters */ public abstract int getRequiredWidth(); public abstract int getRequiredHeight(); public boolean isDynamicSize() { return getRequiredWidth() <= 0 || getRequiredHeight() <= 0; } public Drawable getLoadingImage() { return null; } public int getImageType() { return 0; } String getLoaderKey() { if (loaderKey == null) { loaderKey = currentUrl + "!" + getRequiredWidth() + "x" + getRequiredWidth(); } return loaderKey; } /* options */ public boolean skipScaleBeforeCache() { return false; } public boolean skipLoadingImage() { return false; } public boolean useSampling() { return false; } } public abstract static class ViewImageHolder<T extends View> extends ImageHolder { /** View instance. */ T view; public ViewImageHolder(final T view) { super(view.getContext()); this.view = view; touch(); } @Override public void touch() { final T view = this.view; if (view != null && view instanceof ImagesLoadListenerProvider) { this.listener = ((ImagesLoadListenerProvider)view).getImagesLoadListener(); } } @Override public void post(final Runnable r) { if (context instanceof Activity) { ((Activity)context).runOnUiThread(r); } else { view.post(r); } } @Override public int getRequiredHeight() { final View view = this.view; final LayoutParams params = view.getLayoutParams(); if (params == null || params.height == LayoutParams.WRAP_CONTENT) { return -1; } final int h = view.getHeight(); return h > 0 ? h : params.height; } @Override public int getRequiredWidth() { final View view = this.view; final LayoutParams params = view.getLayoutParams(); if (params == null || params.width == LayoutParams.WRAP_CONTENT) { return -1; } final int w = view.getWidth(); return w > 0 ? w : params.width; } @Override public void destroy() { super.destroy(); view = null; } } static class ImageViewHolder extends ViewImageHolder<ImageView> { public ImageViewHolder(final ImageView view) { super(view); } @Override public void setImage(final Drawable d) { view.setImageDrawable(d); } } static class LoadableImageViewHolder extends ImageViewHolder { public LoadableImageViewHolder(final LoadableImageView view) { super(view); } @Override public boolean skipScaleBeforeCache() { return ((LoadableImageView)view).isSkipScaleBeforeCache(); } @Override public boolean skipLoadingImage() { return ((LoadableImageView)view).isSkipLoadingImage(); } @Override public boolean useSampling() { return ((LoadableImageView)view).isUseSampling(); } @Override public Drawable getLoadingImage() { return ((LoadableImageView)view).getLoadingImage(); } @Override public void setLoadingImage(final Drawable d) { final LoadableImageView view = (LoadableImageView)this.view; setImage(d); view.setTemporaryScaleType(ScaleType.FIT_XY); } @Override public int getImageType() { return ((LoadableImageView)this.view).getImageType(); } } static class CompoundButtonHolder extends ViewImageHolder<CompoundButton> { public CompoundButtonHolder(final CompoundButton view) { super(view); } @Override public void setImage(final Drawable d) { view.setButtonDrawable(d); } } static class TextViewHolder extends ViewImageHolder<TextView> { public TextViewHolder(final TextView view) { super(view); } @Override public void setImage(final Drawable d) { if (view instanceof LoadableTextView) { ((LoadableTextView) view).setLoadedDrawable(d); } else { view.setCompoundDrawablesWithIntrinsicBounds(d, null, null, null); } } @Override public int getRequiredHeight() { return -1; } @Override public int getRequiredWidth() { return -1; } } }
package org.epics.vtype; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.Collection; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.epics.util.array.ListNumber; import org.epics.util.text.NumberFormats; import org.epics.util.time.TimestampFormat; /** * Various utility methods for runtime handling of the types defined in * this package. * * @author carcassi */ public class ValueUtil { private ValueUtil() { // Can't instanciate } private static Collection<Class<?>> types = Arrays.<Class<?>>asList(VByte.class, VByteArray.class, VDouble.class, VDoubleArray.class, VEnum.class, VEnumArray.class, VFloat.class, VFloatArray.class, VInt.class, VIntArray.class, VMultiDouble.class, VMultiEnum.class, VMultiInt.class, VMultiString.class, VShort.class, VShortArray.class, VStatistics.class, VString.class, VStringArray.class, VTable.class); /** * Returns the type of the object by returning the class object of one * of the VXxx interfaces. The getClass() methods returns the * concrete implementation type, which is of little use. If no * super-interface is found, Object.class is used. * * @param obj an object implementing a standard type * @return the type is implementing */ public static Class<?> typeOf(Object obj) { if (obj == null) return null; return typeOf(obj.getClass()); } private static Class<?> typeOf(Class<?> clazz) { if (clazz.equals(Object.class)) return Object.class; for (int i = 0; i < clazz.getInterfaces().length; i++) { Class<?> interf = clazz.getInterfaces()[i]; if (types.contains(interf)) return interf; } return typeOf(clazz.getSuperclass()); } /** * Extracts the alarm information if present. * * @param obj an object implementing a standard type * @return the alarm information for the object */ public static Alarm alarmOf(Object obj) { if (obj == null) { return ValueFactory.alarmNone(); } if (obj instanceof Alarm) return (Alarm) obj; return null; } /** * Extracts the alarm information if present, based on value * and connection status. * * @param value a value * @param connected the connection status * @return the alarm information */ public static Alarm alarmOf(Object value, boolean connected) { if (value != null) { return alarmOf(value); } else if (connected) { return ValueFactory.newAlarm(AlarmSeverity.INVALID, "No value"); } else { return ValueFactory.newAlarm(AlarmSeverity.UNDEFINED, "Disconnected"); } } /** * Extracts the time information if present. * * @param obj an object implementing a standard type * @return the time information for the object */ public static Time timeOf(Object obj) { if (obj instanceof Time) return (Time) obj; return null; } /** * Extracts the display information if present. * * @param obj an object implementing a standard type * @return the display information for the object */ public static Display displayOf(Object obj) { if (!(obj instanceof Display)) return null; Display display = (Display) obj; if (display.getLowerAlarmLimit() == null || display.getLowerDisplayLimit() == null) return null; return display; } /** * Checks whether the display limits are non-null and non-NaN. * * @param display a display * @return true if the display limits have actual values */ public static boolean displayHasValidDisplayLimits(Display display) { if (display.getLowerDisplayLimit() == null || display.getLowerDisplayLimit().isNaN()) { return false; } if (display.getUpperDisplayLimit() == null || display.getUpperDisplayLimit().isNaN()) { return false; } return true; } /** * Extracts the numericValueOf the object and normalizes according * to the display range. * * @param obj an object implementing a standard type * @return the value normalized in its display range, or null * if no value or display information is present */ public static Double normalizedNumericValueOf(Object obj) { return normalize(numericValueOf(obj), displayOf(obj)); } /** * Normalizes the given value according to the given display information. * * @param value a value * @param display the display information * @return the normalized value, or null of either value or display is null */ public static Double normalize(Number value, Display display) { if (value == null || display == null) { return null; } return (value.doubleValue() - display.getLowerDisplayLimit()) / (display.getUpperDisplayLimit() - display.getLowerDisplayLimit()); } /** * Normalizes the given value according to the given range; * * @param value a value * @param lowValue the lowest value in the range * @param highValue the highest value in the range * @return the normalized value, or null if any value is null */ public static Double normalize(Number value, Number lowValue, Number highValue) { if (value == null || lowValue == null || highValue == null) { return null; } return (value.doubleValue() - lowValue.doubleValue()) / (highValue.doubleValue() - lowValue.doubleValue()); } /** * Extracts a numeric value for the object. If it's a numeric scalar, * the value is returned. If it's a numeric array, the first element is * returned. If it's a numeric multi array, the value of the first * element is returned. * * @param obj an object implementing a standard type * @return the numeric value */ public static Double numericValueOf(Object obj) { if (obj instanceof VNumber) { Number value = ((VNumber) obj).getValue(); if (value != null) { return value.doubleValue(); } } if (obj instanceof VEnum) { return (double) ((VEnum) obj).getIndex(); } if (obj instanceof VNumberArray) { ListNumber data = ((VNumberArray) obj).getData(); if (data != null && data.size() != 0) { return data.getDouble(0); } } if (obj instanceof VEnumArray) { ListNumber data = ((VEnumArray) obj).getIndexes(); if (data != null && data.size() != 0) { return data.getDouble(0); } } if (obj instanceof MultiScalar) { List values = ((MultiScalar) obj).getValues(); if (!values.isEmpty()) return numericValueOf(values.get(0)); } return null; } /** * Converts a VImage to an AWT BufferedImage, so that it can be displayed. * The content of the vImage buffer is copied, so further changes * to the VImage will not modify the BufferedImage. * * @param vImage the image to be converted * @return a new BufferedImage */ public static BufferedImage toImage(VImage vImage) { BufferedImage image = new BufferedImage(vImage.getWidth(), vImage.getHeight(), BufferedImage.TYPE_3BYTE_BGR); System.arraycopy(vImage.getData(), 0, ((DataBufferByte) image.getRaster().getDataBuffer()).getData(), 0, vImage.getWidth() * vImage.getHeight() * 3); return image; } /** * Converts an AWT BufferedImage to a VImage. * <p> * Currently, only TYPE_3BYTE_BGR is supported * * @param image * @return a new image */ public static VImage toVImage(BufferedImage image) { if (image.getType() != BufferedImage.TYPE_3BYTE_BGR) { throw new IllegalArgumentException("Only BufferedImages of type TYPE_3BYTE_BGR can currently be converted to VImage"); } byte[] buffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); return ValueFactory.newVImage(image.getHeight(), image.getWidth(), buffer); } /** * Returns true if the two displays contain the same information. * * @param d1 the first display * @param d2 the second display * @return true if they match */ public static boolean displayEquals(Display d1, Display d2) { if (d1 == d2) { return true; } if (Objects.equals(d1.getFormat(), d2.getFormat()) && Objects.equals(d1.getUnits(), d2.getUnits()) && Objects.equals(d1.getLowerDisplayLimit(), d2.getLowerDisplayLimit()) && Objects.equals(d1.getLowerAlarmLimit(), d2.getLowerAlarmLimit()) && Objects.equals(d1.getLowerWarningLimit(), d2.getLowerWarningLimit()) && Objects.equals(d1.getUpperWarningLimit(), d2.getUpperWarningLimit()) && Objects.equals(d1.getUpperAlarmLimit(), d2.getUpperAlarmLimit()) && Objects.equals(d1.getUpperDisplayLimit(), d2.getUpperDisplayLimit()) && Objects.equals(d1.getLowerCtrlLimit(), d2.getLowerCtrlLimit()) && Objects.equals(d1.getUpperCtrlLimit(), d2.getUpperCtrlLimit())) { return true; } return false; } private static volatile TimestampFormat defaultTimestampFormat = new TimestampFormat(); private static volatile NumberFormat defaultNumberFormat = NumberFormats.toStringFormat(); private static volatile ValueFormat defaultValueFormat = new SimpleValueFormat(3); private static volatile Map<AlarmSeverity, Integer> rgbSeverityColor = createDefaultSeverityColorMap(); private static Map<AlarmSeverity, Integer> createDefaultSeverityColorMap() { Map<AlarmSeverity, Integer> colorMap = new EnumMap<>(AlarmSeverity.class); colorMap.put(AlarmSeverity.NONE, Color.GREEN.getRGB()); colorMap.put(AlarmSeverity.MINOR, Color.YELLOW.getRGB()); colorMap.put(AlarmSeverity.MAJOR, Color.RED.getRGB()); colorMap.put(AlarmSeverity.INVALID, Color.MAGENTA.getRGB()); colorMap.put(AlarmSeverity.UNDEFINED, Color.DARK_GRAY.getRGB()); return colorMap; } /** * Changes the color map for AlarmSeverity. The new color map must be complete * and not null; * * @param map the new color map */ public static void setAlarmSeverityColorMap(Map<AlarmSeverity, Integer> map) { if (map == null) { throw new IllegalArgumentException("Alarm severity color map can't be null"); } for (AlarmSeverity alarmSeverity : AlarmSeverity.values()) { if (!map.containsKey(alarmSeverity)) { throw new IllegalArgumentException("Missing color for AlarmSeverity." + alarmSeverity); } } Map<AlarmSeverity, Integer> colorMap = new EnumMap<>(AlarmSeverity.class); colorMap.putAll(map); rgbSeverityColor = colorMap; } /** * Returns the rgb value for the given severity. * * @param severity an alarm severity * @return the rgb color */ public static int colorFor(AlarmSeverity severity) { return rgbSeverityColor.get(severity); } /** * The default object to format and parse timestamps. * * @return the default timestamp format */ public static TimestampFormat getDefaultTimestampFormat() { return defaultTimestampFormat; } /** * Changes the default timestamp format. * * @param defaultTimestampFormat the new default timestamp format */ public static void setDefaultTimestampFormat(TimestampFormat defaultTimestampFormat) { ValueUtil.defaultTimestampFormat = defaultTimestampFormat; } /** * The default format for numbers. * * @return the default number format */ public static NumberFormat getDefaultNumberFormat() { return defaultNumberFormat; } /** * Changes the default format for numbers. * * @param defaultNumberFormat the new default number format */ public static void setDefaultNumberFormat(NumberFormat defaultNumberFormat) { ValueUtil.defaultNumberFormat = defaultNumberFormat; } /** * The default format for VTypes. * * @return the default format */ public static ValueFormat getDefaultValueFormat() { return defaultValueFormat; } /** * Changes the default format for VTypes. * * @param defaultValueFormat the new default format */ public static void setDefaultValueFormat(ValueFormat defaultValueFormat) { ValueUtil.defaultValueFormat = defaultValueFormat; } public static ListNumber numericColumnOf(VTable table, String columnName) { if (columnName == null) { return null; } for (int i = 0; i < table.getColumnCount(); i++) { if (columnName.equals(table.getColumnName(i))) { if (table.getColumnType(i).isPrimitive()) { return (ListNumber) table.getColumnData(i); } else { throw new IllegalArgumentException("Column '" + columnName +"' is not numeric (contains " + table.getColumnType(i).getSimpleName() + ")"); } } } throw new IllegalArgumentException("Column '" + columnName +"' was not found"); } }
package edu.umd.cs.findbugs.util; import java.util.LinkedHashMap; import java.util.Map; import org.apache.bcel.classfile.JavaClass; /** * Provide a HashMap that can only grow to a specified maximum capacity, * with entries discarded using a LRU policy to keep the size of the HashMap * within that bound. * * @author pugh */ public class MapCache<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = 0L; int maxCapacity; /** * Create a new MapCache * @param maxCapacity - maximum number of entries in the map */ public MapCache(int maxCapacity) { super(16, 0.75f, true); this.maxCapacity = maxCapacity; count = new int[maxCapacity]; } int [] count; @Override public V get(Object k) { if (false) { int age = count.length-1; for(Map.Entry<K,V> e : entrySet()) { if (e.getKey().equals(k)) { count[age]++; if (age > 20 && k instanceof JavaClass) { System.out.println("Reusing value from " + age + " steps ago "); System.out.println("Class " + ((JavaClass)k).getClassName()); new RuntimeException().printStackTrace(System.out); } break; } age } } return super.get(k); } @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { boolean result = size() > maxCapacity; K key = eldest.getKey(); if (false && result && key instanceof JavaClass) System.out.println("Dropping " + ((JavaClass)key).getClassName()); return result; } public String getStatistics() { StringBuffer b = new StringBuffer(); for(int c : count) b.append(c).append(" "); return b.toString(); } }
package org.flymine.io.gff3; import junit.framework.TestCase; import java.util.*; import java.io.StringReader; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URLDecoder; import org.apache.commons.lang.StringEscapeUtils; /** * Tests for the GFF3Parser class. * * @author Kim Rutherford */ public class GFF3ParserTest extends TestCase { public GFF3ParserTest (String arg) { super(arg); } public void testParse() throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/gff_test_data.gff3"))); List records = new ArrayList(); Iterator iter = GFF3Parser.parse(reader); while (iter.hasNext()) { GFF3Record record = (GFF3Record) iter.next(); records.add(record); } String [] expected = new String[]{ "<GFF3Record: sequenceID: ctg123 source: null type: gene start: 1000 end: 9000 score: null strand: + phase: null attributes: {ID=[gene00001], Name=[EDEN, zen]}>", "<GFF3Record: sequenceID: ctg123 source: null type: TF_binding_site start: 1000 end: 1012 score: null strand: + phase: null attributes: {ID=[tfbs00001], Name=[name1, name2], Parent=[gene00001]}>", "<GFF3Record: sequenceID: ctg123 source: null type: mRNA start: 1050 end: 9000 score: null strand: + phase: null attributes: {ID=[mRNA00001], Parent=[gene00001], Name=[EDEN.1]}>", "<GFF3Record: sequenceID: ctg123 source: null type: five_prime_UTR start: 1050 end: 1200 score: null strand: + phase: null attributes: {Parent=[mRNA0001]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 1201 end: 1500 score: null strand: + phase: 0 attributes: {Parent=[mRNA0001]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 3000 end: 3902 score: null strand: + phase: 0 attributes: {Parent=[mRNA0001]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 5000 end: 5500 score: null strand: + phase: 0 attributes: {Parent=[mRNA0001]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 7000 end: 7600 score: null strand: + phase: 0 attributes: {Parent=[mRNA0001]}>", "<GFF3Record: sequenceID: ctg123 source: null type: three_prime_UTR start: 7601 end: 9000 score: null strand: + phase: null attributes: {Parent=[mRNA0001]}>", "<GFF3Record: sequenceID: ctg123 source: null type: mRNA start: 1050 end: 9000 score: null strand: + phase: null attributes: {ID=[mRNA00002], Parent=[gene00001], Name=[EDEN.2]}>", "<GFF3Record: sequenceID: ctg123 source: null type: five_prime_UTR start: 1050 end: 1200 score: null strand: + phase: null attributes: {Parent=[mRNA0002]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 1201 end: 1500 score: null strand: + phase: 0 attributes: {Parent=[mRNA0002]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 5000 end: 5500 score: null strand: + phase: 0 attributes: {Parent=[mRNA0002]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 7000 end: 7600 score: null strand: + phase: 0 attributes: {Parent=[mRNA0002]}>", "<GFF3Record: sequenceID: ctg123 source: null type: three_prime_UTR start: 7601 end: 9000 score: null strand: + phase: null attributes: {Parent=[mRNA0002]}>", "<GFF3Record: sequenceID: ctg123 source: null type: mRNA start: 1300 end: 9000 score: null strand: + phase: null attributes: {ID=[mRNA00003], Parent=[gene00001], Name=[EDEN.3]}>", "<GFF3Record: sequenceID: ctg123 source: null type: five_prime_UTR start: 1300 end: 1500 score: null strand: + phase: null attributes: {Parent=[mRNA0003]}>", "<GFF3Record: sequenceID: ctg123 source: null type: five_prime_UTR start: 3000 end: 3300 score: null strand: + phase: null attributes: {Parent=[mRNA0003]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 3301 end: 3902 score: null strand: + phase: 0 attributes: {Parent=[mRNA0003]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 5000 end: 5500 score: null strand: + phase: 2 attributes: {Parent=[mRNA0003]}>", "<GFF3Record: sequenceID: ctg123 source: null type: CDS start: 7000 end: 7600 score: null strand: + phase: 2 attributes: {Parent=[mRNA0003]}>", "<GFF3Record: sequenceID: ctg123 source: null type: three_prime_UTR start: 7601 end: 9000 score: null strand: + phase: null attributes: {Parent=[mRNA0003]}>", }; assertEquals(expected.length, records.size()); GFF3Record record0 = (GFF3Record) records.get(0); List names = (List) record0.getAttributes().get("Name"); assertEquals("EDEN", names.get(0)); assertEquals("zen", names.get(1)); assertEquals(9000, record0.getEnd()); assertNull(record0.getSource()); GFF3Record record1 = (GFF3Record) records.get(1); assertEquals("name1", record1.getNames().get(0)); assertEquals("gene00001", record1.getParents().get(0)); assertNull(record1.getOntologyTerm()); for (int i = 0; i < 22; i++) { assertEquals(expected[i], ((GFF3Record) records.get(i)).toString()); } } public void testDecoding() throws Exception { String input = "2L\t.\tgene\t14263522\t14328265\t.\t+\t.\t" + "ID=CG15288;Name=wb;Dbxref=FlyBase:FBan0015288,FlyBase:FBgn0004002;cyto_range=35A3-35A4;" + "dbxref_2nd=FlyBase:FBgn0025691,FlyBase:FBgn0032544,GB:CG15288;gbunit=AE003643;synonym=wb;" + "synonym_2nd=A1,BEST:CK02229,BG:DS03792.1,CK02229,CT35236,DLAM,D-laminin+%26agr%3B2,l(2)09437," + "l(2)34Fb,l(2)br1,l34Fb,laminin,laminin+%26agr%3B1%2C2,Laminin+%26agr%3B1%2C2,LM-A/%26agr%3B2,wing+blistered"; GFF3Record record = new GFF3Record(input); } public void testFixGreek() { String input = "<br/>&agr;<br/>&Agr;<br/>&bgr;<br/>&Bgr;<br/>&ggr;" + "<br/>&Ggr;<br/>&dgr;<br/>&Dgr;<br/>&egr;<br/>&Egr;<br/>&zgr;" + "<br/>&Zgr;<br/>&eegr;<br/>&EEgr;<br/>&thgr;<br/>&THgr;<br/>&igr;" + "<br/>&Igr;<br/>&kgr;<br/>&Kgr;<br/>&lgr;<br/>&Lgr;<br/>&mgr;<br/>&Mgr;" + "<br/>&ngr;<br/>&Ngr;<br/>&xgr;<br/>&Xgr;<br/>&ogr;<br/>&Ogr;<br/>&pgr;<br/>" + "&Pgr;<br/>&rgr;<br/>&Rgr;<br/>&sgr;<br/>&Sgr;<br/>&sfgr;<br/>&tgr;<br/>&Tgr;" + "<br/>&ugr;<br/>&Ugr;<br/>&phgr;<br/>&PHgr;<br/>&khgr;<br/>&KHgr;<br/>&psgr;" + "<br/>&PSgr;<br/>&ohgr;<br/>&OHgr;"; String expect = "<br/>&alpha;<br/>&Alpha;<br/>&beta;<br/>&Beta;<br/>&gamma;" + "<br/>&Gamma;<br/>&delta;<br/>&Delta;<br/>&epsilon;<br/>&Epsilon;<br/>&zeta;" + "<br/>&Zeta;<br/>&eta;<br/>&Eta;<br/>&theta;<br/>&Theta;<br/>&iota;" + "<br/>&Iota;<br/>&kappa;<br/>&Kappa;<br/>&lambda;<br/>&Lambda;<br/>&mu;<br/>&Mu;" + "<br/>&nu;<br/>&Nu;<br/>&xi;<br/>&Xi;<br/>&omicron;<br/>&Omicron;<br/>&pi;" + "<br/>&Pi;<br/>&rho;<br/>&Rho;<br/>&sigma;<br/>&Sigma;<br/>&sigmaf;<br/>&tau;<br/>&Tau;" + "<br/>&upsilon;<br/>&Upsilon;<br/>&phi;<br/>&Phi;<br/>&chi;<br/>&Chi;<br/>&psi;" + "<br/>&Psi;<br/>&omega;<br/>&Omega;"; String output = GFF3Record.fixEntityNames(input); assertEquals(expect, output); } public void testSpaces() throws Exception { String gff="4\t.\texon\t22335\t22528\t.\t-\t.\tID=CG32013:2;Parent=CG32013-RA,CG32013-RB;Gap=A+B;Target=C+D;Other=E+F\n"; GFF3Record record = new GFF3Record(gff); assertEquals(Arrays.asList(new Object[]{"A+B"}), record.getAttributes().get("Gap")); assertEquals(Arrays.asList(new Object[]{"C+D"}), record.getAttributes().get("Target")); assertEquals(Arrays.asList(new Object[]{"E F"}), record.getAttributes().get("Other")); } public void testToGFF3() throws Exception { String original="4\t.\texon\t22335\t22528\t.\t-\t.\tID=CG32013%3A2;Parent=CG32013-RA\n" + "4\t.\texon\t22335\t22528\t1000.0\t-\t1\tID=CG32013%3A2;Parent=CG32013-RA\n"; StringBuffer sb = new StringBuffer(); Iterator iter = GFF3Parser.parse(new BufferedReader(new StringReader(original))); while (iter.hasNext()) { sb.append(((GFF3Record) iter.next()).toGFF3()).append("\n"); } assertEquals(original, sb.toString()); } public void testParents() throws Exception { String gff="4\t.\texon\t22335\t22528\t.\t-\t.\tID=CG32013:2;Parent=CG32013-RA,CG32013-RB\n"; StringBuffer sb = new StringBuffer(); Iterator iter = GFF3Parser.parse(new BufferedReader(new StringReader(gff))); GFF3Record record = (GFF3Record) iter.next(); List expected = new ArrayList(Arrays.asList(new String[] {"CG32013-RA", "CG32013-RB"})); assertEquals(expected, record.getParents()); } }
package gherkin.pickles; import gherkin.SymbolCounter; import gherkin.ast.Background; import gherkin.ast.DataTable; import gherkin.ast.DocString; import gherkin.ast.Examples; import gherkin.ast.Feature; import gherkin.ast.GherkinDocument; import gherkin.ast.Location; import gherkin.ast.Node; import gherkin.ast.Scenario; import gherkin.ast.ScenarioDefinition; import gherkin.ast.ScenarioOutline; import gherkin.ast.Step; import gherkin.ast.TableCell; import gherkin.ast.TableRow; import gherkin.ast.Tag; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.Collections.unmodifiableList; public class Compiler { public List<Pickle> compile(GherkinDocument gherkinDocument) { List<Pickle> pickles = new ArrayList<>(); Feature feature = gherkinDocument.getFeature(); if (feature == null) { return pickles; } String language = feature.getLanguage(); List<Tag> featureTags = feature.getTags(); List<PickleStep> backgroundSteps = new ArrayList<>(); for (ScenarioDefinition scenarioDefinition : feature.getChildren()) { if (scenarioDefinition instanceof Background) { backgroundSteps = pickleSteps(scenarioDefinition); } else if (scenarioDefinition instanceof Scenario) { compileScenario(pickles, backgroundSteps, (Scenario) scenarioDefinition, featureTags, language); } else { compileScenarioOutline(pickles, backgroundSteps, (ScenarioOutline) scenarioDefinition, featureTags, language); } } return pickles; } private void compileScenario(List<Pickle> pickles, List<PickleStep> backgroundSteps, Scenario scenario, List<Tag> featureTags, String language) { List<PickleStep> steps = new ArrayList<>(); if (!scenario.getSteps().isEmpty()) steps.addAll(backgroundSteps); List<Tag> scenarioTags = new ArrayList<>(); scenarioTags.addAll(featureTags); scenarioTags.addAll(scenario.getTags()); steps.addAll(pickleSteps(scenario)); Pickle pickle = new Pickle( scenario.getName(), language, steps, pickleTags(scenarioTags), singletonList(pickleLocation(scenario.getLocation())) ); pickles.add(pickle); } private void compileScenarioOutline(List<Pickle> pickles, List<PickleStep> backgroundSteps, ScenarioOutline scenarioOutline, List<Tag> featureTags, String language) { for (final Examples examples : scenarioOutline.getExamples()) { if (examples.getTableHeader() == null) continue; List<TableCell> variableCells = examples.getTableHeader().getCells(); for (final TableRow values : examples.getTableBody()) { List<TableCell> valueCells = values.getCells(); List<PickleStep> steps = new ArrayList<>(); if (!scenarioOutline.getSteps().isEmpty()) steps.addAll(backgroundSteps); List<Tag> tags = new ArrayList<>(); tags.addAll(featureTags); tags.addAll(scenarioOutline.getTags()); tags.addAll(examples.getTags()); for (Step scenarioOutlineStep : scenarioOutline.getSteps()) { String stepText = interpolate(scenarioOutlineStep.getText(), variableCells, valueCells); // TODO: Use an Array of location in DataTable/DocString as well. // If the Gherkin AST classes supported // a list of locations, we could just reuse the same classes PickleStep pickleStep = new PickleStep( stepText, createPickleArguments(scenarioOutlineStep.getArgument(), variableCells, valueCells), asList( pickleLocation(values.getLocation()), pickleStepLocation(scenarioOutlineStep) ) ); steps.add(pickleStep); } Pickle pickle = new Pickle( interpolate(scenarioOutline.getName(), variableCells, valueCells), language, steps, pickleTags(tags), asList( pickleLocation(values.getLocation()), pickleLocation(scenarioOutline.getLocation()) ) ); pickles.add(pickle); } } } private List<Argument> createPickleArguments(Node argument) { List<TableCell> noCells = emptyList(); return createPickleArguments(argument, noCells, noCells); } private List<Argument> createPickleArguments(Node argument, List<TableCell> variableCells, List<TableCell> valueCells) { List<Argument> result = new ArrayList<>(); if (argument == null) return result; if (argument instanceof DataTable) { DataTable t = (DataTable) argument; List<TableRow> rows = t.getRows(); List<PickleRow> newRows = new ArrayList<>(rows.size()); for (TableRow row : rows) { List<TableCell> cells = row.getCells(); List<PickleCell> newCells = new ArrayList<>(); for (TableCell cell : cells) { newCells.add( new PickleCell( pickleLocation(cell.getLocation()), interpolate(cell.getValue(), variableCells, valueCells) ) ); } newRows.add(new PickleRow(newCells)); } result.add(new PickleTable(newRows)); } else if (argument instanceof DocString) { DocString ds = (DocString) argument; result.add( new PickleString( pickleLocation(ds.getLocation()), interpolate(ds.getContent(), variableCells, valueCells) ) ); } else { throw new RuntimeException("Unexpected argument type: " + argument); } return result; } private List<PickleStep> pickleSteps(ScenarioDefinition scenarioDefinition) { List<PickleStep> result = new ArrayList<>(); for (Step step : scenarioDefinition.getSteps()) { result.add(pickleStep(step)); } return unmodifiableList(result); } private PickleStep pickleStep(Step step) { return new PickleStep( step.getText(), createPickleArguments(step.getArgument()), singletonList(pickleStepLocation(step)) ); } private String interpolate(String name, List<TableCell> variableCells, List<TableCell> valueCells) { int col = 0; for (TableCell variableCell : variableCells) { TableCell valueCell = valueCells.get(col++); String header = variableCell.getValue(); String value = valueCell.getValue(); name = name.replace("<" + header + ">", value); } return name; } private PickleLocation pickleStepLocation(Step step) { return new PickleLocation( step.getLocation().getLine(), step.getLocation().getColumn() + (step.getKeyword() != null ? SymbolCounter.countSymbols(step.getKeyword()) : 0) ); } private PickleLocation pickleLocation(Location location) { return new PickleLocation(location.getLine(), location.getColumn()); } private List<PickleTag> pickleTags(List<Tag> tags) { List<PickleTag> result = new ArrayList<>(); for (Tag tag : tags) { result.add(pickleTag(tag)); } return result; } private PickleTag pickleTag(Tag tag) { return new PickleTag(pickleLocation(tag.getLocation()), tag.getName()); } }
package com.exedio.cope.instrument; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.lang.reflect.Modifier; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import com.exedio.cope.AttributeValue; import com.exedio.cope.LengthViolationException; import com.exedio.cope.NestingRuntimeException; import com.exedio.cope.NotNullViolationException; import com.exedio.cope.ReadOnlyViolationException; import com.exedio.cope.Type; import com.exedio.cope.UniqueViolationException; import com.exedio.cope.util.ReactivationConstructorDummy; // TODO use jspm final class Generator { private static final String THROWS_NULL = "if {0} is null."; private static final String THROWS_UNIQUE = "if {0} is not unique."; private static final String THROWS_LENGTH = "if {0} violates its length constraint."; private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the attributes initially needed."; private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for attribute {0}."; private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given attributes initially."; private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}."; private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only."; private static final String GETTER = "Returns the value of the persistent attribute {0}."; private static final String CHECKER = "Returns whether the given value corresponds to the hash in {0}."; private static final String SETTER = "Sets a new value for the persistent attribute {0}."; private static final String SETTER_DATA = "Sets the new data for the data attribute {0}."; private static final String SETTER_DATA_IOEXCEPTION = "if accessing {0} throws an IOException."; private static final String GETTER_DATA_URL = "Returns a URL the data of the data attribute {0} is available under."; private static final String GETTER_DATA_VARIANT = "Returns a URL the data of the {1} variant of the data attribute {0} is available under."; private static final String GETTER_DATA_MAJOR = "Returns the major mime type of the data attribute {0}."; private static final String GETTER_DATA_MINOR = "Returns the minor mime type of the data attribute {0}."; private static final String GETTER_DATA_DATA = "Returns the data of the data attribute {0}."; private static final String TOUCHER = "Sets the current date for the date attribute {0}."; private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique attributes."; private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to attribute {0}."; private static final String QUALIFIER = "Returns the qualifier."; private static final String QUALIFIER_GETTER = "Returns the qualifier."; private static final String QUALIFIER_SETTER = "Sets the qualifier."; private static final String VECTOR_GETTER = "Returns the value of the vector."; private static final String VECTOR_SETTER = "Sets the vector."; private static final String TYPE = "The persistent type information for {0}."; private final Writer o; private final String lineSeparator; Generator(final Writer output) { this.o=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } public static final String toCamelCase(final String name) { final char first = name.charAt(0); if (Character.isUpperCase(first)) return name; else return Character.toUpperCase(first) + name.substring(1); } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private static final String getShortName(final Class aClass) { final String name = aClass.getName(); final int pos = name.lastIndexOf('.'); return name.substring(pos+1); } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { o.write("\t\t\tthrows"); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\t"); o.write(((Class)i.next()).getName()); } o.write(lineSeparator); } } private final void writeCommentHeader() throws IOException { o.write("/**"); o.write(lineSeparator); o.write(lineSeparator); o.write("\t **"); o.write(lineSeparator); } private final void writeCommentGenerated() throws IOException { o.write("\t * <p><small>"+Instrumentor.GENERATED+"</small>"); o.write(lineSeparator); } private final void writeCommentFooter() throws IOException { o.write("\t *"); o.write(lineSeparator); o.write(" */"); } private static final String link(final String target) { return "{@link #" + target + '}'; } private static final String link(final String target, final String name) { return "{@link #" + target + ' ' + name + '}'; } private static final String format(final String pattern, final String parameter1) { return MessageFormat.format(pattern, new Object[]{ parameter1 }); } private static final String format(final String pattern, final String parameter1, final String parameter2) { return MessageFormat.format(pattern, new Object[]{ parameter1, parameter2 }); } private void writeInitialConstructor(final CopeClass copeClass) throws IOException { if(!copeClass.hasInitialConstructor()) return; final List initialAttributes = copeClass.getInitialAttributes(); final SortedSet constructorExceptions = copeClass.getConstructorExceptions(); writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_INITIAL, copeClass.getName())); o.write(lineSeparator); writeCommentGenerated(); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write("\t * @param "); o.write(initialAttribute.getName()); o.write(' '); o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(initialAttribute.getName()))); o.write(lineSeparator); } for(Iterator i = constructorExceptions.iterator(); i.hasNext(); ) { final Class constructorException = (Class)i.next(); o.write("\t * @throws "); o.write(constructorException.getName()); o.write(' '); boolean first = true; final StringBuffer initialAttributesBuf = new StringBuffer(); for(Iterator j = initialAttributes.iterator(); j.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)j.next(); if(!initialAttribute.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else initialAttributesBuf.append(", "); initialAttributesBuf.append(initialAttribute.getName()); } final String pattern; if(NotNullViolationException.class.equals(constructorException)) pattern = THROWS_NULL; else if(UniqueViolationException.class.equals(constructorException)) pattern = THROWS_UNIQUE; else if(LengthViolationException.class.equals(constructorException)) pattern = THROWS_LENGTH; else throw new RuntimeException(constructorException.getName()); o.write(format(pattern, initialAttributesBuf.toString())); o.write(lineSeparator); } writeCommentFooter(); final String modifier = Modifier.toString(copeClass.getInitialConstructorModifier()); if(modifier.length()>0) { o.write(modifier); o.write(' '); } o.write(copeClass.getName()); o.write('('); boolean first = true; for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write(lineSeparator); o.write("\t\t\t\tfinal "); o.write(initialAttribute.getBoxedType()); o.write(' '); o.write(initialAttribute.getName()); } o.write(')'); o.write(lineSeparator); writeThrowsClause(constructorExceptions); o.write("\t{"); o.write(lineSeparator); o.write("\t\tthis(new "+AttributeValue.class.getName()+"[]{"); o.write(lineSeparator); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write("\t\t\tnew "+AttributeValue.class.getName()+"("); o.write(initialAttribute.copeClass.getName()); o.write('.'); o.write(initialAttribute.getName()); o.write(','); writeAttribute(initialAttribute); o.write("),"); o.write(lineSeparator); } o.write("\t\t});"); o.write(lineSeparator); for(Iterator i = copeClass.getConstructorExceptions().iterator(); i.hasNext(); ) { final Class exception = (Class)i.next(); o.write("\t\tthrowInitial"); o.write(getShortName(exception)); o.write("();"); o.write(lineSeparator); } o.write("\t}"); } private void writeGenericConstructor(final CopeClass copeClass) throws IOException { final Option option = copeClass.genericConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC, copeClass.getName())); o.write(lineSeparator); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + Type.class.getName() + "#newItem Type.newItem}")); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write( Modifier.toString( option.getModifier(copeClass.isAbstract() ? Modifier.PROTECTED : Modifier.PRIVATE) ) ); o.write(' '); o.write(copeClass.getName()); o.write("(final "+AttributeValue.class.getName()+"[] initialAttributes)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(initialAttributes);"); o.write(lineSeparator); o.write("\t}"); } private void writeReactivationConstructor(final CopeClass copeClass) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(CONSTRUCTOR_REACTIVATION); o.write(lineSeparator); writeCommentGenerated(); o.write("\t * @see Item#Item(" + ReactivationConstructorDummy.class.getName() + ",int)"); o.write(lineSeparator); writeCommentFooter(); o.write( copeClass.isAbstract() ? "protected " : "private " ); o.write(copeClass.getName()); o.write("("+ReactivationConstructorDummy.class.getName()+" d,final int pk)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(d,pk);"); o.write(lineSeparator); o.write("\t}"); } private void writeAccessMethods(final CopeAttribute copeAttribute) throws IOException { final String type = copeAttribute.getBoxedType(); // getter if(copeAttribute.getterOption.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(GETTER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedGetterModifier())); o.write(' '); o.write(type); if(copeAttribute.hasIsGetter()) o.write(" is"); else o.write(" get"); o.write(toCamelCase(copeAttribute.getName())); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); writeGetterBody(copeAttribute); o.write("\t}"); } // setter if(copeAttribute.hasGeneratedSetter()) { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(copeAttribute.getName())); o.write("(final "); o.write(type); o.write(' '); o.write(copeAttribute.getName()); o.write(')'); o.write(lineSeparator); writeThrowsClause(copeAttribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); writeSetterBody(copeAttribute); o.write("\t}"); // touch for date attributes if(copeAttribute instanceof CopeNativeAttribute && ((CopeNativeAttribute)copeAttribute).touchable) { writeCommentHeader(); o.write("\t * "); o.write(format(TOUCHER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedSetterModifier())); o.write(" void touch"); o.write(toCamelCase(copeAttribute.getName())); o.write("()"); o.write(lineSeparator); writeThrowsClause(copeAttribute.getToucherExceptions()); o.write("\t{"); o.write(lineSeparator); writeToucherBody(copeAttribute); o.write("\t}"); } } for(Iterator i = copeAttribute.getHashes().iterator(); i.hasNext(); ) { final CopeHash hash = (CopeHash)i.next(); writeHash(hash); } } private void writeHash(final CopeHash hash) throws IOException { final CopeAttribute storage = hash.storageAttribute; // checker writeCommentHeader(); o.write("\t * "); o.write(format(CHECKER, link(hash.name))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(storage.getGeneratedGetterModifier())); o.write(" boolean check"); o.write(toCamelCase(hash.name)); o.write("(final "); o.write(storage.getBoxedType()); o.write(' '); o.write(hash.name); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); writeCheckerBody(hash); o.write("\t}"); // setter writeCommentHeader(); o.write("\t * "); o.write(format(SETTER, link(hash.name))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(storage.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(hash.name)); o.write("(final "); o.write(storage.getBoxedType()); o.write(' '); o.write(hash.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(storage.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); writeSetterBody(hash); o.write("\t}"); } private void writeDataGetterMethod(final CopeDataAttribute attribute, final Class returnType, final String part, final CopeDataVariant variant, final String commentPattern) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(variant==null ? format(commentPattern, link(attribute.getName())) : format(commentPattern, link(attribute.getName()), link(variant.name, variant.shortName))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(attribute.getGeneratedGetterModifier())); o.write(' '); o.write(returnType.getName()); o.write(" get"); o.write(toCamelCase(attribute.getName())); o.write(part); if(variant!=null) o.write(variant.methodAppendix); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn get"); o.write(part); o.write('('); o.write(attribute.copeClass.getName()); o.write('.'); if(variant!=null) o.write(variant.name); else o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeDataAccessMethods(final CopeDataAttribute attribute) throws IOException { final String mimeMajor = attribute.mimeMajor; final String mimeMinor = attribute.mimeMinor; // getters writeDataGetterMethod(attribute, String.class, "URL", null, GETTER_DATA_URL); final List variants = attribute.getVariants(); if(variants!=null) { for(Iterator i = variants.iterator(); i.hasNext(); ) writeDataGetterMethod(attribute, String.class, "URL", (CopeDataVariant)i.next(), GETTER_DATA_VARIANT); } writeDataGetterMethod(attribute, String.class, "MimeMajor", null, GETTER_DATA_MAJOR); writeDataGetterMethod(attribute, String.class, "MimeMinor", null, GETTER_DATA_MINOR); writeDataGetterMethod(attribute, InputStream.class, "Data", null, GETTER_DATA_DATA); // setters if(attribute.hasGeneratedSetter()) { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER_DATA, link(attribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); o.write("\t * @throws "); o.write(IOException.class.getName()); o.write(' '); o.write(format(SETTER_DATA_IOEXCEPTION, "<code>data</code>")); o.write(lineSeparator); writeCommentFooter(); o.write(Modifier.toString(attribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(attribute.getName())); o.write("(final " + InputStream.class.getName() + " data"); if(mimeMajor==null) o.write(",final "+String.class.getName()+" mimeMajor"); if(mimeMinor==null) o.write(",final "+String.class.getName()+" mimeMinor"); o.write(')'); final SortedSet setterExceptions = attribute.getSetterExceptions(); writeThrowsClause(setterExceptions); if(setterExceptions.isEmpty()) o.write("throws "); o.write(IOException.class.getName()); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); final SortedSet exceptionsToCatch = new TreeSet(attribute.getExceptionsToCatchInSetter()); exceptionsToCatch.remove(ReadOnlyViolationException.class); exceptionsToCatch.remove(LengthViolationException.class); exceptionsToCatch.remove(UniqueViolationException.class); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\tset("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(",data"); o.write(mimeMajor==null ? ",mimeMajor" : ",null"); o.write(mimeMinor==null ? ",mimeMinor" : ",null"); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); o.write("\t}"); } } private void writeUniqueFinder(final CopeUniqueConstraint constraint) throws IOException { final CopeAttribute[] copeAttributes = constraint.copeAttributes; final String className = copeAttributes[0].getParent().name; writeCommentHeader(); o.write("\t * "); o.write(format(FINDER_UNIQUE, lowerCamelCase(className))); o.write(lineSeparator); writeCommentGenerated(); for(int i=0; i<copeAttributes.length; i++) { o.write("\t * @param "); o.write(copeAttributes[i].getName()); o.write(' '); o.write(format(FINDER_UNIQUE_PARAMETER, link(copeAttributes[i].getName()))); o.write(lineSeparator); } writeCommentFooter(); o.write(Modifier.toString((constraint.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) )); o.write(' '); o.write(className); o.write(" findBy"); o.write(toCamelCase(constraint.name)); o.write('('); final Set qualifiers = new HashSet(); for(int i=0; i<copeAttributes.length; i++) { if(i>0) o.write(','); final CopeAttribute copeAttribute = copeAttributes[i]; o.write("final "); o.write(copeAttribute.getBoxedType()); o.write(' '); o.write(copeAttribute.getName()); } o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(className); o.write(')'); if(copeAttributes.length==1) { o.write(copeAttributes[0].copeClass.getName()); o.write('.'); o.write(copeAttributes[0].getName()); o.write(".searchUnique("); writeAttribute(copeAttributes[0]); } else { o.write(copeAttributes[0].copeClass.getName()); o.write('.'); o.write(constraint.name); o.write(".searchUnique(new Object[]{"); writeAttribute(copeAttributes[0]); for(int i = 1; i<copeAttributes.length; i++) { o.write(','); writeAttribute(copeAttributes[i]); } o.write('}'); } o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeAttribute(final CopeAttribute attribute) throws IOException { if(attribute.isBoxed()) o.write(attribute.getBoxingPrefix()); o.write(attribute.getName()); if(attribute.isBoxed()) o.write(attribute.getBoxingPostfix()); } private void writeQualifierParameters(final CopeQualifier qualifier) throws IOException { final CopeAttribute[] keys = qualifier.keyAttributes; for(int i = 0; i<keys.length; i++) { if(i>0) o.write(','); o.write("final "); o.write(keys[i].persistentType); o.write(' '); o.write(keys[i].javaAttribute.name); } } private void writeQualifierCall(final CopeQualifier qualifier) throws IOException { final CopeAttribute[] keys = qualifier.keyAttributes; for(int i = 0; i<keys.length; i++) { o.write(','); o.write(keys[i].javaAttribute.name); } } private void writeQualifier(final CopeQualifier qualifier) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write(qualifier.qualifierClassString); o.write(" get"); o.write(toCamelCase(qualifier.name)); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(qualifier.qualifierClassString); o.write(")"); o.write(qualifier.name); o.write(".getQualifier(new Object[]{this"); writeQualifierCall(qualifier); o.write("});"); o.write(lineSeparator); o.write("\t}"); final List qualifierAttributes = Arrays.asList(qualifier.uniqueConstraint.copeAttributes); for(Iterator i = qualifier.qualifierClass.getCopeAttributes().iterator(); i.hasNext(); ) { final CopeAttribute attribute = (CopeAttribute)i.next(); if(qualifierAttributes.contains(attribute)) continue; writeQualifierGetter(qualifier, attribute); writeQualifierSetter(qualifier, attribute); } } private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_GETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); final String resultType = attribute.persistentType; o.write("public final "); // TODO: obey attribute visibility o.write(resultType); o.write(" get"); o.write(toCamelCase(attribute.getName())); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(resultType); o.write(')'); o.write(qualifier.name); o.write(".get(new Object[]{this"); writeQualifierCall(qualifier); o.write("},"); o.write(qualifier.qualifierClassString); o.write('.'); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_SETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); final String resultType = attribute.persistentType; o.write("public final void set"); // TODO: obey attribute visibility o.write(toCamelCase(attribute.getName())); o.write('('); writeQualifierParameters(qualifier); o.write(",final "); o.write(resultType); o.write(' '); o.write(attribute.getName()); o.write(')'); o.write(lineSeparator); writeThrowsClause(Arrays.asList(new Class[]{ NotNullViolationException.class, LengthViolationException.class, ReadOnlyViolationException.class, ClassCastException.class})); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(qualifier.name); o.write(".set(new Object[]{this"); writeQualifierCall(qualifier); o.write("},"); o.write(qualifier.qualifierClassString); o.write('.'); o.write(attribute.getName()); o.write(','); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeVector(final CopeVector vector) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(VECTOR_GETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write(List.class.getName()); o.write(" get"); o.write(toCamelCase(vector.name)); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(vector.copeClass.getName()); o.write('.'); o.write(vector.name); o.write(".get(this);"); o.write(lineSeparator); o.write("\t}"); writeCommentHeader(); o.write("\t * "); o.write(VECTOR_SETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write("public final void set"); // TODO: obey attribute visibility o.write(toCamelCase(vector.name)); o.write("(final "); o.write(Collection.class.getName()); o.write(' '); o.write(vector.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(Arrays.asList(new Class[]{ UniqueViolationException.class, NotNullViolationException.class, LengthViolationException.class, ReadOnlyViolationException.class, ClassCastException.class})); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(vector.copeClass.getName()); o.write('.'); o.write(vector.name); o.write(".set(this,"); o.write(vector.name); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private final void writeType(final CopeClass copeClass) throws IOException { final Option option = copeClass.typeOption; if(option.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(TYPE, lowerCamelCase(copeClass.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(option.getModifier(Modifier.PUBLIC) | Modifier.STATIC | Modifier.FINAL)); // TODO obey class visibility o.write(" "+Type.class.getName()+" TYPE = "); o.write(lineSeparator); o.write("\t\tnew "+Type.class.getName()+"("); o.write(copeClass.getName()); o.write(".class)"); o.write(lineSeparator); o.write(";"); } } void writeClassFeatures(final CopeClass copeClass) throws IOException, InjectorParseException { if(!copeClass.isInterface()) { //System.out.println("onClassEnd("+jc.getName()+") writing"); writeInitialConstructor(copeClass); writeGenericConstructor(copeClass); writeReactivationConstructor(copeClass); for(final Iterator i = copeClass.getCopeAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final CopeAttribute copeAttribute = (CopeAttribute)i.next(); //System.out.println("onClassEnd("+jc.getName()+") writing attribute "+copeAttribute.getName()); if(copeAttribute instanceof CopeDataAttribute) writeDataAccessMethods((CopeDataAttribute)copeAttribute); else writeAccessMethods(copeAttribute); } for(final Iterator i = copeClass.getUniqueConstraints().iterator(); i.hasNext(); ) { // write unique finder methods final CopeUniqueConstraint constraint = (CopeUniqueConstraint)i.next(); writeUniqueFinder(constraint); } for(final Iterator i = copeClass.getQualifiers().iterator(); i.hasNext(); ) { final CopeQualifier qualifier = (CopeQualifier)i.next(); writeQualifier(qualifier); } for(final Iterator i = copeClass.getVectors().iterator(); i.hasNext(); ) { final CopeVector vector = (CopeVector)i.next(); writeVector(vector); } writeType(copeClass); } } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final CopeAttribute attribute) throws IOException { o.write("\t\treturn "); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPrefix()); o.write('('); o.write(attribute.persistentType); o.write(")get("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(')'); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPostfix()); o.write(';'); o.write(lineSeparator); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final CopeAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\tset("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(','); if(attribute.isBoxed()) o.write(attribute.getBoxingPrefix()); o.write(attribute.getName()); if(attribute.isBoxed()) o.write(attribute.getBoxingPostfix()); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeToucherBody(final CopeAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInToucher(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\ttouch("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeCheckerBody(final CopeHash hash) throws IOException { o.write("\t\treturn "); o.write(hash.copeClass.getName()); o.write('.'); o.write(hash.name); o.write(".check(this,"); o.write(hash.name); o.write(");"); o.write(lineSeparator); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final CopeHash hash) throws IOException { final CopeAttribute attribute = hash.storageAttribute; final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\t"); o.write(attribute.copeClass.getName()); o.write('.'); o.write(hash.name); o.write(".set(this,"); o.write(hash.name); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } private void writeTryCatchClausePrefix(final SortedSet exceptionsToCatch) throws IOException { if(!exceptionsToCatch.isEmpty()) { o.write("\t\ttry"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write('\t'); } } private void writeTryCatchClausePostfix(final SortedSet exceptionsToCatch) throws IOException { if(!exceptionsToCatch.isEmpty()) { o.write("\t\t}"); o.write(lineSeparator); for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); ) { final Class exceptionClass = (Class)i.next(); o.write("\t\tcatch("+exceptionClass.getName()+" e)"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write("\t\t\tthrow new "+NestingRuntimeException.class.getName()+"(e);"); o.write(lineSeparator); o.write("\t\t}"); o.write(lineSeparator); } } } }
package example; // -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ import java.awt.*; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; import javax.swing.*; import javax.swing.event.*; public final class MainPanel extends JPanel { private static final String MYSITE = "https://ateraimemo.com/"; private MainPanel() { super(new BorderLayout()); JTextArea textArea = new JTextArea(); JEditorPane editor = new JEditorPane("text/html", String.format("<html><a href='%s'>%s</a>", MYSITE, MYSITE)); editor.setOpaque(false); editor.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); editor.setEditable(false); editor.addHyperlinkListener(e -> { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { BrowserLauncher.openUrl(MYSITE); textArea.setText(e.toString()); } }); JPanel p = new JPanel(); p.add(editor); p.setBorder(BorderFactory.createTitledBorder("BrowserLauncher.openUrl(...)")); add(p, BorderLayout.NORTH); add(new JScrollPane(textArea)); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } // Bare Bones Browser Launch // // Version 1.5 // // December 10, 2005 // // Supports: Mac OS X, GNU/Linux, Unix, Windows XP // // Example Usage: // // BareBonesBrowserLaunch.openUrl(url); // // Public Domain Software -- Free to Use as You Like // // class BareBonesBrowserLaunch { @SuppressWarnings("PMD.ClassNamingConventions") final class BrowserLauncher { private static final String ERR_MSG = "Error attempting to launch web browser"; private BrowserLauncher() { /* Singleton */ } public static void openUrl(String url) { String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class<?> fileMgr = Class.forName("com.apple.eio.FileManager"); // Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class}); @SuppressWarnings({"unchecked", "checkstyle:abbreviationaswordinname"}) Method openURL = fileMgr.getDeclaredMethod("openURL", String.class); openURL.invoke(null, new Object[] {url}); } else if (osName.startsWith("Windows")) { Runtime.getRuntime().exec("rundll32 url.dll, FileProtocolHandler " + url); } else { // assume Unix or Linux String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"}; String browser = null; for (int count = 0; count < browsers.length && Objects.isNull(browser); count++) { String[] cmd = {"which", browsers[count]}; if (Runtime.getRuntime().exec(cmd).waitFor() == 0) { browser = browsers[count]; } } if (Objects.nonNull(browser)) { Runtime.getRuntime().exec(new String[] {browser, url}); } else { throw new UnsupportedOperationException("Could not find web browser"); } } } catch (IOException | InterruptedException | ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(null, ERR_MSG + ":\n" + ex.getLocalizedMessage(), "titlebar", JOptionPane.ERROR_MESSAGE); } } }
package com.caldroid; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.TextView; import com.antonyt.infiniteviewpager.InfinitePagerAdapter; import com.antonyt.infiniteviewpager.InfiniteViewPager; @SuppressLint("DefaultLocale") public class CaldroidFragment extends DialogFragment { public String TAG = "CaldroidFragment"; /** * To customize the selected background drawable and text color */ public static int selectedBackgroundDrawable = -1; public static int selectedTextColor = Color.BLACK; public final static int NUMBER_OF_PAGES = 4; /** * To customize the disabled background drawable and text color */ public static int disabledBackgroundDrawable = -1; public static int disabledTextColor = Color.GRAY; /** * Caldroid view components */ private Button leftArrowButton; private Button rightArrowButton; private TextView monthTitleTextView; private GridView weekdayGridView; private InfiniteViewPager dateViewPager; private DatePageChangeListener pageChangeListener; private ArrayList<DateGridFragment> fragments; /** * Initial data */ protected int month = -1; protected int year = -1; protected ArrayList<DateTime> disableDates = new ArrayList<DateTime>(); protected ArrayList<DateTime> selectedDates = new ArrayList<DateTime>(); protected DateTime minDateTime; protected DateTime maxDateTime; protected ArrayList<DateTime> dateInMonthsList; /** * First column of calendar is Sunday */ protected int startDayOfWeek = DateTimeConstants.SUNDAY; /** * A calendar height is not fixed, it may have 5 or 6 rows. Set fitAllMonths * to true so that the calendar will always have 6 rows */ private boolean fitAllMonths = true; /** * datePagerAdapters hold 4 adapters, meant to be reused */ protected ArrayList<CaldroidGridAdapter> datePagerAdapters = new ArrayList<CaldroidGridAdapter>(); /** * To control the navigation */ protected boolean enableSwipe = true; protected boolean showNavigationArrows = true; /** * dateItemClickListener is fired when user click on the date cell */ private OnItemClickListener dateItemClickListener; /** * caldroidListener inform library client of the event happens inside * Caldroid */ private CaldroidListener caldroidListener; /** * Meant to be subclassed. User who wants to provide custom view, need to * provide custom adapter here */ public CaldroidGridAdapter getNewDatesGridAdapter(int month, int year) { return new CaldroidGridAdapter(getActivity(), month, year, disableDates, selectedDates, minDateTime, maxDateTime, startDayOfWeek); } /** * For client to customize the weekDayGridView * * @return */ public GridView getWeekdayGridView() { return weekdayGridView; } /** * Get 4 adapters of the date grid views. Useful to set custom data and * refresh date grid view * * @return */ public ArrayList<CaldroidGridAdapter> getDatePagerAdapters() { return datePagerAdapters; } /** * Move calendar to the specified date * * @param date */ public void moveToDate(Date date) { moveToDateTime(CalendarHelper.convertDateToDateTime(date)); } /** * Move calendar to specified dateTime, with animation * * @param dateTime */ public void moveToDateTime(DateTime dateTime) { DateTime firstOfMonth = new DateTime(year, month, 1, 0, 0); DateTime lastOfMonth = firstOfMonth.dayOfMonth().withMaximumValue(); // To create a swipe effect // Do nothing if the dateTime is in current month // Calendar swipe left when dateTime is in the past if (dateTime.isBefore(firstOfMonth)) { // Get next month of dateTime. When swipe left, month will // decrease DateTime firstDayNextMonth = dateTime.plusMonths(1); // Refresh adapters pageChangeListener.setCurrentDateTime(firstDayNextMonth); int currentItem = dateViewPager.getCurrentItem(); pageChangeListener.refreshAdapters(currentItem); // Swipe left dateViewPager.setCurrentItem(currentItem - 1); } // Calendar swipe right when dateTime is in the future else if (dateTime.isAfter(lastOfMonth)) { // Get last month of dateTime. When swipe right, the month will // increase DateTime firstDayLastMonth = dateTime.minusMonths(1); // Refresh adapters pageChangeListener.setCurrentDateTime(firstDayLastMonth); int currentItem = dateViewPager.getCurrentItem(); pageChangeListener.refreshAdapters(currentItem); // Swipe right dateViewPager.setCurrentItem(currentItem + 1); } } /** * Set month and year for the calendar. This is to avoid naive * implementation of manipulating month and year. All dates within same * month/year give same result * * @param date */ public void setCalendarDate(Date date) { setCalendarDateTime(new DateTime(date)); } public void setCalendarDateTime(DateTime dateTime) { month = dateTime.getMonthOfYear(); year = dateTime.getYear(); // Notify listener if (caldroidListener != null) { caldroidListener.onChangeMonth(month, year); } refreshView(); } /** * Set calendar to previous month */ public void prevMonth() { dateViewPager.setCurrentItem(pageChangeListener.getCurrentPage() - 1); } /** * Set calendar to next month */ public void nextMonth() { dateViewPager.setCurrentItem(pageChangeListener.getCurrentPage() + 1); } /** * Clear all disable dates. Notice this does not refresh the calendar, need * to explicitly call refreshView() */ public void clearDisableDates() { disableDates.clear(); } /** * Set disableDates from ArrayList of Date * * @param disableDateList */ public void setDisableDates(ArrayList<Date> disableDateList) { disableDates.clear(); if (disableDateList == null || disableDateList.size() == 0) { return; } for (Date date : disableDateList) { DateTime dateTime = CalendarHelper.convertDateToDateTime(date); disableDates.add(dateTime); } } /** * Set disableDates from ArrayList of String. By default, the date formatter * is yyyy-MM-dd. For e.g 2013-12-24 * * @param disableDateStrings */ public void setDisableDatesFromString(ArrayList<String> disableDateStrings) { setDisableDatesFromString(disableDateStrings, null); } /** * Set disableDates from ArrayList of String with custom date format. For * example, if the date string is 06-Jan-2013, use date format dd-MMM-yyyy. * This method will refresh the calendar, it's not necessary to call * refreshView() * * @param disableDateStrings * @param dateFormat */ public void setDisableDatesFromString(ArrayList<String> disableDateStrings, String dateFormat) { disableDates.clear(); if (disableDateStrings == null) { return; } for (String dateString : disableDateStrings) { DateTime dateTime = CalendarHelper.getDateTimeFromString( dateString, dateFormat); disableDates.add(dateTime); } } /** * To clear selectedDates. This method does not refresh view, need to * explicitly call refreshView() */ public void clearSelectedDates() { selectedDates.clear(); } /** * Select the dates from fromDate to toDate. By default the background color * is holo_blue_light, and the text color is black. You can customize the * background by changing CaldroidFragment.selectedBackgroundDrawable, and * change the text color CaldroidFragment.selectedTextColor before call this * method. This method does not refresh view, need to call refreshView() * * @param fromDate * @param toDate */ public void setSelectedDates(Date fromDate, Date toDate) { // Ensure fromDate is before toDate if (fromDate == null || toDate == null || fromDate.after(toDate)) { return; } selectedDates.clear(); DateTime fromDateTime = CalendarHelper.convertDateToDateTime(fromDate); DateTime toDateTime = CalendarHelper.convertDateToDateTime(toDate); DateTime dateTime = fromDateTime; while (dateTime.isBefore(toDateTime)) { selectedDates.add(dateTime); dateTime = dateTime.plusDays(1); } selectedDates.add(toDateTime); } /** * Convenient method to select dates from String * * @param fromDateString * @param toDateString * @param dateFormat * @throws ParseException */ public void setSelectedDateStrings(String fromDateString, String toDateString, String dateFormat) throws ParseException { Date fromDate = CalendarHelper.getDateFromString(fromDateString, dateFormat); Date toDate = CalendarHelper .getDateFromString(toDateString, dateFormat); setSelectedDates(fromDate, toDate); } /** * Check if the navigation arrow is shown * * @return */ public boolean isShowNavigationArrows() { return showNavigationArrows; } /** * Show or hide the navigation arrows * * @param showNavigationArrows */ public void setShowNavigationArrows(boolean showNavigationArrows) { this.showNavigationArrows = showNavigationArrows; if (showNavigationArrows) { leftArrowButton.setVisibility(View.VISIBLE); rightArrowButton.setVisibility(View.VISIBLE); } else { leftArrowButton.setVisibility(View.INVISIBLE); rightArrowButton.setVisibility(View.INVISIBLE); } } /** * Enable / Disable swipe to navigate different months * * @return */ public boolean isEnableSwipe() { return enableSwipe; } public void setEnableSwipe(boolean enableSwipe) { this.enableSwipe = enableSwipe; dateViewPager.setEnabled(enableSwipe); } /** * Set min date. This method does not refresh view * * @param minDate */ public void setMinDate(Date minDate) { if (minDate == null) { minDateTime = null; } else { minDateTime = CalendarHelper.convertDateToDateTime(minDate); } } public boolean isFitAllMonths() { return fitAllMonths; } /** * A calendar height is not fixed, it may have 5 or 6 rows. Set fitAllMonths * to true so that the calendar will always have 6 rows */ public void setFitAllMonths(boolean fitAllMonths) { this.fitAllMonths = fitAllMonths; dateViewPager.setFitAllMonths(fitAllMonths); } /** * Convenient method to set min date from String. If dateFormat is null, * default format is yyyy-MM-dd * * @param minDateString * @param dateFormat */ public void setMinDateFromString(String minDateString, String dateFormat) { if (minDateString == null) { setMinDate(null); } else { minDateTime = CalendarHelper.getDateTimeFromString(minDateString, dateFormat); } } /** * Set max date. This method does not refresh view * * @param maxDate */ public void setMaxDate(Date maxDate) { if (maxDate == null) { maxDateTime = null; } else { maxDateTime = CalendarHelper.convertDateToDateTime(maxDate); } } /** * Convenient method to set max date from String. If dateFormat is null, * default format is yyyy-MM-dd * * @param maxDateString * @param dateFormat */ public void setMaxDateFromString(String maxDateString, String dateFormat) { if (maxDateString == null) { setMaxDate(null); } else { maxDateTime = CalendarHelper.getDateTimeFromString(maxDateString, dateFormat); } } /** * Set caldroid listener when user click on a date * * @param caldroidListener */ public void setCaldroidListener(CaldroidListener caldroidListener) { this.caldroidListener = caldroidListener; } /** * Callback to listener when date is valid (not disable, not outside of * min/max date) * * @return */ private OnItemClickListener getDateItemClickListener() { dateItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DateTime dateTime = dateInMonthsList.get(position); if (caldroidListener != null) { if ((minDateTime != null && dateTime.isBefore(minDateTime)) || (maxDateTime != null && dateTime .isAfter(maxDateTime)) || (disableDates != null && disableDates .indexOf(dateTime) != -1)) { return; } caldroidListener.onSelectDate(dateTime.toDate(), view); } } }; return dateItemClickListener; } /** * Refresh view when parameter changes. You should always change all * parameters first, then call this method. */ public void refreshView() { // Refresh title view monthTitleTextView.setText(new DateTime(year, month, 1, 0, 0) .monthOfYear().getAsText().toUpperCase() + " " + year); // Refresh the date grid views for (CaldroidGridAdapter adapter : datePagerAdapters) { adapter.setMinDateTime(minDateTime); adapter.setMaxDateTime(maxDateTime); adapter.setDisableDates(disableDates); adapter.setSelectedDates(selectedDates); adapter.notifyDataSetChanged(); } } /** * Retrieve initial arguments to the fragment Data can include: month, year, * dialogTitle, showNavigationArrows,(String) disableDates, selectedDates, * minDate, maxDate */ private void retrieveInitialArgs() { // Get arguments Bundle args = getArguments(); if (args != null) { // Get month, year month = args.getInt("month", -1); year = args.getInt("year", -1); String dialogTitle = args.getString("dialogTitle"); if (dialogTitle != null) { getDialog().setTitle(dialogTitle); } // Get start day of Week. Default calendar first column is SUNDAY startDayOfWeek = args.getInt("startDayOfWeek", DateTimeConstants.SUNDAY); if (startDayOfWeek > 7) { startDayOfWeek = startDayOfWeek % 7; } // Should show arrow showNavigationArrows = args .getBoolean("showNavigationArrows", true); // Should enable swipe to change month enableSwipe = args.getBoolean("enableSwipe", true); // Get fitAllMonths fitAllMonths = args.getBoolean("fitAllMonths", true); DateTimeFormatter formatter = DateTimeFormat .forPattern("yyyy-MM-dd"); // Get disable dates ArrayList<String> disableDateStrings = args .getStringArrayList("disableDates"); if (disableDateStrings != null && disableDateStrings.size() > 0) { for (String dateString : disableDateStrings) { DateTime dt = formatter.parseDateTime(dateString); disableDates.add(dt); } } // Get selected dates ArrayList<String> selectedDateStrings = args .getStringArrayList("selectedDates"); if (selectedDateStrings != null && selectedDateStrings.size() > 0) { for (String dateString : selectedDateStrings) { DateTime dt = formatter.parseDateTime(dateString); selectedDates.add(dt); } } // Get min date and max date String minDateTimeString = args.getString("minDate"); if (minDateTimeString != null) { minDateTime = CalendarHelper.getDateTimeFromString( minDateTimeString, null); } String maxDateTimeString = args.getString("maxDate"); if (maxDateTimeString != null) { maxDateTime = CalendarHelper.getDateTimeFromString( maxDateTimeString, null); } } if (month == -1 || year == -1) { DateTime dateTime = new DateTime(); month = dateTime.getMonthOfYear(); year = dateTime.getYear(); } } /** * To support faster init * * @param dialogTitle * @param month * @param year * @return */ public static CaldroidFragment newInstance(String dialogTitle, int month, int year) { CaldroidFragment f = new CaldroidFragment(); // Supply num input as an argument. Bundle args = new Bundle(); args.putString("dialogTitle", dialogTitle); args.putInt("month", month); args.putInt("year", year); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onDestroyView() { if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } /** * Setup view */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { retrieveInitialArgs(); View view = inflater.inflate(R.layout.calendar_view, container, false); // For the monthTitleTextView monthTitleTextView = (TextView) view .findViewById(R.id.calendar_month_year_textview); // For the left arrow button leftArrowButton = (Button) view.findViewById(R.id.calendar_left_arrow); rightArrowButton = (Button) view .findViewById(R.id.calendar_right_arrow); // Navigate to previous month when user click leftArrowButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { prevMonth(); } }); // Navigate to next month when user click rightArrowButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { nextMonth(); } }); // Show navigation arrows depend on initial arguments setShowNavigationArrows(showNavigationArrows); // For the weekday gridview ("SUN, MON, TUE, WED, THU, FRI, SAT") weekdayGridView = (GridView) view.findViewById(R.id.weekday_gridview); WeekdayArrayAdapter weekdaysAdapter = new WeekdayArrayAdapter( getActivity(), android.R.layout.simple_list_item_1, getDaysOfWeek()); weekdayGridView.setAdapter(weekdaysAdapter); // Setup all the pages of date grid views. These pages are recycled setupDateGridPages(view); // Refresh view refreshView(); return view; } /** * Setup 4 pages contain date grid views. These pages are recycled to use * memory efficient * * @param view */ private void setupDateGridPages(View view) { // Get current date time DateTime currentDateTime = new DateTime(year, month, 1, 0, 0, 0); dateInMonthsList = CalendarHelper.getFullWeeks(month, year, startDayOfWeek); // Set to pageChangeListener pageChangeListener = new DatePageChangeListener(); pageChangeListener.setCurrentDateTime(currentDateTime); // Setup adapters for the grid views // Current month CaldroidGridAdapter adapter0 = getNewDatesGridAdapter( currentDateTime.getMonthOfYear(), currentDateTime.getYear()); // Next month DateTime nextDateTime = currentDateTime.plusMonths(1); CaldroidGridAdapter adapter1 = getNewDatesGridAdapter( nextDateTime.getMonthOfYear(), nextDateTime.getYear()); // Next 2 month DateTime next2DateTime = nextDateTime.plusMonths(1); CaldroidGridAdapter adapter2 = getNewDatesGridAdapter( next2DateTime.getMonthOfYear(), next2DateTime.getYear()); // Previous month DateTime prevDateTime = currentDateTime.minusMonths(1); CaldroidGridAdapter adapter3 = getNewDatesGridAdapter( prevDateTime.getMonthOfYear(), prevDateTime.getYear()); // Add to the array of adapters datePagerAdapters.add(adapter0); datePagerAdapters.add(adapter1); datePagerAdapters.add(adapter2); datePagerAdapters.add(adapter3); // Set adapters to the pageChangeListener so it can refresh the adapter // when page change pageChangeListener.setCaldroidGridAdapters(datePagerAdapters); // Setup InfiniteViewPager and InfinitePagerAdapter. The // InfinitePagerAdapter is responsible // for reuse the fragments dateViewPager = (InfiniteViewPager) view .findViewById(R.id.months_infinite_pager); // Set enable swipe dateViewPager.setEnabled(enableSwipe); // Set if viewpager wrap around particular month or all months (6 rows) dateViewPager.setFitAllMonths(fitAllMonths); // Set the dateInMonthsList to dateViewPager so it can calculate the // height correctly dateViewPager.setDateInMonthsList(dateInMonthsList); // MonthPagerAdapter actually provides 4 real fragments. The // InfinitePagerAdapter only recycles fragment provided by this // MonthPagerAdapter final MonthPagerAdapter pagerAdapter = new MonthPagerAdapter( getChildFragmentManager()); // Provide initial data to the fragments, before they are attached to // view. fragments = pagerAdapter.getFragments(); for (int i = 0; i < NUMBER_OF_PAGES; i++) { DateGridFragment dateGridFragment = fragments.get(i); CaldroidGridAdapter adapter = datePagerAdapters.get(i); dateGridFragment.setGridAdapter(adapter); dateGridFragment.setOnItemClickListener(getDateItemClickListener()); } // Setup InfinitePagerAdapter to wrap around MonthPagerAdapter InfinitePagerAdapter infinitePagerAdapter = new InfinitePagerAdapter( pagerAdapter); // Use the infinitePagerAdapter to provide data for dateViewPager dateViewPager.setAdapter(infinitePagerAdapter); // Setup pageChangeListener dateViewPager.setOnPageChangeListener(pageChangeListener); } /** * To display the week day title * * @return "SUN, MON, TUE, WED, THU, FRI, SAT" */ private ArrayList<String> getDaysOfWeek() { ArrayList<String> list = new ArrayList<String>(); // 17 Feb 2013 is Sunday DateTime sunday = new DateTime(2013, 2, 17, 0, 0); DateTime nextDay = sunday; if (startDayOfWeek != DateTimeConstants.SUNDAY) { nextDay = sunday.plusDays(startDayOfWeek); } for (int i = 0; i < 7; i++) { list.add(nextDay.dayOfWeek().getAsShortText().toUpperCase()); nextDay = nextDay.plusDays(1); } return list; } /** * DatePageChangeListener refresh the date grid views when user swipe the * calendar * * @author thomasdao * */ public class DatePageChangeListener implements OnPageChangeListener { private int currentPage = InfiniteViewPager.OFFSET; private DateTime currentDateTime; private ArrayList<CaldroidGridAdapter> caldroidGridAdapters; /** * Return currentPage of the dateViewPager * * @return */ public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } /** * Return currentDateTime of the selected page * * @return */ public DateTime getCurrentDateTime() { return currentDateTime; } public void setCurrentDateTime(DateTime dateTime) { this.currentDateTime = dateTime; setCalendarDateTime(currentDateTime); } /** * Return 4 adapters * * @return */ public ArrayList<CaldroidGridAdapter> getCaldroidGridAdapters() { return caldroidGridAdapters; } public void setCaldroidGridAdapters( ArrayList<CaldroidGridAdapter> caldroidGridAdapters) { this.caldroidGridAdapters = caldroidGridAdapters; } /** * Return virtual next position * * @param position * @return */ private int getNext(int position) { return (position + 1) % CaldroidFragment.NUMBER_OF_PAGES; } /** * Return virtual previous position * * @param position * @return */ private int getPrevious(int position) { return (position + 3) % CaldroidFragment.NUMBER_OF_PAGES; } /** * Return virtual current position * * @param position * @return */ private int getCurrent(int position) { return position % CaldroidFragment.NUMBER_OF_PAGES; } @Override public void onPageScrollStateChanged(int position) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } public void refreshAdapters(int position) { // Get adapters to refresh CaldroidGridAdapter currentAdapter = caldroidGridAdapters .get(getCurrent(position)); CaldroidGridAdapter prevAdapter = caldroidGridAdapters .get(getPrevious(position)); CaldroidGridAdapter nextAdapter = caldroidGridAdapters .get(getNext(position)); if (position == currentPage) { // Refresh current adapter currentAdapter.setAdapterDateTime(currentDateTime); currentAdapter.notifyDataSetChanged(); // Refresh previous adapter prevAdapter.setAdapterDateTime(currentDateTime.minusMonths(1)); prevAdapter.notifyDataSetChanged(); // Refresh next adapter nextAdapter.setAdapterDateTime(currentDateTime.plusMonths(1)); nextAdapter.notifyDataSetChanged(); } // Detect if swipe right or swipe left // Swipe right else if (position > currentPage) { // Update current date time to next month currentDateTime = currentDateTime.plusMonths(1); // Refresh the adapter of next gridview nextAdapter.setAdapterDateTime(currentDateTime.plusMonths(1)); nextAdapter.notifyDataSetChanged(); } // Swipe left else { // Update current date time to previous month currentDateTime = currentDateTime.minusMonths(1); // Refresh the adapter of previous gridview prevAdapter.setAdapterDateTime(currentDateTime.minusMonths(1)); prevAdapter.notifyDataSetChanged(); } // Update current page currentPage = position; } /** * Refresh the fragments */ @Override public void onPageSelected(int position) { refreshAdapters(position); // Update current date time of the selected page setCalendarDateTime(currentDateTime); // Update all the dates inside current month CaldroidGridAdapter currentAdapter = caldroidGridAdapters .get(position % CaldroidFragment.NUMBER_OF_PAGES); // Refresh dateInMonthsList dateInMonthsList.clear(); dateInMonthsList.addAll(currentAdapter.getDatetimeList()); } } /** * Customize the weekday gridview */ private class WeekdayArrayAdapter extends ArrayAdapter<String> { public WeekdayArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); } // To prevent cell highlighted when clicked @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return false; } // Set color to gray and text size to 12sp @Override public View getView(int position, View convertView, ViewGroup parent) { // To customize text size and color TextView textView = (TextView) super.getView(position, convertView, parent); String item = getDaysOfWeek().get(position); // Show smaller text if the size of the text is 4 or more in some // locale if (item.length() <= 3) { textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); } else { textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11); } textView.setTextColor(getResources() .getColor(R.color.caldroid_gray)); textView.setGravity(Gravity.CENTER); return textView; } } }
package com.rho; import java.util.Calendar; public class RhoLogger { public static final boolean RHO_STRIP_LOG = false; private static final int L_TRACE = 0; private static final int L_INFO = 1; private static final int L_WARNING = 2; private static final int L_ERROR = 3; private static final int L_FATAL = 4; //private static final int L_NUM_SEVERITIES = 5; private String LogSeverityNames[] = { "TRACE", "INFO", "WARNING", "ERROR", "FATAL" }; private String m_category; private static RhoLogConf m_oLogConf = new RhoLogConf(); private String m_strMessage; private int m_severity; private static String m_SinkLock = ""; private static IRhoRubyHelper m_sysInfo; public static String LOGFILENAME = "RhoLog.txt"; public RhoLogger(String name){ m_category = name; } public static RhoLogConf getLogConf(){ return m_oLogConf; } public String getLogCategory(){ return m_category; } public void setLogCategory(String category){ m_category = category; } public static void close(){ RhoLogConf.close(); } private boolean isEnabled(){ if ( m_severity >= getLogConf().getMinSeverity() ){ if ( m_category.length() == 0 || m_severity >= L_ERROR ) return true; return getLogConf().isCategoryEnabled(m_category); } return false; } private String get2FixedDigit(int nDigit){ if ( nDigit > 9 ) return Integer.toString(nDigit); return "0" + Integer.toString(nDigit); } private String getLocalTimeString(){ Calendar time = Calendar.getInstance(); String strTime = ""; strTime += get2FixedDigit(time.get(Calendar.MONTH) + 1) + "/" + get2FixedDigit(time.get(Calendar.DATE)) + "/" + time.get(Calendar.YEAR) + " " + get2FixedDigit(time.get(Calendar.HOUR_OF_DAY)) + ":" + get2FixedDigit(time.get(Calendar.MINUTE)) + ":" + get2FixedDigit(time.get(Calendar.SECOND)); if ( false ) //comment this to show milliseconds strTime += ":" + get2FixedDigit(time.get(Calendar.MILLISECOND)); //Date date = time.getTime(); return strTime; } private String makeStringSize(String str, int nSize) { if ( str.length() >= nSize ) return str.substring(0, nSize); else { String res = ""; for( int i = 0; i < nSize - str.length(); i++ ) res += ' '; res += str; return res; } } private String getThreadField(){ String strThread = Thread.currentThread().getName(); if ( strThread.startsWith("Thread-")) { try { int nThreadID = Integer.parseInt(strThread.substring(7)); return Integer.toHexString(nThreadID); }catch(Exception exc){} } return strThread; } private void addPrefix(){ //(log level, local date time, thread_id, file basename, line) //I time f5d4fbb0 category| if ( m_severity == L_FATAL ) m_strMessage += LogSeverityNames[m_severity]; else m_strMessage += LogSeverityNames[m_severity].charAt(0); m_strMessage += " " + getLocalTimeString() + ' ' + makeStringSize(getThreadField(),8) + ' ' + makeStringSize(m_category,15) + "| "; } private void logMessage( int severity, String msg ){ logMessage(severity, msg, null, false ); } private void logMessage( int severity, String msg, Throwable e ){ logMessage(severity, msg, e, false ); } private void logMessage( int severity, String msg, Throwable e, boolean bOutputOnly ){ m_severity = severity; if ( !isEnabled() ) return; m_strMessage = ""; if ( getLogConf().isLogPrefix() ) addPrefix(); if ( msg != null ) m_strMessage += msg; if ( e != null ) { m_strMessage += (msg != null && msg.length() > 0 ? ";" : "") + e.getClass().getName() + ": "; String emsg = e.getMessage(); if ( emsg != null ) m_strMessage += emsg; } if (m_strMessage.length() > 0 || m_strMessage.charAt(m_strMessage.length() - 1) != '\n') m_strMessage += '\n'; synchronized( m_SinkLock ){ getLogConf().sinkLogMessage( m_strMessage, bOutputOnly ); if ( (isSimulator() || m_severity == L_FATAL) && e != null ){ //TODO: redirect printStackTrace to our log //e.printStackTrace(); } } if ( m_severity == L_FATAL ) processFatalError(); } static boolean isSimulator() { return m_sysInfo.isSimulator(); } protected void processFatalError(){ if ( isSimulator() ) throw new RuntimeException(); System.exit(0); } public void TRACE(String message) { logMessage( L_TRACE, message); } public void TRACE(String message,Throwable e) { logMessage( L_TRACE, message, e ); } public void INFO(String message) { logMessage( L_INFO, message); } public void INFO_OUT(String message) { //logMessage( L_INFO, message, null, true); //TODO: INFO_OUT System.out.print(m_category + ": " + message + "\n"); System.out.flush(); } public void WARNING(String message) { logMessage( L_WARNING, message); } public void ERROR(String message) { logMessage( L_ERROR, message); } public void ERROR(Throwable e) { logMessage( L_ERROR, "", e ); } public void ERROR(String message,Throwable e) { logMessage( L_ERROR, message, e ); } public void ERROR_OUT(String message,Throwable e) { //logMessage( L_ERROR, message, e, true ); System.out.print(m_category + ": " + message + ". " + ( e != null ? e.getClass().getName() : "Exception") + (e != null ? e.getMessage() : "" ) +"\n"); if ( e != null ) e.printStackTrace(); System.out.flush(); } public void FATAL(String message) { logMessage( L_FATAL, message); } public void FATAL(Throwable e) { logMessage( L_FATAL, "", e); } public void FATAL(String message, Throwable e) { logMessage( L_FATAL, message, e); } public void ASSERT(boolean exp, String message) { if ( !exp ) logMessage( L_FATAL, message); } public static String getLogText(){ return m_oLogConf.getLogText(); } public static int getLogTextPos(){ return m_oLogConf.getLogTextPos(); } public static void clearLog(){ synchronized( m_SinkLock ){ getLogConf().clearLog(); } } public static void InitRhoLog()throws Exception{ m_sysInfo = RhoClassFactory.createRhoRubyHelper(); RhoConf.InitRhoConf(); //Set defaults m_oLogConf.setLogPrefix(true); m_oLogConf.setLogToFile(true); if ( isSimulator() ) { m_oLogConf.setMinSeverity( L_INFO ); m_oLogConf.setLogToOutput(true); m_oLogConf.setEnabledCategories("*"); m_oLogConf.setDisabledCategories(""); m_oLogConf.setMaxLogFileSize(0);//No limit }else{ m_oLogConf.setMinSeverity( L_ERROR ); m_oLogConf.setLogToOutput(false); m_oLogConf.setEnabledCategories(""); m_oLogConf.setMaxLogFileSize(1024*50); } if ( RhoConf.getInstance().getRhoRootPath().length() > 0 ) m_oLogConf.setLogFilePath( RhoConf.getInstance().getRhoRootPath() + LOGFILENAME ); //load configuration if exist //m_oLogConf.saveToFile(""); RhoConf.getInstance().loadConf(); m_oLogConf.loadFromConf(RhoConf.getInstance()); } }
package edu.vu.isis.ammo.core.network; import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Enumeration; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.zip.CRC32; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.os.Looper; /** * Two long running threads and one short. * The long threads are for sending and receiving messages. * The short thread is to connect the socket. * The sent messages are placed into a queue if the socket is connected. * * @author phreed * */ public class TcpChannel { private static final Logger logger = LoggerFactory.getLogger(TcpChannel.class); private static final int BURP_TIME = 5 * 1000; // 5 seconds expressed in milliseconds private boolean isEnabled = false; private Socket socket = null; private ConnectorThread connectorThread; private ReceiverThread receiverThread; private SenderThread senderThread; private int connectTimeout = 5 * 1000; // this should come from network preferences private int socketTimeout = 5 * 1000; // milliseconds. private String gatewayHost = null; private int gatewayPort = -1; private ByteOrder endian = ByteOrder.LITTLE_ENDIAN; private final Object syncObj; private long flatLineTime; private TcpChannel(NetworkService driver) { super(); logger.trace("Thread <{}>TcpChannel::<constructor>", Thread.currentThread().getId()); this.syncObj = this; this.connectorThread = new ConnectorThread(this, driver); this.senderThread = new SenderThread(this, driver); this.receiverThread = new ReceiverThread(this, driver); this.flatLineTime = 20 * 60 * 1000; // 20 minutes in milliseconds } public static TcpChannel getInstance(NetworkService driver) { logger.trace("Thread <{}>::getInstance", Thread.currentThread().getId()); TcpChannel instance = new TcpChannel(driver); return instance; } public boolean isConnected() { return this.connectorThread.isConnected(); } /** * Was the status changed as a result of enabling the connection. * @return */ public boolean isEnabled() { return this.isEnabled; } public boolean enable() { logger.trace("Thread <{}>::enable", Thread.currentThread().getId()); synchronized (this.syncObj) { if (this.isEnabled == true) return false; this.isEnabled = true; this.connectorThread.start(); this.senderThread.start(); this.receiverThread.start(); } return true; } public boolean disable() { logger.trace("Thread <{}>::disable", Thread.currentThread().getId()); synchronized (this.syncObj) { if (this.isEnabled == false) return false; this.isEnabled = false; // this.connectorThread.stop(); // this.senderThread.stop(); // this.receiverThread.stop(); } return true; } public boolean setConnectTimeout(int value) { logger.trace("Thread <{}>::setConnectTimeout {}", Thread.currentThread().getId(), value); this.connectTimeout = value; return true; } public boolean setSocketTimeout(int value) { logger.trace("Thread <{}>::setSocketTimeout {}", Thread.currentThread().getId(), value); this.socketTimeout = value; this.reset(); return true; } public void setFlatLineTime(long flatLineTime) { this.flatLineTime = flatLineTime; } public boolean setHost(String host) { logger.trace("Thread <{}>::setHost {}", Thread.currentThread().getId(), host); if ( gatewayHost != null && gatewayHost.equals(host) ) return false; this.gatewayHost = host; this.reset(); return true; } public boolean setPort(int port) { logger.trace("Thread <{}>::setPort {}", Thread.currentThread().getId(), port); if (gatewayPort == port) return false; this.gatewayPort = port; this.reset(); return true; } public String toString() { return "socket: host["+this.gatewayHost+"] port["+this.gatewayPort+"]"; } /** * forces a reconnection. */ public void reset() { logger.trace("Thread <{}>::reset", Thread.currentThread().getId()); logger.trace("connector: {} sender: {} receiver: {}", new String[] { this.connectorThread.showState(), this.senderThread.showState(), this.receiverThread.showState()}); this.connectorThread.reset(); } /** * manages the connection. * enable or disable expresses the operator intent. * There is no reason to run the thread unless the channel is enabled. * * Any of the properties of the channel * @author phreed * */ private static class ConnectorThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(ConnectorThread.class); private static final String DEFAULT_HOST = "10.0.2.2"; private static final int DEFAULT_PORT = 32896; private static final int GATEWAY_RETRY_TIME = 20 * 1000; // 20 seconds private TcpChannel parent; private INetworkService.OnConnectHandler handler; private final State state; private long heartstamp; public long getHeartStamp() { synchronized (this.state) { return this.heartstamp; } } public void resetHeartStamp() { synchronized (this.state) { this.heartstamp = System.currentTimeMillis(); } } private ConnectorThread(TcpChannel parent, INetworkService.OnConnectHandler handler) { logger.trace("Thread <{}>ConnectorThread::<constructor>", Thread.currentThread().getId()); this.parent = parent; this.state = new State(); this.handler = handler; this.resetHeartStamp(); } private class State { private int value; static private final int CONNECTED = 0; // the socket is good an active static private final int CONNECTING = 1; // trying to connect static private final int DISCONNECTED = 2; // the socket is disconnected static private final int STALE = 4; // indicating there is a message static private final int LINK_WAIT = 5; // indicating the underlying link is down static private final int EXCEPTION = 6; // something really bad happened private long attempt; // used to uniquely name the connection public State() { this.value = STALE; this.attempt = Long.MIN_VALUE; } public synchronized void set(int state) { logger.trace("Thread <{}>State::set {}", Thread.currentThread().getId(), this.toString()); if (state == STALE) { logger.error("set stale only from the special setStale method"); return; } this.value = state; this.notifyAll(); } public synchronized int get() { return this.value; } public synchronized boolean isConnected() { return this.value == CONNECTED; } /** * Previously this method would only set the state to stale * if the current state were CONNECTED. It may be important * to return to STALE from other states as well. * For example during a failed link attempt. * Therefore if the attempt value matches then reset to STALE * This also causes a reset to reliably perform a notify. * * @param attempt value (an increasing integer) * @return */ public synchronized boolean failure(long attempt) { if (attempt != this.attempt) return true; attempt++; this.value = STALE; this.notifyAll(); return true; } public String toString () { switch (value) { case CONNECTED: return "CONNECTED"; case CONNECTING: return "CONNECTING"; case DISCONNECTED: return "DISCONNECTED"; case STALE: return "STALE"; case LINK_WAIT: return "LINK_WAIT"; case EXCEPTION: return "EXCEPTION"; default: return "Undefined State"; } } } public boolean isConnected() { return this.state.isConnected(); } public long getAttempt() { return this.state.attempt; } public String showState() { return this.state.toString(); } /** * reset forces the channel closed if open. */ public void reset() { this.state.failure(this.state.attempt); } public void failure(long attempt) { this.state.failure(attempt); } /** * A value machine based. * Most of the time this machine will be in a CONNECTED value. * In that CONNECTED value the machine wait for the connection value to * change or for an interrupt indicating that the thread is being shut down. * * The value machine takes care of the following constraints: * We don't need to reconnect unless. * 1) the connection has been lost * 2) the connection has been marked stale * 3) the connection is enabled. * 4) an explicit reconnection was requested * * @return */ @Override public void run() { try { logger.trace("Thread <{}>ConnectorThread::run", Thread.currentThread().getId()); MAINTAIN_CONNECTION: while (true) { logger.debug("state: {}",this.showState()); switch (this.state.get()) { case State.STALE: disconnect(); this.state.set(State.LINK_WAIT); break; case State.LINK_WAIT: if (isLinkUp()) { this.state.set(State.DISCONNECTED); } // on else wait for link to come up TODO triggered through broadcast receiver break; case State.DISCONNECTED: if ( !this.connect() ) { this.state.set(State.CONNECTING); } else { this.state.set(State.CONNECTED); } break; case State.CONNECTING: // keep trying if ( this.connect() ) { this.state.set(State.CONNECTED); } else { try { Thread.sleep(GATEWAY_RETRY_TIME); } catch (InterruptedException ex) { logger.info("sleep interrupted - intentional disable, exiting thread ..."); this.reset(); break MAINTAIN_CONNECTION; } } break; case State.CONNECTED: handler.auth(); default: { try { synchronized (this.state) { while (this.isConnected()) // this is IMPORTANT don't remove it. this.state.wait(BURP_TIME); // wait for somebody to change the connection status } } catch (InterruptedException ex) { logger.info("connection intentionally disabled {}", this.state ); this.state.set(State.STALE); break MAINTAIN_CONNECTION; } } } } } catch (Exception ex) { this.state.set(State.EXCEPTION); } try { this.parent.socket.close(); } catch (IOException ex) { ex.printStackTrace(); } } private boolean disconnect() { logger.trace("Thread <{}>ConnectorThread::disconnect", Thread.currentThread().getId()); try { if (this.parent.socket == null) return true; this.parent.socket.close(); } catch (IOException e) { return false; } return true; } private boolean isLinkUp() { return true; } /** * connects to the gateway * @return */ private boolean connect() { logger.trace("Thread <{}>ConnectorThread::connect", Thread.currentThread().getId()); String host = (parent.gatewayHost != null) ? parent.gatewayHost : DEFAULT_HOST; int port = (parent.gatewayPort > 10) ? parent.gatewayPort : DEFAULT_PORT; InetAddress ipaddr = null; try { ipaddr = InetAddress.getByName(host); } catch (UnknownHostException e) { logger.info("could not resolve host name"); return false; } parent.socket = new Socket(); InetSocketAddress sockAddr = new InetSocketAddress(ipaddr, port); try { parent.socket.connect(sockAddr, parent.connectTimeout); } catch (IOException ex) { logger.warn("connection to {}:{} failed : " + ex.getLocalizedMessage(), ipaddr, port); parent.socket = null; return false; } if (parent.socket == null) return false; try { parent.socket.setSoTimeout(parent.socketTimeout); } catch (SocketException ex) { return false; } logger.info("connection to {}:{} established ", ipaddr, port); return true; } } /** * do your best to send the message. * * @param size * @param checksum * @param message * @return */ public boolean sendRequest(int size, CRC32 checksum, byte[] payload, INetworkService.OnSendMessageHandler handler) { synchronized (this.syncObj) { this.senderThread.putMsg(new GwMessage(size, checksum, payload, handler) ); return true; } } public class GwMessage { public final int size; public final CRC32 checksum; public final byte[] payload; public final INetworkService.OnSendMessageHandler handler; public GwMessage(int size, CRC32 checksum, byte[] payload, INetworkService.OnSendMessageHandler handler) { this.size = size; this.checksum = checksum; this.payload = payload; this.handler = handler; } } /** * A thread for receiving incoming messages on the socket. * The main method is run(). * */ public static class SenderThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(SenderThread.class); static private final int WAIT_CONNECT = 1; // waiting for connection static private final int SENDING = 2; // indicating the next thing is the size static private final int TAKING = 3; // indicating the next thing is the size static private final int INTERRUPTED = 4; // the run was canceled via an interrupt static private final int EXCEPTION = 5; // the run failed by some unhandled exception public String showState () { switch (state) { case WAIT_CONNECT: return "WAIT_CONNECT"; case SENDING: return "SENDING"; case TAKING: return "TAKING"; case INTERRUPTED: return "INTERRUPTED"; case EXCEPTION: return "EXCEPTION"; default: return "Undefined State"; } } private int state; private final TcpChannel parent; private ConnectorThread connector; @SuppressWarnings("unused") private final INetworkService.OnSendMessageHandler handler; private final BlockingQueue<GwMessage> queue; private SenderThread(TcpChannel parent, INetworkService.OnSendMessageHandler handler) { logger.trace("Thread <{}>SenderThread::<constructor>", Thread.currentThread().getId()); this.parent = parent; this.handler = handler; this.connector = parent.connectorThread; this.queue = new LinkedBlockingQueue<GwMessage>(20); } public void updateConnector(ConnectorThread connector) { this.connector = connector; } public void putMsg(GwMessage msg) { try { this.queue.put(msg); } catch (InterruptedException ex) { ex.printStackTrace(); } } private void failOutStream(OutputStream os, long attempt) { if (os == null) return; try { os.close(); } catch (IOException ex) { logger.warn("close failed {}", ex.getLocalizedMessage()); } this.connector.failure(attempt); } /** * Initiate a connection to the server and then wait for a response. * All responses are of the form: * size : int32 * checksum : int32 * bytes[] : <size> * This is done via a simple value machine. * If the checksum doesn't match the connection is dropped and restarted. * * Once the message has been read it is passed off to... */ @Override public void run() { logger.trace("Thread <{}>SenderThread::run", Thread.currentThread().getId()); state = TAKING; DataOutputStream dos = null; try { // one integer for size & four bytes for checksum ByteBuffer buf = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE + 4); buf.order(parent.endian); GwMessage msg = null; long attempt = Long.MAX_VALUE; while (true) { logger.debug("state: {}",this.showState()); switch (state) { case WAIT_CONNECT: synchronized (this.connector.state) { while (! this.connector.isConnected()) { try { logger.trace("Thread <{}>SenderThread::value.wait", Thread.currentThread().getId()); this.connector.state.wait(BURP_TIME); } catch (InterruptedException ex) { logger.warn("thread interupted {}",ex.getLocalizedMessage()); return ; // looks like the thread is being shut down. } } attempt = this.connector.getAttempt(); } try { // if connected then proceed // keep the working socket so that if something goes wrong // the socket can be checked to see if it has changed // in the interim. OutputStream os = this.parent.socket.getOutputStream(); dos = new DataOutputStream(os); } catch (IOException ex) { logger.warn("io exception acquiring socket for writing messages {}", ex.getLocalizedMessage()); if (msg.handler != null) msg.handler.ack(false); this.failOutStream(dos, attempt); break; } state = SENDING; break; case TAKING: msg = queue.take(); // THE MAIN BLOCKING CALL state = WAIT_CONNECT; break; case SENDING: buf.rewind(); buf.putInt(msg.size); long cvalue = msg.checksum.getValue(); byte[] checksum = new byte[] { (byte)cvalue, (byte)(cvalue >>> 8), (byte)(cvalue >>> 16), (byte)(cvalue >>> 24) }; logger.debug("checksum [{}]", checksum); buf.put(checksum, 0, 4); try { dos.write(buf.array()); dos.write(msg.payload); dos.flush(); } catch (SocketException ex) { logger.warn("exception writing to a socket {}", ex.getLocalizedMessage()); if (msg.handler != null) msg.handler.ack(false); this.failOutStream(dos, attempt); this.state = WAIT_CONNECT; break; } catch (IOException ex) { logger.warn("io exception writing messages"); if (msg.handler != null) msg.handler.ack(false); this.failOutStream(dos, attempt); this.state = WAIT_CONNECT; break; } // legitimately sent to gateway. if (msg.handler != null) msg.handler.ack(true); this.connector.resetHeartStamp(); state = TAKING; break; } } } catch (InterruptedException ex) { logger.warn("interupted writing messages"); this.state = INTERRUPTED; } catch (Exception ex) { logger.warn("interupted writing messages"); this.state = EXCEPTION; } logger.warn("sender thread exiting ..."); } } /** * A thread for receiving incoming messages on the socket. * The main method is run(). * */ public static class ReceiverThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(ReceiverThread.class); final private INetworkService.OnReceiveMessageHandler handler; private TcpChannel parent = null; private ConnectorThread connector = null; // private TcpChannel.ConnectorThread; volatile private int state; static private final int SHUTDOWN = 0; // the run is being stopped static private final int START = 1; // indicating the next thing is the size static private final int RESTART = 2; // indicating the next thing is the size static private final int WAIT_CONNECT = 3; // waiting for connection static private final int WAIT_RECONNECT = 4; // waiting for connection static private final int STARTED = 5; // indicating there is a message static private final int SIZED = 6; // indicating the next thing is a checksum static private final int CHECKED = 7; // indicating the bytes are being read static private final int DELIVER = 8; // indicating the message has been read static private final int EXCEPTION = 9; // the run failed by some unhandled exception public String showState () { switch (state) { case SHUTDOWN: return "SHUTDOWN"; case START: return "START"; case RESTART: return "RESTART"; case WAIT_CONNECT: return "WAIT_CONNECT"; case WAIT_RECONNECT: return "WAIT_RECONNECT"; case STARTED: return "STARTED"; case SIZED: return "SIZED"; case CHECKED: return "CHECKED"; case DELIVER: return "DELIVER"; case EXCEPTION: return "EXCEPTION"; default: return "Undefined State "+String.valueOf(state); } } private ReceiverThread(TcpChannel parent, INetworkService.OnReceiveMessageHandler handler ) { logger.trace("Thread <{}>ReceiverThread::<constructor>", Thread.currentThread().getId()); this.parent = parent; this.handler = handler; this.connector = parent.connectorThread; } public void updateConnector(ConnectorThread connector) { this.connector = connector; } @Override public void start() { super.start(); logger.trace("Thread <{}>::start", Thread.currentThread().getId()); } private void failInStream(InputStream is, long attempt) { if (is == null) return; try { is.close(); } catch (IOException e) { logger.warn("close failed {}", e.getLocalizedMessage()); } this.connector.failure(attempt); } /** * Initiate a connection to the server and then wait for a response. * All responses are of the form: * size : int32 * checksum : int32 * bytes[] : <size> * This is done via a simple value machine. * If the checksum doesn't match the connection is dropped and restarted. * * Once the message has been read it is passed off to... */ @Override public void run() { logger.trace("Thread <{}>ReceiverThread::run", Thread.currentThread().getId()); //Looper.prepare(); try { state = WAIT_CONNECT; int bytesToRead = 0; // indicates how many bytes should be read int bytesRead = 0; // indicates how many bytes have been read long checksum = 0; byte[] message = null; byte[] byteToReadBuffer = new byte[Integer.SIZE/Byte.SIZE]; byte[] checksumBuffer = new byte[Long.SIZE/Byte.SIZE]; BufferedInputStream bis = null; long attempt = Long.MAX_VALUE; while (true) { switch (state) { case WAIT_RECONNECT: break; case RESTART: break; default: logger.debug("state: {}",this.showState()); } switch (state) { case WAIT_RECONNECT: case WAIT_CONNECT: // look for the size synchronized (this.connector.state) { while (! this.connector.isConnected() ) { try { logger.trace("Thread <{}>ReceiverThread::value.wait", Thread.currentThread().getId()); this.connector.state.wait(BURP_TIME); } catch (InterruptedException ex) { logger.warn("thread interupted {}",ex.getLocalizedMessage()); shutdown(bis); // looks like the thread is being shut down. return; } } attempt = this.connector.getAttempt(); } try { InputStream insock = this.parent.socket.getInputStream(); bis = new BufferedInputStream(insock, 1024); } catch (IOException ex) { logger.error("could not open input stream on socket {}", ex.getLocalizedMessage()); failInStream(bis, attempt); break; } if (bis == null) break; this.state = START; break; case RESTART: case START: try { int temp = bis.read(byteToReadBuffer); if (temp < 0) { logger.error("START: end of socket"); failInStream(bis, attempt); this.state = WAIT_CONNECT; break; // read error - end of connection } } catch (SocketTimeoutException ex) { // the following checks the heart-stamp // TODO no pace-maker messages are sent, this could be added if needed. long elapsedTime = System.currentTimeMillis() - this.connector.getHeartStamp(); if (parent.flatLineTime < elapsedTime) { logger.warn("heart timeout : {}", elapsedTime); failInStream(bis, attempt); this.state = WAIT_RECONNECT; // essentially the same as WAIT_CONNECT break; } this.state = RESTART; break; } catch (IOException ex) { logger.error("START: read error {}", ex.getLocalizedMessage()); failInStream(bis, attempt); this.state = WAIT_CONNECT; break; // read error - set our value back to wait for connect } this.state = STARTED; break; case STARTED: // look for the size { ByteBuffer bbuf = ByteBuffer.wrap(byteToReadBuffer); bbuf.order(this.parent.endian); bytesToRead = bbuf.getInt(); if (bytesToRead < 0) break; // bad read keep trying if (bytesToRead > 100000) { logger.warn("message too large {} wrong size!!, we will be out of sync, disconnect ", bytesToRead); failInStream(bis, attempt); this.state = WAIT_CONNECT; break; } this.state = SIZED; } break; case SIZED: // look for the checksum { try { bis.read(checksumBuffer, 0, 4); } catch (SocketTimeoutException ex) { logger.trace("timeout on socket"); continue; } catch (IOException e) { logger.trace("SIZED: read error"); failInStream(bis, attempt); this.state = WAIT_CONNECT; break; } ByteBuffer bbuf = ByteBuffer.wrap(checksumBuffer); bbuf.order(this.parent.endian); checksum = bbuf.getLong(); message = new byte[bytesToRead]; logger.info("checksum {} {}", checksumBuffer, checksum); bytesRead = 0; this.state = CHECKED; } break; case CHECKED: // read the message while (bytesRead < bytesToRead) { try { int temp = bis.read(message, bytesRead, bytesToRead - bytesRead); bytesRead += (temp >= 0) ? temp : 0; } catch (SocketTimeoutException ex) { logger.trace("timeout on socket"); continue; } catch (IOException ex) { logger.trace("CHECKED: read error"); this.state = WAIT_CONNECT; failInStream(bis, attempt); break; } } if (bytesRead < bytesToRead) { failInStream(bis, attempt); this.state = WAIT_CONNECT; break; } this.state = DELIVER; break; case DELIVER: // deliver the message to the gateway this.handler.deliver(message, checksum); this.connector.resetHeartStamp(); message = null; this.state = START; break; } } } catch (Exception ex) { logger.warn("interupted writing messages {}",ex.getLocalizedMessage()); this.state = EXCEPTION; ex.printStackTrace(); } logger.warn("sender thread exiting ..."); } private void shutdown(BufferedInputStream bis) { logger.debug("no longer listening, thread closing"); try { bis.close(); } catch (IOException e) {} return; } } /** * A routine to get the local ip address * TODO use this someplace * * @return */ public String getLocalIpAddress() { logger.trace("Thread <{}>::getLocalIpAddress", Thread.currentThread().getId()); try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { logger.error( ex.toString()); } return null; } }
package com.intellij.sh; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.editorActions.TypedHandlerDelegate; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.sh.psi.ShFile; import org.jetbrains.annotations.NotNull; public class ShTypedHandler extends TypedHandlerDelegate { @NotNull @Override public Result checkAutoPopup(char charTyped, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if (!(file instanceof ShFile)) return Result.CONTINUE; int currentLine = editor.getCaretModel().getPrimaryCaret().getLogicalPosition().line; if ((currentLine == 0 && charTyped == '!') || charTyped == '/') { AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null); return Result.STOP; } return Result.CONTINUE; } }
package imcode.server.document.textdocument; import imcode.server.Imcms; import imcode.server.document.DocumentDomainObject; import imcode.server.document.DocumentTypeDomainObject; import imcode.server.document.DocumentVisitor; import imcode.util.LazilyLoadedObject; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.lang.UnhandledException; import com.imcode.imcms.api.I18nLanguage; import com.imcode.imcms.api.I18nSupport; import com.imcode.imcms.api.Meta; import com.imcode.imcms.dao.ImageDao; import com.imcode.imcms.dao.TextDao; import com.imcode.imcms.mapping.DocumentMenusMap; public class TextDocumentDomainObject extends DocumentDomainObject { /** * Modified text indexes. * * Every modified text can be saved to history. * This controlled by setting boolean flag. * * Required when saving only particular set of text fields. * * TODO: Move to thread local or make separate call */ private Map<Integer, Boolean> modifiedTextIndexes = new TreeMap<Integer, Boolean>(); /** * Holds map of loaded images. * * Latter can be loaded as lazy object in loadAllLazyLoaded. * * For now loaded only by demand. */ private Map<I18nLanguage, Map<Integer, ImageDomainObject>> images = new HashMap<I18nLanguage, Map<Integer, ImageDomainObject>>(); /** * Holds map of loaded texts. * * Latter can be loaded as lazy object in loadAllLazyLoaded. * * For now loaded only by demand. */ private Map<I18nLanguage, Map<Integer, TextDomainObject>> texts = new HashMap<I18nLanguage, Map<Integer, TextDomainObject>>(); private LazilyLoadedObject<CopyableHashMap> includes = new LazilyLoadedObject<CopyableHashMap>(new CopyableHashMapLoader()); private LazilyLoadedObject<DocumentMenusMap> menus = new LazilyLoadedObject<DocumentMenusMap>(new LazilyLoadedObject.Loader<DocumentMenusMap>() { public DocumentMenusMap load() { return new DocumentMenusMap(); } }); private LazilyLoadedObject<TemplateNames> templateNames = new LazilyLoadedObject<TemplateNames>(new LazilyLoadedObject.Loader<TemplateNames>() { public TemplateNames load() { return new TemplateNames(); } }); public TextDocumentDomainObject() { this(ID_NEW) ; } public TextDocumentDomainObject(int documentId) { setId(documentId); } public void loadAllLazilyLoaded() { super.loadAllLazilyLoaded(); // TODO i18n: Do not load here !!! // Implement exactley as images!! // texts.load(); //loadAllImages(); //images.load(); includes.load(); menus.load(); templateNames.load(); } public Object clone() throws CloneNotSupportedException { TextDocumentDomainObject clone = (TextDocumentDomainObject)super.clone(); // TODO i18n: Clone texts // TODO i18n: Clone images //clone.texts = (LazilyLoadedObject) texts.clone(); //clone.images = (LazilyLoadedObject) images.clone(); clone.texts = new HashMap<I18nLanguage, Map<Integer, TextDomainObject>>(); clone.images = new HashMap<I18nLanguage, Map<Integer, ImageDomainObject>>(); clone.includes = (LazilyLoadedObject) includes.clone(); clone.menus = (LazilyLoadedObject) menus.clone() ; clone.templateNames = (LazilyLoadedObject) templateNames.clone() ; return clone; } public DocumentTypeDomainObject getDocumentType() { return DocumentTypeDomainObject.TEXT ; } public Set getChildDocumentIds() { Set childDocuments = new HashSet() ; for ( Iterator iterator = getMenus().values().iterator(); iterator.hasNext(); ) { MenuDomainObject menu = (MenuDomainObject)iterator.next(); MenuItemDomainObject[] menuItems = menu.getMenuItems() ; for ( int i = 0; i < menuItems.length; i++ ) { MenuItemDomainObject menuItem = menuItems[i]; childDocuments.add( new Integer(menuItem.getDocumentId()) ) ; } } return childDocuments ; } /** * Returns images map for current language. */ private Map<Integer, ImageDomainObject> getImagesMap() { I18nLanguage language = I18nSupport.getCurrentLanguage(); return getImagesMap(language); } /** * Returns all images for language specified in case this language is enabled. * * Populates images map with values from the database if language is enabled * on a first run. */ private synchronized Map<Integer, ImageDomainObject> getImagesMap(I18nLanguage language) { Map<Integer, ImageDomainObject> map = images.get(language); if (map == null) { map = new HashMap<Integer, ImageDomainObject>(); if (getMeta().getI18nMeta(language).getEnabled()) { ImageDao dao = (ImageDao)Imcms.getServices().getSpringBean("imageDao"); List<ImageDomainObject> items = dao.getImages(getId(), language.getId()); for (ImageDomainObject item: items) { /* if (item.getSource() instanceof NullImageSource) { int index = Integer.parseInt(item.getName()); ImageDomainObject defaultImage = dao.getDefaultImage(getId(), index); item.setSource(defaultImage.getSource()); } */ map.put(Integer.parseInt(item.getName()), item); } } images.put(language, map); } return map; } public Integer getIncludedDocumentId( int includeIndex ) { return (Integer)getIncludesMap().get( new Integer( includeIndex ) ); } private Map getIncludesMap() { return (Map) includes.get(); } public MenuDomainObject getMenu( int menuIndex ) { Map menusMap = (Map) menus.get(); MenuDomainObject menu = (MenuDomainObject) menusMap.get( new Integer( menuIndex ) ); if (null == menu) { menu = new MenuDomainObject() ; setMenu( menuIndex, menu ); } return menu; } public TextDomainObject getText( int textFieldIndex ) { I18nLanguage language = I18nSupport.getCurrentLanguage(); TextDomainObject item = getText(language, textFieldIndex); return item; } public synchronized TextDomainObject getText(I18nLanguage language, int index) { if (language == null) { throw new IllegalArgumentException("language argument " + "can not be null."); } Map<Integer, TextDomainObject> map = getTextsMap(language); TextDomainObject item = map.get(index); if (item == null) { if (getMeta().getMissingI18nShowRule() == Meta.MissingI18nShowRule.SHOW_IN_DEFAULT_LANGUAGE && !language.equals(I18nSupport.getDefaultLanguage())) { TextDao dao = (TextDao)Imcms.getServices().getSpringBean("textDao"); item = dao.getText(getId(), index, I18nSupport.getDefaultLanguage().getId()); } if (item == null) { item = new TextDomainObject(); item.setId(null); item.setMetaId(getId()); item.setLanguage(language); item.setIndex(index); item.setText(""); item.setType(TextDomainObject.TEXT_TYPE_HTML); } map.put(index, item); } return item; } /** * Returns texts map for current language. */ private Map<Integer, TextDomainObject> getTextsMap() { I18nLanguage language = I18nSupport.getCurrentLanguage(); return getTextsMap(language); } /** * Returns all texts for language specified. */ private synchronized Map<Integer, TextDomainObject> getTextsMap( I18nLanguage language) { Map<Integer, TextDomainObject> map = texts.get(language); if (map == null) { map = new HashMap<Integer, TextDomainObject>(); if (getMeta().getI18nMeta(language).getEnabled()) { TextDao dao = (TextDao)Imcms.getServices().getSpringBean("textDao"); List<TextDomainObject> items = dao.getTexts(getId(), language.getId()); for (TextDomainObject item: items) { map.put(item.getIndex(), item); } } texts.put(language, map); } return map; } public void accept( DocumentVisitor documentVisitor ) { documentVisitor.visitTextDocument(this) ; } /** * Removes all image. */ public synchronized void removeAllImages() { images.clear(); } public void removeAllIncludes() { getIncludesMap().clear(); } public void removeAllMenus() { getMenusMap().clear(); } private Map getMenusMap() { return (Map) menus.get(); } public void removeAllTexts() { texts.clear(); } public void setInclude( int includeIndex, int includedDocumentId ) { getIncludesMap().put( new Integer( includeIndex ), new Integer( includedDocumentId ) ); } public void setMenu( int menuIndex, MenuDomainObject menu ) { getMenusMap().put( new Integer( menuIndex ), menu ); } /** * Sets text to currently active language. */ public void setText( int textIndex, TextDomainObject text ) { setText(I18nSupport.getCurrentLanguage(), textIndex, text); } /** * Sets image. */ public void setText(I18nLanguage language, int imageIndex, TextDomainObject text) { Map<Integer, TextDomainObject> map = getTextsMap(language); map.put(imageIndex, text); } public Map getIncludes() { return Collections.unmodifiableMap( getIncludesMap() ); } public Map<Integer, MenuDomainObject> getMenus() { return Collections.unmodifiableMap( getMenusMap() ); } public String getTemplateName() { return getTemplateNames().getTemplateName(); } private TemplateNames getTemplateNames() { return (TemplateNames) templateNames.get(); } public int getTemplateGroupId() { return getTemplateNames().getTemplateGroupId(); } public Map<Integer, TextDomainObject> getTexts() { return Collections.unmodifiableMap( getTextsMap() ); } public void setTemplateName( String templateName ) { getTemplateNames().setTemplateName(templateName); } public void setTemplateGroupId( int v ) { getTemplateNames().setTemplateGroupId(v); } public String getDefaultTemplateName() { return getTemplateNames().getDefaultTemplateName(); } public void setDefaultTemplateId( String defaultTemplateId ) { getTemplateNames().setDefaultTemplateName(defaultTemplateId); } public void removeInclude( int includeIndex ) { getIncludesMap().remove( new Integer( includeIndex )) ; } public void setLazilyLoadedMenus(LazilyLoadedObject menus) { this.menus = menus; } public void setLazilyLoadedImages(LazilyLoadedObject images) { // TODO i18n: rewrite or remove latter. //this.images = images ; } public void setLazilyLoadedIncludes(LazilyLoadedObject includes) { this.includes = includes ; } public void setLazilyLoadedTexts(LazilyLoadedObject texts) { // TODO i18n: rewrite or remove latter. //this.texts = texts; } public String getDefaultTemplateNameForRestricted1() { return getTemplateNames().getDefaultTemplateNameForRestricted1(); } public String getDefaultTemplateNameForRestricted2() { return getTemplateNames().getDefaultTemplateNameForRestricted2(); } public void setDefaultTemplateIdForRestricted1(String defaultTemplateIdForRestricted1) { getTemplateNames().setDefaultTemplateNameForRestricted1(defaultTemplateIdForRestricted1); } public void setDefaultTemplateIdForRestricted2(String defaultTemplateIdForRestricted2) { getTemplateNames().setDefaultTemplateNameForRestricted2(defaultTemplateIdForRestricted2); } public void setLazilyLoadedTemplateIds(LazilyLoadedObject templateIds) { this.templateNames = templateIds; } private static class CopyableHashMapLoader implements LazilyLoadedObject.Loader<CopyableHashMap> { public CopyableHashMap load() { return new CopyableHashMap(); } } public static class TemplateNames implements LazilyLoadedObject.Copyable<TemplateNames>, Cloneable { private String templateName; private int templateGroupId; private String defaultTemplateName; private String defaultTemplateNameForRestricted1 ; private String defaultTemplateNameForRestricted2 ; public TemplateNames copy() { return (TemplateNames) clone() ; } public Object clone() { try { return super.clone(); } catch ( CloneNotSupportedException e ) { throw new UnhandledException(e); } } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } public int getTemplateGroupId() { return templateGroupId; } public void setTemplateGroupId(int templateGroupId) { this.templateGroupId = templateGroupId; } public String getDefaultTemplateName() { return defaultTemplateName; } public void setDefaultTemplateName(String defaultTemplateName) { this.defaultTemplateName = defaultTemplateName; } public String getDefaultTemplateNameForRestricted1() { return defaultTemplateNameForRestricted1; } public void setDefaultTemplateNameForRestricted1(String defaultTemplateNameForRestricted1) { this.defaultTemplateNameForRestricted1 = defaultTemplateNameForRestricted1; } public String getDefaultTemplateNameForRestricted2() { return defaultTemplateNameForRestricted2; } public void setDefaultTemplateNameForRestricted2(String defaultTemplateNameForRestricted2) { this.defaultTemplateNameForRestricted2 = defaultTemplateNameForRestricted2; } } public Map<Integer, Boolean> getModifiedTextIndexes() { return modifiedTextIndexes; } public void addModifiedTextIndex(int index, boolean saveToHistory) { modifiedTextIndexes.put(index, saveToHistory); } public void removeModifiedTextIndex(int index) { modifiedTextIndexes.remove(index); } public void removeAllModifiedTextIndexs() { modifiedTextIndexes.clear(); } /** * @return Image id mapped to image for current language. */ public Map<Integer, ImageDomainObject> getImages() { return Collections.unmodifiableMap( getImagesMap() ); } /** * Sets images. * This method currently used by only administration interface. */ public synchronized void setImages(int imageIndex, Collection<ImageDomainObject> images) { for (ImageDomainObject image: images) { I18nLanguage language = image.getLanguage(); setImage(language, imageIndex, image); } } /** * Sets image to currently active language. * * Not in use. */ public void setImage(int imageIndex, ImageDomainObject image) { setImage(I18nSupport.getCurrentLanguage(), imageIndex, image); } /** * Sets image. */ public void setImage(I18nLanguage language, int imageIndex, ImageDomainObject image) { Map<Integer, ImageDomainObject> imagesMap = getImagesMap(language); imagesMap.put(imageIndex, image); } /** * Returns all images. */ public Map<I18nLanguage, Map<Integer, ImageDomainObject>> getAllImages() { return images; } /** * Returns i18n-ed image for language bound to the current thread. * * If image for that language is not exists * then returns image according to language rule set in meta. * * @return ImageDomainObject for language bound to the current thread. */ public ImageDomainObject getImage(int imageIndex) { I18nLanguage language = I18nSupport.getCurrentLanguage(); ImageDomainObject image = getImage(language, imageIndex); return image; } /** * Returns image for language specified. */ public synchronized ImageDomainObject getImage(I18nLanguage language, int imageIndex) { if (language == null) { throw new IllegalArgumentException("language argument " + "can not be null."); } Map<Integer, ImageDomainObject> imagesMap = getImagesMap(language); ImageDomainObject image = imagesMap.get(imageIndex); if (image == null) { if (getMeta().getMissingI18nShowRule() == Meta.MissingI18nShowRule.SHOW_IN_DEFAULT_LANGUAGE && !language.equals(I18nSupport.getDefaultLanguage())) { ImageDao imageDao = (ImageDao)Imcms.getServices().getSpringBean("imageDao"); image = imageDao.getDefaultImage(getId(), imageIndex); } if (image == null) { image = new ImageDomainObject(); image.setId(null); image.setMetaId(getId()); image.setLanguage(language); image.setName("" + imageIndex); } imagesMap.put(imageIndex, image); } return image; } /** * Returns languages mapped to images. * This method is used by administration interface. * * @return languages mapped to images. */ /* public synchronized Map<I18nLanguage, ImageDomainObject> getI18nImageMap(int imageIndex) { Map<I18nLanguage, ImageDomainObject> i18nImageMap = images.get(imageIndex); if (i18nImageMap == null) { ImageDao imageDao = (ImageDao)Imcms.getServices().getSpringBean("imageDao"); i18nImageMap = imageDao.getImagesMap(getId(), imageIndex); images.put(imageIndex, i18nImageMap); } return i18nImageMap; } */ /* private synchronized void loadAllImages() { I18nLanguage defaultLanguage = I18nSupport.getDefaultLanguage(); ImageDao imageDao = (ImageDao)Imcms.getServices().getSpringBean("imageDao"); images = imageDao.getImagesMap(getId()); } private synchronized void loadAllTexts() { I18nLanguage defaultLanguage = I18nSupport.getDefaultLanguage(); TextDao textDao = (TextDao)Imcms.getServices().getSpringBean("textDao"); texts = textDao.getAll(getId()); } */ }
package net.somethingdreadful.MAL; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.PopupMenu; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewFlipper; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.MALApi.ListType; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.GenericRecord; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.tasks.NetworkTask; import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener; import net.somethingdreadful.MAL.tasks.TaskJob; import net.somethingdreadful.MAL.tasks.WriteDetailTask; import java.util.ArrayList; import java.util.Collection; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class IGF extends Fragment implements OnScrollListener, OnItemLongClickListener, OnItemClickListener, NetworkTaskCallbackListener { Context context; ListType listType = ListType.ANIME; // just to have it proper initialized TaskJob taskjob; GridView Gridview; PrefManager pref; ViewFlipper viewflipper; SwipeRefreshLayout swipeRefresh; Activity activity; ArrayList<GenericRecord> gl = new ArrayList<GenericRecord>(); ListViewAdapter<GenericRecord> ga; IGFCallbackListener callback; NetworkTask networkTask; int page = 1; int list = -1; int resource; boolean useSecondaryAmounts; boolean loading = true; boolean detail = false; /* setSwipeRefreshEnabled() may be called before swipeRefresh exists (before onCreateView() is * called), so save it and apply it in onCreateView() */ boolean swipeRefreshEnabled = true; String query; /* * set the watched/read count & status on the covers. */ public static void setStatus(String myStatus, TextView textview, TextView progressCount, ImageView actionButton) { actionButton.setVisibility(View.GONE); progressCount.setVisibility(View.GONE); if (myStatus == null) { textview.setText(""); } else if (myStatus.equals("watching")) { textview.setText(R.string.cover_Watching); progressCount.setVisibility(View.VISIBLE); actionButton.setVisibility(View.VISIBLE); } else if (myStatus.equals("reading")) { textview.setText(R.string.cover_Reading); progressCount.setVisibility(View.VISIBLE); actionButton.setVisibility(View.VISIBLE); } else if (myStatus.equals("completed")) { textview.setText(R.string.cover_Completed); } else if (myStatus.equals("on-hold")) { textview.setText(R.string.cover_OnHold); progressCount.setVisibility(View.VISIBLE); } else if (myStatus.equals("dropped")) { textview.setText(R.string.cover_Dropped); } else if (myStatus.equals("plan to watch")) { textview.setText(R.string.cover_PlanningToWatch); } else if (myStatus.equals("plan to read")) { textview.setText(R.string.cover_PlanningToRead); } else { textview.setText(""); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { setRetainInstance(true); View view = inflater.inflate(R.layout.record_igf_layout, container, false); viewflipper = (ViewFlipper) view.findViewById(R.id.viewFlipper); Gridview = (GridView) view.findViewById(R.id.gridview); Gridview.setOnItemClickListener(this); Gridview.setOnItemLongClickListener(this); Gridview.setOnScrollListener(this); context = getActivity(); activity = getActivity(); pref = new PrefManager(context); useSecondaryAmounts = pref.getUseSecondaryAmountsEnabled(); if (pref.getTraditionalListEnabled()) { Gridview.setColumnWidth((int) Math.pow(9999, 9999)); //remain in the listview mode resource = R.layout.record_igf_listview; } else { resource = R.layout.record_igf_gridview; } swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh); if (isOnHomeActivity()) { swipeRefresh.setOnRefreshListener((Home) getActivity()); swipeRefresh.setColorScheme( R.color.holo_blue_bright, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light ); } swipeRefresh.setEnabled(swipeRefreshEnabled); if (taskjob != null && !taskjob.equals(TaskJob.SEARCH)) { if (list == -1) getRecords(true, null, pref.getDefaultList()); else refresh(); } NfcHelper.disableBeam(activity); if (callback != null) callback.onIGFReady(this); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = activity; if (IGFCallbackListener.class.isInstance(activity)) callback = (IGFCallbackListener)activity; } private boolean isOnHomeActivity() { return getActivity() != null && getActivity().getClass() == Home.class; } /* * add +1 episode/volume/chapters to the anime/manga. */ public void setProgressPlusOne(Anime anime, Manga manga) { if (listType.equals(ListType.ANIME)) { anime.setWatchedEpisodes(anime.getWatchedEpisodes() + 1); if (anime.getWatchedEpisodes() == anime.getEpisodes()) anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime); } else { manga.setProgress(useSecondaryAmounts, manga.getProgress(useSecondaryAmounts) + 1); if (manga.getProgress(useSecondaryAmounts) == manga.getTotal(useSecondaryAmounts)) manga.setReadStatus(GenericRecord.STATUS_COMPLETED); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga); } refresh(); } /* * mark the anime/manga as completed. */ public void setMarkAsComplete(Anime anime, Manga manga) { if (listType.equals(ListType.ANIME)) { anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED); if (anime.getEpisodes() > 0) anime.setWatchedEpisodes(anime.getEpisodes()); anime.setDirty(true); gl.remove(anime); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime); } else { manga.setReadStatus(GenericRecord.STATUS_COMPLETED); manga.setDirty(true); gl.remove(manga); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga); } refresh(); } /* * handle the loading indicator */ private void toggleLoadingIndicator(boolean show) { if (viewflipper != null) { viewflipper.setDisplayedChild(show ? 1 : 0); } } public void toggleSwipeRefreshAnimation(boolean show) { if (swipeRefresh != null) { swipeRefresh.setRefreshing(show); } } public void setSwipeRefreshEnabled(boolean enabled) { swipeRefreshEnabled = enabled; if (swipeRefresh != null) { swipeRefresh.setEnabled(enabled); } } /* * get the anime/manga lists. * (if clear is true the whole list will be cleared and loaded) */ public void getRecords(boolean clear, TaskJob task, int list) { if (task != null) { taskjob = task; } if (list != this.list) { this.list = list; } /* only show loading indicator if * - is not own list and not page 1 * - force sync and list is empty (only show swipe refresh animation if not empty) or should * be cleared */ boolean isEmpty = gl.isEmpty(); toggleLoadingIndicator((page == 1 && !isList()) || (taskjob.equals(TaskJob.FORCESYNC) && (isEmpty || clear))); /* show swipe refresh animation if * - loading more pages * - forced update */ toggleSwipeRefreshAnimation((page > 1 && !isList() || taskjob.equals(TaskJob.FORCESYNC)) && !taskjob.equals(TaskJob.SEARCH)); loading = true; try{ if (clear){ gl.clear(); if (ga == null) { setAdapter(); } ga.clear(); resetPage(); } Bundle data = new Bundle(); data.putInt("page", page); if (networkTask != null) networkTask.cancelTask(); networkTask = new NetworkTask(taskjob, listType, context, data, this); networkTask.execute(isList() ? MALManager.listSortFromInt(list, listType) : query); }catch (Exception e){ Log.e("MALX", "error getting records: " + e.getMessage()); } } public void searchRecords(String search) { if (search != null && !search.equals(query) && !search.isEmpty()) { // no need for searching the same again or empty string query = search; page = 1; setSwipeRefreshEnabled(false); getRecords(true, TaskJob.SEARCH, 0); } } /* * reset the page number of anime/manga lists. */ public void resetPage() { if (!isList()) { page = 1; Gridview.setSelection(0); } } /* * set the adapter anime/manga */ public void setAdapter() { ga = new ListViewAdapter<GenericRecord>(context, resource); ga.setNotifyOnChange(true); } /* * refresh the covers. */ public void refresh() { try { if (ga == null) setAdapter(); ga.clear(); ga.supportAddAll(gl); if (Gridview.getAdapter() == null) Gridview.setAdapter(ga); } catch (Exception e) { if (MALApi.isNetworkAvailable(context)) { e.printStackTrace(); if (taskjob.equals(TaskJob.SEARCH)) { Crouton.makeText(activity, R.string.crouton_error_Search, Style.ALERT).show(); } else { if (listType.equals(ListType.ANIME)) { Crouton.makeText(activity, R.string.crouton_error_Anime_Sync, Style.ALERT).show(); } else { Crouton.makeText(activity, R.string.crouton_error_Manga_Sync, Style.ALERT).show(); } } Log.e("MALX", "error on refresh: " + e.getMessage()); } else { Crouton.makeText(activity, R.string.crouton_error_noConnectivity, Style.ALERT).show(); } } loading = false; } /* * check if the taskjob is my personal anime/manga list */ public boolean isList() { return taskjob.equals(TaskJob.GETLIST) || taskjob.equals(TaskJob.FORCESYNC); } /* * set the list with the new page/list. */ @SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions @Override public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) { if (!cancelled) // don't change the UI if cancelled toggleLoadingIndicator(false); if ( !cancelled || (cancelled && job.equals(TaskJob.FORCESYNC))) { // forced sync tasks are completed even after cancellation ArrayList resultList; try { if (type == ListType.ANIME) { resultList = (ArrayList<Anime>) result; } else { resultList = (ArrayList<Manga>) result; } } catch (ClassCastException e) { Log.e("MALX", "error reading result because of invalid result class: " + result.getClass().toString()); resultList = null; } if (resultList != null) { if (resultList.size() == 0 && taskjob.equals(TaskJob.SEARCH)) { if (this.page == 1) doRecordsLoadedCallback(type, job, false, true, cancelled); } else { if (job.equals(TaskJob.FORCESYNC)) doRecordsLoadedCallback(type, job, false, false, cancelled); if (!cancelled) { // only add results if not cancelled (on FORCESYNC) if (detail || job.equals(TaskJob.FORCESYNC)) { // a forced sync always reloads all data, so clear the list gl.clear(); detail = false; } gl.addAll(resultList); refresh(); } } } else { doRecordsLoadedCallback(type, job, true, false, cancelled); // no resultList ? something went wrong } } networkTask = null; toggleSwipeRefreshAnimation(false); toggleLoadingIndicator(false); } @Override public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) { doRecordsLoadedCallback(type, job, true, true, false); } private void doRecordsLoadedCallback(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) { if (callback != null) callback.onRecordsLoadingFinished(type, job, error, resultEmpty, cancelled); } /* * handle the gridview click by navigating to the detailview. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent startDetails = new Intent(getView().getContext(), DetailView.class); startDetails.putExtra("net.somethingdreadful.MAL.recordID", ga.getItem(position).getId()); startDetails.putExtra("net.somethingdreadful.MAL.recordType", listType); startActivity(startDetails); if (isList() || taskjob.equals(TaskJob.SEARCH)) this.detail = true; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } /* * load more pages if we are almost on the bottom. */ @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount - firstVisibleItem <= (visibleItemCount * 2) && !loading) { loading = true; if (taskjob != TaskJob.GETLIST && taskjob != TaskJob.FORCESYNC) { page = page + 1; getRecords(false, null, 0); } } } /* * corpy the anime title to the clipboard on long click. */ @SuppressLint("NewApi") @SuppressWarnings("deprecation") @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Crouton.makeText(activity, R.string.crouton_info_Copied, Style.CONFIRM).show(); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); c.setText(gl.get(position).getTitle()); } else { android.content.ClipboardManager c1 = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData c2; c2 = android.content.ClipData.newPlainText("Atarashii", gl.get(position).getTitle()); c1.setPrimaryClip(c2); } return false; } static class ViewHolder { TextView label; TextView progressCount; TextView flavourText; ImageView cover; ImageView bar; ImageView actionButton; } /* * the custom adapter for the covers anime/manga. */ public class ListViewAdapter<T> extends ArrayAdapter<T> { public ListViewAdapter(Context context, int resource) { super(context, resource); } @SuppressWarnings("deprecation") public View getView(int position, View view, ViewGroup parent) { final GenericRecord record = gl.get(position); ViewHolder viewHolder; if (view == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(resource, parent, false); viewHolder = new ViewHolder(); viewHolder.label = (TextView) view.findViewById(R.id.animeName); viewHolder.progressCount = (TextView) view.findViewById(R.id.watchedCount); viewHolder.cover = (ImageView) view.findViewById(R.id.coverImage); viewHolder.bar = (ImageView) view.findViewById(R.id.textOverlayPanel); viewHolder.actionButton = (ImageView) view.findViewById(R.id.popUpButton); viewHolder.flavourText = (TextView) view.findViewById(R.id.stringWatched); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } try { if (taskjob.equals(TaskJob.GETMOSTPOPULAR) || taskjob.equals(TaskJob.GETTOPRATED)) { viewHolder.progressCount.setVisibility(View.VISIBLE); viewHolder.progressCount.setText(Integer.toString(position + 1)); viewHolder.actionButton.setVisibility(View.GONE); viewHolder.flavourText.setText(R.string.label_Number); } else if (listType.equals(ListType.ANIME)) { viewHolder.progressCount.setText(Integer.toString(((Anime) record).getWatchedEpisodes())); setStatus(((Anime) record).getWatchedStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton); } else { if (useSecondaryAmounts) viewHolder.progressCount.setText(Integer.toString(((Manga) record).getVolumesRead())); else viewHolder.progressCount.setText(Integer.toString(((Manga) record).getChaptersRead())); setStatus(((Manga) record).getReadStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton); } viewHolder.label.setText(record.getTitle()); Picasso.with(context) .load(record.getImageUrl()) .error(R.drawable.cover_error) .placeholder(R.drawable.cover_loading) .into(viewHolder.cover); if (viewHolder.actionButton.getVisibility() == View.VISIBLE) { viewHolder.actionButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(context, v); popup.getMenuInflater().inflate(R.menu.record_popup, popup.getMenu()); if (!listType.equals(ListType.ANIME)) popup.getMenu().findItem(R.id.plusOne).setTitle(R.string.action_PlusOneRead); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.plusOne: if (listType.equals(ListType.ANIME)) setProgressPlusOne((Anime) record, null); else setProgressPlusOne(null, (Manga) record); break; case R.id.markCompleted: if (listType.equals(ListType.ANIME)) setMarkAsComplete((Anime) record, null); else setMarkAsComplete(null, (Manga) record); break; } return true; } }); popup.show(); } }); } viewHolder.bar.setAlpha(175); } catch (Exception e) { Log.e("MALX", "error on the ListViewAdapter: " + e.getMessage()); } return view; } public void supportAddAll(Collection<? extends T> collection) { for (T record : collection) { this.add(record); } } } }
package io.github.cloudiator.rest.api; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import io.github.cloudiator.rest.UserInfo; import io.github.cloudiator.rest.converter.ProcessConverter; import io.github.cloudiator.rest.converter.ProcessNewConverter; import io.github.cloudiator.rest.model.CloudiatorProcess; import io.github.cloudiator.rest.model.CloudiatorProcessNew; import io.github.cloudiator.rest.model.Queue; import io.github.cloudiator.rest.queue.QueueService; import io.github.cloudiator.rest.queue.QueueService.QueueItem; import io.github.cloudiator.util.Base64IdEncoder; import io.github.cloudiator.util.IdEncoder; import io.swagger.annotations.ApiParam; import java.util.List; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.cloudiator.messages.Process.CreateProcessRequest; import org.cloudiator.messages.Process.DeleteProcessRequest; import org.cloudiator.messages.Process.ProcessCreatedResponse; import org.cloudiator.messages.Process.ProcessDeletedResponse; import org.cloudiator.messages.Process.ProcessQueryRequest; import org.cloudiator.messages.Process.ProcessQueryRequest.Builder; import org.cloudiator.messages.Process.ProcessQueryResponse; import org.cloudiator.messaging.ResponseException; import org.cloudiator.messaging.services.ProcessService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; @Controller public class ProcessApiController implements ProcessApi { private static final Logger log = LoggerFactory.getLogger(ProcessApiController.class); private final ObjectMapper objectMapper; private final HttpServletRequest request; private static final ProcessNewConverter PROCESS_NEW_CONVERTER = ProcessNewConverter.INSTANCE; private static final ProcessConverter PROCESS_CONVERTER = ProcessConverter.INSTANCE; private final IdEncoder idEncoder = Base64IdEncoder.create(); private final ProcessService processService; private final QueueService queueService; @org.springframework.beans.factory.annotation.Autowired public ProcessApiController(ObjectMapper objectMapper, HttpServletRequest request, ProcessService processService, QueueService queueService) { this.objectMapper = objectMapper; this.request = request; this.processService = processService; this.queueService = queueService; } public ResponseEntity<Queue> createProcess( @ApiParam(value = "Process to be created ", required = true) @Valid @RequestBody CloudiatorProcessNew process) { String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { final String tenant = UserInfo.of(request).tenant(); final CreateProcessRequest createProcessRequest = CreateProcessRequest.newBuilder() .setUserId(tenant).setProcess(PROCESS_NEW_CONVERTER.apply(process)).build(); final QueueItem<ProcessCreatedResponse> queueItem = queueService .queueCallback(tenant, processCreatedResponse -> "process/" + processCreatedResponse.getProcessGroup() .getId()); processService.createProcessAsync(createProcessRequest, queueItem.getCallback()); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.LOCATION, queueItem.getQueueLocation()); return new ResponseEntity<>(queueItem.getQueue(), httpHeaders, HttpStatus.ACCEPTED); } return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @Override public ResponseEntity<Queue> deleteProcess( @ApiParam(value = "Unique identifier of the resource", required = true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { if (Strings.isNullOrEmpty(id)) { throw new ApiException(400, "id is null or empty"); } final String tenant = UserInfo.of(request).tenant(); final DeleteProcessRequest deleteProcessRequest = DeleteProcessRequest.newBuilder() .setUserId(tenant).setProcessId(id).build(); final QueueItem<ProcessDeletedResponse> queueItem = queueService.queueCallback(tenant); processService.deleteProcessAsync(deleteProcessRequest, queueItem.getCallback()); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.LOCATION, queueItem.getQueueLocation()); return new ResponseEntity<>(queueItem.getQueue(), httpHeaders, HttpStatus.ACCEPTED); } return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @Override public ResponseEntity<CloudiatorProcess> findProcess( @ApiParam(value = "Unique identifier of the resource", required = true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { final String tenant = UserInfo.of(request).tenant(); if (Strings.isNullOrEmpty(id)) { throw new ApiException(400, "ProcessId is null or empty"); } final ProcessQueryRequest processQueryRequest = ProcessQueryRequest.newBuilder() .setProcessId(id) .setUserId(tenant).build(); try { final ProcessQueryResponse processQueryResponse = processService .queryProcesses(processQueryRequest); if (processQueryResponse.getProcessesCount() == 0) { throw new ApiException(404, "Process not found"); } if (processQueryResponse.getProcessesCount() > 1) { throw new ApiException(500, "Multiple process found for id"); } final CloudiatorProcess process = PROCESS_CONVERTER .applyBack(processQueryResponse.getProcesses(0)); //TODO: needs to be refactored for Single and Cluster Process //process.setNodeGroup(idEncoder.encode(process.getNodeGroup())); return new ResponseEntity<>(process, HttpStatus.OK); } catch (ResponseException e) { throw new ApiException(e.code(), e.getMessage()); } } return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } public ResponseEntity<List<CloudiatorProcess>> getProcesses( @ApiParam(value = "Id of the schedule. ") @Valid @RequestParam(value = "scheduleId", required = false) String scheduleId) { String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { try { final String tenant = UserInfo.of(request).tenant(); final Builder builder = ProcessQueryRequest.newBuilder().setUserId(tenant); if (!Strings.isNullOrEmpty(scheduleId)) { builder.setScheduleId(scheduleId); } final ProcessQueryResponse processQueryResponse = processService .queryProcesses(builder.build()); return new ResponseEntity<>( processQueryResponse.getProcessesList().stream().map(PROCESS_CONVERTER::applyBack) .collect( Collectors.toList()), HttpStatus.OK); } catch (ResponseException e) { throw new ApiException(e.code(), e.getMessage()); } } return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } }
package net.somethingdreadful.MAL; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.PopupMenu; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewFlipper; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.MALApi.ListType; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.GenericRecord; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.tasks.NetworkTask; import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener; import net.somethingdreadful.MAL.tasks.TaskJob; import net.somethingdreadful.MAL.tasks.WriteDetailTask; import java.util.ArrayList; import java.util.Collection; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class IGF extends Fragment implements OnScrollListener, OnItemLongClickListener, OnItemClickListener, NetworkTaskCallbackListener { Context context; ListType listType = ListType.ANIME; // just to have it proper initialized TaskJob taskjob; GridView Gridview; PrefManager pref; ViewFlipper viewflipper; SwipeRefreshLayout swipeRefresh; Activity activity; ArrayList<GenericRecord> gl = new ArrayList<GenericRecord>(); ListViewAdapter<GenericRecord> ga; IGFCallbackListener callback; NetworkTask networkTask; int page = 1; int list = -1; int resource; boolean useSecondaryAmounts; boolean loading = true; boolean detail = false; boolean hasmorepages = false; /* setSwipeRefreshEnabled() may be called before swipeRefresh exists (before onCreateView() is * called), so save it and apply it in onCreateView() */ boolean swipeRefreshEnabled = true; String query; /* * set the watched/read count & status on the covers. */ public static void setStatus(String myStatus, TextView textview, TextView progressCount, ImageView actionButton) { actionButton.setVisibility(View.GONE); progressCount.setVisibility(View.GONE); if (myStatus == null) { textview.setText(""); } else if (myStatus.equals("watching")) { textview.setText(R.string.cover_Watching); progressCount.setVisibility(View.VISIBLE); actionButton.setVisibility(View.VISIBLE); } else if (myStatus.equals("reading")) { textview.setText(R.string.cover_Reading); progressCount.setVisibility(View.VISIBLE); actionButton.setVisibility(View.VISIBLE); } else if (myStatus.equals("completed")) { textview.setText(R.string.cover_Completed); } else if (myStatus.equals("on-hold")) { textview.setText(R.string.cover_OnHold); progressCount.setVisibility(View.VISIBLE); } else if (myStatus.equals("dropped")) { textview.setText(R.string.cover_Dropped); } else if (myStatus.equals("plan to watch")) { textview.setText(R.string.cover_PlanningToWatch); } else if (myStatus.equals("plan to read")) { textview.setText(R.string.cover_PlanningToRead); } else { textview.setText(""); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { setRetainInstance(true); View view = inflater.inflate(R.layout.record_igf_layout, container, false); viewflipper = (ViewFlipper) view.findViewById(R.id.viewFlipper); Gridview = (GridView) view.findViewById(R.id.gridview); Gridview.setOnItemClickListener(this); Gridview.setOnItemLongClickListener(this); Gridview.setOnScrollListener(this); context = getActivity(); activity = getActivity(); pref = new PrefManager(context); useSecondaryAmounts = pref.getUseSecondaryAmountsEnabled(); if (pref.getTraditionalListEnabled()) { Gridview.setColumnWidth((int) Math.pow(9999, 9999)); //remain in the listview mode resource = R.layout.record_igf_listview; } else { resource = R.layout.record_igf_gridview; } swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh); if (isOnHomeActivity()) { swipeRefresh.setOnRefreshListener((Home) getActivity()); swipeRefresh.setColorScheme( R.color.holo_blue_bright, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light ); } swipeRefresh.setEnabled(swipeRefreshEnabled); if ( gl.size() > 0 ) // there are already records, fragment has been rotated refresh(); NfcHelper.disableBeam(activity); if (callback != null) callback.onIGFReady(this); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = activity; if (IGFCallbackListener.class.isInstance(activity)) callback = (IGFCallbackListener)activity; } private boolean isOnHomeActivity() { return getActivity() != null && getActivity().getClass() == Home.class; } /* * add +1 episode/volume/chapters to the anime/manga. */ public void setProgressPlusOne(Anime anime, Manga manga) { if (listType.equals(ListType.ANIME)) { anime.setWatchedEpisodes(anime.getWatchedEpisodes() + 1); if (anime.getWatchedEpisodes() == anime.getEpisodes()) anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime); } else { manga.setProgress(useSecondaryAmounts, manga.getProgress(useSecondaryAmounts) + 1); if (manga.getProgress(useSecondaryAmounts) == manga.getTotal(useSecondaryAmounts)) manga.setReadStatus(GenericRecord.STATUS_COMPLETED); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga); } refresh(); } /* * mark the anime/manga as completed. */ public void setMarkAsComplete(Anime anime, Manga manga) { if (listType.equals(ListType.ANIME)) { anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED); if (anime.getEpisodes() > 0) anime.setWatchedEpisodes(anime.getEpisodes()); anime.setDirty(true); gl.remove(anime); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(anime); } else { manga.setReadStatus(GenericRecord.STATUS_COMPLETED); manga.setDirty(true); gl.remove(manga); new WriteDetailTask(listType, TaskJob.UPDATE, context).execute(manga); } refresh(); } /* * handle the loading indicator */ private void toggleLoadingIndicator(boolean show) { if (viewflipper != null) { viewflipper.setDisplayedChild(show ? 1 : 0); } } public void toggleSwipeRefreshAnimation(boolean show) { if (swipeRefresh != null) { swipeRefresh.setRefreshing(show); } } public void setSwipeRefreshEnabled(boolean enabled) { swipeRefreshEnabled = enabled; if (swipeRefresh != null) { swipeRefresh.setEnabled(enabled); } } /* * get the anime/manga lists. * (if clear is true the whole list will be cleared and loaded) */ public void getRecords(boolean clear, TaskJob task, int list) { if (task != null) { taskjob = task; } if (list != this.list) { this.list = list; } /* only show loading indicator if * - is not own list and not page 1 * - force sync and list is empty (only show swipe refresh animation if not empty) or should * be cleared */ boolean isEmpty = gl.isEmpty(); toggleLoadingIndicator((page == 1 && !isList()) || (taskjob.equals(TaskJob.FORCESYNC) && (isEmpty || clear))); /* show swipe refresh animation if * - loading more pages * - forced update */ toggleSwipeRefreshAnimation((page > 1 && !isList() || taskjob.equals(TaskJob.FORCESYNC)) && !taskjob.equals(TaskJob.SEARCH)); loading = true; try{ if (clear){ gl.clear(); if (ga == null) { setAdapter(); } ga.clear(); resetPage(); } Bundle data = new Bundle(); data.putInt("page", page); if (networkTask != null) networkTask.cancelTask(); networkTask = new NetworkTask(taskjob, listType, context, data, this); networkTask.execute(isList() ? MALManager.listSortFromInt(list, listType) : query); }catch (Exception e){ Log.e("MALX", "error getting records: " + e.getMessage()); } } public void searchRecords(String search) { if (search != null && !search.equals(query) && !search.equals("")) { // no need for searching the same again or empty string query = search; page = 1; setSwipeRefreshEnabled(false); getRecords(true, TaskJob.SEARCH, 0); } } /* * reset the page number of anime/manga lists. */ public void resetPage() { if (!isList()) { page = 1; Gridview.setSelection(0); } } /* * set the adapter anime/manga */ public void setAdapter() { ga = new ListViewAdapter<GenericRecord>(context, resource); ga.setNotifyOnChange(true); } /* * refresh the covers. */ public void refresh() { try { if (ga == null) setAdapter(); ga.clear(); ga.supportAddAll(gl); if (Gridview.getAdapter() == null) Gridview.setAdapter(ga); } catch (Exception e) { if (MALApi.isNetworkAvailable(context)) { e.printStackTrace(); if (taskjob.equals(TaskJob.SEARCH)) { Crouton.makeText(activity, R.string.crouton_error_Search, Style.ALERT).show(); } else { if (listType.equals(ListType.ANIME)) { Crouton.makeText(activity, R.string.crouton_error_Anime_Sync, Style.ALERT).show(); } else { Crouton.makeText(activity, R.string.crouton_error_Manga_Sync, Style.ALERT).show(); } } Log.e("MALX", "error on refresh: " + e.getMessage()); } else { Crouton.makeText(activity, R.string.crouton_error_noConnectivity, Style.ALERT).show(); } } loading = false; } /* * check if the taskjob is my personal anime/manga list */ public boolean isList() { return taskjob != null && (taskjob.equals(TaskJob.GETLIST) || taskjob.equals(TaskJob.FORCESYNC)); } private boolean jobReturnsPagedResults(TaskJob job) { return !job.equals(TaskJob.FORCESYNC) && !job.equals(TaskJob.GETLIST); } /* * set the list with the new page/list. */ @SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions @Override public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) { if (!cancelled) // don't change the UI if cancelled toggleLoadingIndicator(false); if ( !cancelled || (cancelled && job.equals(TaskJob.FORCESYNC))) { // forced sync tasks are completed even after cancellation ArrayList resultList; try { if (type == ListType.ANIME) { resultList = (ArrayList<Anime>) result; } else { resultList = (ArrayList<Manga>) result; } } catch (ClassCastException e) { Log.e("MALX", "error reading result because of invalid result class: " + result.getClass().toString()); resultList = null; } if (resultList != null) { if (resultList.size() == 0 && taskjob.equals(TaskJob.SEARCH)) { if (this.page == 1) doRecordsLoadedCallback(type, job, false, true, cancelled); } else { if (job.equals(TaskJob.FORCESYNC)) doRecordsLoadedCallback(type, job, false, false, cancelled); if (!cancelled) { // only add results if not cancelled (on FORCESYNC) if (detail || job.equals(TaskJob.FORCESYNC)) { // a forced sync always reloads all data, so clear the list gl.clear(); detail = false; } if (jobReturnsPagedResults(job)) hasmorepages = resultList.size() > 0; gl.addAll(resultList); refresh(); } } } else { doRecordsLoadedCallback(type, job, true, false, cancelled); // no resultList ? something went wrong } } networkTask = null; toggleSwipeRefreshAnimation(false); toggleLoadingIndicator(false); } @Override public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) { doRecordsLoadedCallback(type, job, true, true, false); } private void doRecordsLoadedCallback(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) { if (callback != null) callback.onRecordsLoadingFinished(type, job, error, resultEmpty, cancelled); } /* * handle the gridview click by navigating to the detailview. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent startDetails = new Intent(getView().getContext(), DetailView.class); startDetails.putExtra("net.somethingdreadful.MAL.recordID", ga.getItem(position).getId()); startDetails.putExtra("net.somethingdreadful.MAL.recordType", listType); startActivity(startDetails); if (isList() || taskjob.equals(TaskJob.SEARCH)) this.detail = true; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } /* * load more pages if we are almost on the bottom. */ @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // don't do anything if there is nothing in the list if (firstVisibleItem == 0 && visibleItemCount == 0 && totalItemCount == 0) return; if (totalItemCount - firstVisibleItem <= (visibleItemCount * 2) && !loading && hasmorepages){ loading = true; if (jobReturnsPagedResults(taskjob)){ page++; getRecords(false, null, list); } } } /* * corpy the anime title to the clipboard on long click. */ @SuppressLint("NewApi") @SuppressWarnings("deprecation") @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Crouton.makeText(activity, R.string.crouton_info_Copied, Style.CONFIRM).show(); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); c.setText(gl.get(position).getTitle()); } else { android.content.ClipboardManager c1 = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData c2; c2 = android.content.ClipData.newPlainText("Atarashii", gl.get(position).getTitle()); c1.setPrimaryClip(c2); } return false; } static class ViewHolder { TextView label; TextView progressCount; TextView flavourText; ImageView cover; ImageView bar; ImageView actionButton; } /* * the custom adapter for the covers anime/manga. */ public class ListViewAdapter<T> extends ArrayAdapter<T> { public ListViewAdapter(Context context, int resource) { super(context, resource); } @SuppressWarnings("deprecation") public View getView(int position, View view, ViewGroup parent) { final GenericRecord record = gl.get(position); ViewHolder viewHolder; if (view == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(resource, parent, false); viewHolder = new ViewHolder(); viewHolder.label = (TextView) view.findViewById(R.id.animeName); viewHolder.progressCount = (TextView) view.findViewById(R.id.watchedCount); viewHolder.cover = (ImageView) view.findViewById(R.id.coverImage); viewHolder.bar = (ImageView) view.findViewById(R.id.textOverlayPanel); viewHolder.actionButton = (ImageView) view.findViewById(R.id.popUpButton); viewHolder.flavourText = (TextView) view.findViewById(R.id.stringWatched); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } try { if (taskjob.equals(TaskJob.GETMOSTPOPULAR) || taskjob.equals(TaskJob.GETTOPRATED)) { viewHolder.progressCount.setVisibility(View.VISIBLE); viewHolder.progressCount.setText(Integer.toString(position + 1)); viewHolder.actionButton.setVisibility(View.GONE); viewHolder.flavourText.setText(R.string.label_Number); } else if (listType.equals(ListType.ANIME)) { viewHolder.progressCount.setText(Integer.toString(((Anime) record).getWatchedEpisodes())); setStatus(((Anime) record).getWatchedStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton); } else { if (useSecondaryAmounts) viewHolder.progressCount.setText(Integer.toString(((Manga) record).getVolumesRead())); else viewHolder.progressCount.setText(Integer.toString(((Manga) record).getChaptersRead())); setStatus(((Manga) record).getReadStatus(), viewHolder.flavourText, viewHolder.progressCount, viewHolder.actionButton); } viewHolder.label.setText(record.getTitle()); Picasso.with(context) .load(record.getImageUrl()) .error(R.drawable.cover_error) .placeholder(R.drawable.cover_loading) .into(viewHolder.cover); if (viewHolder.actionButton.getVisibility() == View.VISIBLE) { viewHolder.actionButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(context, v); popup.getMenuInflater().inflate(R.menu.record_popup, popup.getMenu()); if (!listType.equals(ListType.ANIME)) popup.getMenu().findItem(R.id.plusOne).setTitle(R.string.action_PlusOneRead); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.plusOne: if (listType.equals(ListType.ANIME)) setProgressPlusOne((Anime) record, null); else setProgressPlusOne(null, (Manga) record); break; case R.id.markCompleted: if (listType.equals(ListType.ANIME)) setMarkAsComplete((Anime) record, null); else setMarkAsComplete(null, (Manga) record); break; } return true; } }); popup.show(); } }); } viewHolder.bar.setAlpha(175); } catch (Exception e) { Log.e("MALX", "error on the ListViewAdapter: " + e.getMessage()); } return view; } public void supportAddAll(Collection<? extends T> collection) { for (T record : collection) { this.add(record); } } } }
package org.spine3.server.procman; import com.google.protobuf.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spine3.base.CommandContext; import org.spine3.base.EventContext; import org.spine3.base.EventRecord; import org.spine3.client.CommandRequest; import org.spine3.server.BoundedContext; import org.spine3.server.CommandDispatcher; import org.spine3.server.EntityRepository; import org.spine3.server.EventDispatcher; import org.spine3.server.util.EventRecords; import org.spine3.type.CommandClass; import org.spine3.type.EventClass; import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static org.spine3.client.Commands.getCommand; /** * The abstract base for Process Managers repositories. * * @param <I> the type of IDs of process managers * @param <PM> the type of process managers * @param <M> the type of process manager state messages * @see ProcessManager * @author Alexander Litus */ public abstract class ProcessManagerRepository<I, PM extends ProcessManager<I, M>, M extends Message> extends EntityRepository<I, PM, M> implements CommandDispatcher, EventDispatcher { /** * {@inheritDoc} */ protected ProcessManagerRepository(BoundedContext boundedContext) { super(boundedContext); } /** * Intended to return a process manager ID based on the command and command context. * * <p>The default implementation uses {@link #getId(Message)} method and does not use the {@code context}. * Override any of these methods if you need. * * @param command command which the process manager handles * @param context context of the command * @return a process manager ID * @see #getId(Message) */ @SuppressWarnings("UnusedParameters") // Overriding implementations may use the `context` parameter. protected I getId(Message command, CommandContext context) { return getId(command); } /** * Intended to return a process manager ID based on the event and event context. * * <p>The default implementation uses {@link #getId(Message)} method and does not use the {@code context}. * Override any of these methods if you need. * * @param event event which the process manager handles * @param context context of the event * @return a process manager ID */ @SuppressWarnings("UnusedParameters") // Overriding implementations may use the `context` parameter. protected I getId(Message event, EventContext context) { return getId(event); } /** * Returns a process manager ID based on the command/event message. * * @param message a command/event which the process manager handles * @return a process manager ID * @see ProcessManagerId#from(Message) */ protected I getId(Message message) { // We cast to this type because assume that all commands/events for the manager refer to IDs of the same type <I>. // If this assumption fails, we would get ClassCastException. @SuppressWarnings("unchecked") final I result = (I) ProcessManagerId.from(message).value(); return result; } @Override public Set<CommandClass> getCommandClasses() { final Class<? extends ProcessManager> pmClass = getEntityClass(); final Set<Class<? extends Message>> commandClasses = ProcessManager.getHandledCommandClasses(pmClass); final Set<CommandClass> result = CommandClass.setOf(commandClasses); return result; } @Override public Set<EventClass> getEventClasses() { final Class<? extends ProcessManager> pmClass = getEntityClass(); final Set<Class<? extends Message>> eventClasses = ProcessManager.getHandledEventClasses(pmClass); final Set<EventClass> result = EventClass.setOf(eventClasses); return result; } /** * Dispatches the command to a corresponding process manager. * * <p>If there is no stored process manager with such an ID, a new process manager is created * and stored after it handles the passed command. * * @param request a request to dispatch * @see ProcessManager#dispatchCommand(Message, CommandContext) * @see #getId(Message, CommandContext) */ @Override public List<EventRecord> dispatch(CommandRequest request) throws InvocationTargetException { final Message command = getCommand(checkNotNull(request)); final CommandContext context = request.getContext(); final I id = getId(command, context); final PM manager = load(id); final List<EventRecord> events = manager.dispatchCommand(command, context); store(manager); return events; } /** * Dispatches the event to a corresponding process manager. * * <p>If there is no stored process manager with such an ID, a new process manager is created * and stored after it handles the passed event. * * @param event the event to dispatch * @see ProcessManager#dispatchEvent(Message, EventContext) * @see #getId(Message, EventContext) */ @Override public void dispatch(EventRecord event) { final Message eventMessage = EventRecords.getEvent(event); final EventContext context = event.getContext(); final I id = getId(eventMessage, context); final PM manager = load(id); try { manager.dispatchEvent(eventMessage, context); store(manager); } catch (InvocationTargetException e) { log().error("Error during dispatching event", e); } } /** * Loads or creates a process manager by the passed ID. * * <p>The process manager is created if there was no manager with such an ID stored before. * * @param id the ID of the process manager to load * @return loaded or created process manager instance */ @Nonnull @Override public PM load(I id) { PM result = super.load(id); if (result == null) { result = create(id); } return result; } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(ProcessManagerRepository.class); } private static Logger log() { return LogSingleton.INSTANCE.value; } }
package org.jboss.forge.addon.shell.command; import org.jboss.forge.addon.resource.Resource; import org.jboss.forge.addon.shell.ui.AbstractShellCommand; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UIExecutionContext; import org.jboss.forge.addon.ui.context.UISelection; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.output.UIOutput; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.addon.ui.result.Results; import org.jboss.forge.addon.ui.util.Metadata; /** * * @author <a href="ggastald@redhat.com">George Gastaldi</a> */ public class PwdCommand extends AbstractShellCommand { @Override public void initializeUI(UIBuilder builder) throws Exception { // no arguments } @Override public UICommandMetadata getMetadata(UIContext context) { return Metadata.from(super.getMetadata(context), getClass()).name("pwd") .description("Print the full filename of the current working directory."); } @Override public Result execute(UIExecutionContext shellContext) throws Exception { UIContext uiContext = shellContext.getUIContext(); UISelection<Resource<?>> selection = uiContext.getInitialSelection(); Resource<?> currentResource = selection.get(); if (currentResource != null) { UIOutput output = uiContext.getProvider().getOutput(); output.out().println(currentResource.getFullyQualifiedName()); } return Results.success(); } }
package de.triplet.simpleprovider; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import java.util.ArrayList; import java.util.List; @SuppressWarnings("unused") // Public API public abstract class AbstractProvider extends ContentProvider { protected final String mLogTag; protected SQLiteDatabase mDatabase; protected AbstractProvider() { mLogTag = getClass().getName(); } @Override public final boolean onCreate() { try { SimpleSQLHelper dbHelper = new SimpleSQLHelper(getContext(), getDatabaseFileName(), getSchemaVersion()); dbHelper.setTableClass(getClass()); mDatabase = dbHelper.getWritableDatabase(); return true; } catch (SQLiteException e) { Log.w(mLogTag, "Database Opening exception", e); } return false; } protected String getDatabaseFileName() { return getClass().getName().toLowerCase() + ".db"; } /** * Returns the current schema version. This number will be used to automatically trigger * upgrades and downgrades. You may override this method in derived classes if anything has * changed in the schema classes. * @return */ protected int getSchemaVersion() { return 1; } protected abstract String getAuthority(); @Override public String getType(Uri uri) { return null; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { final SelectionBuilder builder = buildBaseQuery(uri); final Cursor cursor = builder.where(selection, selectionArgs).query(mDatabase, projection, sortOrder); if (cursor != null) { cursor.setNotificationUri(getContentResolver(), uri); } return cursor; } private ContentResolver getContentResolver() { Context context = getContext(); if (context == null) { return null; } return context.getContentResolver(); } private SelectionBuilder buildBaseQuery(Uri uri) { List<String> pathSegments = uri.getPathSegments(); if (pathSegments == null) { return null; } SelectionBuilder builder = new SelectionBuilder(pathSegments.get(0)); if (pathSegments.size() == 2) { builder.whereEquals(BaseColumns._ID, uri.getLastPathSegment()); } return builder; } @Override public Uri insert(Uri uri, ContentValues values) { List<String> segments = uri.getPathSegments(); if (segments == null || segments.size() != 1) { return null; } long rowId = mDatabase.insert(segments.get(0), null, values); if (rowId > -1) { getContentResolver().notifyChange(uri, null); return ContentUris.withAppendedId(uri, rowId); } return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SelectionBuilder builder = buildBaseQuery(uri); int count = builder.where(selection, selectionArgs).delete(mDatabase); if (count > 0) { getContentResolver().notifyChange(uri, null); } return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { final SelectionBuilder builder = buildBaseQuery(uri); int count = builder.where(selection, selectionArgs).update(mDatabase, values); if (count > 0) { getContentResolver().notifyChange(uri, null); } return count; } @SuppressWarnings("NullableProblems") @Override public final ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { ContentProviderResult[] result = null; mDatabase.beginTransaction(); try { result = super.applyBatch(operations); mDatabase.setTransactionSuccessful(); } finally { mDatabase.endTransaction(); } return result; } }
package org.slc.sli.api.security; import java.lang.reflect.Field; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.core.UriBuilder; import org.apache.commons.lang3.tuple.Pair; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.common.exceptions.InvalidClientException; import org.springframework.security.oauth2.common.exceptions.RedirectMismatchException; import org.springframework.security.oauth2.provider.ClientToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.stereotype.Component; import org.slc.sli.api.security.oauth.ApplicationAuthorizationValidator; import org.slc.sli.api.security.oauth.OAuthAccessException; import org.slc.sli.api.security.oauth.OAuthAccessException.OAuthError; import org.slc.sli.api.security.resolve.RolesToRightsResolver; import org.slc.sli.api.security.resolve.UserLocator; import org.slc.sli.api.util.SecurityUtil; import org.slc.sli.api.util.SecurityUtil.SecurityTask; import org.slc.sli.domain.Entity; import org.slc.sli.domain.MongoEntity; import org.slc.sli.domain.NeutralCriteria; import org.slc.sli.domain.NeutralQuery; import org.slc.sli.domain.Repository; import org.slc.sli.domain.enums.Right; /** * Manages SLI User/app sessions * Provides functionality to update existing session based on Oauth life-cycle stages * * @author dkornishev * */ @Component public class OauthMongoSessionManager implements OauthSessionManager { private static final Pattern USER_AUTH = Pattern.compile("Bearer (.+)", Pattern.CASE_INSENSITIVE); private static final String APPLICATION_COLLECTION = "application"; private static final String SESSION_COLLECTION = "userSession"; @Value("${sli.session.length}") private int sessionLength; @Value("${sli.session.hardLogout}") private int hardLogout; @Autowired private Repository<Entity> repo; @Autowired private RolesToRightsResolver resolver; @Autowired private UserLocator locator; private ObjectMapper jsoner = new ObjectMapper(); @Autowired private ApplicationAuthorizationValidator appValidator; /** * Creates a new app session * Creates user session if needed */ @Override @SuppressWarnings("unchecked") public void createAppSession(String sessionId, String clientId, String redirectUri, String state, String tenantId, String samlId) { NeutralQuery nq = new NeutralQuery(new NeutralCriteria("client_id", "=", clientId)); Entity app = repo.findOne(APPLICATION_COLLECTION, nq); if (app == null) { RuntimeException x = new InvalidClientException(String.format("No app with id %s registered", clientId)); error(x.getMessage(), x); throw x; } else if (redirectUri != null && !redirectUri.startsWith((String) app.getBody().get("redirect_uri"))) { RuntimeException x = new RedirectMismatchException("Invalid redirect_uri specified " + redirectUri); error(x.getMessage() + " expected " + app.getBody().get("redirect_uri"), x); throw x; } Entity sessionEntity = sessionId == null ? null : repo.findById(SESSION_COLLECTION, sessionId); if (sessionEntity == null) { sessionEntity = repo.create(SESSION_COLLECTION, new HashMap<String, Object>()); sessionEntity.getBody().put("expiration", System.currentTimeMillis() + this.sessionLength); sessionEntity.getBody().put("hardLogout", System.currentTimeMillis() + this.hardLogout); sessionEntity.getBody().put("tenantId", tenantId); sessionEntity.getBody().put("appSession", new ArrayList<Map<String, Object>>()); } List<Map<String, Object>> appSessions = (List<Map<String, Object>>) sessionEntity.getBody().get("appSession"); appSessions.add(newAppSession(clientId, redirectUri, state, samlId)); repo.update(SESSION_COLLECTION, sessionEntity); } /** * Provides the URI to which the user should be redirected * Upon receipt of successful SAML message */ @Override @SuppressWarnings("unchecked") public Pair<String, URI> composeRedirect(String samlId, SLIPrincipal principal) { NeutralQuery nq = new NeutralQuery(); nq.addCriteria(new NeutralCriteria("appSession.samlId", "=", samlId)); Entity session = repo.findOne(SESSION_COLLECTION, nq); if (session == null) { RuntimeException x = new IllegalStateException(String.format("No session with samlId %s", samlId)); error("Attempted to access invalid session", x); throw x; } List<Map<String, Object>> appSessions = (List<Map<String, Object>>) session.getBody().get("appSession"); URI redirect = null; for (Map<String, Object> appSession : appSessions) { if (appSession.get("samlId").equals(samlId)) { UriBuilder builder = UriBuilder.fromUri((String) appSession.get("redirectUri")); Map<String, Object> code = (Map<String, Object>) appSession.get("code"); builder.queryParam("code", (String) code.get("value")); if (appSession.get("state") != null) { builder.queryParam("state", appSession.get("state")); } Map<String, Object> mapForm = jsoner.convertValue(principal, Map.class); mapForm.remove("entity"); session.getBody().put("principal", mapForm); repo.update(SESSION_COLLECTION, session); redirect = builder.build(); break; } } return Pair.of(session.getEntityId(), redirect); } /** * Verifies and makes active an app session. Provides the token for the app. * @throws OAuthAccessException * @throws OAuthException */ @Override @SuppressWarnings("unchecked") public String verify(String code, Pair<String, String> clientCredentials) throws OAuthAccessException { NeutralQuery nq = new NeutralQuery(); nq.addCriteria(new NeutralCriteria("appSession.clientId", "=", clientCredentials.getLeft())); nq.addCriteria(new NeutralCriteria("appSession.verified", "=", "false")); nq.addCriteria(new NeutralCriteria("appSession.code.value", "=", code)); nq.addCriteria(new NeutralCriteria("appSession.code.expiration", ">", System.currentTimeMillis())); Entity session = repo.findOne(SESSION_COLLECTION, nq); if (session == null) { RuntimeException x = new IllegalArgumentException(String.format("No session with code/client %s/%s", code, clientCredentials.getLeft())); error("Attempted to access invalid session", x); throw x; } // Locate the application and compare the client secret nq = new NeutralQuery(); nq.addCriteria(new NeutralCriteria("client_id", "=", clientCredentials.getLeft())); nq.addCriteria(new NeutralCriteria("client_secret", "=", clientCredentials.getRight())); Entity app = repo.findOne(APPLICATION_COLLECTION, nq); if (app == null) { OAuthAccessException x = new OAuthAccessException(OAuthError.UNAUTHORIZED_CLIENT, "No application matching credentials found."); error("App credentials mismatch", x); throw x; } //Make sure the user's district has authorized the use of this application SLIPrincipal principal = jsoner.convertValue(session.getBody().get("principal"), SLIPrincipal.class); principal.setEntity(locator.locate((String) principal.getTenantId(), principal.getExternalId()).getEntity()); List<String> authorizedAppIds = appValidator.getAuthorizedApps(principal); //If the list of authorized apps is null, we weren't able to figure out the user's LEA. //TODO: deny access if no context information is available--to fix in oauth hardening if (authorizedAppIds != null && !authorizedAppIds.contains(app.getEntityId())) { throw new OAuthAccessException(OAuthError.UNAUTHORIZED_CLIENT, "User " + principal.getExternalId() + " is not authorized to use " + app.getBody().get("name"), (String) session.getBody().get("state")); } List<Map<String, Object>> appSessions = (List<Map<String, Object>>) session.getBody().get("appSession"); String token = ""; for (Map<String, Object> appSession : appSessions) { Map<String, Object> codeBlock = (Map<String, Object>) appSession.get("code"); if (codeBlock.get("value").equals(code)) { token = (String) appSession.get("token"); appSession.put("verified", "true"); repo.update(SESSION_COLLECTION, session); break; } } return token; } /** * Loads session referenced by the headers * * @param headers * @return */ @Override @SuppressWarnings("unchecked") public OAuth2Authentication getAuthentication(String authz) { OAuth2Authentication auth = createAnonymousAuth(); if (authz != null && !authz.equals("")) { try { Matcher user = USER_AUTH.matcher(authz); if (user.find()) { String accessToken = user.group(1); Entity sessionEntity = findEntityForAccessToken(accessToken); if (sessionEntity != null) { List<Map<String, Object>> sessions = (List<Map<String, Object>>) sessionEntity.getBody().get("appSession"); for (Map<String, Object> session : sessions) { if (session.get("token").equals(accessToken)) { ClientToken token = new ClientToken((String) session.get("clientId"), null /* secret not needed */, null /* Scope is unused */); // Spring doesn't provide a setter for the approved field (used by isAuthorized), so we set it the hard way Field approved = ClientToken.class.getDeclaredField("approved"); approved.setAccessible(true); approved.set(token, true); SLIPrincipal principal = jsoner.convertValue(sessionEntity.getBody().get("principal"), SLIPrincipal.class); principal.setEntity(locator.locate((String) principal.getTenantId(), principal.getExternalId()).getEntity()); Collection<GrantedAuthority> authorities = resolveAuthorities(principal.getRealm(), principal.getRoles()); PreAuthenticatedAuthenticationToken userToken = new PreAuthenticatedAuthenticationToken(principal, accessToken, authorities); userToken.setAuthenticated(true); auth = new OAuth2Authentication(token, userToken); // Extend the session long expire = (Long) sessionEntity.getBody().get("expiration"); sessionEntity.getBody().put("expiration", expire + this.sessionLength); repo.update(SESSION_COLLECTION, sessionEntity); break; } } } } else { info("User is anonymous"); } } catch (Exception e) { error("Error processing authentication. Anonymous context will be returned.", e); } } return auth; } /** * Determines if the specified mongo id maps to a valid OAuth access token. * * @param mongoId id of the oauth session in mongo. * @return id of realm (valid session) or null (not a valid session). */ @Override public Entity getSession(String sessionId) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("_id", "=", sessionId)); Entity session = repo.findOne(SESSION_COLLECTION, neutralQuery); return session; } @Override public boolean logout(String accessToken) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("appSession.token", "=", accessToken)); Entity session = repo.findOne(SESSION_COLLECTION, neutralQuery); boolean deleted = false; if (session != null) { deleted = repo.delete(SESSION_COLLECTION, session.getEntityId()); } return deleted; } private Collection<GrantedAuthority> resolveAuthorities(final String realm, final List<String> roleNames) { Collection<GrantedAuthority> userAuthorities = SecurityUtil.sudoRun(new SecurityTask<Collection<GrantedAuthority>>() { @Override public Collection<GrantedAuthority> execute() { return resolver.resolveRoles(realm, roleNames); } }); return userAuthorities; } private OAuth2Authentication createAnonymousAuth() { String time = Long.toString(System.currentTimeMillis()); SLIPrincipal anon = new SLIPrincipal(time); anon.setEntity(new MongoEntity("user", "-133", new HashMap<String, Object>(), new HashMap<String, Object>())); return new OAuth2Authentication(new ClientToken("UNKNOWN", "UNKNOWN", new HashSet<String>()), new AnonymousAuthenticationToken(time, anon , Arrays.<GrantedAuthority>asList(Right.ANONYMOUS_ACCESS))); } private Entity findEntityForAccessToken(String token) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("appSession.token", "=", token)); neutralQuery.addCriteria(new NeutralCriteria("expiration", ">", System.currentTimeMillis())); neutralQuery.addCriteria(new NeutralCriteria("hardLogout", ">", System.currentTimeMillis())); return repo.findOne(SESSION_COLLECTION, neutralQuery); } private Map<String, Object> newAppSession(String clientId, String redirectUri, String state, String samlId) { Map<String, Object> app = new HashMap<String, Object>(); app.put("clientId", clientId); app.put("redirectUri", redirectUri); app.put("state", state); app.put("samlId", samlId); app.put("verified", "false"); Map<String, Object> code = new HashMap<String, Object>(); code.put("value", "c-" + UUID.randomUUID().toString()); code.put("expiration", System.currentTimeMillis() + this.sessionLength); app.put("code", code); app.put("token", "t-" + UUID.randomUUID().toString()); return app; } }
package gov.nih.nci.evs.browser.utils; import java.io.*; import java.util.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Vector; import java.util.HashSet; import java.util.Arrays; import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption; import org.LexGrid.LexBIG.Utility.Constructors; import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms; import org.LexGrid.concepts.Concept; import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeRenderingList; import org.LexGrid.LexBIG.DataModel.InterfaceElements.CodingSchemeRendering; import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList; import org.LexGrid.LexBIG.DataModel.Collections.ModuleDescriptionList; import org.LexGrid.LexBIG.DataModel.InterfaceElements.ModuleDescription; import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator; import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Core.ConceptReference; import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph; import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList; import org.LexGrid.LexBIG.DataModel.Core.NameAndValue; import org.LexGrid.LexBIG.DataModel.Collections.AssociationList; import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept; import org.LexGrid.LexBIG.DataModel.Core.Association; import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList; import org.LexGrid.codingSchemes.CodingScheme; import org.LexGrid.concepts.Definition; import org.LexGrid.concepts.Comment; import org.LexGrid.concepts.Presentation; import org.apache.log4j.Logger; import org.LexGrid.LexBIG.Exceptions.LBResourceUnavailableException; import org.LexGrid.LexBIG.Exceptions.LBInvocationException; import org.LexGrid.LexBIG.Utility.ConvenienceMethods; import org.LexGrid.commonTypes.EntityDescription; import org.LexGrid.commonTypes.Property; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Collections.AssociationList; import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList; import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept; import org.LexGrid.LexBIG.DataModel.Core.Association; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.ActiveOption; import org.LexGrid.LexBIG.Utility.ConvenienceMethods; import org.LexGrid.commonTypes.EntityDescription; import org.LexGrid.commonTypes.Property; import org.LexGrid.concepts.Concept; import org.LexGrid.relations.Relations; import org.LexGrid.commonTypes.PropertyQualifier; import org.LexGrid.commonTypes.Source; import org.LexGrid.naming.SupportedSource; import org.LexGrid.naming.SupportedPropertyQualifier; import org.LexGrid.LexBIG.DataModel.Core.types.CodingSchemeVersionStatus; import org.LexGrid.naming.SupportedAssociation; import org.LexGrid.naming.SupportedAssociationQualifier; import org.LexGrid.naming.SupportedProperty; import org.LexGrid.naming.SupportedPropertyQualifier; import org.LexGrid.naming.SupportedRepresentationalForm; import org.LexGrid.naming.SupportedSource; import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList; import org.LexGrid.LexBIG.DataModel.Collections.AssociationList; import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept; import org.LexGrid.LexBIG.DataModel.Core.Association; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.naming.Mappings; import org.LexGrid.naming.SupportedHierarchy; import org.LexGrid.LexBIG.DataModel.InterfaceElements.RenderingDetail; import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeTagList; import org.LexGrid.LexBIG.Exceptions.LBParameterException; import gov.nih.nci.evs.browser.properties.NCImBrowserProperties; import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption; import org.LexGrid.LexBIG.Utility.Constructors; import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms; import org.LexGrid.concepts.Entity; import org.apache.commons.codec.language.DoubleMetaphone; /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation kim.ong@ngc.com * */ public class SearchUtils { private boolean apply_sort_score = false; private boolean sort_by_pt_only = true; public CodingSchemeRenderingList csrl = null; private Vector supportedCodingSchemes = null; private static HashMap codingSchemeMap = null; private Vector codingSchemes = null; private static HashMap csnv2codingSchemeNameMap = null; private static HashMap csnv2VersionMap = null; private static List directionList = null; private static String url = null; static final List<String> STOP_WORDS = Arrays.asList(new String[] { "a", "an", "and", "by", "for", "of", "on", "in", "nos", "the", "to", "with"}); private DoubleMetaphone doubleMetaphone = null; public SearchUtils() { initializeSortParameters(); } public SearchUtils(String url) { this.url = url; initializeSortParameters(); } private void initializeSortParameters() { doubleMetaphone = new DoubleMetaphone(); try { NCImBrowserProperties properties = NCImBrowserProperties.getInstance(); String sort_str = properties.getProperty(NCImBrowserProperties.SORT_BY_SCORE); sort_by_pt_only = true; apply_sort_score = true; if (sort_str != null) { if (sort_str.compareTo("false") == 0) { apply_sort_score = false; } else if (sort_str.compareToIgnoreCase("all") == 0) { sort_by_pt_only = false; } } } catch (Exception ex) { } } private static void setCodingSchemeMap() { codingSchemeMap = new HashMap(); csnv2codingSchemeNameMap = new HashMap(); csnv2VersionMap = new HashMap(); try { //RemoteServerUtil rsu = new RemoteServerUtil(); //EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes(); if(csrl == null) System.out.println("csrl is NULL"); CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering(); for (int i=0; i<csrs.length; i++) { CodingSchemeRendering csr = csrs[i]; Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE); if (isActive != null && isActive.equals(Boolean.TRUE)) { CodingSchemeSummary css = csr.getCodingSchemeSummary(); String formalname = css.getFormalName(); String representsVersion = css.getRepresentsVersion(); CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); vt.setVersion(representsVersion); CodingScheme scheme = null; try { scheme = lbSvc.resolveCodingScheme(formalname, vt); if (scheme != null) { codingSchemeMap.put((Object) formalname, (Object) scheme); String value = formalname + " (version: " + representsVersion + ")"; System.out.println(value); csnv2codingSchemeNameMap.put(value, formalname); csnv2VersionMap.put(value, representsVersion); } } catch (Exception e) { String urn = css.getCodingSchemeURI(); try { scheme = lbSvc.resolveCodingScheme(urn, vt); if (scheme != null) { codingSchemeMap.put((Object) formalname, (Object) scheme); String value = formalname + " (version: " + representsVersion + ")"; System.out.println(value); csnv2codingSchemeNameMap.put(value, formalname); csnv2VersionMap.put(value, representsVersion); } } catch (Exception ex) { String localname = css.getLocalName(); try { scheme = lbSvc.resolveCodingScheme(localname, vt); if (scheme != null) { codingSchemeMap.put((Object) formalname, (Object) scheme); String value = formalname + " (version: " + representsVersion + ")"; System.out.println(value); csnv2codingSchemeNameMap.put(value, formalname); csnv2VersionMap.put(value, representsVersion); } } catch (Exception e2) { e2.printStackTrace(); } } } } } } catch (Exception e) { e.printStackTrace(); } } public Vector getSuperconceptCodes(String scheme, String version, String code) { //throws LBException{ long ms = System.currentTimeMillis(); Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(this.url); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0) .getEntityDescription().getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null); for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms)); } return v; } public Vector getSuperconceptCodes_Local(String scheme, String version, String code) { //throws LBException{ long ms = System.currentTimeMillis(); Vector v = new Vector(); try { LexBIGService lbSvc = new LexBIGServiceImpl(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0) .getEntityDescription().getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null); for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms)); } return v; } public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationNames(); for (int i=0; i<ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; } public static String getVocabularyVersionByTag(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i=0; i<csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { if (ltag == null) return css.getRepresentsVersion(); RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); for (int j=0; j<tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return css.getRepresentsVersion(); } } } } } catch (Exception e) { e.printStackTrace(); } System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName); return null; } public static Vector<String> getVersionListData(String codingSchemeName) { Vector<String> v = new Vector(); try { RemoteServerUtil rsu = new RemoteServerUtil(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes(); if(csrl == null) System.out.println("csrl is NULL"); CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering(); for (int i=0; i<csrs.length; i++) { CodingSchemeRendering csr = csrs[i]; Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE); if (isActive != null && isActive.equals(Boolean.TRUE)) { CodingSchemeSummary css = csr.getCodingSchemeSummary(); String formalname = css.getFormalName(); if (formalname.compareTo(codingSchemeName) == 0) { String representsVersion = css.getRepresentsVersion(); v.add(representsVersion); } } } } catch (Exception ex) { } return v; } protected static Association processForAnonomousNodes(Association assoc){ //clone Association except associatedConcepts Association temp = new Association(); temp.setAssociatedData(assoc.getAssociatedData()); temp.setAssociationName(assoc.getAssociationName()); temp.setAssociationReference(assoc.getAssociationReference()); temp.setDirectionalName(assoc.getDirectionalName()); temp.setAssociatedConcepts(new AssociatedConceptList()); for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++) { //Conditionals to deal with anonymous nodes and UMLS top nodes "V-X" //The first three allow UMLS traversal to top node. //The last two are specific to owl anonymous nodes which can act like false //top nodes. if( assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false && !assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") && !assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@") ) { //do nothing } else{ temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i)); } } return temp; } public static NameAndValueList createNameAndValueList(String[] names, String[] values) { NameAndValueList nvList = new NameAndValueList(); for (int i=0; i<names.length; i++) { NameAndValue nv = new NameAndValue(); nv.setName(names[i]); if (values != null) { nv.setContent(values[i]); } nvList.addNameAndValue(nv); } return nvList; } public static LocalNameList vector2LocalNameList(Vector<String> v) { if (v == null) return null; LocalNameList list = new LocalNameList(); for (int i=0; i<v.size(); i++) { String vEntry = (String) v.elementAt(i); list.addEntry(vEntry); } return list; } protected static NameAndValueList createNameAndValueList(Vector names, Vector values) { if (names == null) return null; NameAndValueList nvList = new NameAndValueList(); for (int i=0; i<names.size(); i++) { String name = (String) names.elementAt(i); String value = (String) values.elementAt(i); NameAndValue nv = new NameAndValue(); nv.setName(name); if (value != null) { nv.setContent(value); } nvList.addNameAndValue(nv); } return nvList; } public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { System.out.println("lbSvc == null???"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(vers); ConceptReferenceList crefs = createConceptReferenceList( new String[] {code}, codingSchemeName); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); } catch (Exception e1) { e1.printStackTrace(); } cns = cns.restrictToCodes(crefs); ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, null, false, 1); if (matches == null) { System.out.println("Concep not found."); return null; } // Analyze the result ... if (matches.getResolvedConceptReferenceCount() > 0) { ResolvedConceptReference ref = (ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement(); org.LexGrid.concepts.Concept entry = new org.LexGrid.concepts.Concept(); entry.setEntityCode(ref.getConceptCode()); entry.setEntityDescription(ref.getEntityDescription()); //Concept entry = ref.getReferencedEntry(); return entry; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } public static ConceptReferenceList createConceptReferenceList(String[] codes, String codingSchemeName) { if (codes == null) { return null; } ConceptReferenceList list = new ConceptReferenceList(); for (int i = 0; i < codes.length; i++) { ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(codingSchemeName); cr.setConceptCode(codes[i]); list.addConceptReference(cr); } return list; } public Vector getParentCodes(String scheme, String version, String code) { //SearchUtils util = new SearchUtils(); Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0) { return null; } String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); Vector superconcept_vec = getAssociationSources(scheme, version, code, hierarchicalAssoName); if (superconcept_vec == null) return null; return superconcept_vec; } public ResolvedConceptReferenceList getNext(ResolvedConceptReferencesIterator iterator) { return iterator.getNext(); } /** * Dump_matches to output, for debug purposes * * @param iterator the iterator * @param maxToReturn the max to return */ public static Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn) { return resolveIterator(iterator, maxToReturn, null); } public static Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code) { return resolveIterator(iterator, maxToReturn, code, true); } public static Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code, boolean sortLight) { Vector v = new Vector(); if (maxToReturn == 0) return v; if (iterator == null) { System.out.println("No match."); return v; } int scroll_size = 200; try { int iteration = 0; while (iterator.hasNext()) { iterator = iterator.scroll(scroll_size); ResolvedConceptReferenceList rcrl = iterator.getNext(); if (rcrl != null) { ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference(); if (rcra == null) break; if (rcra.length > 0) { for (int i=0; i<rcra.length; i++) { ResolvedConceptReference rcr = rcra[i]; if (rcr == null) { System.out.println("resolveIterator rcr == null???"); break; } if (sortLight) { org.LexGrid.concepts.Concept ce = new org.LexGrid.concepts.Concept(); ce.setEntityCode(rcr.getConceptCode()); ce.setEntityDescription(rcr.getEntityDescription()); if (code == null) { v.add(ce); } else { if (ce.getEntityCode().compareTo(code) != 0) v.add(ce); } } else { Concept ce = rcr.getReferencedEntry(); if (ce == null) { System.out.println("resolveIterator rcr.getReferencedEntry() returns null???"); break; } else { if (code == null) v.add(ce); else if (ce.getEntityCode().compareTo(code) != 0) v.add(ce); } } } iteration++; if (maxToReturn > 0 & iteration*scroll_size >= maxToReturn) { break; } } } } } catch (Exception e) { e.printStackTrace(); } return v; } public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator( CodedNodeGraph cng, ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveAssociationDepth, int maxToReturn) { CodedNodeSet cns = null; try { cns = cng.toNodeList(graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); if (cns == null) { System.out.println("cng.toNodeList returns null???"); return null; } SortOptionList sortCriteria = null; //Constructors.createSortOptionList(new String[]{"matchToQuery", "code"}); LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; ResolvedConceptReferencesIterator iterator = null; try { iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes); } catch (Exception e) { e.printStackTrace(); } if(iterator == null) { System.out.println("cns.resolve returns null???"); } return iterator; } catch (Exception ex) { ex.printStackTrace(); return null; } } public Vector getSuperconcepts(String scheme, String version, String code) { //String assocName = "hasSubtype"; String hierarchicalAssoName = "hasSubtype"; Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec != null && hierarchicalAssoName_vec.size() > 0) { hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); } return getAssociationSources(scheme, version, code, hierarchicalAssoName); } public Vector getAssociationSources(String scheme, String version, String code, String assocName) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList( new String[] {assocName}, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = false; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator( cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public Vector getSubconcepts(String scheme, String version, String code) { //String assocName = "hasSubtype"; String hierarchicalAssoName = "hasSubtype"; Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec != null && hierarchicalAssoName_vec.size() > 0) { hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); } return getAssociationTargets(scheme, version, code, hierarchicalAssoName); } public Vector getAssociationTargets(String scheme, String version, String code, String assocName) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList( new String[] {assocName}, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = false; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator( cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } //search for "lycogen" public static String preprocessContains(String s) { if (s == null) return null; if (s.length() == 0) return null; s = s.trim(); List<String> words = toWords(s, "\\s", false, false); String delim = ".*"; StringBuffer searchPhrase = new StringBuffer(); int k = -1; searchPhrase.append(delim); for (int i = 0; i < words.size(); i++) { String wd = (String) words.get(i); wd = wd.trim(); if (wd.compareTo("") != 0) { searchPhrase.append(wd); if (words.size() > 1 && i < words.size()-1) { searchPhrase.append("\\s"); } } } searchPhrase.append(delim); String t = searchPhrase.toString(); return t; } private boolean isNumber(String s) { if (s.length() == 0) return false; for(int i=0; i<s.length(); i++) { if(!Character.isDigit(s.charAt(i))) return false; } return true; } public static CodedNodeSet restrictToSource(CodedNodeSet cns, String source) { if (cns == null) return cns; if (source == null || source.compareTo("*") == 0 || source.compareTo("") == 0 || source.compareTo("ALL") == 0) return cns; LocalNameList contextList = null; LocalNameList sourceLnL = null; NameAndValueList qualifierList = null; Vector<String> w2 = new Vector<String>(); w2.add(source); sourceLnL = vector2LocalNameList(w2); LocalNameList propertyLnL = null; CodedNodeSet.PropertyType[] types = new PropertyType[] {PropertyType.PRESENTATION}; try { cns = cns.restrictToProperties(propertyLnL, types, sourceLnL, contextList, qualifierList); } catch (Exception ex) { System.out.println("restrictToSource throws exceptions."); return null; } return cns; } public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code, String source) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { System.out.println("lbSvc == null???"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); ConceptReferenceList crefs = createConceptReferenceList( new String[] {code}, codingSchemeName); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); } catch (Exception e1) { //e1.printStackTrace(); } cns = cns.restrictToCodes(crefs); cns = restrictToSource(cns, source); ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1); if (matches == null) { System.out.println("Concep not found."); return null; } // Analyze the result ... if (matches.getResolvedConceptReferenceCount() > 0) { ResolvedConceptReference ref = (ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement(); Concept entry = ref.getReferencedEntry(); return entry; } } catch (Exception e) { //e.printStackTrace(); return null; } return null; } public Vector<org.LexGrid.concepts.Concept> searchByName(String scheme, String version, String matchText, String matchAlgorithm, int maxToReturn) { return searchByName(scheme, version, matchText, null, matchAlgorithm, maxToReturn); } public Vector<org.LexGrid.concepts.Concept> searchByName(String scheme, String version, String matchText, String source, String matchAlgorithm, int maxToReturn) { String matchText0 = matchText; String matchAlgorithm0 = matchAlgorithm; matchText0 = matchText0.trim(); boolean preprocess = true; if (matchText == null || matchText.length() == 0) { return new Vector(); } matchText = matchText.trim(); if (matchAlgorithm.compareToIgnoreCase("exactMatch") == 0) { //KLO 032409 if (!isNumber(matchText)) { if (nonAlphabetic(matchText) || matchText.indexOf(".") != -1 || matchText.indexOf("/") != -1) { return searchByName(scheme, version, matchText, "RegExp", maxToReturn); } } if (containsSpecialChars(matchText)) { return searchByName(scheme, version, matchText, "RegExp", maxToReturn); } } else if (matchAlgorithm.compareToIgnoreCase("startsWith") == 0) { /* matchText = "^" + matchText; matchAlgorithm = "RegExp"; preprocess = false; */ } else if (matchAlgorithm.compareToIgnoreCase("contains") == 0) //p11.1-q11.1 /100{WBC} { /* //matchText = replaceSpecialCharsWithBlankChar(matchText); if (matchText.indexOf(" ") != -1) { matchText = preprocessContains(matchText); matchAlgorithm = "RegExp"; preprocess = false; } else { String delim = ".*"; matchText = delim + matchText + delim; matchAlgorithm = "RegExp"; preprocess = false; } */ String delim = ".*"; if (containsSpecialChars(matchText)) { matchText = delim + matchText + delim; matchAlgorithm = "RegExp"; preprocess = false; } else if (matchText.indexOf(" ") != -1) { matchText = preprocessContains(matchText); matchAlgorithm = "RegExp"; preprocess = false; //KLO 051209 } else if (matchText.indexOf(" ") == -1) { matchText = delim + matchText + delim; matchAlgorithm = "RegExp"; preprocess = false; } } if (matchAlgorithm.compareToIgnoreCase("RegExp") == 0 && preprocess) { matchText = preprocessRegExp(matchText); } CodedNodeSet cns = null; ResolvedConceptReferencesIterator iterator = null; try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { System.out.println("lbSvc = null"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); //cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); cns = lbSvc.getNodeSet(scheme, versionOrTag, null); if (cns == null) { System.out.println("cns = null"); return null; } //LocalNameList contextList = null; try { cns = cns.restrictToMatchingDesignations(matchText, SearchDesignationOption.ALL, matchAlgorithm, null); cns = restrictToSource(cns, source); } catch (Exception ex) { return null; } LocalNameList restrictToProperties = new LocalNameList(); SortOptionList sortCriteria = null; //Constructors.createSortOptionList(new String[]{"matchToQuery"}); try { // resolve nothing unless sort_by_pt_only is set to false boolean resolveConcepts = false; if (apply_sort_score && !sort_by_pt_only) resolveConcepts = true; try { long ms = System.currentTimeMillis(); iterator = cns.resolve(sortCriteria, null, restrictToProperties, null, resolveConcepts); System.out.println("cns.resolve delay ---- Run time (ms): " + (System.currentTimeMillis() - ms) + " -- matchAlgorithm " + matchAlgorithm); } catch (Exception e) { System.out.println("ERROR: cns.resolve throws exceptions."); } } catch (Exception ex) { ex.printStackTrace(); return null; } } catch (Exception e) { e.printStackTrace(); return null; } if (apply_sort_score) { long ms = System.currentTimeMillis(); try { /* if (sort_by_pt_only) { iterator = sortByScore(matchText0, iterator, maxToReturn, true); } else { iterator = sortByScore(matchText0, iterator, maxToReturn); } */ if (sort_by_pt_only) { iterator = sortByScore(matchText0, iterator, maxToReturn, true, matchAlgorithm); } else { iterator = sortByScore(matchText0, iterator, maxToReturn, matchAlgorithm); } } catch (Exception ex) { } System.out.println("sortByScore delay ---- Run time (ms): " + (System.currentTimeMillis() - ms)); } Vector v = null; if (iterator != null) { //testing KLO //v = resolveIterator( iterator, maxToReturn, null, sort_by_pt_only); long ms = System.currentTimeMillis(); v = resolveIterator( iterator, maxToReturn, null, sort_by_pt_only); System.out.println("resolveIterator delay ---- Run time (ms): " + (System.currentTimeMillis() - ms)); } if (v == null || v.size() == 0) { v = new Vector(); // add exact match for CUI and source code, if there is any (simple search case): //Concept c = DataUtils.getConceptByCode(scheme, version, null, matchText0, source); Concept c = getConceptByCode(scheme, version, null, matchText0, source); if (c != null) { v.add(c); } boolean searchInactive = true; Vector u = new SearchUtils().findConceptWithSourceCodeMatching(scheme, version, source, matchText0, maxToReturn, searchInactive); if (u != null) { for (int j=0; j<u.size(); j++) { c = (Concept) u.elementAt(j); v.add(c); } } if (v != null && v.size() > 0) { if(!apply_sort_score) { SortUtils.quickSort(v); } } } if (v == null || v.size() == 0) { if (matchAlgorithm0.compareTo("contains") == 0) // /100{WBC} & search by code { return searchByName(scheme, version, matchText0, "startsWith", maxToReturn); } } return v; } public void testSearchByName() { String scheme = "NCI Thesaurus"; String version = null; String matchText = "breast canser"; matchText = "dog"; String matchAlgorithm = "DoubleMetaphoneLuceneQuery"; int maxToReturn = 200; long ms = System.currentTimeMillis(); Vector<org.LexGrid.concepts.Concept> v = searchByName(scheme, version, matchText, matchAlgorithm, maxToReturn); System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms)); if (v != null) { System.out.println("v.size() = " + v.size()); for (int i=0; i<v.size(); i++) { int j = i + 1; Concept ce = (Concept) v.elementAt(i); System.out.println("(" + j + ")" + " " + ce.getEntityCode() + " " + ce.getEntityDescription().getContent()); } } } protected static List<String> toWords(String s, String delimitRegex, boolean removeStopWords, boolean removeDuplicates) { String[] words = s.split(delimitRegex); List<String> adjusted = new ArrayList<String>(); for (int i = 0; i < words.length; i++) { String temp = words[i].toLowerCase(); if (removeDuplicates && adjusted.contains(temp)) continue; if (!removeStopWords || !STOP_WORDS.contains(temp)) adjusted.add(temp); } return adjusted; } protected static List<String> toWords2(String s, String delimitRegex, boolean removeStopWords, boolean removeDuplicates) { s = s.trim(); s = replaceSpecialCharsWithBlankChar(s); List<String> adjusted = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(s); while (st.hasMoreTokens()) { String temp = st.nextToken().toLowerCase(); if (removeDuplicates && adjusted.contains(temp)) continue; if (!removeStopWords || !STOP_WORDS.contains(temp)) { adjusted.add(temp); } } return adjusted; } protected static String[] toWords(String s, boolean removeStopWords) { String[] words = s.split("\\s"); List<String> adjusted = new ArrayList<String>(); for (int i = 0; i < words.length; i++) { if (!removeStopWords || !STOP_WORDS.contains(words[i])) adjusted.add(words[i].toLowerCase()); } return adjusted.toArray(new String[adjusted.size()]); } public static String preprocessSearchString(String s) { if (s == null) return null; if (s.length() == 0) return null; StringBuffer searchPhrase = new StringBuffer(); List<String> words = toWords(s, "\\s", true, false); int k = -1; for (int i = 0; i < words.size(); i++) { String wd = (String) words.get(i); wd = wd.trim(); if (wd.compareTo("") != 0) { k++; if (k > 0) { searchPhrase.append(" "); } searchPhrase.append(wd); } } String t = searchPhrase.toString(); return t; } public static boolean nonAlphabetic(String s) { if (s == null) return false; if (s.length() == 0) return true; for (int i=0; i<s.length(); i++) { char ch = s.charAt(i); if (Character.isLetter(ch)) return false; } return true; } /* private static String replaceSpecialChars(String s){ //String escapedChars = "|!(){}[]^\"~*?:;-"; String escapedChars = "|!(){}[]^\"~*?;-_"; for (int i=0; i<escapedChars.length(); i++) { char c = escapedChars.charAt(i); s = s.replace(c, ' '); } return s; } */ private static String escapeSpecialChars(String s, String specChars) { String escapeChar = "\\"; StringBuffer regex = new StringBuffer(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (specChars.indexOf(c) != -1) { regex.append(escapeChar); } regex.append(c); } return regex.toString(); } private static String replaceSpecialChars(String s){ String escapedChars = "/"; for (int i=0; i<escapedChars.length(); i++) { char c = escapedChars.charAt(i); s = s.replace(c, '.'); } return s; } public static String preprocessRegExp(String s) { s = replaceSpecialChars(s); //s = escapeSpecialChars(s, "()"); s = escapeSpecialChars(s, "(){}\\,-[]"); String prefix = s.toLowerCase(); String[] words = toWords(prefix, false); // include stop words StringBuffer regex = new StringBuffer(); regex.append('^'); for (int i = 0; i < words.length; i++) { boolean lastWord = i == words.length - 1; String word = words[i]; int word_length = word.length(); if (word_length > 0) { regex.append('('); if (word.charAt(word.length() - 1) == '.') { regex.append(word.substring(0, word.length())); regex.append("\\w*"); } else { regex.append(word); } regex.append("\\s").append(lastWord ? '*' : '+'); regex.append(')'); } } return regex.toString(); } /** * Sorts the given concept references based on a scoring algorithm * designed to provide a more natural ordering. Scores are determined by * comparing each reference against a provided search term. * @param searchTerm The term used for comparison; single or multi-word. * @param toSort The iterator containing references to sort. * @param maxToReturn Sets upper limit for number of top-scored items returned. * @return Iterator over sorted references. * @throws LBException */ protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn) throws LBException { // Determine the set of individual words to compare against. List<String> compareWords = toScoreWords(searchTerm); // Create a bucket to store results. Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>(); // Score all items ... while (toSort.hasNext()) { // Working in chunks of 100. ResolvedConceptReferenceList refs = toSort.next(100); for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference ref = refs.getResolvedConceptReference(i); String code = ref.getConceptCode(); Concept ce = ref.getReferencedEntry(); // Note: Preferred descriptions carry more weight, // but we process all terms to allow the score to improve // based on any contained presentation. Presentation[] allTermsForConcept = ce.getPresentation(); for (Presentation p : allTermsForConcept) { float score = score(p.getValue().getContent(), compareWords); // Check for a previous match on this code for a different presentation. // If already present, keep the highest score. if (score > 0.) { if (scoredResult.containsKey(code)) { ScoredTerm scoredTerm = (ScoredTerm) scoredResult.get(code); if (scoredTerm.score > score) continue; } scoredResult.put(code, new ScoredTerm(ref, score)); } } } } // Return an iterator that will sort the scored result. return new ScoredIterator(scoredResult.values(), maxToReturn); } protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn, String algorithm) throws LBException { // Determine the set of individual words to compare against. List<String> compareWords = toScoreWords(searchTerm); List<String> compareCodes = new ArrayList<String>(); for (int k=0; k<compareWords.size(); k++) { String word = (String) compareWords.get(k); compareCodes.add(word); } String target = ""; if (algorithm.compareTo("DoubleMetaphoneLuceneQuery") == 0) { compareCodes = new ArrayList<String>(); for (int k=0; k<compareWords.size(); k++) { String word = (String) compareWords.get(k); String doubleMetaphonecode = doubleMetaphoneEncode(word); compareCodes.add(doubleMetaphonecode); target = target + doubleMetaphonecode; if (k < compareWords.size()-1) target = target + " "; } } // Create a bucket to store results. Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>(); // Score all items ... int knt = 0; while (toSort.hasNext()) { // Working in chunks of 100. long ms = System.currentTimeMillis(); ResolvedConceptReferenceList refs = toSort.next(500); // slow why??? System.out.println("Run time (ms): toSort.next() method call took " + (System.currentTimeMillis() - ms) + " millisec."); ms = System.currentTimeMillis(); for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference ref = refs.getResolvedConceptReference(i); String code = ref.getConceptCode(); Concept ce = ref.getReferencedEntry(); // Note: Preferred descriptions carry more weight, // but we process all terms to allow the score to improve // based on any contained presentation. Presentation[] allTermsForConcept = ce.getPresentation(); for (Presentation p : allTermsForConcept) { float score = (float) 0.0; if (algorithm.compareTo("DoubleMetaphoneLuceneQuery") != 0) { score = score(p.getValue().getContent(), compareWords); } else { score = score(p.getValue().getContent(), compareWords, compareCodes, target, true); } if (score > 0.) { // Check for a previous match on this code for a different presentation. // If already present, keep the highest score. if (scoredResult.containsKey(code)) { ScoredTerm scoredTerm = (ScoredTerm) scoredResult.get(code); if (scoredTerm.score > score) continue; } scoredResult.put(code, new ScoredTerm(ref, score)); } } } int num_concepts = refs.getResolvedConceptReferenceCount(); knt = knt + num_concepts; //if (knt > 1000) break; System.out.println("" + knt + " completed. Run time (ms): Assigning scores to " + num_concepts + " concepts took " + (System.currentTimeMillis() - ms) + " millisec."); } // Return an iterator that will sort the scored result. return new ScoredIterator(scoredResult.values(), maxToReturn); } protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn, boolean descriptionOnly) throws LBException { if (!descriptionOnly) return sortByScore(searchTerm, toSort, maxToReturn); // Determine the set of individual words to compare against. List<String> compareWords = toScoreWords(searchTerm); // Create a bucket to store results. Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>(); // Score all items ... while (toSort.hasNext()) { // Working in chunks of 100. ResolvedConceptReferenceList refs = toSort.next(100); for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference ref = refs.getResolvedConceptReference(i); String code = ref.getConceptCode(); String name = ref.getEntityDescription().getContent(); float score = score(name, compareWords); if (score > 0.) { scoredResult.put(code, new ScoredTerm(ref, score)); } } } // Return an iterator that will sort the scored result. return new ScoredIterator(scoredResult.values(), maxToReturn); } protected ResolvedConceptReferencesIterator sortByScore(String searchTerm, ResolvedConceptReferencesIterator toSort, int maxToReturn, boolean descriptionOnly, String algorithm) throws LBException { if (!descriptionOnly) return sortByScore(searchTerm, toSort, maxToReturn); // Determine the set of individual words to compare against. List<String> compareWords = toScoreWords(searchTerm); List<String> compareCodes = new ArrayList<String>(compareWords.size()); String target = ""; if (algorithm.compareTo("DoubleMetaphoneLuceneQuery") == 0) { for (int k=0; k<compareWords.size(); k++) { String word = (String) compareWords.get(k); String doubleMetaphonecode = doubleMetaphoneEncode(word); compareCodes.set(k, doubleMetaphonecode); target = target + doubleMetaphonecode; if (k < compareWords.size()-1) target = target + " "; } } // Create a bucket to store results. Map<String, ScoredTerm> scoredResult = new TreeMap<String, ScoredTerm>(); // Score all items ... while (toSort.hasNext()) { // Working in chunks of 100. long ms = System.currentTimeMillis(); ResolvedConceptReferenceList refs = toSort.next(500); // slow why??? System.out.println("Run time (ms): toSort.next() took " + (System.currentTimeMillis() - ms) + " millisec."); ms = System.currentTimeMillis(); for (int i = 0; i < refs.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference ref = refs.getResolvedConceptReference(i); String code = ref.getConceptCode(); String name = ref.getEntityDescription().getContent(); float score = (float) 0.0;//score(name, compareWords, true, i); if (algorithm.compareTo("DoubleMetaphoneLuceneQuery") == 0) { score = score(name, compareWords, compareCodes, target, true); } else { score = score(name, compareWords); } if (score > 0.) { scoredResult.put(code, new ScoredTerm(ref, score)); } } System.out.println("Run time (ms): assigning scores took " + (System.currentTimeMillis() - ms) + " millisec."); } // Return an iterator that will sort the scored result. return new ScoredIterator(scoredResult.values(), maxToReturn); } /** * Returns a score providing a relative comparison of the given * text against a set of keywords. * <p> * Currently the score is evaluated as a simple percentage * based on number of words in the first set that are also in the * second, with minor adjustment for order (matching later * words given slightly higher weight, anticipating often the * subject of search will follow descriptive text). Weight * is also increased for shorter phrases (measured in # words) * If the text is indicated to be preferred, the score is doubled * to promote 'bubbling to the top'. * <p> * Ranking from the original search is available but not * currently used in the heuristic (tends to throw-off desired * alphabetic groupings later). * * @param text * @param keywords * @param isPreferred * @param searchRank * @return The score; a higher value indicates a stronger match. */ protected float score(String text, List<String> keywords) { List<String> wordsToCompare = toScoreWords(text); float totalWords = wordsToCompare.size(); float matchScore = 0; float position = 0; for (Iterator<String> words = wordsToCompare.listIterator(); words.hasNext(); position++) { String word = words.next(); if (keywords.contains(word)) matchScore += ((position / 10) + 1); } return Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)); //Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)) /* scoring method for DoubleMetaphoneLuceneQuery */ /** * Return words from the given string to be used in scoring * algorithms, in order of occurrence and ignoring duplicates, * stop words, whitespace and common separators. * @param s * @return List */ protected List<String> toScoreWords(String s) { //return toWords(s, "[\\s,:+-;]", true, true); return toWords2(s, "[\\s,:+-;]", true, true); } private boolean containsSpecialChars(String s){ String escapedChars = "/.|!(){}[]^\"~*?;-_"; for (int i=0; i<escapedChars.length(); i++) { char c = escapedChars.charAt(i); if (s.indexOf(c) != -1) return true; } return false; } private static String replaceSpecialCharsWithBlankChar(String s){ String escapedChars = "/.|!(){}[]^\"~*?;-_,"; for (int i=0; i<escapedChars.length(); i++) { char c = escapedChars.charAt(i); s = s.replace(c, ' '); } s = s.trim(); return s; } private CodedNodeSet restrictToActiveStatus(CodedNodeSet cns, boolean activeOnly) { if (cns == null) return null; if (!activeOnly) return cns; // no restriction, do nothing try { cns = cns.restrictToStatus(CodedNodeSet.ActiveOption.ACTIVE_ONLY, null); return cns; } catch (Exception e) { e.printStackTrace(); return null; } } public Vector findConceptWithSourceCodeMatching(String scheme, String version, String sourceAbbr, String code, int maxToReturn, boolean searchInactive) { if (sourceAbbr == null || code == null) return new Vector(); LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); if (lbSvc == null) { System.out.println("lbSvc = null"); return null; } LocalNameList contextList = null; NameAndValueList qualifierList = null; Vector<String> v = null; if (code != null && code.compareTo("") != 0) { qualifierList = new NameAndValueList(); NameAndValue nv = new NameAndValue(); nv.setName("source-code"); nv.setContent(code); qualifierList.addNameAndValue(nv); } LocalNameList propertyLnL = null; // sourceLnL Vector<String> w2 = new Vector<String>(); w2.add(sourceAbbr); LocalNameList sourceLnL = vector2LocalNameList(w2); if (sourceAbbr.compareTo("*") == 0 || sourceAbbr.compareToIgnoreCase("ALL") == 0) { sourceLnL = null; } ResolvedConceptReferencesIterator matchIterator = null; SortOptionList sortCriteria = null;//Constructors.createSortOptionList(new String[]{"matchToQuery", "code"}); try { CodedNodeSet cns = lbSvc.getCodingSchemeConcepts(scheme, null); if (cns == null) { System.out.println("lbSvc.getCodingSchemeConceptsd returns null"); return null; } CodedNodeSet.PropertyType[] types = new PropertyType[] {PropertyType.PRESENTATION}; cns = cns.restrictToProperties(propertyLnL, types, sourceLnL, contextList, qualifierList); if (cns != null) { boolean activeOnly = !searchInactive; cns = restrictToActiveStatus(cns, activeOnly); try { matchIterator = cns.resolve(sortCriteria, null,null);//ConvenienceMethods.createLocalNameList(getPropertyForCodingScheme(cs)),null); } catch (Exception ex) { } if (matchIterator != null) { v = resolveIterator( matchIterator, maxToReturn); return v; } } } catch (Exception e) { //getLogger().error("ERROR: Exception in findConceptWithSourceCodeMatching."); return null; } return null; } private static final boolean isInteger(final String s) { for (int x = 0; x < s.length(); x++) { final char c = s.charAt(x); if (x == 0 && (c == '-')) continue; // negative if ((c >= '0') && (c <= '9')) continue; // 0 - 9 return false; // invalid } return true; // valid } protected String doubleMetaphoneEncode(String word) { if (word == null || word.length() == 0) return word; if (isInteger(word)) return word; /* String firstChar = word.substring(0, 1).toUpperCase(); return firstChar + doubleMetaphone.encode(word); */ return doubleMetaphone.encode(word); } public static void main(String[] args) { String url = "http://lexevsapi-qa.nci.nih.gov/lexevsapi50"; if (args.length == 1) { url = args[0]; System.out.println(url); } SearchUtils test = new SearchUtils(url); test.testSearchByName(); } }
package de.unituebingen.ub.ubtools.solrmarcMixin; import org.marc4j.marc.DataField; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.VariableField; import org.solrmarc.index.SolrIndexer; import org.solrmarc.index.SolrIndexerMixin; import org.solrmarc.tools.Utils; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TuelibMixin extends SolrIndexerMixin { private final static Logger logger = Logger.getLogger(TuelibMixin.class.getName()); private Set<String> isils_cache = null; @Override public void perRecordInit(final Record record) { isils_cache = null; } /** * Determine Record Title * * @param record the record * @return String nicely formatted title */ public String getTitle(final Record record) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final String title_a = (title.getSubfield('a') == null) ? null : title.getSubfield('a').getData(); final String title_b = (title.getSubfield('b') == null) ? null : title.getSubfield('b').getData(); if (title_a == null && title_b == null) return null; StringBuilder complete_title = new StringBuilder(); if (title_a == null) complete_title.append(Utils.cleanData(title_b)); else if (title_b == null) complete_title.append(Utils.cleanData(title_a)); else { // Neither title_a nor title_b are null. complete_title.append(Utils.cleanData(title_a)); complete_title.append(' '); complete_title.append(Utils.cleanData(title_b)); } final String title_c = (title.getSubfield('c') == null) ? null : title.getSubfield('c').getData(); if (title_c != null) { complete_title.append(' '); complete_title.append(Utils.cleanData(title_c)); } final String title_n = (title.getSubfield('n') == null) ? null : title.getSubfield('n').getData(); if (title_n != null) { complete_title.append(' '); complete_title.append(Utils.cleanData(title_n)); } return complete_title.toString(); } /** * Determine Record Title Subfield * * @param record the record * @param subfield_code * @return String nicely formatted title subfield */ public String getTitleSubfield(final Record record, final String subfield_code) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final Subfield subfield = title.getSubfield(subfield_code.charAt(0)); if (subfield == null) return null; final String subfield_data = subfield.getData(); if (subfield_data == null) return null; return Utils.cleanData(subfield_data); } /** * get the local subjects from LOK-tagged fields and get subjects from 936k and 689a subfields * <p/> * LOK = Field * |0 689 = Subfield * |a Imperialismus = Subfield with local subject * * @param record the record * @return Set of local subjects */ public Set<String> getAllTopics(final Record record) { final Set<String> topics = SolrIndexer.getAllSubfields(record, "600:610:611:630:650:653:656:689a:936a", " "); for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().equals("689")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA == null || subfieldA.getData().length() <= 1) { continue; } topics.add(subfieldA.getData()); } return topics; } /** * Hole das Sachschlagwort aus 689|a (wenn 689|d != z oder f) * * @param record the record * @return Set "topic_facet" */ public Set<String> getFacetTopics(final Record record) { final Set<String> result = SolrIndexer.getAllSubfields(record, "600x:610x:611x:630x:648x:650a:650x:651x:655x", " "); String topic_string; // Check 689 subfield a and d final List<VariableField> fields = record.getVariableFields("689"); if (fields != null) { DataField dataField; for (final VariableField variableField : fields) { dataField = (DataField) variableField; final Subfield subfieldD = dataField.getSubfield('d'); if (subfieldD == null) { continue; } topic_string = subfieldD.getData().toLowerCase(); if (topic_string.equals("f") || topic_string.equals("z")) { continue; } final Subfield subfieldA = dataField.getSubfield('a'); if (subfieldA != null) { result.add(subfieldA.getData()); } } } return result; } /** * Returns either a Set<String> of parent (URL + colon + material type). URLs are taken from 856$u and material * types from 856$3, 856$z or 856$x. For missing type subfields the text "Unbekanntes Material" will be used. * Furthermore 024$2 will be checked for "doi". If we find this we generate a URL with a DOI resolver from the * DOI in 024$a and set the "material type" to "DOI Link". * * @param record the record * @return A, possibly empty, Set<String> containing the URL/material-type pairs. */ public Set<String> getUrlsAndMaterialTypes(final Record record) { final Map<String, Set<String>> materialTypeToURLsMap = new TreeMap<String, Set<String>>(); final Set<String> urls_and_material_types = new LinkedHashSet<>(); for (final VariableField variableField : record.getVariableFields("856")) { final DataField field = (DataField) variableField; final Subfield subfield_3 = field.getSubfield('3'); final String material_type; if (subfield_3 != null) material_type = subfield_3.getData(); else { final Subfield subfield_z = field.getSubfield('z'); if (subfield_z != null) material_type = subfield_z.getData(); else { final Subfield subfield_x = field.getSubfield('x'); material_type = (subfield_x == null) ? "Unbekanntes Material" : subfield_x.getData(); } } // Extract all links from u-subfields and resolve URNs: for (final Subfield subfield_u : field.getSubfields('u')) { Set<String> URLs = materialTypeToURLsMap.get(material_type); if (URLs == null) { URLs = new HashSet<String>(); materialTypeToURLsMap.put(material_type, URLs); } final String link = subfield_u.getData(); URLs.add(link.startsWith("urn:") ? "https://nbn-resolving.org/" + link : link); } } // Remove duplicates while favouring SWB and, if not present, DNB links: for (final String material_type : materialTypeToURLsMap.keySet()) { if (material_type.equals("Unbekanntes Material")) { for (final String url : materialTypeToURLsMap.get(material_type)) urls_and_material_types.add(url + ":Unbekanntes Material"); } else { // Locate SWB and DNB URLs, if present: String swbURL = null; String dnbURL = null; for (final String url : materialTypeToURLsMap.get(material_type)) { if (url.startsWith("http://swbplus.bsz-bw.de")) swbURL = url; else if (url.startsWith("http://d-nb.info")) dnbURL = url; } if (swbURL != null) urls_and_material_types.add(swbURL + ":" + material_type); else if (dnbURL != null) urls_and_material_types.add(dnbURL + ":" + material_type); else { // Add the kitchen sink. for (final String url : materialTypeToURLsMap.get(material_type)) urls_and_material_types.add(url + ":" + material_type); } } } // Handle DOI's: for (final VariableField variableField : record.getVariableFields("024")) { final DataField field = (DataField) variableField; final Subfield subfield_2 = field.getSubfield('2'); if (subfield_2 != null && subfield_2.getData().equals("doi")) { final Subfield subfield_a = field.getSubfield('a'); if (subfield_a != null) { final String url = "https://doi.org/" + subfield_a.getData(); urls_and_material_types.add(url + ":DOI"); } } } return urls_and_material_types; } private final static Pattern EXTRACTION_PATTERN = Pattern.compile("^\\([^)]+\\)(\\.+)$"); /** * Returns either a Set<String> of parent (ID + colon + parent title). Only IDs w/o titles will not be returned, * instead a warning will be emitted on stderr. * * @param record the record * @return A, possibly empty, Set<String> containing the ID/title pairs. */ public Set<String> getContainerIdsWithTitles(final Record record) { final Set<String> containerIdsAndTitles = new TreeSet<String>(); for (final String tag : new String[]{"800", "810", "830", "773"}) { for (final VariableField variableField : record.getVariableFields(tag)) { final DataField field = (DataField) variableField; final Subfield titleSubfield = field.getSubfield('t'); final Subfield volumeSubfield = field.getSubfield('v'); final Subfield idSubfield = field.getSubfield('w'); if (titleSubfield == null || idSubfield == null) continue; final Matcher matcher = EXTRACTION_PATTERN.matcher(idSubfield.getData()); if (!matcher.matches()) continue; final String parentId = matcher.group(1); containerIdsAndTitles.add(parentId + "\u001F" + titleSubfield.getData() + "\u001F" + (volumeSubfield == null ? "" : volumeSubfield.getData())); } } return containerIdsAndTitles; } /** * Returns either a Set<String> of parent (ID + colon + parent title). Only IDs w/o titles will not be returned, * instead a warning will be emitted on stderr. * * @return A, possibly empty, Set<String> containing the ID/title pairs. * @arg fields_and_subfields fields_and_subfields, a colon-separated "list" of field tags where each * tag must be followed by two subfield codes e.g. "800aw:810aw:830aw". * The first subfield code for each tag must indicate the "title" subfield * and the second subfield code the ID subfield. * @arg optional_field_extraction_regex */ public Set<String> getContainerIdsWithTitles(final Record record, final String fields_and_subfields, final String optional_field_extraction_regex) { final String[] fields_and_subfields_array = fields_and_subfields.split(":"); if (fields_and_subfields_array.length == 0) { logger.warning("in getContainerIdsOrTitles(): missing fields and subfields to select!"); throw new RuntimeException("in getContainerIdsOrTitles(): missing fields and subfields to select!"); } Pattern extraction_pattern = null; if (!optional_field_extraction_regex.isEmpty()) extraction_pattern = Pattern.compile(optional_field_extraction_regex); final Set<String> container_ids_and_titles = new LinkedHashSet<>(); for (final String aFields_and_subfields_array : fields_and_subfields_array) { final char title_subfield_code = aFields_and_subfields_array.charAt(3); final char id_subfield_code = aFields_and_subfields_array.charAt(4); for (final VariableField variableField : record.getVariableFields(aFields_and_subfields_array.substring(0, 3))) { final DataField field = (DataField) variableField; final List<Subfield> title_subfields = field.getSubfields(title_subfield_code); final List<Subfield> id_subfields = field.getSubfields(id_subfield_code); final int title_subfield_size = title_subfields.size(); final int id_subfield_size = id_subfields.size(); if (title_subfield_size != id_subfield_size) { System.err.println("Warning: in getContainerIdsWithTitles(): size # of title subfields (" + title_subfield_size + ") != # of id subfields (" + id_subfield_size + ")!"); continue; } final Iterator<Subfield> id_iter = field.getSubfields(id_subfield_code).iterator(); final Iterator<Subfield> title_iter = field.getSubfields(title_subfield_code).iterator(); while (id_iter.hasNext()) { String parent_ref = id_iter.next().getData(); if (extraction_pattern != null) { final Matcher matcher = extraction_pattern.matcher(parent_ref); if (!matcher.matches()) { System.err.println("in getContainerIdsWithTitles() in multi_part.bsh: parent ID \"" + parent_ref + "\"did not match the pattern \"" + extraction_pattern.pattern() + "\"!"); title_iter.next(); continue; } parent_ref = matcher.group(1); } container_ids_and_titles.add(parent_ref + ":" + title_iter.next().getData()); } } } return container_ids_and_titles; } /** * Returns either a Set<String> of parent (ID + colon + child title). * * @param record the record * @param fieldsAndSubfields fieldsAndSubfields, a colon-separated "list" of field tags where each * tag must be followed by two subfield codes e.g. "800aw:810aw:830aw". * The first subfield code for each tag must indicate the "title" subfield * and the second subfield code the ID subfield. * @return A, possibly empty, Set<String> containing the ID/title pairs. */ public Set<String> getContaineeIdsWithTitles(final Record record, final String fieldsAndSubfields) { final String[] fieldsAndSubfieldsArray = fieldsAndSubfields.split(":"); if (fieldsAndSubfieldsArray.length == 0) { throw new IllegalArgumentException("Missing fields and subfields to select!"); } final Set<String> containerIdsAndTitles = new LinkedHashSet<>(); for (final String fieldAndSubfield : fieldsAndSubfieldsArray) { final char idSubfieldCode = fieldAndSubfield.charAt(3); final char titleSubfieldCode = fieldAndSubfield.charAt(4); final String tag = fieldAndSubfield.substring(0, 3); for (final VariableField variableField : record.getVariableFields(tag)) { final DataField dataField = (DataField) variableField; final Subfield idSubfield = dataField.getSubfield(idSubfieldCode); final Subfield titleSubfield = dataField.getSubfield(titleSubfieldCode); if (idSubfield == null || titleSubfield == null) { if (idSubfield != null || titleSubfield != null) { logger.fine("Weird, either title or ID is missing!"); } continue; } containerIdsAndTitles.add(idSubfield.getData() + ":" + titleSubfield.getData()); } } return containerIdsAndTitles; } /** * @param record the record * @param fieldnums * @return */ public Set<String> getSuperMP(final Record record, final String fieldnums) { final Set<String> retval = new LinkedHashSet<>(); final HashMap<String, String> resvalues = new HashMap<>(); final HashMap<String, Integer> resscores = new HashMap<>(); String value; String id; Integer score; Integer cscore; String fnum; String fsfc; final String[] fields = fieldnums.split(":"); for (final String field : fields) { fnum = field.replaceAll("[a-z]+$", ""); fsfc = field.replaceAll("^[0-9]+", ""); final List<VariableField> fs = record.getVariableFields(fnum); if (fs == null) { continue; } for (final VariableField variableField : fs) { final DataField dataField = (DataField) variableField; final Subfield subfieldW = dataField.getSubfield('w'); if (subfieldW == null) { continue; } final Subfield fsubany = dataField.getSubfield(fsfc.charAt(0)); if (fsubany == null) { continue; } value = fsubany.getData().trim(); id = subfieldW.getData().replaceAll("^\\([^\\)]+\\)", ""); // Count number of commas in "value": score = value.length() - value.replace(",", "").length(); if (resvalues.containsKey(id)) { cscore = resscores.get(id); if (cscore > score) { continue; } } resvalues.put(id, value); resscores.put(id, score); } } for (final String key : resvalues.keySet()) { value = "(" + key + ")" + resvalues.get(key); retval.add(value); } return retval; } /** * get the ISILs from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of isils */ public Set<String> getIsils(final Record record) { if (isils_cache != null) { return isils_cache; } final Set<String> isils = new LinkedHashSet<>(); final List<VariableField> fields = record.getVariableFields("LOK"); if (fields != null) { for (final VariableField variableField : fields) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().startsWith("852")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA != null) { isils.add(subfieldA.getData()); } } } if (isils.isEmpty()) { // Nothing worked! isils.add("Unknown"); } this.isils_cache = isils; return isils; } /** * @param record the record * @return */ public String isAvailableInTuebingen(final Record record) { final Set<String> isils = getIsils(record); if (isils.contains("DE-21") || isils.contains("DE-21-110")) { return Boolean.toString(true); } return Boolean.toString(!record.getVariableFields("SIG").isEmpty()); } // TODO: This should be in a translation mapping file private final static HashMap<String, String> isil_to_department_map = new HashMap<String, String>() { { this.put("Unknown", "Unknown"); this.put("DE-21", "Universit\u00E4tsbibliothek T\u00FCbingen"); this.put("DE-21-1", "Universit\u00E4t T\u00FCbingen, Klinik f\u00FCr Psychatrie und Psychologie"); this.put("DE-21-3", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Toxikologie und Pharmakologie"); this.put("DE-21-4", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Augenklinik"); this.put("DE-21-10", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Geowissenschaften"); this.put("DE-21-11", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Schloss Nord"); this.put("DE-21-14", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung j\u00FCngere Urgeschichte und Fr\u00FChgeschichte + Abteilung f\u00FCr Arch\u00E4ologie des Mittelalters"); this.put("DE-21-17", "Universit\u00E4t T\u00FCbingen, Geographisches Institut"); this.put("DE-21-18", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hautklinik"); this.put("DE-21-19", "Universit\u00E4t T\u00FCbingen, Wirtschaftswissenschaftliches Seminar"); this.put("DE-21-20", "Universit\u00E4t T\u00FCbingen, Frauenklinik"); this.put("DE-21-21", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hals-Nasen-Ohrenklinik, Bibliothek"); this.put("DE-21-22", "Universit\u00E4t T\u00FCbingen, Kunsthistorisches Institut"); this.put("DE-21-23", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Pathologie"); this.put("DE-21-24", "Universit\u00E4t T\u00FCbingen, Juristisches Seminar"); this.put("DE-21-25", "Universit\u00E4t T\u00FCbingen, Musikwissenschaftliches Institut"); this.put("DE-21-26", "Universit\u00E4t T\u00FCbingen, Anatomisches Institut"); this.put("DE-21-27", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Anthropologie und Humangenetik"); this.put("DE-21-28", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Astronomie und Astrophysik, Abteilung Astronomie"); this.put("DE-21-31", "Universit\u00E4t T\u00FCbingen, Evangelisch-theologische Fakult\u00E4t"); this.put("DE-21-32a", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Alte Geschichte"); this.put("DE-21-32b", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Mittelalterliche Geschichte"); this.put("DE-21-32c", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Neuere Geschichte"); this.put("DE-21-34", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Indologie und Vergleichende Religionswissenschaft"); this.put("DE-21-35", "Universit\u00E4t T\u00FCbingen, Katholisch-theologische Fakult\u00E4t"); this.put("DE-21-39", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Mathematik"); this.put("DE-21-37", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Sportwissenschaft"); this.put("DE-21-42", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Orient- uns Islamwissenschaft"); this.put("DE-21-43", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Erziehungswissenschaft"); this.put("DE-21-45", "Universit\u00E4t T\u00FCbingen, Philologisches Seminar"); this.put("DE-21-46", "Universit\u00E4t T\u00FCbingen, Philosophisches Seminar"); this.put("DE-21-50", "Universit\u00E4t T\u00FCbingen, Physiologisches Institut"); this.put("DE-21-51", "Universit\u00E4t T\u00FCbingen, Psychologisches Institut"); this.put("DE-21-52", "Universit\u00E4t T\u00FCbingen, Ludwig-Uhland-Institut f\u00FCr Empirische Kulturwissenschaft"); this.put("DE-21-53", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Ethnologie"); this.put("DE-21-54", "Universit\u00E4t T\u00FCbingen, Universit\u00E4tsklinik f\u00FCr Zahn-, Mund- und Kieferheilkunde"); this.put("DE-21-58", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Politikwissenschaft"); this.put("DE-21-62", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Osteurop\u00E4ische Geschichte und Landeskunde"); this.put("DE-21-63", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Tropenmedizin"); this.put("DE-21-64", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Geschichtliche Landeskunde und Historische Hilfswissenschaften"); this.put("DE-21-65", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Apotheke"); this.put("DE-21-74", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Informations-Technologie"); this.put("DE-21-78", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Biometrie"); this.put("DE-21-81", "Universit\u00E4t T\u00FCbingen, Inst. f. Astronomie und Astrophysik/Abt. Geschichte der Naturwiss."); this.put("DE-21-85", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Soziologie"); this.put("DE-21-86", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Datenverarbeitung"); this.put("DE-21-89", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Arbeits- und Sozialmedizin"); this.put("DE-21-92", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Gerichtliche Medizin"); this.put("DE-21-93", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ethik und Geschichte der Medizin"); this.put("DE-21-95", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Hirnforschung"); this.put("DE-21-98", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Physik"); this.put("DE-21-99", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung f\u00FCr \u00E4ltere Urgeschichteund Quart\u00E4r\u00F6kologie"); this.put("DE-21-106", "Universit\u00E4t T\u00FCbingen, Seminar f\u00FCr Zeitgeschichte"); this.put("DE-21-108", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4tsbibliothek Neuphilologie"); this.put("DE-21-109", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Sinologie und Koreanistik"); this.put("DE-21-110", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Kriminologie"); this.put("DE-21-112", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4t f\u00FCr Biologie, Bibliothek"); this.put("DE-21-116", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Molekularbiologie der Pflanzen, Forschungsgruppe Pflanzenbiochemie"); this.put("DE-21-117", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Informationsverarbeitung"); this.put("DE-21-118", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Archiv"); this.put("DE-21-119", "Universit\u00E4t T\u00FCbingen, Wilhelm-Schickard-Institut f\u00FCr Informatik"); this.put("DE-21-120", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Japanologie"); this.put("DE-21-121", "Universit\u00E4t T\u00FCbingen, Internationales Zentrum f\u00FCr Ethik in den Wissenschaften"); this.put("DE-21-123", "Universit\u00E4t T\u00FCbingen, Medizinbibliothek"); this.put("DE-21-124", "Universit\u00E4t T\u00FCbingen, Institut f. Medizinische Virologie und Epidemiologie d. Viruskrankheiten"); this.put("DE-21-126", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Mikrobiologie und Hygiene"); this.put("DE-21-203", "Universit\u00E4t T\u00FCbingen, Sammlung Werner Schweikert - Archiv der Weltliteratur"); this.put("DE-21-205", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Islamische Theologie"); } }; /** * get the collections from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of collections */ public Set<String> getCollections(final Record record) { final Set<String> isils = getIsils(record); final Set<String> collections = new HashSet<>(); for (final String isil : isils) { final String collection = isil_to_department_map.get(isil); if (collection != null) { collections.add(collection); } else { throw new IllegalArgumentException("Unknown ISIL: " + isil); } } if (collections.isEmpty()) collections.add("Unknown"); return collections; } /** * @param record the record */ public String getInstitution(final Record record) { final Set<String> collections = getCollections(record); return collections.iterator().next(); } /** * @param record the record */ public String getBSZIndexedDate(final Record record) { for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final List<Subfield> subfields = lokfield.getSubfields(); final Iterator<Subfield> subfieldsIter = subfields.iterator(); while (subfieldsIter.hasNext()) { Subfield subfield = subfieldsIter.next(); char formatCode = subfield.getCode(); String dataString = subfield.getData(); if (formatCode != '0' || !dataString.startsWith("938") || !subfieldsIter.hasNext()) { continue; } subfield = subfieldsIter.next(); formatCode = subfield.getCode(); if (formatCode != 'a') { continue; } dataString = subfield.getData(); if (dataString.length() != 4) { continue; } final String sub_year_text = dataString.substring(0, 2); final int sub_year = Integer.parseInt("20" + sub_year_text); final int current_year = Calendar.getInstance().get(Calendar.YEAR); final String year; if (sub_year > current_year) { // It is from the last century year = "19" + sub_year_text; } else { year = "20" + sub_year_text; } final String month = dataString.substring(2, 4); return year + "-" + month + "-01T11:00:00:000Z"; } } return null; } private final static Pattern PAGE_RANGE_PATTERN1 = Pattern.compile("\\s*(\\d+)\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN2 = Pattern.compile("\\s*\\[(\\d+)\\]\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN3 = Pattern.compile("\\s*(\\d+)\\s*ff"); private final static Pattern YEAR_PATTERN = Pattern.compile("(\\d\\d\\d\\d)"); private final static Pattern VOLUME_PATTERN = Pattern.compile("^\\s*(\\d+)$"); /** * @param record the record */ public String getPageRange(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936h"); if (field_value == null) return null; final Matcher matcher1 = PAGE_RANGE_PATTERN1.matcher(field_value); if (matcher1.matches()) return matcher1.group(1) + "-" + matcher1.group(2); final Matcher matcher2 = PAGE_RANGE_PATTERN2.matcher(field_value); if (matcher2.matches()) return matcher2.group(1) + "-" + matcher2.group(2); final Matcher matcher3 = PAGE_RANGE_PATTERN3.matcher(field_value); if (matcher3.matches()) return matcher3.group(1) + "-"; return null; } /** * @param record the record */ public String getContainerYear(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936j"); if (field_value == null) return null; final Matcher matcher = YEAR_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } /** * @param record the record */ public String getContainerVolume(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936d"); if (field_value == null) return null; final Matcher matcher = VOLUME_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } }
package com.intellij.openapi.vcs.changes.shelf; import com.intellij.ide.DeleteProvider; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.peer.PeerFactory; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.PopupHandler; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.content.Content; import com.intellij.util.messages.MessageBus; import com.intellij.util.ui.Tree; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import java.awt.event.KeyEvent; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; public class ShelvedChangesViewManager implements ProjectComponent { private ChangesViewContentManager myContentManager; private ShelveChangesManager myShelveChangesManager; private final Project myProject; private Tree myTree = new ShelfTree(); private Content myContent = null; private ShelvedChangeDeleteProvider myDeleteProvider = new ShelvedChangeDeleteProvider(); public static DataKey<ShelvedChangeList[]> SHELVED_CHANGELIST_KEY = DataKey.create("ShelveChangesManager.ShelvedChangeListData"); public ShelvedChangesViewManager(Project project, ChangesViewContentManager contentManager, ShelveChangesManager shelveChangesManager, final MessageBus bus) { myProject = project; myContentManager = contentManager; myShelveChangesManager = shelveChangesManager; bus.connect().subscribe(ShelveChangesManager.SHELF_TOPIC, new ChangeListener() { public void stateChanged(ChangeEvent e) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { updateChangesContent(); } }, ModalityState.NON_MODAL); } }); myTree.setRootVisible(false); myTree.setShowsRootHandles(true); myTree.setCellRenderer(new ShelfTreeCellRenderer()); final CustomShortcutSet diffShortcut = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_D, SystemInfo.isMac ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK)); ActionManager.getInstance().getAction("ChangesView.Diff").registerCustomShortcutSet(diffShortcut, myTree); PopupHandler.installPopupHandler(myTree, "ShelvedChangesPopupMenu", ActionPlaces.UNKNOWN); } public void projectOpened() { updateChangesContent(); } public void projectClosed() { } @NonNls @NotNull public String getComponentName() { return "ShelvedChangesViewManager"; } public void initComponent() { } public void disposeComponent() { } private void updateChangesContent() { final List<ShelvedChangeList> changes = myShelveChangesManager.getShelvedChangeLists(); if (changes.size() == 0) { if (myContent != null) { myContentManager.removeContent(myContent); } myContent = null; } else { if (myContent == null) { myContent = PeerFactory.getInstance().getContentFactory().createContent(new JScrollPane(myTree), "Shelf", false); myContent.setCloseable(false); myContentManager.addContent(myContent); } myTree.setModel(buildChangesModel()); } } private TreeModel buildChangesModel() { DefaultMutableTreeNode root = new DefaultMutableTreeNode(); DefaultTreeModel model = new DefaultTreeModel(root); final List<ShelvedChangeList> changeLists = myShelveChangesManager.getShelvedChangeLists(); for(ShelvedChangeList changeListData: changeLists) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(changeListData); model.insertNodeInto(node, root, root.getChildCount()); List<ShelvedChange> changes = changeListData.getChanges(); for(ShelvedChange change: changes) { DefaultMutableTreeNode pathNode = new DefaultMutableTreeNode(change); model.insertNodeInto(pathNode, node, node.getChildCount()); } } return model; } private class ShelfTree extends Tree implements TypeSafeDataProvider { public void calcData(DataKey key, DataSink sink) { if (key == SHELVED_CHANGELIST_KEY) { final List<ShelvedChangeList> list = TreeUtil.collectSelectedObjectsOfType(this, ShelvedChangeList.class); if (list != null) { sink.put(SHELVED_CHANGELIST_KEY, list.toArray(new ShelvedChangeList[list.size()])); } } else if (key == DataKeys.CHANGES) { List<ShelvedChange> shelvedChanges = TreeUtil.collectSelectedObjectsOfType(this, ShelvedChange.class); if (shelvedChanges.size() > 0) { Change[] changes = new Change[shelvedChanges.size()]; for(int i=0; i<shelvedChanges.size(); i++) { changes [i] = shelvedChanges.get(i).getChange(myProject); } sink.put(DataKeys.CHANGES, changes); } else { final List<ShelvedChangeList> changeLists = TreeUtil.collectSelectedObjectsOfType(this, ShelvedChangeList.class); if (changeLists.size() > 0) { List<Change> changes = new ArrayList<Change>(); for(ShelvedChangeList changeList: changeLists) { shelvedChanges = changeList.getChanges(); for(ShelvedChange shelvedChange: shelvedChanges) { changes.add(shelvedChange.getChange(myProject)); } } sink.put(DataKeys.CHANGES, changes.toArray(new Change[changes.size()])); } } } else if (key == DataKeys.DELETE_ELEMENT_PROVIDER) { sink.put(DataKeys.DELETE_ELEMENT_PROVIDER, myDeleteProvider); } } } private static class ShelfTreeCellRenderer extends ColoredTreeCellRenderer { public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object nodeValue = node.getUserObject(); if (nodeValue instanceof ShelvedChangeList) { ShelvedChangeList changeListData = (ShelvedChangeList) nodeValue; append(changeListData.DESCRIPTION, SimpleTextAttributes.REGULAR_ATTRIBUTES); final String date = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT).format(changeListData.DATE); append(" (" + date + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES); setIcon(StdFileTypes.PATCH.getIcon()); } else if (nodeValue instanceof ShelvedChange) { ShelvedChange change = (ShelvedChange) nodeValue; append(change.getFileName(), new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, change.getFileStatus().getColor())); append(" ("+ change.getDirectory() + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES); setIcon(FileTypeManager.getInstance().getFileTypeByFileName(change.getFileName()).getIcon()); } } } private class ShelvedChangeDeleteProvider implements DeleteProvider { public void deleteElement(DataContext dataContext) { //noinspection unchecked ShelvedChangeList[] shelvedChangeLists = (ShelvedChangeList[]) dataContext.getData(SHELVED_CHANGELIST_KEY.getName()); if (shelvedChangeLists == null || shelvedChangeLists.length == 0) return; String message = (shelvedChangeLists.length == 1) ? VcsBundle.message("shelve.changes.delete.confirm", shelvedChangeLists[0].DESCRIPTION) : VcsBundle.message("shelve.changes.delete.multiple.confirm", shelvedChangeLists.length); int rc = Messages.showOkCancelDialog(myProject, message, VcsBundle.message("shelvedChanges.delete.title"), Messages.getWarningIcon()); if (rc != 0) return; for(ShelvedChangeList changeList: shelvedChangeLists) { ShelveChangesManager.getInstance(myProject).deleteChangeList(changeList); } } public boolean canDeleteElement(DataContext dataContext) { //noinspection unchecked ShelvedChangeList[] shelvedChangeLists = (ShelvedChangeList[]) dataContext.getData(SHELVED_CHANGELIST_KEY.getName()); return shelvedChangeLists != null && shelvedChangeLists.length > 0; } } }
package com.intellij.psi.impl.source.tree.injected; import com.intellij.psi.impl.source.xml.XmlTextImpl; import com.intellij.psi.xml.XmlText; import com.intellij.openapi.util.TextRange; /** * @author cdr */ public class XmlTextLiteralEscaper implements LiteralTextEscaper<XmlTextImpl> { private final XmlText myXmlText; public XmlTextLiteralEscaper(final XmlText xmlText) { myXmlText = xmlText; } public boolean decode(XmlTextImpl host, final TextRange rangeInsideHost, StringBuilder outChars) { int startInDecoded = host.physicalToDisplay(rangeInsideHost.getStartOffset()); int endInDecoded = host.physicalToDisplay(rangeInsideHost.getEndOffset()); outChars.append(host.getValue(), startInDecoded, endInDecoded); return true; } public int getOffsetInHost(final int offsetInDecoded, final TextRange rangeInsideHost) { int displayStart = myXmlText.physicalToDisplay(rangeInsideHost.getStartOffset()); return myXmlText.displayToPhysical(offsetInDecoded+displayStart); //return myXmlText.displayToPhysical(offsetInDecoded); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.HierarchyEvent; import java.awt.event.KeyEvent; import java.util.EventObject; import java.util.Objects; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JTable table = new JTable(8, 4); table.getColumnModel().getColumn(0).setCellEditor(new CustomComponentCellEditor(new JTextField())); table.getColumnModel().getColumn(1).setCellEditor(new CustomCellEditor(new JTextField())); table.getColumnModel().getColumn(2).setCellEditor(new CustomComponentCellEditor2(new CustomComponent())); add(new JScrollPane(table)); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class CustomCellEditor extends DefaultCellEditor { private static final int BUTTON_WIDTH = 20; private final JButton button = new JButton(); protected CustomCellEditor(JTextField field) { super(field); field.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, BUTTON_WIDTH)); field.addHierarchyListener(e -> { Component c = e.getComponent(); if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && c instanceof JTextField && c.isShowing()) { // System.out.println("hierarchyChanged: SHOWING_CHANGED"); JTextField tc = (JTextField) c; tc.removeAll(); tc.add(button); Rectangle r = tc.getBounds(); button.setBounds(r.width - BUTTON_WIDTH, 0, BUTTON_WIDTH, r.height); // tc.requestFocusInWindow(); } }); } @Override public Component getComponent() { // @see JTable#updateUI() SwingUtilities.updateComponentTreeUI(button); return super.getComponent(); } } // class CustomComponentCellEditor extends AbstractCellEditor implements TableCellEditor { class CustomComponentCellEditor extends DefaultCellEditor { private final JTextField field; private final JPanel panel = new JPanel(new BorderLayout()); protected CustomComponentCellEditor(JTextField field) { super(field); this.field = field; JButton button = new JButton() { @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.width = 25; return d; } }; field.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0)); panel.add(field); panel.add(button, BorderLayout.EAST); panel.setFocusable(false); } // public Object getCellEditorValue() { // // System.out.println(" " + field.getText()); // return field.getText(); @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { // System.out.println("getTableCellEditorComponent"); field.setText(Objects.toString(value, "")); EventQueue.invokeLater(() -> { field.setCaretPosition(field.getText().length()); field.requestFocusInWindow(); }); return panel; } @Override public boolean isCellEditable(EventObject e) { // System.out.println("isCellEditable"); // if (e instanceof KeyEvent) { // // System.out.println("KeyEvent"); // EventQueue.invokeLater(() -> { // char kc = ((KeyEvent) e).getKeyChar(); // if (!Character.isIdentifierIgnorable(kc)) { // field.setText(field.getText() + kc); // field.setCaretPosition(field.getText().length()); // // field.requestFocusInWindow(); EventQueue.invokeLater(() -> { if (e instanceof KeyEvent) { KeyEvent ke = (KeyEvent) e; char kc = ke.getKeyChar(); // int kc = ke.getKeyCode(); if (Character.isUnicodeIdentifierStart(kc)) { field.setText(field.getText() + kc); } } }); return super.isCellEditable(e); } @Override public Component getComponent() { return panel; } } class CustomComponent extends JPanel { // static class CustomTextField extends JTextField { // @Override protected boolean processKeyBinding (KeyStroke ks, KeyEvent e, int condition, boolean pressed) { // return super.processKeyBinding(ks, e, condition, pressed); // public final CustomTextField field = new CustomTextField(); public final JTextField field = new JTextField(); private final JButton button = new JButton(); protected CustomComponent() { super(new BorderLayout()); // this.setFocusable(false); this.add(field); this.add(button, BorderLayout.EAST); } @Override protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { if (!field.isFocusOwner() && !pressed) { field.requestFocusInWindow(); EventQueue.invokeLater(() -> KeyboardFocusManager.getCurrentKeyboardFocusManager().redispatchEvent(field, e)); } return super.processKeyBinding(ks, e, condition, pressed); // field.requestFocusInWindow(); // return field.processKeyBinding(ks, e, condition, pressed); } } class CustomComponentCellEditor2 extends DefaultCellEditor { private final CustomComponent component; protected CustomComponentCellEditor2(CustomComponent component) { super(component.field); this.component = component; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { component.field.setText(Objects.toString(value, "")); return this.component; } @Override public Component getComponent() { return component; } }
package org.spicej.testutil; import static org.junit.Assert.assertArrayEquals; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import org.spicej.impl.SimulationTickSource; import org.spicej.impl.SleepWakeup; public class InputStreamReaderRecorder { private final SimulationTickSource t; private long[] recording; private boolean running = true; private long finishedTick = 0; private final SleepWakeup sleepFinish = new SleepWakeup(); public InputStreamReaderRecorder(SimulationTickSource t) { this.t = t; } public void assertTimestamps(long... expected) { waitFor(); if (!Arrays.equals(expected, recording)) { System.err.println("exp: " + Arrays.toString(expected)); System.err.println("act: " + Arrays.toString(recording)); } assertArrayEquals(expected, recording); } public void startRecording(InputStream sut, int target, int blockSize) { recording = new long[target]; running = true; Thread t = new Thread(new Runner(sut, target, blockSize)); t.setDaemon(true); t.start(); } public void waitFor() { while (running) sleepFinish.sleep(); } private class Runner implements Runnable { private InputStream suti; private long t0; private int target; private int blockSize; public Runner(InputStream sut, int target, int blockSize) { this.suti = sut; this.target = target; this.blockSize = blockSize; t0 = t.getCurrentTick(); } @Override public void run() { try { int done = 0; byte[] block = new byte[blockSize]; while (done < target) { try { int result = blockSize == 0 ? suti.read() : suti.read(block, 0, Math.min(blockSize, target - done)); if (result == -1) throw new AssertionError("not enough bytes"); int rd = blockSize == 0 ? 1 : result; for (int i = done; i < done + rd; i++) recording[i] = t.getCurrentTick() - t0; done += rd; } catch (IOException e) { throw new Error(e); } } } finally { running = false; sleepFinish.wakeup(); } } } }
package com.google.sps; import com.google.sps.data.Event; import com.google.sps.data.User; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.builder.EqualsBuilder; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class UserTest { private static final String NAME = "Bob Smith"; private static final String EMAIL = "bobsmith@example.com"; private static final Set<String> INTERESTS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("Conservation", "Food"))); private static final Set<String> NEW_INTERESTS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("Conservation", "Food", "Music"))); private static final Set<String> SKILLS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("Cooking"))); private static final String NEW_INTEREST = "Music"; private static final Set<Event> EVENTS_HOSTING = Collections.emptySet(); private static final Set<Event> EVENTS_PARTICIPATING = Collections.emptySet(); private static final Set<Event> EVENTS_VOLUNTEERING = Collections.emptySet(); @Test public void buildInstanceWithAllFields() { // Create a User with all fields set, and verify that all fields are correctly set User user = new User.Builder(NAME, EMAIL) .setInterests(INTERESTS) .setSkills(SKILLS) .setEventsHosting(EVENTS_HOSTING) .setEventsParticipating(EVENTS_PARTICIPATING) .setEventsVolunteering(EVENTS_VOLUNTEERING) .build(); Assert.assertEquals(NAME, user.getName()); Assert.assertEquals(EMAIL, user.getEmail()); Assert.assertEquals(INTERESTS, user.getInterests()); Assert.assertEquals(SKILLS, user.getSkills()); Assert.assertEquals(EVENTS_HOSTING, user.getEventsHosting()); Assert.assertEquals(EVENTS_PARTICIPATING, user.getEventsParticipating()); Assert.assertEquals(EVENTS_VOLUNTEERING, user.getEventsVolunteering()); } @Test public void transferInstanceToBuilderWithAllFields() { // Create a User with all fields set, and check that its fields can be correctly transferred to // its Builder. User expectedUser = new User.Builder(NAME, EMAIL) .setInterests(INTERESTS) .setSkills(SKILLS) .setEventsHosting(EVENTS_HOSTING) .setEventsParticipating(EVENTS_PARTICIPATING) .setEventsVolunteering(EVENTS_VOLUNTEERING) .build(); User actualUser = expectedUser.toBuilder().build(); Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedUser, actualUser)); } @Test public void addToExistingInterests() { // Add a new interest to a User's existing set of interests. User user = new User.Builder(NAME, EMAIL).setInterests(INTERESTS).build(); user = user.toBuilder().addInterest(NEW_INTEREST).build(); Assert.assertEquals(NEW_INTERESTS, user.getInterests()); } }
import java.util.Objects; public class MovementRoutine { public MovementRoutine (String command, int numberOfCommands) { _command = command; _numberOfCommands = numberOfCommands; } public boolean containsRoutine (MovementRoutine compare) { System.out.println("contains "+compare.getCommand().contains(_command)); return (_command.indexOf(compare.getCommand()) != -1); } public void removeRoutine (MovementRoutine compare) { System.out.println("Removing "+compare.getCommand()+" from "+_command); _command = _command.replace(compare.getCommand(), ""); _numberOfCommands -= compare.numberOfCommands(); } public String getCommand () { return _command; } public int getLength () { return ((_command == null) ? 0 : _command.length()); } public int numberOfCommands () { return _numberOfCommands; } @Override public String toString () { return _command; } @Override public int hashCode () { return Objects.hash(_command, _numberOfCommands); } @Override public boolean equals (Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() == obj.getClass()) { MovementRoutine temp = (MovementRoutine) obj; return (_command.equals(temp._command)); } return false; } private String _command; private int _numberOfCommands; }
public class var { public static Component lamp = new Component(3); public static Component fan = new Component(2); public static Component pump = new Component(0);}
package org.eigenbase.sql; import java.util.*; import org.eigenbase.reltype.*; import org.eigenbase.resource.*; import org.eigenbase.sql.fun.*; import org.eigenbase.sql.parser.*; import org.eigenbase.sql.type.*; import org.eigenbase.sql.validate.*; import org.eigenbase.util.*; public class SqlJdbcFunctionCall extends SqlFunction { private static final String numericFunctions; private static final String stringFunctions; private static final String timeDateFunctions; private static final String systemFunctions; /** * List of all numeric function names defined by JDBC. */ private static final String [] allNumericFunctions = { "ABS", "ACOS", "ASIN", "ATAN", "ATAN2", "CEILING", "COS", "COT", "DEGREES", "EXP", "FLOOR", "LOG", "LOG10", "MOD", "PI", "POWER", "RADIANS", "RAND", "ROUND", "SIGN", "SIN", "SQRT", "TAN", "TRUNCATE" }; /** * List of all string function names defined by JDBC. */ private static final String [] allStringFunctions = { "ASCII", "CHAR", "CONCAT", "DIFFERENCE", "INSERT", "LCASE", "LEFT", "LENGTH", "LOCATE", "LTRIM", "REPEAT", "REPLACE", "RIGHT", "RTRIM", "SOUNDEX", "SPACE", "SUBSTRING", "UCASE" // "ASCII", "CHAR", "DIFFERENCE", "LOWER", // "LEFT", "TRIM", "REPEAT", "REPLACE", // "RIGHT", "SPACE", "SUBSTRING", "UPPER", "INITCAP", "OVERLAY" }; /** * List of all time/date function names defined by JDBC. */ private static final String [] allTimeDateFunctions = { "CURDATE", "CURTIME", "DAYNAME", "DAYOFMONTH", "DAYOFWEEK", "DAYOFYEAR", "HOUR", "MINUTE", "MONTH", "MONTHNAME", "NOW", "QUARTER", "SECOND", "TIMESTAMPADD", "TIMESTAMPDIFF", "WEEK", "YEAR" }; /** * List of all system function names defined by JDBC. */ private static final String [] allSystemFunctions = { "DATABASE", "IFNULL", "USER" }; static { numericFunctions = constructFuncList(allNumericFunctions); stringFunctions = constructFuncList(allStringFunctions); timeDateFunctions = constructFuncList(allTimeDateFunctions); systemFunctions = constructFuncList(allSystemFunctions); } private final String jdbcName; private final MakeCall lookupMakeCallObj; private SqlCall lookupCall; private SqlNode [] thisOperands; public SqlJdbcFunctionCall(String name) { super( "{fn " + name + "}", SqlKind.JDBC_FN, null, null, SqlTypeStrategies.otcVariadic, null); jdbcName = name; lookupMakeCallObj = JdbcToInternalLookupTable.instance.lookup(name); lookupCall = null; } private static String constructFuncList(String [] functionNames) { StringBuilder sb = new StringBuilder(); boolean first = true; for (int i = 0; i < functionNames.length; ++i) { String funcName = functionNames[i]; if (JdbcToInternalLookupTable.instance.lookup(funcName) == null) { continue; } if (first) { first = false; } else { sb.append(","); } sb.append(funcName); } return sb.toString(); } public SqlCall createCall( SqlLiteral functionQualifier, SqlParserPos pos, SqlNode ... operands) { thisOperands = operands; return super.createCall(functionQualifier, pos, operands); } public SqlCall getLookupCall() { if (null == lookupCall) { lookupCall = lookupMakeCallObj.createCall(thisOperands, SqlParserPos.ZERO); } return lookupCall; } public String getAllowedSignatures() { return lookupMakeCallObj.operator.getAllowedSignatures(getName()); } public RelDataType deriveType( SqlValidator validator, SqlValidatorScope scope, SqlCall call) { // Override SqlFunction.deriveType, because function-resolution is // not relevant to a JDBC function call. // REVIEW: jhyde, 2006/4/18: Should SqlJdbcFunctionCall even be a // subclass of SqlFunction? final SqlNode [] operands = call.operands; for (int i = 0; i < operands.length; ++i) { RelDataType nodeType = validator.deriveType(scope, operands[i]); validator.setValidatedNodeType(operands[i], nodeType); } RelDataType type = validateOperands(validator, scope, call); return type; } public RelDataType inferReturnType( SqlOperatorBinding opBinding) { // only expected to come here if validator called this method SqlCallBinding callBinding = (SqlCallBinding) opBinding; if (null == lookupMakeCallObj) { throw callBinding.newValidationError( EigenbaseResource.instance().FunctionUndefined.ex( getName())); } if (!lookupMakeCallObj.checkNumberOfArg( opBinding.getOperandCount())) { throw callBinding.newValidationError( EigenbaseResource.instance().WrongNumberOfParam.ex( getName(), thisOperands.length, getArgCountMismatchMsg())); } if (!lookupMakeCallObj.operator.checkOperandTypes( new SqlCallBinding( callBinding.getValidator(), callBinding.getScope(), getLookupCall()), false)) { throw callBinding.newValidationSignatureError(); } return lookupMakeCallObj.operator.validateOperands( callBinding.getValidator(), callBinding.getScope(), getLookupCall()); } private String getArgCountMismatchMsg() { StringBuilder ret = new StringBuilder(); int [] possible = lookupMakeCallObj.getPossibleArgCounts(); for (int i = 0; i < possible.length; i++) { if (i > 0) { ret.append(" or "); } ret.append(possible[i]); } ret.append(" parameter(s)"); return ret.toString(); } public void unparse( SqlWriter writer, SqlNode [] operands, int leftPrec, int rightPrec) { writer.print("{fn "); writer.print(jdbcName); final SqlWriter.Frame frame = writer.startList("(", ")"); for (int i = 0; i < operands.length; i++) { writer.sep(","); operands[i].unparse(writer, leftPrec, rightPrec); } writer.endList(frame); writer.print("}"); } /** * @see java.sql.DatabaseMetaData#getNumericFunctions */ public static String getNumericFunctions() { return numericFunctions; } /** * @see java.sql.DatabaseMetaData#getStringFunctions */ public static String getStringFunctions() { return stringFunctions; } /** * @see java.sql.DatabaseMetaData#getTimeDateFunctions */ public static String getTimeDateFunctions() { return timeDateFunctions; } /** * @see java.sql.DatabaseMetaData#getSystemFunctions */ public static String getSystemFunctions() { return systemFunctions; } /** * Represent a Strategy Object to create a {@link SqlCall} by providing the * feature of reording, adding/dropping operands. */ private static class MakeCall { final SqlOperator operator; final int [] order; /** * List of the possible numbers of operands this function can take. */ final int [] argCounts; private MakeCall( SqlOperator operator, int argCount) { this.operator = operator; this.order = null; this.argCounts = new int[] { argCount }; } /** * Creates a MakeCall strategy object with reordering of operands. * * <p>The reordering is specified by an int array where the value of * element at position <code>i</code> indicates to which element in a * new SqlNode[] array the operand goes. * * @param operator * @param order * * @pre order != null * @pre order[i] < order.length * @pre order.length > 0 * @pre argCounts == order.length */ MakeCall( SqlOperator operator, int argCount, int [] order) { Util.pre(null != order, "null!=order"); Util.pre(order.length > 0, "order.length > 0"); // Currently operation overloading when reordering is necessary is // NOT implemented Util.pre(argCount == order.length, "argCounts==order.length"); this.operator = operator; this.order = order; this.argCounts = new int[] { order.length }; // sanity checking ... for (int i = 0; i < order.length; i++) { Util.pre(order[i] < order.length, "order[i] < order.length"); } } final int [] getPossibleArgCounts() { return this.argCounts; } /** * Uses the data in {@link #order} to reorder a SqlNode[] array. * * @param operands */ protected SqlNode [] reorder(SqlNode [] operands) { assert (operands.length == order.length); SqlNode [] newOrder = new SqlNode[operands.length]; for (int i = 0; i < operands.length; i++) { assert operands[i] != null; int joyDivision = order[i]; assert newOrder[joyDivision] == null : "mapping is not 1:1"; newOrder[joyDivision] = operands[i]; } return newOrder; } /** * Creates and return a {@link SqlCall}. If the MakeCall strategy object * was created with a reording specified the call will be created with * the operands reordered, otherwise no change of ordering is applied * * @param operands */ SqlCall createCall( SqlNode [] operands, SqlParserPos pos) { if (null == order) { return operator.createCall(pos, operands); } return operator.createCall(pos, reorder(operands)); } /** * Returns false if number of arguments are unexpected, otherwise true. * This function is supposed to be called with an {@link SqlNode} array * of operands direct from the oven, e.g no reording or adding/dropping * of operands...else it would make much sense to have this methods */ boolean checkNumberOfArg(int length) { for (int i = 0; i < argCounts.length; i++) { if (argCounts[i] == length) { return true; } } return false; } } /** * Lookup table between JDBC functions and internal representation */ private static class JdbcToInternalLookupTable { /** * The {@link org.eigenbase.util.Glossary#SingletonPattern singleton} * instance. */ static final JdbcToInternalLookupTable instance = new JdbcToInternalLookupTable(); private final Map<String, MakeCall> map = new HashMap<String, MakeCall>(); private JdbcToInternalLookupTable() { // A table of all functions can be found at // which is also provided in the javadoc for this class. // See also SqlOperatorTests.testJdbcFn, which contains the list. map.put( "ABS", new MakeCall(SqlStdOperatorTable.absFunc, 1)); map.put( "EXP", new MakeCall(SqlStdOperatorTable.expFunc, 1)); map.put( "LOG", new MakeCall(SqlStdOperatorTable.lnFunc, 1)); map.put( "LOG10", new MakeCall(SqlStdOperatorTable.log10Func, 1)); map.put( "MOD", new MakeCall(SqlStdOperatorTable.modFunc, 2)); map.put( "POWER", new MakeCall(SqlStdOperatorTable.powerFunc, 2)); map.put( "CONCAT", new MakeCall(SqlStdOperatorTable.concatOperator, 2)); map.put( "INSERT", new MakeCall( SqlStdOperatorTable.overlayFunc, 4, new int[] { 0, 2, 3, 1 })); map.put( "LCASE", new MakeCall(SqlStdOperatorTable.lowerFunc, 1)); map.put( "LENGTH", new MakeCall(SqlStdOperatorTable.characterLengthFunc, 1)); map.put( "LOCATE", new MakeCall(SqlStdOperatorTable.positionFunc, 2)); map.put( "LTRIM", new MakeCall(SqlStdOperatorTable.trimFunc, 1) { SqlCall createCall(SqlNode [] operands) { assert (null != operands); assert (1 == operands.length); SqlNode [] newOperands = new SqlNode[3]; newOperands[0] = SqlLiteral.createSymbol( SqlTrimFunction.Flag.LEADING, null); newOperands[1] = SqlLiteral.createCharString(" ", null); newOperands[2] = operands[0]; return super.createCall(newOperands, null); } }); map.put( "RTRIM", new MakeCall(SqlStdOperatorTable.trimFunc, 1) { SqlCall createCall(SqlNode [] operands) { assert (null != operands); assert (1 == operands.length); SqlNode [] newOperands = new SqlNode[3]; newOperands[0] = SqlLiteral.createSymbol( SqlTrimFunction.Flag.TRAILING, null); newOperands[1] = SqlLiteral.createCharString(" ", null); newOperands[2] = operands[0]; return super.createCall(newOperands, null); } }); map.put( "SUBSTRING", new MakeCall(SqlStdOperatorTable.substringFunc, 3)); map.put( "UCASE", new MakeCall(SqlStdOperatorTable.upperFunc, 1)); map.put( "CURDATE", new MakeCall(SqlStdOperatorTable.currentDateFunc, 0)); map.put( "CURTIME", new MakeCall(SqlStdOperatorTable.localTimeFunc, 0)); map.put( "NOW", new MakeCall(SqlStdOperatorTable.currentTimestampFunc, 0)); } /** * Tries to lookup a given function name JDBC to an internal * representation. Returns null if no function defined. */ public MakeCall lookup(String name) { return map.get(name); } } } // End SqlJdbcFunctionCall.java
package org.postgresql.test.jdbc2; import org.postgresql.test.TestUtil; import java.sql.*; import junit.framework.TestCase; /* * CallableStatement tests. * @author Paul Bethe */ public class CallableStmtTest extends TestCase { private Connection con; public CallableStmtTest (String name) { super(name); } protected void setUp() throws Exception { con = TestUtil.openDB(); TestUtil.createTable(con, "int_table", "id int"); Statement stmt = con.createStatement (); stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getString (varchar) " + "RETURNS varchar AS ' DECLARE inString alias for $1; begin " + "return ''bob''; end; ' LANGUAGE plpgsql;"); stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getDouble (float) " + "RETURNS float AS ' DECLARE inString alias for $1; begin " + "return 42.42; end; ' LANGUAGE plpgsql;"); if (TestUtil.haveMinimumServerVersion(con, "7.3")) { stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getVoid (float) " + "RETURNS void AS ' DECLARE inString alias for $1; begin " + " return; end; ' LANGUAGE plpgsql;"); } stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getInt (int) RETURNS int " + " AS 'DECLARE inString alias for $1; begin " + "return 42; end;' LANGUAGE plpgsql;"); stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getShort (int2) RETURNS int2 " + " AS 'DECLARE inString alias for $1; begin " + "return 42; end;' LANGUAGE plpgsql;"); stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getNumeric (numeric) " + "RETURNS numeric AS ' DECLARE inString alias for $1; " + "begin return 42; end; ' LANGUAGE plpgsql;"); stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getNumericWithoutArg() " + "RETURNS numeric AS ' " + "begin return 42; end; ' LANGUAGE plpgsql;"); stmt.execute("CREATE OR REPLACE FUNCTION testspg__getarray() RETURNS int[] as 'SELECT ''{1,2}''::int[];' LANGUAGE sql"); stmt.execute("CREATE OR REPLACE FUNCTION testspg__raisenotice() RETURNS int as 'BEGIN RAISE NOTICE ''hello''; RAISE NOTICE ''goodbye''; RETURN 1; END;' LANGUAGE plpgsql"); stmt.execute("CREATE OR REPLACE FUNCTION testspg__insertInt(int) RETURNS int as 'BEGIN INSERT INTO int_table(id) VALUES ($1); RETURN 1; END;' LANGUAGE plpgsql"); stmt.close (); } protected void tearDown() throws Exception { Statement stmt = con.createStatement (); TestUtil.dropTable(con, "int_table"); stmt.execute ("drop FUNCTION testspg__getString (varchar);"); stmt.execute ("drop FUNCTION testspg__getDouble (float);"); if (TestUtil.haveMinimumServerVersion(con, "7.3")) { stmt.execute( "drop FUNCTION testspg__getVoid(float);"); } stmt.execute ("drop FUNCTION testspg__getInt (int);"); stmt.execute ("drop FUNCTION testspg__getShort(int2)"); stmt.execute ("drop FUNCTION testspg__getNumeric (numeric);"); stmt.execute ("drop FUNCTION testspg__getNumericWithoutArg ();"); stmt.execute ("DROP FUNCTION testspg__getarray();"); stmt.execute ("DROP FUNCTION testspg__raisenotice();"); stmt.execute ("DROP FUNCTION testspg__insertInt(int);"); TestUtil.closeDB(con); } final String func = "{ ? = call "; final String pkgName = "testspg__"; public void testGetUpdateCount() throws SQLException { CallableStatement call = con.prepareCall (func + pkgName + "getDouble (?) }"); call.setDouble (2, (double)3.04); call.registerOutParameter (1, Types.DOUBLE); call.execute (); assertEquals(-1, call.getUpdateCount()); assertNull(call.getResultSet()); assertEquals(42.42, call.getDouble(1), 0.00001); call.close(); // test without an out parameter call = con.prepareCall( "{ call " + pkgName + "getDouble(?) }"); call.setDouble( 1, (double)3.04 ); call.execute(); assertEquals(-1, call.getUpdateCount()); ResultSet rs = call.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(42.42, rs.getDouble(1), 0.00001); assertTrue(!rs.next()); rs.close(); assertEquals(-1, call.getUpdateCount()); assertTrue(!call.getMoreResults()); call.close(); } public void testGetDouble () throws Throwable { CallableStatement call = con.prepareCall (func + pkgName + "getDouble (?) }"); call.setDouble (2, (double)3.04); call.registerOutParameter (1, Types.DOUBLE); call.execute (); assertEquals(42.42, call.getDouble(1), 0.00001); // test without an out parameter call = con.prepareCall( "{ call " + pkgName + "getDouble(?) }"); call.setDouble( 1, (double)3.04 ); call.execute(); if (TestUtil.haveMinimumServerVersion(con, "7.3")) { call = con.prepareCall( "{ call " + pkgName + "getVoid(?) }"); call.setDouble( 1, (double)3.04 ); call.execute(); } } public void testGetInt () throws Throwable { CallableStatement call = con.prepareCall (func + pkgName + "getInt (?) }"); call.setInt (2, 4); call.registerOutParameter (1, Types.INTEGER); call.execute (); assertEquals(42, call.getInt(1)); } public void testGetShort () throws Throwable { if ( TestUtil.isProtocolVersion(con, 3) ) { CallableStatement call = con.prepareCall (func + pkgName + "getShort (?) }"); call.setShort (2, (short)4); call.registerOutParameter (1, Types.SMALLINT); call.execute (); assertEquals(42, call.getShort(1)); } } public void testGetNumeric () throws Throwable { CallableStatement call = con.prepareCall (func + pkgName + "getNumeric (?) }"); call.setBigDecimal (2, new java.math.BigDecimal(4)); call.registerOutParameter (1, Types.NUMERIC); call.execute (); assertEquals(new java.math.BigDecimal(42), call.getBigDecimal(1)); } public void testGetNumericWithoutArg () throws Throwable { CallableStatement call = con.prepareCall (func + pkgName + "getNumericWithoutArg () }"); call.registerOutParameter (1, Types.NUMERIC); call.execute (); assertEquals(new java.math.BigDecimal(42), call.getBigDecimal(1)); } public void testGetString () throws Throwable { CallableStatement call = con.prepareCall (func + pkgName + "getString (?) }"); call.setString (2, "foo"); call.registerOutParameter (1, Types.VARCHAR); call.execute (); assertEquals("bob", call.getString(1)); } public void testGetArray() throws SQLException { CallableStatement call = con.prepareCall(func + pkgName + "getarray()}"); call.registerOutParameter(1, Types.ARRAY); call.execute(); Array arr = call.getArray(1); ResultSet rs = arr.getResultSet(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertTrue(!rs.next()); } public void testRaiseNotice() throws SQLException { Statement statement = con.createStatement(); statement.execute("SET SESSION client_min_messages = 'NOTICE'"); CallableStatement call = con.prepareCall(func + pkgName + "raisenotice()}"); call.registerOutParameter(1, Types.INTEGER); call.execute(); SQLWarning warn = call.getWarnings(); assertNotNull(warn); assertEquals("hello", warn.getMessage()); warn = warn.getNextWarning(); assertNotNull(warn); assertEquals("goodbye", warn.getMessage()); assertEquals(1, call.getInt(1)); } public void testWasNullBeforeFetch() throws SQLException { CallableStatement cs = con.prepareCall("{? = call lower(?)}"); cs.registerOutParameter(1, Types.VARCHAR); cs.setString(2, "Hi"); try { cs.wasNull(); fail("expected exception"); } catch(Exception e) { assertTrue(e instanceof SQLException); } } public void testFetchBeforeExecute() throws SQLException { CallableStatement cs = con.prepareCall("{? = call lower(?)}"); cs.registerOutParameter(1, Types.VARCHAR); cs.setString(2, "Hi"); try { cs.getString(1); fail("expected exception"); } catch(Exception e) { assertTrue(e instanceof SQLException); } } public void testFetchWithNoResults() throws SQLException { CallableStatement cs = con.prepareCall("{call now()}"); cs.execute(); try { cs.getObject(1); fail("expected exception"); } catch(Exception e) { assertTrue(e instanceof SQLException); } } public void testBadStmt () throws Throwable { tryOneBadStmt ("{ ?= " + pkgName + "getString (?) }"); tryOneBadStmt ("{ ?= call getString (?) "); tryOneBadStmt ("{ = ? call getString (?); }"); } protected void tryOneBadStmt (String sql) throws SQLException { try { con.prepareCall (sql); fail("Bad statement (" + sql + ") was not caught."); } catch (SQLException e) { } } public void testBatchCall() throws SQLException { CallableStatement call = con.prepareCall ("{ call " + pkgName + "insertInt(?) }"); call.setInt(1, 1); call.addBatch(); call.setInt(1, 2); call.addBatch(); call.setInt(1, 3); call.addBatch(); call.executeBatch(); call.close(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id FROM int_table ORDER BY id"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(!rs.next()); } }
package ch.unizh.ini.caviar.eventprocessing.tracking; import ch.unizh.ini.stereo3D.*; import ch.unizh.ini.caviar.chip.*; import ch.unizh.ini.caviar.eventprocessing.EventFilter2D; import ch.unizh.ini.caviar.event.*; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.graphics.*; import com.sun.opengl.util.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.InputEvent; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; import java.io.*; import java.util.*; import javax.media.opengl.*; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.swing.*; import javax.media.opengl.glu.GLU; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.ConcurrentModificationException; import java.text.*; /** * Tracks Rat's Paw *<p> * </p> * * @author rogister */ public class PawTrackerStereoBoard3 extends EventFilter2D implements FrameAnnotater, Observer, AE3DPlayerInterface, AE3DRecorderInterface /*, PreferenceChangeListener*/ { // recorder /player variables int INITIAL_PACKET_SIZE = 1000; public static DateFormat loggingFilenameDateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ssZ"); AE3DOutputStream loggingOutputStream; AE3DFileInputStream inputStream; AE3DPlayerRecorderFrame playerRecorderFrame; File recordFile; File playFile; float playTimeBin = 20000; // micro s boolean forward = true; boolean pauseEnabled = false; boolean playEnabled = false; boolean displayPlay = false; boolean recordEnabled = false; volatile boolean toclear = true; AEPacket3D loggingPacket; AEPacket3D inputPacket; AEPacket3D displayPacket = null; Hashtable direct3DEvents = new Hashtable(); volatile boolean displayDirect3D = false; volatile boolean recordPure3D = false; // log data File logFile; BufferedWriter logWriter; volatile boolean logEnabled = false; /* try { Thread.sleep(1000); System.out.println("playing"); } catch (java.lang.InterruptedException e ){ } */ if(!pauseEnabled){ try { if(forward){ inputPacket = inputStream.readPacketByTime((int)playTimeBin); } else { inputPacket = inputStream.readPacketByTime(-(int)playTimeBin); } // System.out.println("new inputPacket :"+inputPacket); if(toclear){ clearEventPoints(); toclear = false; } if (inputPacket!=null){ if(inputPacket.getType()==Event3D.DIRECT3D){ // direct display. how? to work there, paul 080208 // switch display flag displayPacket = inputPacket.getPrunedCopy(); synchronized(displayPacket){ storeDisplayPacket(); } // it is here that events shoud be added to hashtable, not in display displayDirect3D = true; // try { // Thread.sleep(100); // // System.out.println("playing"); // } catch (java.lang.InterruptedException e ){ } else { // switch display flag displayDirect3D = false; processPacket(inputPacket); } } }catch(EOFException e){ System.err.println("EOF exception: "+e.getMessage()); try{ //pauseEnabled = true; Thread.sleep(10); clearEventPoints(); inputStream.rewind(); }catch(Exception ee){ System.err.println("rewind exception: "+ee.getMessage()); ee.printStackTrace(); } } catch (IOException e){ playEnabled = false; e.printStackTrace(); } } //end if not pause // display all events in last packet // for all events, add to right and left displayPlay = true; if (show3DWindow&&!windowDeleted) a3DCanvas.repaint(); // pause thread try { Thread.sleep(40); // System.out.println("playing"); } catch (java.lang.InterruptedException e ){ } } // end without disabling playing, press stop to come back to normal display mode } private void storeDisplayPacket(){ // fill hashtable with current events // storing events in hashtable where key is x-y-z int n=inputPacket.getNumEvents(); // System.out.println("processPacket inputPacket n:"+n); if(inputPacket.getType()==Event3D.DIRECT3D){ for(int i=0;i<n;i++){ Event3D ev = new Event3D(inputPacket.getEvent(i)); // if(ev.type==Event3D.DIRECT3D){ String key = new String(ev.x0+"-"+ev.y0+"-"+ev.z0); synchronized(direct3DEvents){ if(ev.value>valueThreshold){ direct3DEvents.put(key,ev); } else { // deletion? direct3DEvents.remove(key); } } } } } public float getFractionalPosition() { if(inputStream==null){ // log.warning("AEViewer.AEPlayer.getFractionalPosition: null fileAEInputStream, returning 0"); return 0; } return inputStream.getFractionalPosition(); } public void setFractionalPosition(float frac) { inputStream.setFractionalPosition(frac); } public AE3DFileInputStream getInputStream(){ return inputStream; } synchronized public void processPacket( AEPacket3D inputPacket ){ int x = 0; int y = 0; int d = 0; float f = 0; int method = 0; int lead_side = 0; EventPoint leadPoints[][]; EventPoint slavePoints[][]; int n=inputPacket.getNumEvents(); // System.out.println("processPacket inputPacket n:"+n); for(int i=0;i<n;i++){ f = inputPacket.getValues()[i]; x = inputPacket.getCoordinates_x()[i]; y = inputPacket.getCoordinates_y()[i]; d = inputPacket.getDisparities()[i]; method = inputPacket.getMethods()[i]; lead_side = inputPacket.getLead_sides()[i]; if(x>=retinaSize||y>=retinaSize||d>=retinaSize){ // error message System.out.println("processPacket i:"+i+" n:"+n+" error: x:"+x+" y:"+y+" d:"+d +" f:"+f+" m:"+method+" ls:"+lead_side+" ts:"+inputPacket.getTimestamps()[i]); } else { if (lead_side==LEFT){ leadPoints = leftPoints; slavePoints = rightPoints; } else { leadPoints = rightPoints; slavePoints = leftPoints; } if (d<0){ //remove event int xs = d*-1; if (method==LEFT_MOST_METHOD){ leadPoints[x][y].prevDisparityLink = xs; leadPoints[x][y].disparityLink = DELETE_LINK; //delete slavePoints[xs][y].attachedTo = NO_LINK; } else { leadPoints[x][y].prevDisparityLink2 = xs; leadPoints[x][y].disparityLink2 = DELETE_LINK; //delete slavePoints[xs][y].attachedTo2 = NO_LINK; } remove3DEvent(leadPoints[x][y],method,lead_side); } else { // add event leadPoints[x][y].previousValue = leadPoints[x][y].lastValue; leadPoints[x][y].lastValue = f; leadPoints[x][y].accValue = f; leadPoints[x][y].shortFilteredValue = f; if (method==LEFT_MOST_METHOD){ int ax = slavePoints[d][y].attachedTo; slavePoints[d][y].attachedTo = x; if(leadPoints[x][y].disparityLink>NO_LINK){ slavePoints[leadPoints[x][y].disparityLink][y].attachedTo = NO_LINK; } leadPoints[x][y].disparityLink = d; leadPoints[x][y].changed = true; new3DEvent(leadPoints[x][y],method,lead_side); if (ax>NO_LINK){ leadPoints[ax][y].prevDisparityLink = d; leadPoints[ax][y].disparityLink = DELETE_LINK; // remove3DEvent(leadPoints[ax][y],method,lead_side); } } else { int ax = slavePoints[d][y].attachedTo2; slavePoints[d][y].attachedTo2 = x; if(leadPoints[x][y].disparityLink2>NO_LINK){ slavePoints[leadPoints[x][y].disparityLink2][y].attachedTo2 = NO_LINK; } leadPoints[x][y].disparityLink2 = d; leadPoints[x][y].changed = true; new3DEvent(leadPoints[x][y],method,lead_side); if (ax>NO_LINK){ leadPoints[ax][y].prevDisparityLink2 = d; leadPoints[ax][y].disparityLink2 = DELETE_LINK; // remove3DEvent(leadPoints[ax][y],method,lead_side); } } } } }//end for } synchronized public void revert(){ forward = !forward; } synchronized public boolean isForward(){ return forward; } synchronized public void stop(){ pauseEnabled = false; playEnabled = false; displayPlay = false; toclear = true; displayDirect3D = false; // stop runnable } synchronized public void speedUp(){ // increase time-bin by factor 2 playTimeBin = playTimeBin*2; } synchronized public void slowDown(){ // decrease playTimeBin = playTimeBin/2; } public float getSpeed(){ return playTimeBin; } /** the number of classes of objects */ /** additional classes */ /** additional classes */ /** Point : all data about a point in opengl 3D space */ /** EventPoint : all data about a point in retina space */ /* public void updateLabel2From( EventPoint ep ){ if(getValue(currentTime)>valueThreshold){ if(ep.getValue(currentTime)>valueThreshold){ if( ep.groupLabel2==0) { newLabel2(); } else { if(groupLabel2 == 0 || groupLabel2>ep.groupLabel2){ groupLabel2 = ep.groupLabel2; } else { ep.groupLabel2 = groupLabel2; } } } else { newLabel2(); } } } */ public void newLabel(){ labelNumber++; groupLabel = new Integer(labelNumber); } public void newLabel2(){ labelNumber++; groupLabel2 = new Integer(labelNumber); } public void noLabel(){ groupLabel = new Integer(0); groupLabel2 = new Integer(0); } // simpler version ofr otpimization ,no decay // public float getValue( int currentTime ){ // if(useFilter){ // return shortFilteredValue; // } else { // return accValue; // // return accValue; // commented out for optimization public float getValue( int currentTime ){ return shortFilteredValue-decayedValue(shortFilteredValue,currentTime-updateTime); /* removed for temporary optimization if(useFilter){ if (decayOn) return shortFilteredValue-decayedValue(shortFilteredValue,currentTime-updateTime); else return shortFilteredValue; } else { if (decayOn) return accValue-decayedValue(accValue,currentTime-updateTime); else return accValue; } **/ } public float getAccValue( int currentTime ){ if (decayOn) return accValue-decayedValue(accValue,currentTime-updateTime); else return accValue; } // public float getFreeValue( int currentTime ){ // if (decayOn) return free-decayedValue(free,currentTime-updateTime); // else return free; public float getShortFilteredValue( int currentTime ){ if (decayOn) return shortFilteredValue-decayedValue(shortFilteredValue,currentTime-updateTime); else return shortFilteredValue; } public float getDecayedFilteredValue( int currentTime ){ return decayedFilteredValue-decayedValue(decayedFilteredValue,currentTime-updateTime); } public float getPreviousShortFilteredValue( int currentTime ){ return previousShortFilteredValue-decayedValue(previousShortFilteredValue,currentTime-previousUpdate); } public int getX0( int method ){ if(changed) { computeXYZ0( LEFT_MOST_METHOD ); computeXYZ0( RIGHT_MOST_METHOD ); } if (method==LEFT_MOST_METHOD) return x0; else return x0r; } public int getY0( int method ){ if(changed) { computeXYZ0( LEFT_MOST_METHOD ); computeXYZ0( RIGHT_MOST_METHOD ); } if (method==LEFT_MOST_METHOD) return y0; else return y0r; } public int getZ0( int method ){ if(changed) { computeXYZ0( LEFT_MOST_METHOD ); computeXYZ0( RIGHT_MOST_METHOD ); } if (method==LEFT_MOST_METHOD){ return z0; } else { return z0r; } } public void computeXYZ0( int method ){ changed = false; int dx = disparityLink; if(method==RIGHT_MOST_METHOD) dx = disparityLink2; if(dx>NO_LINK){ // if matched point exists // dx is coordinate of matched pixel in other retina // result long xt = 0; long yt = 0; long zt = 0; Point p1; Point p3; if(side==LEFT){ p1 = new Point(leftPoints[x][y].xr,leftPoints[x][y].yr,leftPoints[x][y].zr); p3 = new Point(rightPoints[dx][y].xr,rightPoints[dx][y].yr,rightPoints[dx][y].zr); } else { p1 = new Point(leftPoints[dx][y].xr,leftPoints[dx][y].yr,leftPoints[dx][y].zr); p3 = new Point(rightPoints[x][y].xr,rightPoints[x][y].yr,rightPoints[x][y].zr); } // p3 is left focal point Point p2 = new Point(left_focal_x,left_focal_y,left_focal_z); // p4 is right focal point Point p4 = new Point(right_focal_x,right_focal_y,right_focal_z); double mua = 0; double mub = 0; Point p13 = p1.minus(p3); Point p43 = p4.minus(p3); // should check if solution exists here Point p21 = p2.minus(p1); // should check if solution exists here double d1343 = p13.x * p43.x + p13.y * p43.y + p13.z * p43.z; double d4321 = p43.x * p21.x + p43.y * p21.y + p43.z * p21.z; double d1321 = p13.x * p21.x + p13.y * p21.y + p13.z * p21.z; double d4343 = p43.x * p43.x + p43.y * p43.y + p43.z * p43.z; double d2121 = p21.x * p21.x + p21.y * p21.y + p21.z * p21.z; double denom = d2121 * d4343 - d4321 * d4321; // if (ABS(denom) < EPS) return(FALSE); double numer = d1343 * d4321 - d1321 * d4343; mua = numer / denom; mub = (d1343 + d4321 * (mua)) / d4343; xt = Math.round(p1.x + mua * p21.x); yt = Math.round(p1.y + mua * p21.y); zt = Math.round(p1.z + mua * p21.z); // pb->x = p3.x + *mub * p43.x; // pb->y = p3.y + *mub * p43.y; // pb->z = p3.z + *mub * p43.z; // store results for both methods if(method==RIGHT_MOST_METHOD){ x0r = (int)xt; y0r = (int)yt; z0r = (int)zt; } else { x0 = (int)xt; y0 = (int)yt; z0 = (int)zt; } } } } // end class EventPoint /// private class FingerCluster{ int id = 0; int x=0; int y=0; int z = 0; int time = 0; int nbEvents = 0; //for ball tracker, hacked here int x_size = 0; int y_size = 0; int z_size = 0; // boolean activated = false; public FingerCluster( ){ //for ball tracker, hacked here x_size = 10; //finger_surround; y_size = 10; z_size = 10; } public FingerCluster( int x, int y, int z, int time ){ // activated = true; this.time = time; id = nbFingerClusters++; this.x = x; this.y = y; this.z = z; //for ball tracker, hacked here x_size = 10; y_size = 10; z_size = 10; nbEvents = 1; } public void reset(){ // activated = false; //for ball tracker, hacked here x_size = 10; y_size = 10; z_size = 10; x = 0; //end tip y = 0; z = 0; nbEvents = 0; } public void add( int x, int y, int z, float mix, int time){ // mix = mix/(finger_surround*finger_surround); // /100 mix = mix/100; float exp_mix = expansion_mix;// /100; if(mix>1) mix=1; if(mix<0) mix = 0; if(exp_mix>1) exp_mix=1; if(exp_mix<0) exp_mix = 0; this.time = time; this.x = Math.round(x*mix + this.x*(1-mix)); this.y = Math.round(y*mix + this.y*(1-mix)); this.z = Math.round(z*mix + this.z*(1-mix)); // int max_size = finger_surround * scaleFactor; //for ball tracker, hacked here // take remaining difference after cluster has moved int diffx = Math.abs(this.x - x);// half size needed to incorporate new event float x_dist_weight = Math.round((float)Math.abs(x_size - diffx)/x_size); // x_dist_weight = x_dist_weight * x_dist_weight; int diffy = Math.abs(this.y - y);// half size needed to incorporate new event float y_dist_weight = Math.round((float)Math.abs(y_size - diffy)/y_size); // y_dist_weight = y_dist_weight * y_dist_weight; int diffz = Math.abs(this.z - z);// half size needed to incorporate new event float z_dist_weight = Math.round((float)Math.abs(z_size - diffz)/z_size); // z_dist_weight = z_dist_weight * z_dist_weight; // need to weight size change by inverse of neasrest to cluster center? if(x_dist_weight>1) x_dist_weight=0; // if(x_dist_weight<0) x_dist_weight = 0; if(y_dist_weight>1) y_dist_weight=0; // if(y_dist_weight<0) y_dist_weight = 0; if(z_dist_weight>1) z_dist_weight=0; // if(z_dist_weight<0) z_dist_weight = 0; float exp_mix_x = exp_mix*(1-x_dist_weight); float exp_mix_y = exp_mix*(1-y_dist_weight); float exp_mix_z = exp_mix*(1-z_dist_weight); x_size = Math.round(diffx*exp_mix_x + x_size*(1-exp_mix_x)); y_size = Math.round(diffy*exp_mix_y + y_size*(1-exp_mix_y)); z_size = Math.round(diffz*exp_mix_z + z_size*(1-exp_mix_z)); // if(x_size>500||x_size<0){ // int i = 0; // if(y_size>500||y_size<0){ // int j = 0; // if(z_size>500||z_size<0){ // int k = 0; nbEvents++; } } // end class FingerCluster private class PlaneTracker{ int id = 0; // int x=0; // int y=0; int z = 0; int z0 = 0; // int time = 0; //for ball tracker, hacked here int x_size = 0; int y_size = 0; // int z_size = 0; // boolean activated = false; public PlaneTracker( ){ //for ball tracker, hacked here // x_size = 10; //plane_tracker_size; // y_size = 10; // z_size = 10; } public PlaneTracker( int z ){ // activated = true; // this.time = time; id = nbFingerClusters++; // this.x = x; // this.y = y; this.z = z; z0 = z; //for ball tracker, hacked here // x_size = 10; // y_size = 10; // z_size = 10; } public void reset(){ // activated = false; //for ball tracker, hacked here // x_size = 10; // y_size = 10; // z_size = 10; // x = 0; //end tip // y = 0; z = z0; } public void add( int x, int y, int z, float mix){ if(isInSearchSpace(x,y,z)){ int zsp = zFromSearchSpace(x,y,z); if(zsp<this.z){ mix = mix/100; if(mix>1) mix = 1; if(mix<0) mix = 0; // this.time = time; this.z = Math.round(zsp*mix + this.z*(1-mix)); } } } } // end class PlaneTracker // do not forget to add a set and a get/is method for each new parameter, at the end of this .java file // Global variables // array of event points for all computation protected EventPoint leftPoints[][]; protected EventPoint rightPoints[][]; // protected EventPoint leftPoints2[][]; // protected EventPoint rightPoints2[][]; protected int correctionMatrix[][]; // private boolean logDataEnabled=false;//previously used for ball tracker private PrintStream logStream=null; int currentTime = 0; float[] densities = new float[lowFilter_density]; // float[] densities2 = new float[lowFilter_density2]; // float largeRangeTotal; float shortRangeTotal; float shortFRadius; // float largeFRadius; int shortRadiusSq; // int largeRadiusSq; float invDensity1; float invDensity2; protected float grayValue = 0.5f; protected int colorScale = 2; private int redBlueShown=0; private int method=0; private int display3DChoice=0; private int displaySign=0; private int testChoice=0; // private boolean averageMode = false; // private boolean fuseMode = false; // private boolean cutMode = false; // private boolean probaMode = false; // private boolean veryCompactMode = false; // private boolean compactMode = false; private boolean searchSpaceMode = false; private boolean clearSpaceMode = false; private boolean showDisparity = false; private boolean testDrawing = false; private boolean showLabels = false; boolean windowDeleted = true; private int nbFingers = 0; //number of fingers tracked, maybe put it somewhere else private int nbFingerClusters = 1;//number of created tracked // protected FingerCluster[] fingers = new FingerCluster[MAX_NB_FINGERS]; protected Vector<FingerCluster> fingers = new Vector(); protected PlaneTracker planeTracker; // a bit hacked, for subsampling record of tracker data int prev_tracker_x = 0; int prev_tracker_y = 0; int prev_tracker_z = 0; /** Creates a new instance of PawTracker */ public PawTrackerStereoBoard3(AEChip chip) { super(chip); this.chip=chip; renderer=(AEChipRenderer)chip.getRenderer(); chip.getRenderer().addAnnotator(this); // to draw the clusters chip.getCanvas().addAnnotator(this); // System.out.println("build resetPawTracker4 "+trackerID); initFilter(); resetPawTracker(); // validateParameterChanges(); chip.addObserver(this); // System.out.println("End build resetPawTrackerStereoBoard"); } public void initFilter() { } private void resetPawTracker(){ // doReset = false; // allEvents.clear(); // System.out.println("reset PawTrackerStereoBoard3 reset"); // pb with reset and display : null pointer if happens at the same time leftPoints = new EventPoint[retinaSize][retinaSize]; for (int i=0; i<leftPoints.length; i++){ for (int j=0; j<leftPoints[i].length; j++){ leftPoints[i][j] = new EventPoint(i,j); } } rightPoints = new EventPoint[retinaSize][retinaSize]; for (int i=0; i<rightPoints.length; i++){ for (int j=0; j<rightPoints[i].length; j++){ rightPoints[i][j] = new EventPoint(i,j); } } // leftPoints2 = new EventPoint[retinaSize][retinaSize]; // for (int i=0; i<leftPoints2.length; i++){ // for (int j=0; j<leftPoints2[i].length; j++){ // leftPoints2[i][j] = new EventPoint(i,j); // rightPoints2 = new EventPoint[retinaSize][retinaSize]; // for (int i=0; i<rightPoints2.length; i++){ // for (int j=0; j<rightPoints2[i].length; j++){ // rightPoints2[i][j] = new EventPoint(i,j); compute3DParameters(); // to remove: validateParameterChanges(); // resetCorrectionMatrix(); // to remove: createCorrectionMatrix(); // reset group labels (have a vector of them or.. ? // scoresFrame = new float[retinaSize][retinaSize]; resetClusterTrackers(); setResetPawTracking(false);//this should also update button in panel but doesn't' // System.out.println("End of resetPawTrackerStereoBoard"); } private void resetClusterTrackers(){ fingers.clear(); // = new FingerCluster[MAX_NB_FINGERS]; nbFingers = 0; // setResetPawTracking(false);//this should also update button in panel but doesn't' int z = (int)Math.round((cage_distance-0.1)*scaleFactor); planeTracker = new PlaneTracker(z); } private void initDefault(String key, String value){ if(getPrefs().get(key,null)==null) getPrefs().put(key,value); } // the method that actually does the tracking synchronized private void track(EventPacket<BinocularEvent> ae){ // if(isResetPawTracking()){ // reset // resetPawTracker(); // return; //maybe continue then int n=ae.getSize(); if(n==0) return; // if(validateParameters){ // validateParameterChanges(); float step = event_strength / (colorScale + 1); if( !chip.getAeViewer().isSingleStep()){ chip.getAeViewer().aePlayer.pause(); } currentTime = ae.getLastTimestamp(); for(BinocularEvent e:ae){ // BinocularEvent be=(BinocularEvent)e; processEvent(e); } clearDeadFingerTrackers(currentTime); printClusterData(); if( !chip.getAeViewer().isSingleStep()){ chip.getAeViewer().aePlayer.resume(); } } public void printClusterData(){ if(recordTrackerData){ // extract x,y,z int n = 0; for(FingerCluster fc:fingers){ n++; if(fc.nbEvents>tracker_viable_nb_events){ // if(!fingers.isEmpty()) { // FingerCluster fc = fingers.firstElement(); // subsampling based on distance with previous record if(distanceBetween(prev_tracker_x,prev_tracker_y,prev_tracker_z,fc.x,fc.y,fc.z)>trackerSubsamplingDistance*scaleFactor){ // update prev prev_tracker_x = fc.x; prev_tracker_y = fc.y; prev_tracker_z = fc.z; int xsp = xFromSearchSpace(fc.x,fc.y,fc.z); int ysp = yFromSearchSpace(fc.x,fc.y,fc.z); int zsp = zFromSearchSpace(fc.x,fc.y,fc.z); //rotation to correct? int sizex = fc.x_size; int sizey = fc.y_size; int sizez = fc.z_size;//*2; //System.out.println(fc.x+" "+fc.y+" "+fc.z+" "+xsp+" "+ysp+" "+zsp+" "+sizex+" "+sizey+" "+sizez); System.out.println(xsp+" "+ysp+" "+zsp); } } }*/ } if(recordEnabled){ boolean recordEvent = true; // record only visible events, if clearSpaceMode, only those inside area of interest ep.setChanged(true); if(clearSpaceMode){ if(!isInSearchSpace(ep.getX0(method),ep.getY0(method),ep.getZ0(method))){ recordEvent = false; } } if(recordEvent){ int disp = -1; if (method==LEFT_MOST_METHOD){ disp = ep.disparityLink; } else { disp = ep.disparityLink2; } if(recordPure3D){ if(ep.getZ0(method)!=0) { //empty event for some reason, to look into Event3D e = new Event3D(ep.getX0(method),ep.getY0(method),ep.getZ0(method), ep.getValue(currentTime),currentTime); loggingPacket.addEvent(e); } } else { // create 3d event, add to logging packet // Event3D e = new Event3D(ep.x,ep.y,disp,method,lead_side, // ep.getValue(currentTime),ep.updateTime); Event3D e = new Event3D(ep.x,ep.y,disp,method,lead_side, ep.getValue(currentTime),currentTime); loggingPacket.addEvent(e); } } } } // delete event function void remove3DEvent( EventPoint ep, int method, int lead_side ){ if(recordEnabled){ ep.setChanged(true); boolean recordEvent = true; // if(ep.getZ0(method)==0) recordEvent = false; //empty event for some reason, to look into // record only visible events, if clearSpaceMode, only those inside area of interest if(clearSpaceMode){ if(!isInSearchSpace(ep.getX0(method),ep.getY0(method),ep.getZ0(method))){ recordEvent = false; } } if(recordEvent){ int disp = -1; if (method==LEFT_MOST_METHOD){ disp = ep.prevDisparityLink*-1; } else { disp = ep.prevDisparityLink2*-1; } // create 3d event with zero value , add to logging packet if(recordPure3D){ if(ep.getZ0(method)!=0) { //empty event for some reason, to look into Event3D e = new Event3D(ep.getX0(method),ep.getY0(method),ep.getZ0(method), 0,currentTime); loggingPacket.addEvent(e); } } else { Event3D e = new Event3D(ep.x,ep.y,disp,method,lead_side, 0,currentTime); //currentTime? loggingPacket.addEvent(e); } } } } // finger cluster functions void addToFingerTracker( EventPoint ep, int method ){ /** * check additional constraints to be deemed a finger: * find if end node of skeletton in range * find closer fingertracker * if none, create new fingertracker * * call fingerTracker.add * which mix previous position with current eventPoint position * * */ if(isInSearchSpace(ep.getX0(method),ep.getY0(method),ep.getZ0(method))){ // find nearest // FingerCluster fc = getNearestFinger(ep,finger_surround,method); Vector<FingerCluster> fcv = getNearestFingerClusters(ep,finger_surround,method); // if(fc==null){ if(fcv.isEmpty()){ if(nbFingers<max_finger_clusters){ fingers.add(new FingerCluster(ep.getX0(method),ep.getY0(method),ep.getZ0(method),ep.updateTime)); // System.out.println(currentTime+" create finger at: ["+ep.getX0(method)+"," // +ep.getY0(method)+","+ep.getZ0(method)+"] with updateTime:"+ep.updateTime); nbFingers++; }// else { // System.out.println(currentTime+" cannot create new tracker: nbFingers="+nbFingers); } else { //fc.add(ep.getX0(method),ep.getY0(method),ep.getZ0(method),finger_mix,ep.updateTime); FingerCluster fc = fcv.firstElement(); int prev_x = fc.x; int prev_y = fc.y; int prev_z = fc.z; fc.add(ep.getX0(method),ep.getY0(method),ep.getZ0(method),finger_mix,ep.updateTime); //fcv.remove(fc); // push close neighbouring clusters away //int surroundSq = finger_surround*finger_surround+16; //for(FingerCluster fa:fcv){ // pushCloseCluster(fa,fc,surroundSq); // rebounce on too close neighbouring clusters fcv = getNearestFingerClusters(fc.x,fc.y,fc.z,finger_surround); if(fcv.size()>1){ // recursive fcv.remove(fc); rebounceOnCloseClusters(prev_x,prev_y,prev_z,fc,fcv.firstElement(),1); } } } } private void rebounceOnCloseClusters( int x, int y, int z, FingerCluster fc, FingerCluster obstacle, int n ){ if(n>10) return; //safety on recusrivity float surroundSq = finger_surround*finger_surround+16; int prev_x = fc.x; int prev_y = fc.y; int prev_z = fc.z; // compute dist ob-fc float dx = obstacle.x-fc.x; float dy = obstacle.y-fc.y; float dz = obstacle.z-fc.z; float dist = dx*dx + dy*dy + dz*dz; if(dist>surroundSq) return; float distx = dx*dx; float disty = dy*dy; float distz = dz*dz; float px = (distx/surroundSq)*finger_surround; float py = (disty/surroundSq)*finger_surround; float pz = (distz/surroundSq)*finger_surround; // float rebounceStrength = (float)Math.sin(Math.acos(cos_fc))*surroundSq; // pushing vectors // int push_x = Math.round((obstacle.x-x)*rebounceStrength); // int push_y = Math.round((obstacle.y-y)*rebounceStrength); // int push_z = Math.round((obstacle.z-z)*rebounceStrength); // fc.x += push_x; // fc.y += push_y; // fc.z += push_z; if(x-obstacle.x>0){ fc.x += px; } else { fc.x -= px; } if(y-obstacle.y>0){ fc.y += py; } else { fc.y -= py; } if(z-obstacle.z>0){ fc.z += pz; } else { fc.z -= pz; } if(fc.x>4000||fc.x<-100){ int h = 0; } if(fc.y>4000||fc.y<-100){ int h = 0; } if(fc.z>4000||fc.z<-100){ int h = 0; } Vector<FingerCluster> fcv = getNearestFingerClusters(fc.x,fc.y,fc.z,finger_surround); if(fcv.size()>1){ // recursive fcv.remove(fc); rebounceOnCloseClusters(prev_x,prev_y,prev_z,fc,fcv.firstElement(),++n); } } private FingerCluster getNearestFinger( EventPoint ep, int surround, int method ){ float min_dist=Float.MAX_VALUE; FingerCluster closest=null; // float currentDistance=0; int surroundSq = surround*surround; float dist = min_dist; int dx = 0; int dy = 0; int dz =0; StringBuffer sb = new StringBuffer(); for(FingerCluster fc:fingers){ if(fc!=null){ // if(fc.activated){ dx = ep.getX0(method)-fc.x; dy = ep.getY0(method)-fc.y; dz = ep.getZ0(method)-fc.z; dist = dx*dx + dy*dy + dz*dz; if(dist<surroundSq){ if(dist<min_dist){ closest = fc; min_dist = dist; } } sb.append("getNearestFinger ep: ["+ep.getX0(method)+","+ep.getY0(method)+","+ep.getZ0(method)+ "] fc: ["+fc.x+","+fc.y+","+fc.z+"] dist="+dist+" surroundsq="+surroundSq+" mindist="+min_dist+"\n"); } } if(closest==null){ System.out.println(sb); } return closest; } private Vector<FingerCluster> getNearestFingerClusters( EventPoint ep, int surround, int method ){ return getNearestFingerClusters(ep.getX0(method),ep.getY0(method),ep.getZ0(method),surround); } private Vector<FingerCluster> getNearestFingerClusters( int x, int y, int z, int surround ){ float min_dist=Float.MAX_VALUE; Vector<FingerCluster> closest=new Vector(); // float currentDistance=0; int surroundSq = surround*surround; float dist = min_dist; int dx = 0; int dy = 0; int dz =0; // StringBuffer sb = new StringBuffer(); try { for(FingerCluster fc:fingers){ if(fc!=null){ // if(fc.activated){ dx = x-fc.x; dy = y-fc.y; dz = z-fc.z; dist = dx*dx + dy*dy + dz*dz; if(dist<=surroundSq){ if(dist<min_dist){ closest.add(0,fc); min_dist = dist; } else { closest.add(fc); } } // sb.append(currentTime+" getNearestFinger ep: ["+ep.getX0(method)+","+ep.getY0(method)+","+ep.getZ0(method)+ // "] fc: ["+fc.x+","+fc.y+","+fc.z+"] dist="+dist+" surroundsq="+surroundSq+" mindist="+min_dist+"\n"); } } } catch (java.util.ConcurrentModificationException cme ){ System.out.println("Warning: getNearestFingerClusters: ConcurrentModificationException caught"); } // if(closest==null){ // if(closest.isEmpty()){ // System.out.println(sb+" fingers.size:"+fingers.size()); return closest; } synchronized private void clearDeadFingerTrackers(int time){ Vector<FingerCluster> toRemove = new Vector(); for(FingerCluster fc:fingers){ // if(fc!=null){ if(fc.nbEvents<tracker_viable_nb_events){ if(time-fc.time>tracker_prelifeTime){ toRemove.add(fc); nbFingers } } else { if(time-fc.time>tracker_lifeTime){ toRemove.add(fc); nbFingers } } } // fingers.removeAll(toRemove); for(FingerCluster fc:toRemove){ fingers.remove(fc); fc=null; // System.out.println("clearDeadFingerTrackers delete Tracker"); } // System.out.println("clearDeadFingerTrackers "+nbFingers); } private void lead_add( int x, int y ){ //leftPoints[x][y].count++; // change to } private void lead_rem( int x, int y, int lead_side, int method, EventPoint leftPoints[][], EventPoint rightPoints[][]){ int yl = y;// + yLeftCorrection; int yr = y;// + yRightCorrection; if(yl<0||yl>=retinaSize)return; if(yr<0||yr>=retinaSize)return; EventPoint leadPoints[][]; EventPoint slavePoints[][]; if (lead_side==LEFT){ leadPoints = leftPoints; slavePoints = rightPoints; } else { leadPoints = rightPoints; slavePoints = leftPoints; } if(method==LEFT_MOST_METHOD){ int ax = leadPoints[x][yl].disparityLink; if (ax>NO_LINK) { // rightPoints[ax][yr].free+=leftPoints[ax][yl].getAccValue(leftTime); //? // if(rightPoints[ax][yr].getFreeValue(rightTime)>=rightPoints[ax][yr].getAccValue(rightTime)){ // rightPoints[ax][yr].attachedTo = -1; slavePoints[ax][yr].attachedTo = NO_LINK; // rightPoints[ax][yr].free=rightPoints[ax][yr].getValue(rightTime); leadPoints[x][yl].prevDisparityLink = leadPoints[x][yl].disparityLink; leadPoints[x][yl].disparityLink = DELETE_LINK; // points had a depth but no more, update neighbours average depth //updateAverageDepthAround(leadPoints,x,yl,dispAvgRange); //resetGCAround(leadPoints,x,yl); } else { leadPoints[x][y].disparityLink = DELETE_LINK; //delete } // remove3DEvent(leadPoints[x][y],method,lead_side); } else { int ax = leadPoints[x][yl].disparityLink2; if (ax>NO_LINK) { // rightPoints[ax][yr].free+=leftPoints[ax][yl].getAccValue(leftTime); //? // if(rightPoints[ax][yr].getFreeValue(rightTime)>=rightPoints[ax][yr].getAccValue(rightTime)){ // rightPoints[ax][yr].attachedTo = -1; slavePoints[ax][yr].attachedTo2 = NO_LINK; // rightPoints[ax][yr].free=rightPoints[ax][yr].getValue(rightTime); leadPoints[x][yl].prevDisparityLink2 = leadPoints[x][yl].disparityLink2; leadPoints[x][yl].disparityLink2 = DELETE_LINK; // points had a depth but no more, update neighbours average depth //updateAverageDepthAround(leadPoints,x,yl,dispAvgRange); // resetGCAround(leadPoints,x,yl); } else { leadPoints[x][y].disparityLink2 = DELETE_LINK; //delete } // remove3DEvent(leadPoints[x][y],method,lead_side); } } private void slave_add( int x, int y ){ // int yr = y;// + yRightCorrection; // if(yr<0||yr>=retinaSize)return; // rightPoints[x][yr].free=rightPoints[x][yr].getValue(rightTime); //rightPoints[x][y].accumulation=rightPoints[ax][y].getCurrentValue(; } private void slave_rem( int x, int y, int lead_side, int method, EventPoint leftPoints[][], EventPoint rightPoints[][]){ int yl = y;// + yLeftCorrection; int yr = y;//+ yRightCorrection; if(yl<0||yl>=retinaSize)return; if(yr<0||yr>=retinaSize)return; EventPoint leadPoints[][]; EventPoint slavePoints[][]; int leadTime; int slaveTime; if (lead_side==LEFT){ leadPoints = leftPoints; slavePoints = rightPoints; leadTime = currentTime; slaveTime = currentTime; } else { leadPoints = rightPoints; slavePoints = leftPoints; leadTime = currentTime; slaveTime = currentTime; } // if (rightPoints[x][yr].free>0) // rightPoints[x][yr].free=rightPoints[x][yr].getValue(rightTime); // if (rightPoints[x][y].getCurrentValue()>0) rightPoints[x][y].accumulation--; if(method==LEFT_MOST_METHOD){ if (slavePoints[x][yr].getValue(slaveTime)<=valueThreshold){ int ax = slavePoints[x][yr].attachedTo; if(ax>NO_LINK){ leadPoints[ax][yl].prevDisparityLink = x; leadPoints[ax][yl].disparityLink = DELETE_LINK; //delete slavePoints[x][yr].attachedTo = NO_LINK; // points had a depth but no more, update neighbours average depth // remove3DEvent(leadPoints[ax][y],method,lead_side); // updateAverageDepthAround(leadPoints,ax,yl,dispAvgRange); // resetGCAround(leadPoints,ax,yl); } } } else { if (slavePoints[x][yr].getValue(slaveTime)<=valueThreshold){ int ax = slavePoints[x][yr].attachedTo2; if(ax>NO_LINK){ leadPoints[ax][yl].prevDisparityLink2 = x; leadPoints[ax][yl].disparityLink2 = DELETE_LINK; //delete slavePoints[x][yr].attachedTo2 = NO_LINK; // points had a depth but no more, update neighbours average depth // remove3DEvent(leadPoints[ax][y],method,lead_side); // updateAverageDepthAround(leadPoints,ax,yl,dispAvgRange); // resetGCAround(leadPoints,ax,yl); // add leftMost method as parameter here? } } } } private void slave_check( int x, int y, int lead_side, int method, EventPoint leftPoints[][], EventPoint rightPoints[][] ){ // int yl = y;// + yLeftCorrection; // int yr = y;// + yRightCorrection; // if(yl<0||yl>=retinaSize)return; // if(yr<0||yr>=retinaSize)return; boolean done = false; int ax = 0; EventPoint leadPoints[][] = rightPoints; EventPoint slavePoints[][] = leftPoints; // int leadTime; // int slaveTime; if (lead_side==LEFT){ leadPoints = leftPoints; slavePoints = rightPoints; // leadTime = currentTime; // slaveTime = currentTime; } //else { // leadPoints = rightPoints; // slavePoints = leftPoints; // leadTime = currentTime; //to uniformise // slaveTime = currentTime; if (leadPoints[x][y].getValue(currentTime)<=valueThreshold){ return; } if(method==LEFT_MOST_METHOD){ for(int i=0;i<slavePoints.length;i++){ if(done) break; if((slavePoints[i][y].getValue(currentTime)>valueThreshold) // &&isInRange(i,x,disparity_range) // &&((slavePoints[i][y].getValue(currentTime)<=leadPoints[x][y].getValue(currentTime)+valueMargin) // &&(slavePoints[i][y].getValue(currentTime)>=leadPoints[x][y].getValue(currentTime)-valueMargin)) ){ ax = slavePoints[i][y].attachedTo; if(ax>NO_LINK){ if(leadPoints[ax][y].getValue(currentTime)<valueThreshold){ leadPoints[ax][y].prevDisparityLink = i; leadPoints[ax][y].disparityLink = DELETE_LINK; slavePoints[i][y].attachedTo = NO_LINK; // points had a depth but no more, update neighbours average depth // remove3DEvent(leadPoints[ax][y],method,lead_side); //updateAverageDepthAround(leadPoints,ax,yl,dispAvgRange); //resetGCAround(leadPoints,ax,yl); ax = NO_LINK; // slavePoints[i][yr].attachedTo = -1; } //should check here if group label is "different" (from...?) and if yes reset ax to NO_LINK } if(ax>x||ax==NO_LINK){ boolean doLink = true; if(useGroups){ if(x-1>=0){ if(leadPoints[x-1][y].getValue(currentTime)>valueThreshold){ if(leadPoints[x-1][y].disparityLink>NO_LINK){ if(slavePoints[i][y].groupLabel!=slavePoints[leadPoints[x-1][y].disparityLink][y].groupLabel){ doLink = false; } } else { doLink = false; } } } if(i-1>=0){ if(slavePoints[i-1][y].getValue(currentTime)>valueThreshold){ if(slavePoints[i-1][y].attachedTo>NO_LINK){ if(leadPoints[x][y].groupLabel!=leadPoints[slavePoints[i-1][y].attachedTo][y].groupLabel){ doLink = false; } } else { doLink = false; } } } } if(doLink){ slavePoints[i][y].attachedTo = x; if(leadPoints[x][y].disparityLink>NO_LINK){ slavePoints[leadPoints[x][y].disparityLink][y].attachedTo = NO_LINK; } leadPoints[x][y].disparityLink = i; // points now has a depth, update neighbours average depth // // updateAverageDepthAround(leadPoints,x,yl,dispAvgRange); //addToGCAround(leadPoints,x,yl,dispAvgRange); leadPoints[x][y].changed = true; // commented out to check speed of matching // to put back! new3DEvent(leadPoints[x][y],method,lead_side); // addToFingerTracker(leadPoints[x][y],method); // if(rightPoints[i][yr].getFreeValue(rightTime)>0){ //rightPoints[i][y].free-=leftPoints[ax][y].getCurrentValue(); // rightPoints[i][yr].free=0; // detach previous left if (ax>NO_LINK){ leadPoints[ax][y].prevDisparityLink = i; leadPoints[ax][y].disparityLink = DELETE_LINK; // remove3DEvent(leadPoints[ax][y],method,lead_side); // points had a depth but no more, update neighbours average depth // updateAverageDepthAround(leadPoints,ax,yl,dispAvgRange); // resetGCAround(leadPoints,ax,yl); } done = true; } // end if doLink } } //else { // debug // System.out.println(""); } // end for } else { // right most method for(int i=slavePoints.length-1;i>=0;i if(done) break; if((slavePoints[i][y].getValue(currentTime)>valueThreshold) // &&((slavePoints[i][y].getValue(currentTime)<=leadPoints[x][y].getValue(leadTime)+valueMargin) // &&(slavePoints[i][y].getValue(currentTime)>=leadPoints[x][y].getValue(leadTime)-valueMargin)) ){ ax = slavePoints[i][y].attachedTo2; if(ax>NO_LINK){ if(leadPoints[ax][y].getValue(currentTime)<valueThreshold){ leadPoints[ax][y].prevDisparityLink2 = i; leadPoints[ax][y].disparityLink2 = DELETE_LINK; slavePoints[i][y].attachedTo2 = NO_LINK; // points had a depth but no more, update neighbours average depth //updateAverageDepthAround(leadPoints,ax,yl,dispAvgRange); // remove3DEvent(leadPoints[ax][y],method,lead_side); // resetGCAround(leadPoints,ax,yl); ax = NO_LINK; // slavePoints[i][yr].attachedTo = -1; } } if(ax<x||ax==NO_LINK){ // group condition boolean doLink = true; if(useGroups){ if(x+1<retinaSize){ if(leadPoints[x+1][y].getValue(currentTime)>valueThreshold){ if(leadPoints[x+1][y].disparityLink2>NO_LINK){ if(slavePoints[i][y].groupLabel2!=slavePoints[leadPoints[x+1][y].disparityLink2][y].groupLabel2){ doLink = false; } } else { doLink = false; } } } if(i+1<retinaSize){ if(slavePoints[i+1][y].getValue(currentTime)>valueThreshold){ if(slavePoints[i+1][y].attachedTo2>NO_LINK){ if(leadPoints[x][y].groupLabel2!=leadPoints[slavePoints[i+1][y].attachedTo2][y].groupLabel2){ doLink = false; } } else { doLink = false; // this removes all events exept borders // because new events are not linked? // to avoid old unlinked events // we shoud do otherwise } } } } if(doLink){ slavePoints[i][y].attachedTo2 = x; if(leadPoints[x][y].disparityLink2>NO_LINK){ slavePoints[leadPoints[x][y].disparityLink2][y].attachedTo2 = NO_LINK; } leadPoints[x][y].disparityLink2 = i; // points now has a depth, update neighbours average depth // leadPoints[x][y].changed = true; new3DEvent(leadPoints[x][y],method,lead_side); // updateAverageDepthAround(leadPoints,x,yl,dispAvgRange); // addToGCAround(leadPoints,x,yl,dispAvgRange); // commented out to check speed of matching // to put back! // addToFingerTracker(leadPoints[x][y],method); // if(rightPoints[i][yr].getFreeValue(rightTime)>0){ //rightPoints[i][y].free-=leftPoints[ax][y].getCurrentValue(); // rightPoints[i][yr].free=0; // detach previous left if (ax>NO_LINK){ leadPoints[ax][y].prevDisparityLink2 = i; leadPoints[ax][y].disparityLink2 = DELETE_LINK; // points had a depth but no more, update neighbours average depth // remove3DEvent(leadPoints[ax][y],method,lead_side); // updateAverageDepthAround(leadPoints,ax,yl,dispAvgRange); //resetGCAround(leadPoints,ax,yl); } done = true; } } // end if doLink } } // end for } if(done&&ax!=NO_LINK) slave_check(ax,y,lead_side,method,leftPoints,rightPoints); } private void lead_check( int y , int lead_side, int method, EventPoint leftPoints[][], EventPoint rightPoints[][] ){ // int yl = y;// + yLeftCorrection; // if(yl<0||yl>=retinaSize)return; //to remove // look for unassigned left events boolean done = false; EventPoint leadPoints[][] = rightPoints; // int leadTime = currentTime; if (lead_side==LEFT){ leadPoints = leftPoints; }// else { // leadPoints = rightPoints; if(method==LEFT_MOST_METHOD){ for(int i=0;i<leadPoints.length;i++){ //if(done) break; //for fast matching if ((leadPoints[i][y].getValue(currentTime)>valueThreshold)){//&&(leftPoints[i][yl].disparityLink<0)){ slave_check(i,y,lead_side,method,leftPoints,rightPoints); // if(useFastMatching) // done = true; // speed problem when commented out } } } else { // add test on label for limiting scope? for(int i=leadPoints.length-1;i>=0;i // if(done) break; //for fast matching if ((leadPoints[i][y].getValue(currentTime)>valueThreshold)){//&&(leftPoints[i][yl].disparityLink<0)){ slave_check(i,y,lead_side,method,leftPoints,rightPoints); // if(useFastMatching) //done = true; } } } } private boolean isInRange( int x, int y , int range){ if(x>y){ if(x-y>range) return false; return true; } else { if(y-x>range) return false; return true; } } private void processDisparity( int leftOrRight, int x, int y, float value, float previous_value, int lead_side, int method, EventPoint leftPoints[][], EventPoint rightPoints[][] ){ // + event int type = 0; if(previous_value<value){ type = 1; } if(leftOrRight==lead_side){ boolean change = false; // value = leftPoints[e.x][cy].getAccValue(leftTime); if(type==1){ // increase lx count if(value>valueThreshold){ change = true; } } else { //remove event if(value<=valueThreshold){ lead_rem( x, y, lead_side,method,leftPoints,rightPoints); change = true; } } // call right check if (change) slave_check(x,y,lead_side,method,leftPoints,rightPoints); } else { boolean change = false; // value = rightPoints[e.x][cy].getAccValue(rightTime); if(type==1){ // increase lx count if(value>valueThreshold){ change = true; } } else { //remove event if(value<=valueThreshold){ slave_rem( x, y, lead_side,method,leftPoints,rightPoints ); change = true; } } if (change) lead_check(y,lead_side,method,leftPoints,rightPoints); } } // processing one event protected void processEvent(BinocularEvent e){ // resetEnabled = true; //int leftOrRight = e.side; int leftOrRight = e.eye == BinocularEvent.Eye.LEFT ? 0 : 1; //be sure if left is same as here // System.out.println("processEvent leftOrRight:"+leftOrRight+" e.eye:"+e.eye+" type:"+e.getType()); int type=e.polarity==BinocularEvent.Polarity.Off? 0: 1; // paul test opposite polariry // int type=e.polarity==BinocularEvent.Polarity.Off? 1: 0; int dy = e.y; int dx = e.x; int cy = dy; if(useCorrections){ // shift y if(leftOrRight==LEFT){ dy += yLeftCorrection; // leftTime = e.timestamp; } else { dy += yRightCorrection; // rightTime = e.timestamp; } // to add: shift x // to add : rotate around center // for any x,y, find new xr,yr after rotation around center // center of picture is 64,64 int half = retinaSize/2; float correctAngle = 0; if (leftOrRight==LEFT){ correctAngle = correctLeftAngle; } else { correctAngle = correctRightAngle; } if (correctAngle!=0){ int xr = Math.round((float) ( (Math.cos(Math.toRadians(correctAngle))*(dx-half)) - (Math.sin(Math.toRadians(correctAngle))*(dy-half)) )) + half; int yr = Math.round((float) ( (Math.sin(Math.toRadians(correctAngle))*(dx-half)) + (Math.cos(Math.toRadians(correctAngle))*(dy-half)) )) + half; dy = yr; dx = xr; } //int cy = e.y; if(dx<0||dx>retinaSize){ return; } // correct y curvature cy = dy; if(dy>=0&&dy<retinaSize){ if(correctY){ cy = correctionMatrix[e.x][cy]; } } else return; if(cy<0||cy>=retinaSize){ return; } } float value = 0; if(leftOrRight==LEFT){ // if(type==1) System.out.println("processEvent leftPoints add("+e.x+","+cy+") type:"+type+" etype1:"+e.getType()+" etype2:"+e.getType()); leftPoints[e.x][cy].updateFrom(e,e.x,cy,LEFT); // filter if(useFilter){ fastDualLowFilterFrame(leftPoints[e.x][cy], leftPoints, rightPoints ); // fastDualLowFilterFrame(leftPoints2[e.x][cy], leftPoints2, leftOrRight, LEFT, false, leftPoints2, rightPoints2); // fastDualLowFilterFrame(leftPoints[e.x][cy], leftPoints, rightPoints, RIGHT ); // fastDualLowFilterFrame(leftPoints2[e.x][cy], leftPoints2, leftOrRight, RIGHT, false, leftPoints2, rightPoints2); } else { // update group label leftPoints[e.x][cy].updateLabel(); value = leftPoints[e.x][cy].getAccValue(currentTime); float previousValue = 0; if(type==0){ previousValue = value+1; } processDisparity( leftOrRight, e.x, cy, value, previousValue, LEFT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( leftOrRight, e.x, cy, value, previousValue, LEFT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( leftOrRight, e.x, cy, value, previousValue, RIGHT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( leftOrRight, e.x, cy, value, previousValue, RIGHT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); // processDisparity( leftOrRight, e.x, cy, value, type, RIGHT, true ); } } else { // System.out.println("processEvent rightPoints add("+e.x+","+cy+") type:"+type); // if(type==1) System.out.println("processEvent rightPoints add("+e.x+","+cy+") type:"+type+" etype1:"+e.getType()+" etype2:"+e.getType()); rightPoints[e.x][cy].updateFrom(e,e.x,cy,RIGHT); // filter if(useFilter){ fastDualLowFilterFrame(rightPoints[e.x][cy], leftPoints, rightPoints ); // fastDualLowFilterFrame(rightPoints[e.x][cy], leftPoints, rightPoints, RIGHT ); // fastDualLowFilterFrame(rightPoints[e.x][cy], rightPoints, leftOrRight, LEFT, true, leftPoints, rightPoints); // fastDualLowFilterFrame(rightPoints2[e.x][cy], rightPoints2, leftOrRight, LEFT, false, leftPoints2, rightPoints2); // fastDualLowFilterFrame(rightPoints[e.x][cy], rightPoints, leftOrRight, RIGHT, true, leftPoints, rightPoints); // fastDualLowFilterFrame(rightPoints2[e.x][cy], rightPoints2, leftOrRight, RIGHT, false, leftPoints2, rightPoints2); } else { // update group label rightPoints[e.x][cy].updateLabel(); value = rightPoints[e.x][cy].getAccValue(currentTime); float previousValue = 0; if(type==0){ previousValue = value+1; } processDisparity( leftOrRight, e.x, cy, value, previousValue, LEFT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( leftOrRight, e.x, cy, value, previousValue, LEFT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( leftOrRight, e.x, cy, value, previousValue, RIGHT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( leftOrRight, e.x, cy, value, previousValue, RIGHT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); // processDisparity( leftOrRight, e.x, cy, value, type, RIGHT, true ); } } } private synchronized int xFromSearchSpace(int x, int y, int z){ return x; } private synchronized int yFromSearchSpace(int x, int y, int z){ int y_rx = rotateYonX( y, z, 0, 0, -retina_tilt_angle); return y_rx; } private synchronized int zFromSearchSpace(int x, int y, int z){ int z_rx = rotateZonX( y, z, 0, 0, -retina_tilt_angle); return z_rx; } private synchronized boolean isInSearchSpace( int x, int y, int z){ boolean res = true; // Paul: to modify since we are now in real 3D, no need for rotation int y_rx = rotateYonX( y, z, 0, 0, -retina_tilt_angle); int z_rx = rotateZonX( y, z, 0, 0, -retina_tilt_angle); // int z_rx2 = rotateZonX( y_rx, z_rx, door_ya, -door_z, platformAngle); // int y_rx2 = rotateYonX( y_rx, z_rx, door_ya, -door_z, platformAngle); // int half = retinaSize/2; // int x_ry = rotateXonY( x, z_rx, half, 180-middleAngle); // int z_ry = rotateZonY( x, z_rx, half, 0, 180-middleAngle); // point must be in front of cage door and above cage's platform // if(z_ry*zDirection<=-door_z){ if(z_rx>(cage_distance+5)*scaleFactor){ res = false; } if(y_rx<-(retina_height-cage_door_height)*scaleFactor + retinaSize/2){ res = false; } // get rid of nose // hack, to parametrize if(y_rx>(grasp_max_elevation-(retina_height-cage_door_height))*scaleFactor){ res = false; } // if(y>door_yc&&z>-door_z-5){ // res = false; return res; } protected int rotateYonX( int y, int z, int yRotationCenter, int zRotationCenter, float angle){ return( Math.round((float) ( (Math.sin(Math.toRadians(angle))*(z-zRotationCenter)) + (Math.cos(Math.toRadians(angle))*(y-yRotationCenter)) ))+yRotationCenter ); } protected int rotateZonX( int y, int z, int yRotationCenter, int zRotationCenter, float angle){ return( Math.round((float) ( (Math.cos(Math.toRadians(angle))*(z-zRotationCenter)) - (Math.sin(Math.toRadians(angle))*(y-yRotationCenter)) ))+zRotationCenter ); } protected int rotateXonY( int x, int z, int xRotationCenter, int zRotationCenter, float angle){ return( Math.round((float) ( (Math.cos(Math.toRadians(angle))*(x-xRotationCenter)) - (Math.sin(Math.toRadians(angle))*(z-zRotationCenter)) ))+xRotationCenter ); } protected int rotateZonY( int x, int z, int xRotationCenter, int zRotationCenter, float angle){ return( Math.round((float) ( (Math.sin(Math.toRadians(angle))*(x-xRotationCenter)) + (Math.cos(Math.toRadians(angle))*(z-zRotationCenter))) )+zRotationCenter ); } protected float distanceBetween( int x1, int y1, int x2, int y2){ double dx = (double)(x1-x2); double dy = (double)(y1-y2); float dist = (float)Math.sqrt((dy*dy)+(dx*dx)); return dist; } protected float distanceBetween( int x1, int y1, int z1, int x2, int y2, int z2){ double dx = (double)(x1-x2); double dy = (double)(y1-y2); double dz = (double)(z1-z2); float dist = (float)Math.sqrt((dy*dy)+(dx*dx)+(dz*dz)); return dist; } protected float direction( float x0, float y0, float x1, float y1 ){ double dx = (double)(x1-x0); double dy = (double)(y1-y0); double size = Math.sqrt((dy*dy)+(dx*dx)); double orientation = Math.toDegrees(Math.acos(dx/size)); if (y0>y1){ orientation = 360-orientation; } return (float)orientation; } protected float orientation( int x0, int y0, int x1, int y1 ){ double dx = (double)(x1-x0); double dy = (double)(y1-y0); double size = Math.sqrt((dy*dy)+(dx*dx)); double orientation = Math.toDegrees(Math.acos(dx/size)); if (y0>y1){ orientation = 180-orientation; } return (float)orientation; } float[] resetDensities( int density ){ float[] densities = new float[density]; for (int k=0;k<density;k++){ densities[k] = (float)k/density; } return densities; } float obtainedDensity( float value, float density, float inverseDensity, float[] densities){ int cat = (int)(value / inverseDensity); float res = 0; if (cat>0){ if(cat>=density){ res = 1; } else { res = densities[cat]; } } return res; } // for optimization, radius2 must be > radius1 // uses global densities and densities2 arrays // leftMost is policy of disparity matching void fastDualLowFilterFrame( EventPoint ep, EventPoint[][] leftPoints, EventPoint[][] rightPoints ){ float dist = 0; float f = 0; // float dr = 0; float sdr = 0; // int cat = 0; // float bn = 0; // float sn = 0; EventPoint[][] eventPoints; int leftOrRight = ep.zDirection; EventPoint[][] leadPoints; EventPoint[][] slavePoints; if(ep.side==LEFT){ eventPoints = leftPoints; } else { eventPoints = rightPoints; } // for all points in square around // if point within circle // add value by distance // number++ // end if // end for // average on number // add to res int i=0; int j=0; int x = ep.x; int y = ep.y; for (i=x-lowFilter_radius; i<x+lowFilter_radius+1;i++){ if(i>=0&&i<retinaSize){ for (j=y-lowFilter_radius; j<y+lowFilter_radius+1;j++){ if(j>=0&&j<retinaSize){ EventPoint influencedPoint = eventPoints[i][j]; // if within circle dist = ((i-x)*(i-x)) + ((j-y)*(j-y)); // smaller range filter influence on neighbour if(dist<shortRadiusSq){ f = 1; sdr = (float)Math.sqrt(dist)/shortFRadius; if (sdr!=0) f = 1/sdr; // do not decay value here : we want to know what was brute value of last update influencedPoint.previousShortFilteredValue = influencedPoint.shortFilteredValue; influencedPoint.previousDecayedFilteredValue = influencedPoint.decayedFilteredValue; //influencedPoint.previousUpdate = influencedPoint.updateTime; influencedPoint.shortFilteredValue += (ep.lastValue * f)/shortRangeTotal; // use get..Value(time) to decay value influencedPoint.decayedFilteredValue = influencedPoint.getDecayedFilteredValue(ep.updateTime) + (ep.lastValue * f)/shortRangeTotal; influencedPoint.updateTime = ep.updateTime; //influencedPoint.updateTime = ep.updateTime; if (influencedPoint.shortFilteredValue<0) { influencedPoint.shortFilteredValue = 0; influencedPoint.decayedFilteredValue = 0; } // update border status // isOnPawShape(influencedPoint,ep.updateTime,eventPoints); // update group label status influencedPoint.updateLabel(); // compute 3D correspondances // if(!useLarge){ processDisparity( ep.side, influencedPoint.x, influencedPoint.y, influencedPoint.shortFilteredValue, influencedPoint.previousShortFilteredValue, LEFT, LEFT_MOST_METHOD, leftPoints, rightPoints); processDisparity( ep.side, influencedPoint.x, influencedPoint.y, influencedPoint.shortFilteredValue, influencedPoint.previousShortFilteredValue, LEFT, RIGHT_MOST_METHOD, leftPoints, rightPoints); processDisparity( ep.side, influencedPoint.x, influencedPoint.y, influencedPoint.shortFilteredValue, influencedPoint.previousShortFilteredValue, RIGHT, LEFT_MOST_METHOD, leftPoints, rightPoints); processDisparity( ep.side, influencedPoint.x, influencedPoint.y, influencedPoint.shortFilteredValue, influencedPoint.previousShortFilteredValue, RIGHT, RIGHT_MOST_METHOD, leftPoints, rightPoints); // processDisparity( leftOrRight, influencedPoint.x, influencedPoint.y, // influencedPoint.shortFilteredValue, // influencedPoint.previousShortFilteredValue, RIGHT, true,leftPoints, rightPoints ); } } } } } } protected float decayedValue( float value, int time ){ float res=value; float dt = (float)time/decayTimeLimit; if(dt<0)dt = -dt; if(dt<1){ res = value * dt; } return res; } void checkPlayerRecorderFrame(){ if(showPlayer && playerRecorderFrame==null) createPlayerRecorderFrame(); } void createPlayerRecorderFrame(){ playerRecorderFrame = new AE3DPlayerRecorderFrame(); playerRecorderFrame.setPlayer(this); playerRecorderFrame.setRecorder(this); // dialogFrame.setPreferredSize(playerRecorderDialog.getPreferredSize()); playerRecorderFrame.pack(); playerRecorderFrame.setVisible(true); } // show 2D view void checkInsideIntensityFrame(){ if(show2DWindow && insideIntensityFrame==null) createInsideIntensityFrame(); } JFrame insideIntensityFrame=null; GLCanvas insideIntensityCanvas=null; private static final GLU glu = new GLU(); int highlight_x = 0; int highlight_y = 0; int highlight_xR = 0; boolean highlight = false; float rotation = 0; // GLUT glut=null; void createInsideIntensityFrame(){ insideIntensityFrame=new JFrame("Combined Frame"); insideIntensityFrame.setPreferredSize(new Dimension(retinaSize*intensityZoom,retinaSize*intensityZoom)); insideIntensityCanvas=new GLCanvas(); insideIntensityCanvas.addKeyListener( new KeyListener(){ /** Handle the key typed event from the text field. */ public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_C){ // show color, red&blue, onlyred, only blue redBlueShown++; if(redBlueShown>3)redBlueShown=0; switch(redBlueShown){ case 0: System.out.println("show red and blue"); break; case 1: System.out.println("show only red (Right)"); break; case 2: System.out.println("show only blue (Left)"); break; case 3: System.out.println("show only correspondances"); break; default:; } insideIntensityCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_M){ // show method method++; if(method>6)method=0; System.out.println("show method:"+method); // switch(method){ // case 0: System.out.println("show left left-most"); break; // case 1: System.out.println("show left right-most"); break; // case 2: System.out.println("show right left-most"); break; // case 3: System.out.println("show onright right-most"); break; // default:; insideIntensityCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_F){ showOnlyAcc=!showOnlyAcc; insideIntensityCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_D){ showDisparity=!showDisparity; insideIntensityCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_T){ testDrawing=!testDrawing; insideIntensityCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_G){ showLabels=!showLabels; insideIntensityCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_SPACE){ // displaytime if(chip.getAeViewer().aePlayer.isPaused()){ chip.getAeViewer().aePlayer.resume(); } else { chip.getAeViewer().aePlayer.pause(); } } } }); insideIntensityCanvas.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { int dx=insideIntensityCanvas.getWidth()-1; int dy=insideIntensityCanvas.getHeight()-1; // 4 is window's border width // int x = Math.round((evt.getX()-4) / intensityZoom); // int y = Math.round((dy-evt.getY()) / intensityZoom); int x = (int)((evt.getX()-3) / intensityZoom); int y = (int)((dy-evt.getY()) / intensityZoom); // System.out.println("got x:"+x+" y:"+y+" from ["+evt.getX()+","+evt.getY()+"]"); // System.out.println("width=" + dx + " heigt="+dy); highlight_x = x; highlight_y = y; if (evt.getButton()==1||evt.getButton()==2){ highlight = true; // GL gl=insideIntensityCanvas.getGL(); } else { highlight = false; } // System.out.println("Selected pixel x,y=" + x + "," + y); int jr = y;// - yRightCorrection; int jl = y;//- yLeftCorrection; if(jr>=0&&jr<retinaSize&&jl>=0&&jl<retinaSize&&x>=0&&x<retinaSize){ EventPoint epL = leftPoints[x][jl]; EventPoint epR = rightPoints[x][jr]; EventPoint epL2 = leftPoints[x][jl]; EventPoint epR2 = rightPoints[x][jr]; float flr=-1; float link=NO_LINK; if (evt.getButton()==1){ switch(method){ case 0: highlight_xR = epL.disparityLink; break; case 1: highlight_xR = epL.disparityLink2; break; case 2: highlight_xR = epR.disparityLink; break; case 3: highlight_xR = epR.disparityLink2; break; default:; } // highlight_xR = epL.disparityLink; // if(highlight_xR>0&&highlight_xR<retinaSize){ // EventPoint epLR = rightPoints[highlight_xR][jr]; // flr = epLR.getValue(currentTime); } else if (evt.getButton()==2){ switch(method){ case 0: highlight_xR = epR.attachedTo; break; case 1: highlight_xR = epR.attachedTo2; break; case 2: highlight_xR = epL.attachedTo; break; case 3: highlight_xR = epL.attachedTo2; break; default:; } // highlight_xR = epR.attachedTo; // if(highlight_xR>0&&highlight_xR<retinaSize){ // EventPoint epLR = leftPoints[highlight_xR][jr]; // flr = epLR.getValue(currentTime); // link = epLR.disparityLink; } float fr=0; float fl=0; fr = epR.getValue(currentTime); fl = epL.getValue(currentTime); float vll = 0; float vlr = 0; float vrl = 0; float vrr = 0; int gll = 0; int glr = 0; int grl = 0; int grr = 0; int dll = NO_LINK,dlr = NO_LINK,drl = NO_LINK,drr = NO_LINK; if(epL.disparityLink>NO_LINK){ dll = epL.disparityLink - x; EventPoint epLk = rightPoints[epL.disparityLink][jl]; vll = epLk.getValue(currentTime); gll = epLk.groupLabel; } if(epL2.disparityLink2>NO_LINK){ dlr = epL2.disparityLink2 - x; EventPoint epL2k = rightPoints[epL2.disparityLink2][jl]; vlr = epL2k.getValue(currentTime); glr = epL2k.groupLabel2; } if(epR.disparityLink>NO_LINK){ drl = epR.disparityLink - x; EventPoint epRk = leftPoints[epR.disparityLink][jr]; vrl = epRk.getValue(currentTime); grl = epRk.groupLabel; } if(epR2.disparityLink2>NO_LINK){ drr = epR2.disparityLink2 - x; EventPoint epR2k = leftPoints[epR2.disparityLink2][jr]; vrr = epR2k.getValue(currentTime); grr = epR2k.groupLabel2; } // if (flr>-1) { if (evt.getButton()==1){ System.out.println("LL("+x+","+jl+")="+fl+" z:"+dll+" linked to ("+epL.disparityLink+","+jl+")="+vll +" label:"+epL.groupLabel+" to label:"+gll); System.out.println("LR("+x+","+jl+")="+fl+" z:"+dlr+" linked to ("+epL2.disparityLink2+","+jl+")="+vlr +" label2:"+epL2.groupLabel2+" to label2:"+glr); System.out.println("RL("+x+","+jr+")="+fr+" z:"+drl+" linked to ("+epR.disparityLink+","+jl+")="+vrl +" label:"+epR.groupLabel+" to label:"+grl); System.out.println("RR("+x+","+jr+")="+fr+" z:"+drr+" linked to ("+epR2.disparityLink2+","+jl+")="+vrr +" label2:"+epR2.groupLabel2+" to label2:"+grr); // System.out.println("Left("+x+","+jl+")=" + fl + " linked to right("+highlight_xR+","+jr+")="+flr); // System.out.println("with z:"+leftPoints[x][y].z+" and z0:"+leftPoints[x][y].z0); } else if (evt.getButton()==2){ // System.out.println("Right("+x+","+jr+")=" + fr + " linked to right("+highlight_xR+","+jl+")="+flr+" dlink:"+link); // System.out.println("with z:"+leftPoints[highlight_xR][y].z+" and z0:"+leftPoints[highlight_xR][y].z0); System.out.println("LL("+x+","+jl+"):"+dll ); System.out.println("LR("+x+","+jl+"):"+dlr ); System.out.println("RL("+x+","+jr+"):"+drl ); System.out.println("RR("+x+","+jr+"):"+drr ); } // } else { // System.out.println("Left("+x+","+jl+")=" + fl + " not linked"); //System.out.println("+ label:"+epL.groupLabel+" label2:"+epL.groupLabel2); // float rt = epR.updateTime; // float lt = epL.updateTime; // System.out.println("left event time:"+lt+" lefttime: "+currentTime); // System.out.println("right event time:"+rt+" righttime: "+currentTime); if(testDrawing){ if (evt.getButton()==1){ leftPoints[x][jl] = new EventPoint(x,jl,1.0f,epR.updateTime); // leftPoints2[x][jl] = new EventPoint(x,jl,1.0f,epR.updateTime); processDisparity( LEFT, x, jl, 1.0f, 0, LEFT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( LEFT, x, jl, 1.0f, 0, LEFT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( LEFT, x, jl, 1.0f, 0, RIGHT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( LEFT, x, jl, 1.0f, 0, RIGHT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); } else if (evt.getButton()==2){ rightPoints[x][jl] = new EventPoint(x,jl,1.0f,epR.updateTime); // rightPoints2[x][jl] = new EventPoint(x,jl,1.0f,epR.updateTime); processDisparity( RIGHT, x, jl, 1.0f, 0, LEFT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( RIGHT, x, jl, 1.0f, 0, LEFT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( RIGHT, x, jl, 1.0f, 0, RIGHT, LEFT_MOST_METHOD,leftPoints, rightPoints ); processDisparity( RIGHT, x, jl, 1.0f, 0, RIGHT, RIGHT_MOST_METHOD,leftPoints, rightPoints ); } else if (evt.getButton()==0){ leftPoints[x][jl] = new EventPoint(x,jl,0.0f,epR.updateTime); // leftPoints2[x][jl] = new EventPoint(x,jl,0.0f,epR.updateTime); rightPoints[x][jl] = new EventPoint(x,jl,0.0f,epR.updateTime); // rightPoints2[x][jl] = new EventPoint(x,jl,0.0f,epR.updateTime); } } } if(showCorrectionMatrix){ if(y>=0&&y<retinaSize&&x>=0&&x<retinaSize){ if(correctionMatrix==null){ System.out.println("correctionMatrix==null"); } else { System.out.println("correctionMatrix value="+correctionMatrix[x][y]); } } else { System.out.println("out of correctionMatrix bound"); } } insideIntensityCanvas.display(); } public void mouseReleased(MouseEvent e){ } }); insideIntensityCanvas.addGLEventListener(new GLEventListener(){ public void init(GLAutoDrawable drawable) { } private void drawIntMatrix( int[][] intMatrix, GL gl) { for (int i = 0; i<intMatrix.length; i++){ for (int j = 0; j<intMatrix[i].length; j++){ float f = 0; if(showCorrectionGradient){ // to get it in gradient f = (float)intMatrix[i][j]/(float)retinaSize; // to get it in gradient gl.glColor3f(f,f,f); } else { f = (float)intMatrix[i][j]; if(f>0){ if (f%2==0) gl.glColor3f(1,1,1); else gl.glColor3f(0,0,0); } } gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } } } private void drawEventPoints( EventPoint[][] eventPoints, GL gl, int currentTime, boolean left, int yCorrection, boolean useFirst ){ // System.out.println("1. display drawEventPoints time: "+currentTime+" length: "+eventPoints.length); int dLink = NO_LINK; for (int i = 0; i<eventPoints.length; i++){ for (int j = 0; j<eventPoints[i].length; j++){ EventPoint ep = eventPoints[i][j]; if(ep==null)break; float f=0; float b=0; float g=0; float r=0; // f = ep.accValue - decayedValue(ep.accValue,currentTime-ep.updateTime); if (showOnlyAcc) { f = ep.getAccValue(currentTime); } else { // if(showSecondFilter){ // f = ep.largeFilteredValue; // } else { // f = ep.getValue(currentTime); // f = ep.getShortFilteredValue(currentTime); f = ep.getValue(currentTime); } if(f>valueThreshold){ f = f*brightness; if(!showRLColors){ gl.glColor3f(f,f,f); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } else { if(left){ dLink = NO_LINK; if(useFirst) dLink = ep.disparityLink; else dLink = ep.disparityLink2; // System.out.println("left:"+left+" value("+i+","+j+"):"+f); if(redBlueShown==0||redBlueShown==2){ if(dLink>NO_LINK&&showDisparity){ gl.glColor3f(0.117f,0.565f,f); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } else { gl.glColor3f(0,0,f); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } if(showLabels){ float red = redFromLabel(ep.groupLabel.intValue()); float green = greenFromLabel(ep.groupLabel.intValue()); float blue = blueFromLabel(ep.groupLabel.intValue()); gl.glColor3f(red,green,blue); // gl.glColor3f(1,1,1); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } } else if(redBlueShown==3){ if(dLink>NO_LINK){ gl.glColor3f(0.117f,0.565f,f); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } // gl.glColor3f(0,0,f); // gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); if(showLabels){ float red = redFromLabel(ep.groupLabel.intValue()); float green = greenFromLabel(ep.groupLabel.intValue()); float blue = blueFromLabel(ep.groupLabel.intValue()); gl.glColor3f(red,green,blue); // gl.glColor3f(1,1,1); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } } } else { dLink = NO_LINK; if(useFirst) dLink = ep.attachedTo; else dLink = ep.attachedTo2; if(redBlueShown==0||redBlueShown==1){ if(dLink>NO_LINK&&showDisparity){ gl.glColor3f(f,0.5f,0); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } else { gl.glColor3f(f,0,0); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } if(showLabels){ float red = redFromLabel(ep.groupLabel.intValue()); float green = greenFromLabel(ep.groupLabel.intValue()); float blue = blueFromLabel(ep.groupLabel.intValue()); gl.glColor3f(red,green,blue); // gl.glColor3f(1,1,1); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } } else if(redBlueShown==3){ if(dLink>NO_LINK){ gl.glColor3f(f,0.5f,0); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } //gl.glColor3f(f,0,0); //gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); if(showLabels){ float red = redFromLabel(ep.groupLabel.intValue()); float green = greenFromLabel(ep.groupLabel.intValue()); float blue = blueFromLabel(ep.groupLabel.intValue()); gl.glColor3f(red,green,blue); // gl.glColor3f(1,1,1); gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } } } } // gl.glRectf(i*intensityZoom,(j+yCorrection)*intensityZoom,(i+1)*intensityZoom,(j+yCorrection+1)*intensityZoom); // gl.glRectf(i*intensityZoom,(j)*intensityZoom,(i+1)*intensityZoom,(j+1)*intensityZoom); } } } } float redFromLabel( int label ){ if (label==0) return 0f; while(label>4){ label-=4; } if (label==0) return 0.5f; if (label==1) return 0.25f; if (label==2) return 0.5f; if (label==3) return 0.75f; if (label==4) return 1f; return 0; } float greenFromLabel( int label ){ if (label==0) return 0f; while(label>4){ label-=4; } if (label==0) return 0.2f; if (label==1) return 0f; if (label==2) return 0.5f; if (label==3) return 0.5f; if (label==4) return 0f; return 0; } float blueFromLabel( int label ){ if (label==0) return 0f; while(label>4){ label-=4; } if (label==0) return 1f; if (label==1) return 0.75f; if (label==2) return 0.75f; if (label==3) return 0.5f; if (label==4) return 0f; return 0; } synchronized public void display(GLAutoDrawable drawable) { GL gl=drawable.getGL(); gl.glLoadIdentity(); //gl.glScalef(drawable.getWidth()/2000,drawable.getHeight()/180,1);//dist to gc, orientation? gl.glClearColor(0,0,0,0); gl.glClear(GL.GL_COLOR_BUFFER_BIT); int font = GLUT.BITMAP_HELVETICA_12; // display inside intensity // System.out.println("display left - right"); if(showCorrectionMatrix){ drawIntMatrix(correctionMatrix,gl); } else { //if(showAcc){ // System.out.println("display left - right showAcc"); // drawEventPoints(leftPoints,gl,currentTime,true,0); if(method==0||method==4||method==6){ if(leftPoints!=null){ // System.out.println("display left "); drawEventPoints(leftPoints,gl,currentTime,true,yLeftCorrection,true); } else { System.out.println("ERROR: 3DSTatic Display: leftPoints is null"); } if(rightPoints!=null){ // System.out.println("display right "); drawEventPoints(rightPoints,gl,currentTime,false,yRightCorrection,true); } else { System.out.println("ERROR: 3DSTatic Display: rightPoints is null"); } } if(method==1||method==4||method==6){ if(leftPoints!=null){ // System.out.println("display left "); drawEventPoints(leftPoints,gl,currentTime,true,yLeftCorrection,false); } else { System.out.println("ERROR: 3DSTatic Display: leftPoints is null"); } if(rightPoints!=null){ // System.out.println("display right "); drawEventPoints(rightPoints,gl,currentTime,false,yRightCorrection,false); } else { System.out.println("ERROR: 3DSTatic Display: rightPoints is null"); } } if(method==2||method==5||method==6){ if(leftPoints!=null){ // System.out.println("display left "); drawEventPoints(leftPoints,gl,currentTime,false,yLeftCorrection,true); } else { System.out.println("ERROR: 3DSTatic Display: leftPoints is null"); } if(rightPoints!=null){ // System.out.println("display right "); drawEventPoints(rightPoints,gl,currentTime,true,yRightCorrection,true); } else { System.out.println("ERROR: 3DSTatic Display: rightPoints is null"); } } if(method==3||method==5||method==6){ if(leftPoints!=null){ // System.out.println("display left "); drawEventPoints(leftPoints,gl,currentTime,false,yLeftCorrection,false); } else { System.out.println("ERROR: 3DSTatic Display: leftPoints is null"); } if(rightPoints!=null){ // System.out.println("display right "); drawEventPoints(rightPoints,gl,currentTime,true,yRightCorrection,false); } else { System.out.println("ERROR: 3DSTatic Display: rightPoints is null"); } } } if(highlight){ gl.glColor3f(1,1,0); gl.glRectf(highlight_x*intensityZoom,highlight_y*intensityZoom,(highlight_x+1)*intensityZoom,(highlight_y+1)*intensityZoom); gl.glColor3f(0,1,0); gl.glRectf(highlight_xR*intensityZoom,highlight_y*intensityZoom,(highlight_xR+1)*intensityZoom,(highlight_y+1)*intensityZoom); } int error=gl.glGetError(); if(error!=GL.GL_NO_ERROR){ // if(glu==null) glu=new GLU(); //log.warning("GL error number "+error+" "+glu.gluErrorString(error)); } } synchronized public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL gl=drawable.getGL(); final int B=10; gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); // very important to load identity matrix here so this works after first resize!!! gl.glOrtho(-B,drawable.getWidth()+B,-B,drawable.getHeight()+B,10000,-10000); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glViewport(0,0,width,height); } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } }); insideIntensityFrame.getContentPane().add(insideIntensityCanvas); insideIntensityFrame.pack(); insideIntensityFrame.setVisible(true); } // show 3D view void check3DFrame(){ if(show3DWindow && a3DFrame==null||show3DWindow && windowDeleted) { windowDeleted = false; create3DFrame(); } } JFrame a3DFrame=null; GLCanvas a3DCanvas=null; int dragOrigX =0; int dragOrigY =0; int dragDestX =0; int dragDestY =0; boolean leftDragged = false; // boolean rightDragreleased = false; float tx =0; float ty =0; float origX=0; float origY=0; float origZ=0; float tz = 0; int rdragOrigX =0; int rdragOrigY =0; int rdragDestX =0; int rdragDestY =0; boolean rightDragged = false; float rtx =0; float rty =0; float rOrigX=0; float rOrigY=0; boolean middleDragged = false; float zOrigY=0; int zdragOrigY =0; int zdragDestY =0; float zty =0; // keyboard rotation float krx = 0; float kry = 0; // GLUT glut=null; void create3DFrame(){ a3DFrame=new JFrame("3D Frame"); a3DFrame.setPreferredSize(new Dimension(retinaSize*intensityZoom,retinaSize*intensityZoom)); a3DFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { Frame frame = (Frame)evt.getSource(); // Hide the frame frame.setVisible(false); // If the frame is no longer needed, call dispose frame.dispose(); windowDeleted = true; show3DWindow = false; } }); a3DCanvas=new GLCanvas(); a3DCanvas.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); int but1mask = InputEvent.BUTTON1_DOWN_MASK; int but2mask = InputEvent.BUTTON2_DOWN_MASK; int but3mask = InputEvent.BUTTON3_DOWN_MASK; if ((e.getModifiersEx()&but1mask)==but1mask){ if(e.getClickCount()==2){ // reset tx =0; ty =0; origX=0; origY=0; origZ=0; rtx =0; rty =0; rOrigX=0; rOrigY=0; tz = 0; zty = 0; zOrigY=0; } else { // get final x,y for translation dragOrigX = x; dragOrigY = y; } // System.out.println(" x:"+x+" y:"+y); // System.out.println("Left mousePressed tx:"+tx+" ty:"+ty+" origX:"+origX+" origY:"+origY); } else if ((e.getModifiersEx()&but2mask)==but2mask){ // get final x,y for depth translation zdragOrigY = y; // System.out.println(" x:"+x+" y:"+y); // System.out.println("Middle mousePressed y:"+y+" zty:"+zty+" zOrigY:"+zOrigY); }else if ((e.getModifiersEx()&but3mask)==but3mask){ // get final x,y for rotation rdragOrigX = x; rdragOrigY = y; // System.out.println(" x:"+x+" y:"+y); // System.out.println("Right mousePressed rtx:"+rtx+" rty:"+rty+" rOrigX:"+rOrigX+" rOrigY:"+rOrigY); } // a3DCanvas.display(); } public void mouseReleased(MouseEvent e){ int x = e.getX(); int y = e.getY(); // int but1mask = InputEvent.BUTTON1_DOWN_MASK, but3mask = InputEvent.BUTTON3_DOWN_MASK; if(e.getButton()==MouseEvent.BUTTON1){ origX += tx; origY += ty; tx = 0; ty = 0; leftDragged = false; // dragreleased = true; a3DCanvas.display(); //System.out.println("Left mouseReleased tx:"+tx+" ty:"+ty+" origX:"+origX+" origY:"+origY); } else if(e.getButton()==MouseEvent.BUTTON2){ zOrigY += zty; zty = 0; middleDragged = false; a3DCanvas.display(); // System.out.println("Middle mouseReleased zty:"+zty+" zOrigY:"+zOrigY); } else if(e.getButton()==MouseEvent.BUTTON3){ rOrigX += rtx; rOrigY += rty; rtx = 0; rty = 0; rightDragged = false; // dragreleased = true; a3DCanvas.display(); // System.out.println("Right mouseReleased tx:"+tx+" ty:"+ty+" origX:"+origX+" origY:"+origY); } } }); a3DCanvas.addMouseMotionListener(new MouseMotionListener(){ public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); int but1mask = InputEvent.BUTTON1_DOWN_MASK; int but2mask = InputEvent.BUTTON2_DOWN_MASK; int but3mask = InputEvent.BUTTON3_DOWN_MASK; if ((e.getModifiersEx()&but1mask)==but1mask){ // get final x,y for translation dragDestX = x; dragDestY = y; leftDragged = true; a3DCanvas.display(); } else if ((e.getModifiersEx()&but2mask)==but2mask){ // get final x,y for translation zdragDestY = y; middleDragged = true; a3DCanvas.display(); } else if ((e.getModifiersEx()&but3mask)==but3mask){ // get final x,y for translation rdragDestX = x; rdragDestY = y; rightDragged = true; a3DCanvas.display(); } } public void mouseMoved(MouseEvent e) { } }); a3DCanvas.addMouseWheelListener(new MouseWheelListener(){ public void mouseWheelMoved(MouseWheelEvent e) { int notches = e.getWheelRotation(); tz += notches; //System.out.println("mouse wheeled tz:"+tz); a3DCanvas.display(); } }); a3DCanvas.addKeyListener( new KeyListener(){ /** Handle the key typed event from the text field. */ public void keyTyped(KeyEvent e) { } /** Handle the key-pressed event from the text field. */ public void keyPressed(KeyEvent e) { //System.out.println("event time: "+e.getWhen()+ " system time:"+ System.currentTimeMillis()); if(System.currentTimeMillis()-e.getWhen()<100){ if(e.getKeyCode()==KeyEvent.VK_LEFT){ // move krx-=3;//speed a3DCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_RIGHT){ // move krx+=3; a3DCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_DOWN){ // move kry-=3; a3DCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_UP){ // move kry+=3; a3DCanvas.display(); } } } /** Handle the key-released event from the text field. */ public void keyReleased(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_T){ // displaytime System.out.println("current time: "+currentTime); } if(e.getKeyCode()==KeyEvent.VK_SPACE){ // displaytime if(chip.getAeViewer().aePlayer.isPaused()){ chip.getAeViewer().aePlayer.resume(); } else { chip.getAeViewer().aePlayer.pause(); } } if(e.getKeyCode()==KeyEvent.VK_R){ // show color, red&blue, onlyred, only blue display3DChoice++; if(display3DChoice>9)display3DChoice=0; switch(display3DChoice){ case 0: System.out.println("show all"); break; //not bad with average mode on and fuse mode off case 1: System.out.println("show left leader, left most and right most"); break; case 2: System.out.println("show left leader, left most"); break; case 3: System.out.println("show left leader, right most"); break; case 4: System.out.println("show right leader, left most and right most"); break; case 5: System.out.println("show right leader, left most"); break; case 6: System.out.println("show right leader, right most"); break; case 7: System.out.println("show average of all"); break;//inefficient yet case 8: System.out.println("show left and right, left most"); break; case 9: System.out.println("show left and right, right most"); break; default:; } a3DCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_I){ // show color, red&blue, onlyred, only blue displaySign++; if(displaySign>2)displaySign=0; } if(e.getKeyCode()==KeyEvent.VK_S){ searchSpaceMode = !searchSpaceMode; a3DCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_D){ clearSpaceMode = !clearSpaceMode; a3DCanvas.display(); } if(e.getKeyCode()==KeyEvent.VK_B){ // show color, red&blue, onlyred, only blue testChoice++; if(testChoice>7)testChoice=0; System.out.println("testChoice=="+testChoice); a3DCanvas.display(); } } }); a3DCanvas.addGLEventListener(new GLEventListener(){ public void init(GLAutoDrawable drawable) { } // private void draw3DDisparityPacket(GL gl, AEPacket3D packet){ // // for all events in packet, // // display // int n=packet.getNumEvents(); // float b = 0.1f*brightness; // float fx = 0; // float fy = 0; // float fz = 0; // int x = 0; // int y = 0; // int z = 0; // for(int i=0;i<n;i++){ // float f = packet.getValues()[i]; // x = packet.getCoordinates3D_x()[i]; // y = packet.getCoordinates3D_y()[i]; // z = packet.getCoordinates3D_z()[i]; // if(showXColor){ // fx = colorizeFactor*(x%colorizePeriod); // } else { // fx = f; // if(showYColor){ // fy = colorizeFactor*(y%colorizePeriod); // } else { // fy = f; // if(showZColor){ // fz = colorizeFactor*((retinaSize-z)%colorizePeriod); // } else { // fz = f; // shadowCube(gl, x, y, z*zFactor, // cube_size, fz+b, fy+b, fx+b, alpha, shadowFactor); // // shadowCube(gl, x, y, z*zFactor, // // cube_size, 1, 1, 1, 1, 0); // } // end for // packetDisplayed = true; /** draw points in 3D directly from preprocessed recorded data **/ private void draw3DDisplayPacket( GL gl, int currentTime ){ int x = 0; int y = 0; int z = 0; float f = 0; float fx = 0; float fy = 0; float fz = 0; // for all events in hashtable where key is x-y-z synchronized(direct3DEvents){ Event3D ev; Iterator it = direct3DEvents.keySet().iterator(); try { while(it.hasNext()){ //if(subsamplingPlayBackOfPure3D){ // implement it, by zapping some events ev = (Event3D)direct3DEvents.get((String)it.next()); x = ev.x0; y = ev.y0; z = ev.z0; f = ev.value; /* if(showXColor){ fx = colorizeFactor*(x%colorizePeriod); } else { fx = f; } if(showYColor){ fy = colorizeFactor*(y%colorizePeriod); } else { fy = f; } if(showZColor){ fz = colorizeFactor*((retinaSize-z)%colorizePeriod); } else { fz = f; } **/ float b = 0.1f*brightness; // display if(clearSpaceMode){ if(isInSearchSpace(x,y,z)){ if(searchSpaceMode){ int xsp = xFromSearchSpace(x,y,z); int ysp = yFromSearchSpace(x,y,z); int zsp = zFromSearchSpace(x,y,z); x = xsp; y = ysp; z = zsp; } // shadowCube(gl, x, y, z*zFactor, cube_size, fz+b, fy+b, fx+b, alpha, shadowFactor); shadowCube(gl, x, y, z*zFactor, cube_size, f+b, f+b, f+b, alpha, shadowFactor); } } else { // shadowCube(gl, x, y, z*zFactor, cube_size, fz+b, fy+b, fx+b, alpha, shadowFactor); shadowCube(gl, x, y, z*zFactor, cube_size, f+b, f+b, f+b, alpha, shadowFactor); } } } catch (java.util.ConcurrentModificationException e){ // hashtable updated at same time, exit System.err.println(e.getMessage()); return; } } } /** draw points in 3D from the two retina arrays and the information about matched disparities **/ private void draw3DDisparityPoints( GL gl, EventPoint leadPoints[][], int method, int leadTime, EventPoint slavePoints[][], int slaveTime, int zDirection ){ int z = 0; float fx = 0; float fy = 0; float fz = 0; float dl = 0; float dr = 0; int dx = NO_LINK; int dx1 = NO_LINK; int dx2 = NO_LINK; int dxL = NO_LINK; int z0 = 0; int x0 = 0; int z1 = 0; int x1 = 0; int y1 = 0; // System.out.println("draw3DDisparityPoints"); // System.out.println("draw3DDisparityPoints at "+leadTime); int half = retinaSize/2; for(int x=0;x<leadPoints.length;x++){ for(int y=0;y<leadPoints[x].length;y++){ boolean go = true; if(leadPoints[x][y]==null){ // System.out.println("leftpoints["+x+"]["+y+"] null"); go = false; } else { if(leadPoints[x][y].getValue(leadTime)<valueThreshold){ // System.out.println("leadpoints["+x+"]["+y+"] value:"+leadPoints[x][y].getValue(leadTime)+" threshold:"+valueThreshold); // break; go = false; } if(displaySign>0){ if(displaySign==1&&leadPoints[x][y].sign==-1){ go = false; } else if(displaySign==2&&leadPoints[x][y].sign==1){ go = false; } } } if(go){ if(method==LEFT_MOST_METHOD) { dx = leadPoints[x][y].disparityLink; } else { dx = leadPoints[x][y].disparityLink2; } if(dx>NO_LINK){ x0 = leadPoints[x][y].getX0(method); y1 = leadPoints[x][y].getY0(method); z0 = leadPoints[x][y].getZ0(method); // if(x0==0&&y1==0&&z0==0){ // System.out.println("zero for x:"+x+" y:"+y+" dx:"+dx); // if(searchSpaceMode){ // int x0sp = xFromSearchSpace(x0,y,z0,zDirection); // int ysp = yFromSearchSpace(x0,y,z0,zDirection); // int z0sp = zFromSearchSpace(x0,y,z0,zDirection); // x0 = x0sp; // y1 = ysp; // z0 = z0sp; //debug // leftPoints[x][y].z0=z0; boolean highlighted = false; if(highlight){ //if(x==highlight_x&&y+yLeftCorrection==highlight_y){ if(x==highlight_x&&y==highlight_y){ shadowCube(gl, x0, y1, z0*zFactor, cube_size, 1, 1, 0, 1, shadowFactor); // + rays gl.glColor3f(1.0f,1.0f,0.0f); line3D( gl, leadPoints[x][y].xr, leadPoints[x][y].yr, leadPoints[x][y].zr, x0, y1, z0*zFactor); line3D( gl, slavePoints[dx][y].xr, slavePoints[dx][y].yr, slavePoints[dx][y].zr, x0, y1, z0*zFactor); highlighted = true; } } if (!highlighted){ //gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA); //gl.glEnable(gl.GL_BLEND); try { dl = leadPoints[x][y].getValue(leadTime); // or getAccValue()? dr = slavePoints[dx][y].getValue(slaveTime); float f = (dl+dr)/2; //f = f*brightness; if(colorizePeriod<1)colorizePeriod=1; if(showXColor){ fx = colorizeFactor*(x%colorizePeriod); } else { fx = f; } if(showYColor){ fy = colorizeFactor*(y%colorizePeriod); } else { fy = f; } if(showZColor){ fz = colorizeFactor*((retinaSize-z)%colorizePeriod); } else { fz = f; } float b = 0.1f*brightness; float db = 0; // float dt = leadTime - leadPoints[x][y].updateTime; // db = 1 - (decayTimeLimit - dt); // if(db<0) db = 0; if(highlightDecay){ db = 1 - decayedValue(1,leadTime - leadPoints[x][y].updateTime); } int tt = leadTime - leadPoints[x][y].updateTime; // System.out.println("> draw3DDisparityPoints diff "+tt); // System.out.println("draw3DDisparityPoints shadowCube "+f); if(clearSpaceMode){ if(isInSearchSpace(x0,y1,z0)){ if(searchSpaceMode){ int x0sp = xFromSearchSpace(x0,y1,z0); int ysp = yFromSearchSpace(x0,y1,z0); int z0sp = zFromSearchSpace(x0,y1,z0); x0 = x0sp; y1 = ysp; z0 = z0sp; } shadowCube(gl, x0, y1, z0*zFactor, cube_size, fz+b+db, fy+b+db, fx+b, alpha, shadowFactor); } } else { // if(searchSpaceMode){ // int x0sp = xFromSearchSpace(x0,y,z0,zDirection); // int ysp = yFromSearchSpace(x0,y,z0,zDirection); // int z0sp = zFromSearchSpace(x0,y,z0,zDirection); // x0 = x0sp; // y1 = ysp; // z0 = z0sp; // display test with sign //? to test again int sign = leadPoints[x][y].sign; if(sign>0) shadowCube(gl, x0, y1, z0*zFactor, cube_size, fz+b+db, fy+b+db, fx+b, alpha, shadowFactor); else shadowCube(gl, x0, y1, z0*zFactor, cube_size, fy+b+db, fx+b+db, fz+b, alpha, shadowFactor); } } catch(java.lang.NullPointerException ne){ System.err.println(ne.getMessage()+" x:"+x+" y:"+y+" dx:"+dx); } } } else if (dx==DELETE_LINK){ // if just removed if(method==LEFT_MOST_METHOD){ leadPoints[x][y].disparityLink = NO_LINK; } else { leadPoints[x][y].disparityLink2 = NO_LINK; } } } } // end if go } } private void draw3DAxes( GL gl ){ // gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA); // gl.glEnable(gl.GL_BLEND); // gl.glColor4f(0.0f,1.0f,0.0f,0.2f); //x gl.glColor3f(0.0f,1.0f,0.0f); line3D( gl, 0, 0, 0, 200 ,0 ,0); // gl.glColor4f(0.0f,1.0f,0.0f,0.2f); //y gl.glColor3f(0.0f,1.0f,0.0f); line3D( gl, 0, 0, 0, 0 , 200 ,0); // line3D ( gl, retinaSize/2, 5, 0, retinaSize/2 , 5 ,0); // gl.glColor4f(1.0f,0.0f,0.0f,0.2f); //z gl.glColor3f(1.0f,0.0f,0.0f); line3D( gl, 0, 0, 0, 0 ,0 ,200); // gl.glDisable(gl.GL_BLEND); } private void draw3DFrames( GL gl ){ // int half = retinaSize/2; // System.out.println("middleAngle for planeAngle("+planeAngle+")= "+middleAngle); if(showRetina){ gl.glColor3f(0.0f,0.0f,1.0f); line3D( gl, leftPoints[0][0].xr, leftPoints[0][0].yr, leftPoints[0][0].zr, leftPoints[0][retinaSize-1].xr, leftPoints[0][retinaSize-1].yr, leftPoints[0][retinaSize-1].zr); line3D( gl, leftPoints[0][0].xr, leftPoints[0][0].yr, leftPoints[0][0].zr, leftPoints[retinaSize-1][0].xr, leftPoints[retinaSize-1][0].yr, leftPoints[retinaSize-1][0].zr); line3D( gl, leftPoints[0][retinaSize-1].xr, leftPoints[0][retinaSize-1].yr, leftPoints[0][retinaSize-1].zr, leftPoints[retinaSize-1][retinaSize-1].xr, leftPoints[retinaSize-1][retinaSize-1].yr, leftPoints[retinaSize-1][retinaSize-1].zr); line3D( gl, leftPoints[retinaSize-1][0].xr, leftPoints[retinaSize-1][0].yr, leftPoints[retinaSize-1][0].zr, leftPoints[retinaSize-1][retinaSize-1].xr, leftPoints[retinaSize-1][retinaSize-1].yr, leftPoints[retinaSize-1][retinaSize-1].zr); line3D( gl, rightPoints[0][0].xr, rightPoints[0][0].yr, rightPoints[0][0].zr, rightPoints[0][retinaSize-1].xr, rightPoints[0][retinaSize-1].yr, rightPoints[0][retinaSize-1].zr); line3D( gl, rightPoints[0][0].xr, rightPoints[0][0].yr, rightPoints[0][0].zr, rightPoints[retinaSize-1][0].xr, rightPoints[retinaSize-1][0].yr, rightPoints[retinaSize-1][0].zr); line3D( gl, rightPoints[0][retinaSize-1].xr, rightPoints[0][retinaSize-1].yr, rightPoints[0][retinaSize-1].zr, rightPoints[retinaSize-1][retinaSize-1].xr, rightPoints[retinaSize-1][retinaSize-1].yr, rightPoints[retinaSize-1][retinaSize-1].zr); line3D( gl, rightPoints[retinaSize-1][0].xr, rightPoints[retinaSize-1][0].yr, rightPoints[retinaSize-1][0].zr, rightPoints[retinaSize-1][retinaSize-1].xr, rightPoints[retinaSize-1][retinaSize-1].yr, rightPoints[retinaSize-1][retinaSize-1].zr); shadowCube(gl, left_focal_x, left_focal_y, left_focal_z, 10, 0, 1, 0, 0.5f, 0); shadowCube(gl, right_focal_x, right_focal_y, right_focal_z, 10, 0, 1, 0, 0.5f, 0); } // blue frame if(showCage){ gl.glColor3f(0.0f,0.0f,1.0f); // blue color line3D( gl, cage.p1.x, cage.p1.y, cage.p1.z, cage.p2.x, cage.p2.y, cage.p2.z); line3D( gl, cage.p1.x, cage.p1.y, cage.p1.z, cage.p3.x, cage.p3.y, cage.p3.z); line3D( gl, cage.p2.x, cage.p2.y, cage.p2.z, cage.p4.x, cage.p4.y, cage.p4.z); line3D( gl, cage.p3.x, cage.p3.y, cage.p3.z, cage.p4.x, cage.p4.y, cage.p4.z); // cage line3D( gl, cage.p5.x, cage.p5.y, cage.p5.z, cage.p6.x, cage.p6.y, cage.p6.z); line3D( gl, cage.p5.x, cage.p5.y, cage.p5.z, cage.p7.x, cage.p7.y, cage.p7.z); line3D( gl, cage.p6.x, cage.p6.y, cage.p6.z, cage.p8.x, cage.p8.y, cage.p8.z); line3D( gl, cage.p9.x, cage.p9.y, cage.p9.z, cage.p10.x, cage.p10.y, cage.p10.z); line3D( gl, cage.p9.x, cage.p9.y, cage.p9.z, cage.p11.x, cage.p11.y, cage.p11.z); line3D( gl, cage.p10.x, cage.p10.y, cage.p10.z, cage.p12.x, cage.p12.y, cage.p12.z); line3D( gl, cage.p11.x, cage.p11.y, cage.p11.z, cage.p12.x, cage.p12.y, cage.p12.z); } if(showZones){ gl.glColor3f(1.0f,1.0f,0.0f); // yellow color line3D( gl, searchSpace.p1.x, searchSpace.p1.y, searchSpace.p1.z, searchSpace.p2.x, searchSpace.p2.y, searchSpace.p2.z); line3D( gl, searchSpace.p1.x, searchSpace.p1.y, searchSpace.p1.z, searchSpace.p3.x, searchSpace.p3.y, searchSpace.p3.z); line3D( gl, searchSpace.p2.x, searchSpace.p2.y, searchSpace.p2.z, searchSpace.p4.x, searchSpace.p4.y, searchSpace.p4.z); line3D( gl, searchSpace.p3.x, searchSpace.p3.y, searchSpace.p3.z, searchSpace.p4.x, searchSpace.p4.y, searchSpace.p4.z); line3D( gl, searchSpace.p5.x, searchSpace.p5.y, searchSpace.p5.z, searchSpace.p6.x, searchSpace.p6.y, searchSpace.p6.z); line3D( gl, searchSpace.p5.x, searchSpace.p5.y, searchSpace.p5.z, searchSpace.p7.x, searchSpace.p7.y, searchSpace.p7.z); line3D( gl, searchSpace.p6.x, searchSpace.p6.y, searchSpace.p6.z, searchSpace.p8.x, searchSpace.p8.y, searchSpace.p8.z); line3D( gl, searchSpace.p7.x, searchSpace.p7.y, searchSpace.p7.z, searchSpace.p8.x, searchSpace.p8.y, searchSpace.p8.z); line3D( gl, searchSpace.p1.x, searchSpace.p1.y, searchSpace.p1.z, searchSpace.p5.x, searchSpace.p5.y, searchSpace.p5.z); line3D( gl, searchSpace.p2.x, searchSpace.p2.y, searchSpace.p2.z, searchSpace.p6.x, searchSpace.p6.y, searchSpace.p6.z); line3D( gl, searchSpace.p3.x, searchSpace.p3.y, searchSpace.p3.z, searchSpace.p7.x, searchSpace.p7.y, searchSpace.p7.z); line3D( gl, searchSpace.p4.x, searchSpace.p4.y, searchSpace.p4.z, searchSpace.p8.x, searchSpace.p8.y, searchSpace.p8.z); } // gl.glFlush(); } private void line3D(GL gl, float x, float y, float z, float x2, float y2, float z2) { gl.glBegin(gl.GL_LINES); gl.glVertex3f( x,y,z); gl.glVertex3f( x2,y2,z2); gl.glEnd(); } private void shadowCube(GL gl, float x, float y, float z, float size, float r, float g, float b, float alpha, float shadow) { gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA); gl.glEnable(gl.GL_BLEND); gl.glBegin(gl.GL_QUADS); // Draw The Cube Using quads // light gl.glColor4f(r,g,b,alpha); gl.glVertex3f( x+size, y+size,z-size); // Top Right Of The Quad (Top) gl.glVertex3f(x-size, y+size,z-size); // Top Left Of The Quad (Top) gl.glVertex3f(x-size, y+size, z+size); // Bottom Left Of The Quad (Top) gl.glVertex3f( x+size, y+size, z+size); // Bottom Right Of The Quad (Top) gl.glVertex3f( x+size, y+size,z-size); // Top Right Of The Quad (Right) gl.glVertex3f( x+size, y+size, z+size); // Top Left Of The Quad (Right) gl.glVertex3f( x+size,y-size, z+size); // Bottom Left Of The Quad (Right) gl.glVertex3f( x+size,y-size,z-size); // Bottom Right Of The Quad (Right) gl.glVertex3f( x+size, y+size, z+size); // Top Right Of The Quad (Front) gl.glVertex3f(x-size, y+size, z+size); // Top Left Of The Quad (Front) gl.glVertex3f(x-size,y-size, z+size); // Bottom Left Of The Quad (Front) gl.glVertex3f( x+size,y-size, z+size); // Bottom Right Of The Quad (Front) // shade gl.glColor4f(r-shadow,g-shadow,b-shadow,alpha); gl.glVertex3f( x+size,y-size, z+size); // Top Right Of The Quad (Bottom) gl.glVertex3f(x-size,y-size, z+size); // Top Left Of The Quad (Bottom) gl.glVertex3f(x-size,y-size,z-size); // Bottom Left Of The Quad (Bottom) gl.glVertex3f( x+size,y-size,z-size); // Bottom Right Of The Quad (Bottom) gl.glVertex3f( x+size,y-size,z-size); // Top Right Of The Quad (Back) gl.glVertex3f(x-size,y-size,z-size); // Top Left Of The Quad (Back) gl.glVertex3f(x-size, y+size,z-size); // Bottom Left Of The Quad (Back) gl.glVertex3f( x+size, y+size,z-size); // Bottom Right Of The Quad (Back) gl.glVertex3f(x-size, y+size, z+size); // Top Right Of The Quad (Left) gl.glVertex3f(x-size, y+size,z-size); // Top Left Of The Quad (Left) gl.glVertex3f(x-size,y-size,z-size); // Bottom Left Of The Quad (Left) gl.glVertex3f(x-size,y-size, z+size); // Bottom Right Of The Quad (Left) gl.glEnd(); gl.glDisable(gl.GL_BLEND); } private void cube(GL gl, float x, float y, float z, float size) { // gl.glTranslatef(100.0f, 100.0f,0.0f); // gl.glRotatef(rotation,0.0f,1.0f,0.0f); // Rotate The cube around the Y axis // gl.glRotatef(rotation,1.0f,1.0f,1.0f); // gl.glBegin(gl.GL_QUADS); // Draw The Cube Using quads gl.glBegin(gl.GL_LINES); // gl.glColor3f(0.0f,1.0f,0.0f); // Color Blue gl.glVertex3f( x-size, y-size,z-size); gl.glVertex3f(x-size, y+size,z-size); gl.glVertex3f(x-size, y-size, z-size); gl.glVertex3f( x+size, y-size, z-size); // gl.glColor3f(1.0f,0.5f,0.0f); // Color Orange gl.glVertex3f( x-size,y+size, z-size); gl.glVertex3f(x+size,y+size, z-size); gl.glVertex3f(x+size,y+size,z-size); gl.glVertex3f( x+size,y-size,z-size); // gl.glColor3f(1.0f,0.0f,0.0f); // Color Red gl.glVertex3f( x-size, y-size, z-size); gl.glVertex3f(x-size, y-size, z+size); gl.glVertex3f(x-size,y+size, z-size); gl.glVertex3f( x-size,y+size, z+size); // gl.glColor3f(1.0f,1.0f,0.0f); // Color Yellow gl.glVertex3f( x+size,y+size,z-size); gl.glVertex3f(x+size,y+size,z+size); gl.glVertex3f(x+size, y-size,z-size); gl.glVertex3f( x+size, y-size,z+size); // gl.glColor3f(0.0f,0.0f,1.0f); // Color Blue gl.glVertex3f(x-size, y-size, z+size); gl.glVertex3f(x-size, y+size,z+size); gl.glVertex3f(x-size,y-size,z+size); gl.glVertex3f(x+size,y-size, z+size); // gl.glColor3f(1.0f,0.0f,1.0f); // Color Violet gl.glVertex3f( x-size, y+size,z+size); gl.glVertex3f( x+size, y+size, z+size); gl.glVertex3f( x+size,y-size, z+size); gl.glVertex3f( x+size,y+size,z+size); gl.glEnd(); // rotation += 0.9f; } private void rectangle3D(GL gl, float x, float y, float z, float xsize, float ysize, float zsize) { // gl.glTranslatef(100.0f, 100.0f,0.0f); // gl.glRotatef(rotation,0.0f,1.0f,0.0f); // Rotate The cube around the Y axis // gl.glRotatef(rotation,1.0f,1.0f,1.0f); // gl.glBegin(gl.GL_QUADS); // Draw The Cube Using quads gl.glBegin(gl.GL_LINES); // gl.glColor3f(0.0f,1.0f,0.0f); // Color Blue gl.glVertex3f( x-xsize, y-ysize,z-zsize); gl.glVertex3f(x-xsize, y+ysize,z-zsize); gl.glVertex3f(x-xsize, y-ysize, z-zsize); gl.glVertex3f( x+xsize, y-ysize, z-zsize); // gl.glColor3f(1.0f,0.5f,0.0f); // Color Orange gl.glVertex3f( x-xsize,y+ysize, z-zsize); gl.glVertex3f(x+xsize,y+ysize, z-zsize); gl.glVertex3f(x+xsize,y+ysize,z-zsize); gl.glVertex3f( x+xsize,y-ysize,z-zsize); // gl.glColor3f(1.0f,0.0f,0.0f); // Color Red gl.glVertex3f( x-xsize, y-ysize, z-zsize); gl.glVertex3f(x-xsize, y-ysize, z+zsize); gl.glVertex3f(x-xsize,y+ysize, z-zsize); gl.glVertex3f( x-xsize,y+ysize, z+zsize); // gl.glColor3f(1.0f,1.0f,0.0f); // Color Yellow gl.glVertex3f( x+xsize,y+ysize,z-zsize); gl.glVertex3f(x+xsize,y+ysize,z+zsize); gl.glVertex3f(x+xsize, y-ysize,z-zsize); gl.glVertex3f( x+xsize, y-ysize,z+zsize); // gl.glColor3f(0.0f,0.0f,1.0f); // Color Blue gl.glVertex3f(x-xsize, y-ysize, z+zsize); gl.glVertex3f(x-xsize, y+ysize,z+zsize); gl.glVertex3f(x-xsize,y-ysize,z+zsize); gl.glVertex3f(x+xsize,y-ysize, z+zsize); // gl.glColor3f(1.0f,0.0f,1.0f); // Color Violet gl.glVertex3f( x-xsize, y+ysize,z+zsize); gl.glVertex3f( x+xsize, y+ysize, z+zsize); gl.glVertex3f( x+xsize,y-ysize, z+zsize); gl.glVertex3f( x+xsize,y+ysize,z+zsize); gl.glEnd(); // rotation += 0.9f; } private void rotatedRectangle2DFilled(GL gl, float x1, float x2, float y1, float y2, float z1, float z2){ // gl.glTranslatef(100.0f, 100.0f,0.0f); // gl.glRotatef(rotation,0.0f,1.0f,0.0f); // Rotate The cube around the Y axis // gl.glRotatef(rotation,1.0f,1.0f,1.0f); // gl.glBegin(gl.GL_QUADS); // Draw The Cube Using quads gl.glBegin(gl.GL_POLYGON); gl.glVertex3f(x1, y1, z1); gl.glVertex3f( x2, y1, z1); gl.glVertex3f( x1, y1, z1); gl.glVertex3f( x1,y2, z2); gl.glVertex3f( x1, y2,z2); gl.glVertex3f( x2, y2, z2); gl.glVertex3f( x2,y1, z1); gl.glVertex3f( x2,y2,z2); gl.glEnd(); // rotation += 0.9f; } synchronized public void display(GLAutoDrawable drawable) { GL gl=drawable.getGL(); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); //gl.glScalef(drawable.getWidth()/2000,drawable.getHeight()/180,1);//dist to gc, orientation? gl.glClearColor(0,0,0,0); gl.glClear(GL.GL_COLOR_BUFFER_BIT); int font = GLUT.BITMAP_HELVETICA_12; // gl.glEnable(GL.GL_DEPTH_TEST); //enable depth testing // gl.glDepthFunc(GL.GL_LEQUAL); //Type of depth function // glu.gluLookAt(-200,-200,50,-200,-200,0,0.0,1.0,0.0); //System.out.println("display: system time:"+System.currentTimeMillis()); if(leftDragged){ leftDragged = false; tx = dragDestX-dragOrigX; ty = dragOrigY-dragDestY; } if(middleDragged){ middleDragged = false; zty = zdragOrigY-zdragDestY; zty = zty * 20; } if(rightDragged){ rightDragged = false; // rtx = rdragDestX-rdragOrigX; rtx = rdragOrigX-rdragDestX; rty = rdragOrigY-rdragDestY; } float ox = origX+tx; float oy = origY+ty; float oz = zOrigY+zty; // origZ = oz; // origZ+=1.0f; // gl.glTranslatef(ox,oz,oy); // gl.glTranslatef(ox,oy,oz*10); float translation_x = 0; float translation_y = 0; float translation_z = 0; if(goThroughMode) { // gl.glTranslatef(ox-65,oy-25,-oz+tz-1250); // parametrize this in function of pixel size and distance between retinae and open gl angle of vision gl.glTranslatef(ox-1000,oy-25,-oz+tz-15000); translation_x = ox-1000; translation_y = oy-25; translation_z = -oz+tz-15000; } else { gl.glTranslatef(ox,oy,0.0f); translation_x = ox; translation_y = oy; translation_z = 0; if(tz<1)tz=1; gl.glScalef(tz,tz,-tz); } float rx = rOrigX+rtx; float ry = rOrigY+rty; // gl.glTranslatef(-translation_x,-translation_y,-translation_z); // gl.glTranslatef(-translation_x,-translation_y,0); gl.glRotatef(ry+kry,1.0f,0.0f,0.0f); gl.glRotatef(rx+krx,0.0f,1.0f,0.0f); // gl.glTranslatef(translation_x,translation_y,translation_z); // gl.glTranslatef(translation_x,translation_y,0); // keyboard rotation : rOrigY += kry; rOrigX += krx; kry = 0; krx = 0; if(showAxes){ draw3DAxes(gl); } // if(displayPlay){ // draw3DDisparityPacket(gl,inputPacket); // } else { if(showAcc){ if(displayDirect3D){ // display displayPacket draw3DDisplayPacket( gl, currentTime ); } else { switch(display3DChoice){ case 0: // System.out.println("main draw3DDisparityPoints leftPoints at "+leftTime); draw3DDisparityPoints( gl , leftPoints, LEFT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); // System.out.println("main draw3DDisparityPoints leftPoints2 at "+leftTime); draw3DDisparityPoints( gl , leftPoints, RIGHT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); // System.out.println("main draw3DDisparityPoints rightPoints at "+rightTime); draw3DDisparityPoints( gl , rightPoints, LEFT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); // System.out.println("main draw3DDisparityPoints rightPoints2 at "+rightTime); draw3DDisparityPoints( gl , rightPoints, RIGHT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); break; case 1: draw3DDisparityPoints( gl , leftPoints, LEFT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); draw3DDisparityPoints( gl , leftPoints, RIGHT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); break; case 2: draw3DDisparityPoints( gl , leftPoints, LEFT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); break; case 3: draw3DDisparityPoints( gl , leftPoints, RIGHT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); break; case 4: draw3DDisparityPoints( gl , rightPoints, LEFT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); draw3DDisparityPoints( gl , rightPoints, RIGHT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); break; case 5: draw3DDisparityPoints( gl , rightPoints, LEFT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); break; case 6: draw3DDisparityPoints( gl , rightPoints, RIGHT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); break; case 7: // draw3DAverageDisparityPoints( gl, leftPoints, LEFT_MOST_METHOD, leftPoints2, currentTime, rightPoints, rightPoints2, currentTime, 1); // draw3DAverageDisparityPoints( gl, leftPoints2, leftPoints2, currentTime, rightPoints2, rightPoints2, currentTime, 1); break; case 8: draw3DDisparityPoints( gl , leftPoints, LEFT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); draw3DDisparityPoints( gl , rightPoints, RIGHT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); break; case 9: draw3DDisparityPoints( gl , leftPoints, LEFT_MOST_METHOD, currentTime, rightPoints, currentTime, 1); draw3DDisparityPoints( gl , rightPoints, RIGHT_MOST_METHOD, currentTime, leftPoints, currentTime, -1); break; default: } } } if(showFingers||showFingersRange){ // float colorFinger = 0; // float colorFinger2 = 0; /// Color trackerColor = null; try{ for(FingerCluster fc:fingers){ if(fc!=null){ // trackerColor = new Color(fc.id*4); // System.out.println("trackerColor id:"+fc.id // +" color r:"+(float)trackerColor.getRed()/255 // +" color g:"+(float)trackerColor.getGreen()/255 // +" color b:"+(float)trackerColor.getBlue()/255 // +" at x:"+fc.x+" y:"+fc.y+" z:"+fc.z // if(fc.activated){ // gl.glColor3f((float)trackerColor.getRed()/32+0.5f, // (float)trackerColor.getGreen()/32, // (float)trackerColor.getBlue()/32); if(showFingers){ gl.glColor3f(1.0f,0,0); //colorFinger,colorFinger2); //cube(gl,fc.x,fc.y,fc.z,finger_surround); rectangle3D(gl,fc.x,fc.y,fc.z,fc.x_size/2,fc.y_size/2,fc.z_size/2); } if(showFingersRange){ if(fc.nbEvents<tracker_viable_nb_events){ gl.glColor3f(1.0f,1.0f,0.0f); } else { gl.glColor3f(1.0f,0,1.0f); } //colorFinger,colorFinger2); cube(gl,fc.x,fc.y,fc.z,finger_surround/2); // rectangle3D(gl,fc.x,fc.y,fc.z,fc.x_size*2,fc.y_size*2,fc.z_size*2); } } } } catch(java.util.ConcurrentModificationException e){ } } if(trackZPlane){ gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4f(1.0f,0.0f,1.0f,0.9f); // draw z plane at tracker's z int x_mid = Math.round(retinae_distance*scaleFactor/2); int base_height = Math.round((cage_door_height-retina_height)*scaleFactor + retinaSize/2); int y1 = base_height; int y2 = base_height+1000; int z1 = planeTracker.z; int y1_rx = rotateYonX( y1, z1, 0, 0, retina_tilt_angle); int y2_rx = rotateYonX( y2, z1, 0, 0, retina_tilt_angle); int z1_rx = rotateZonX( y1, z1, 0, 0, retina_tilt_angle); int z2_rx = rotateZonX( y2, z1, 0, 0, retina_tilt_angle); rotatedRectangle2DFilled(gl,x_mid-500,x_mid+500,y1_rx,y2_rx,z1_rx,z2_rx); gl.glDisable(gl.GL_BLEND); } // if(showFrame){ draw3DFrames(gl); gl.glPopMatrix(); gl.glFlush(); int error=gl.glGetError(); if(error!=GL.GL_NO_ERROR){ //if(glu==null) glu=new GLU(); //log.warning("GL error number "+error+" "+glu.gluErrorString(error)); System.out.println("GL error number "+error+" "+glu.gluErrorString(error)); } } synchronized public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL gl=drawable.getGL(); final int B=10; gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); // very important to load identity matrix here so this works after first resize!!! // glu.gluPerspective(40.0,(double)x/(double)y,0.5,10.0); if(goThroughMode) { glu.gluPerspective(10.0,(double)width/(double)height,0.5,100000.0); } else { gl.glOrtho(-B,drawable.getWidth()+B,-B,drawable.getHeight()+B,10000,-10000); } gl.glMatrixMode(GL.GL_MODELVIEW); gl.glViewport(0,0,width,height); } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } }); a3DFrame.getContentPane().add(a3DCanvas); a3DFrame.pack(); a3DFrame.setVisible(true); } public void annotate(Graphics2D g) { } protected void drawBoxCentered(GL gl, int x, int y, int sx, int sy){ gl.glBegin(GL.GL_LINE_LOOP); { gl.glVertex2i(x-sx,y-sy); gl.glVertex2i(x+sx,y-sy); gl.glVertex2i(x+sx,y+sy); gl.glVertex2i(x-sx,y+sy); } gl.glEnd(); } protected void drawBox(GL gl, int x, int x2, int y, int y2){ gl.glBegin(GL.GL_LINE_LOOP); { gl.glVertex2i(x,y); gl.glVertex2i(x2,y); gl.glVertex2i(x2,y2); gl.glVertex2i(x,y2); } gl.glEnd(); } synchronized public void annotate(GLAutoDrawable drawable) { final float LINE_WIDTH=5f; // in pixels if(!isFilterEnabled()) return; GL gl=drawable.getGL(); // when we get this we are already set up with scale 1=1 pixel, at LL corner if(gl==null){ log.warning("null GL in PawTrackerStereoBoard3.annotate"); return; } float[] rgb=new float[4]; gl.glPushMatrix(); try{ // if(showZones){ // // draw door // gl.glColor3f(0,1,0); // drawBox(gl,door_xa,door_xb,door_ya,door_yb); }catch(java.util.ConcurrentModificationException e){ log.warning(e.getMessage()); } gl.glPopMatrix(); } // void drawGLCluster(int x1, int y1, int x2, int y2) /** annotate the rendered retina frame to show locations of clusters */ synchronized public void annotate(float[][][] frame) { if(!isFilterEnabled()) return; // disable for now TODO if(chip.getCanvas().isOpenGLEnabled()) return; // done by open gl annotator } public synchronized boolean isLogDataEnabled() { return logDataEnabled; } public synchronized void setLogDataEnabled(boolean logDataEnabled) { this.logDataEnabled = logDataEnabled; getPrefs().putBoolean("PawTrackerStereoBoard3.logDataEnabled",logDataEnabled); /* if(!logDataEnabled) { logStream.flush(); logStream.close(); logStream=null; }else{ try{ logStream=new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("PawTrackerData.txt")))); logStream.println("# clusterNumber lasttimestamp x y avergeEventDistance"); }catch(Exception e){ e.printStackTrace(); } } **/ } public void setDecayTimeLimit(float decayTimeLimit) { this.decayTimeLimit = decayTimeLimit; getPrefs().putFloat("PawTrackerStereoBoard3.decayTimeLimit",decayTimeLimit); } public float getDecayTimeLimit() { return decayTimeLimit; } public void setIntensityZoom(int intensityZoom) { this.intensityZoom = intensityZoom; getPrefs().putInt("PawTrackerStereoBoard3.intensityZoom",intensityZoom); } public int getIntensityZoom() { return intensityZoom; } public void setEvent_strength(float event_strength) { this.event_strength = event_strength; getPrefs().putFloat("PawTrackerStereoBoard3.event_strength",event_strength); } public float getEvent_strength() { return event_strength; } public boolean isResetPawTracking() { return resetPawTracking; } public void setResetPawTracking(boolean resetPawTracking) { this.resetPawTracking = resetPawTracking; getPrefs().putBoolean("PawTrackerStereoBoard3.resetPawTracking",resetPawTracking); if(resetPawTracking){ resetPawTracker(); } } public boolean isResetClusters() { return resetClusters; } public void setResetClusters(boolean resetClusters) { this.resetClusters = resetClusters; getPrefs().putBoolean("PawTrackerStereoBoard3.resetClusters",resetClusters); if(resetClusters){ resetClusterTrackers(); } } public boolean isRestart() { return restart; } public void setRestart(boolean restart) { this.restart = restart; getPrefs().putBoolean("PawTrackerStereoBoard3.restart",restart); } // public boolean isValidateParameters() { // return validateParameters; // public void setValidateParameters(boolean validateParameters) { // this.validateParameters = validateParameters; // getPrefs().putBoolean("PawTrackerStereoBoard3.validateParameters",validateParameters); public void setShowCorrectionGradient(boolean showCorrectionGradient){ this.showCorrectionGradient = showCorrectionGradient; getPrefs().putBoolean("PawTrackerStereoBoard3.showCorrectionGradient",showCorrectionGradient); } public boolean getshowCorrectionGradient(){ return showCorrectionGradient; } public void setShowCorrectionMatrix(boolean showCorrectionMatrix){ this.showCorrectionMatrix = showCorrectionMatrix; getPrefs().putBoolean("PawTrackerStereoBoard3.showCorrectionMatrix",showCorrectionMatrix); } public boolean getShowCorrectionMatrix(){ return showCorrectionMatrix; } // public void setShowSecondFilter(boolean showSecondFilter){ // this.showSecondFilter = showSecondFilter; // getPrefs().putBoolean("PawTrackerStereoBoard3.showSecondFilter",showSecondFilter); // public boolean isShowSecondFilter(){ // return showSecondFilter; public void setScaleAcc(boolean scaleAcc){ this.scaleAcc = scaleAcc; getPrefs().putBoolean("PawTrackerStereoBoard3.scaleAcc",scaleAcc); } public boolean isScaleAcc(){ return scaleAcc; } public void setShowAcc(boolean showAcc){ this.showAcc = showAcc; getPrefs().putBoolean("PawTrackerStereoBoard3.showAcc",showAcc); } public boolean isShowAcc(){ return showAcc; } public void setShowOnlyAcc(boolean showOnlyAcc){ this.showOnlyAcc = showOnlyAcc; getPrefs().putBoolean("PawTrackerStereoBoard3.showOnlyAcc",showOnlyAcc); } public boolean isShowOnlyAcc(){ return showOnlyAcc; } public void setShowDecay(boolean showDecay){ this.showDecay = showDecay; getPrefs().putBoolean("PawTrackerStereoBoard3.showDecay",showDecay); } public boolean isShowDecay(){ return showDecay; } public void setUseFilter(boolean useFilter){ this.useFilter = useFilter; getPrefs().putBoolean("PawTrackerStereoBoard3.useFilter",useFilter); } public boolean isUseFilter(){ return useFilter; } public void setDecayOn(boolean decayOn){ this.decayOn = decayOn; getPrefs().putBoolean("PawTrackerStereoBoard3.decayOn",decayOn); } public boolean isDecayOn(){ return decayOn; } // public void setShowFrame(boolean showFrame){ // this.showFrame = showFrame; // getPrefs().putBoolean("PawTrackerStereoBoard3.showFrame",showFrame); // public boolean isShowFrame(){ // return showFrame; public void setShowCage(boolean showCage){ this.showCage = showCage; getPrefs().putBoolean("PawTrackerStereoBoard3.showCage",showCage); } public boolean isShowCage(){ return showCage; } public void setShowRetina(boolean showRetina){ this.showRetina = showRetina; getPrefs().putBoolean("PawTrackerStereoBoard3.showRetina",showRetina); } public boolean isShowRetina(){ return showRetina; } public void setShow2DWindow(boolean show2DWindow){ this.show2DWindow = show2DWindow; getPrefs().putBoolean("PawTrackerStereoBoard3.show2DWindow",show2DWindow); } public boolean isShow2DWindow(){ return show2DWindow; } public void setShow3DWindow(boolean show3DWindow){ this.show3DWindow = show3DWindow; getPrefs().putBoolean("PawTrackerStereoBoard3.show3DWindow",show3DWindow); } public boolean isShow3DWindow(){ return show3DWindow; } public void setShowPlayer(boolean showPlayer){ this.showPlayer = showPlayer; getPrefs().putBoolean("PawTrackerStereoBoard3.showPlayer",showPlayer); } public boolean isShowPlayer(){ return showPlayer; } // public void setShowScore(boolean showScore){ // this.showScore = showScore; // getPrefs().putBoolean("PawTrackerStereoBoard3.showScore",showScore); // public boolean isShowScore(){ // return showScore; public void setShowRight(boolean showRight){ this.showRight = showRight; getPrefs().putBoolean("PawTrackerStereoBoard3.showRight",showRight); } public boolean isShowRight(){ return showRight; } public void setShowFingers(boolean showFingers){ this.showFingers = showFingers; getPrefs().putBoolean("PawTrackerStereoBoard3.showFingers",showFingers); } public boolean isShowFingers(){ return showFingers; } public void setShowFingersRange(boolean showFingersRange){ this.showFingersRange = showFingersRange; getPrefs().putBoolean("PawTrackerStereoBoard3.showFingersRange",showFingersRange); } public boolean isShowFingersRange(){ return showFingersRange; } // public void setShowFingerTips(boolean showFingerTips){ // this.showFingerTips = showFingerTips; // getPrefs().putBoolean("PawTrackerStereoBoard3.showFingerTips",showFingerTips); // public boolean isShowFingerTips(){ // return showFingerTips; public void setShowZones(boolean showZones){ this.showZones = showZones; getPrefs().putBoolean("PawTrackerStereoBoard3.showZones",showZones); } public boolean isShowZones(){ return showZones; } public void setShowAll(boolean showAll){ this.showAll = showAll; getPrefs().putBoolean("PawTrackerStereoBoard3.showAll",showAll); } public boolean isShowAll(){ return showAll; } public void setUseFastMatching(boolean useFastMatching){ this.useFastMatching = useFastMatching; getPrefs().putBoolean("PawTrackerStereoBoard3.useFastMatching",useFastMatching); } public boolean isUseFastMatching(){ return useFastMatching; } public void setShowRLColors(boolean showRLColors){ this.showRLColors = showRLColors; getPrefs().putBoolean("PawTrackerStereoBoard3.showRLColors",showRLColors); } public boolean isShowRLColors(){ return showRLColors; } public void setShowAxes(boolean showAxes){ this.showAxes = showAxes; getPrefs().putBoolean("PawTrackerStereoBoard3.showAxes",showAxes); } public boolean isShowAxes(){ return showAxes; } public int getLowFilter_radius() { return lowFilter_radius; } public void setLowFilter_radius(int lowFilter_radius) { this.lowFilter_radius = lowFilter_radius; getPrefs().putInt("PawTrackerStereoBoard3.lowFilter_radius",lowFilter_radius); } public int getLowFilter_density() { return lowFilter_density; } public void setLowFilter_density(int lowFilter_density) { this.lowFilter_density = lowFilter_density; getPrefs().putInt("PawTrackerStereoBoard3.lowFilter_density",lowFilter_density); } public float getLowFilter_threshold() { return lowFilter_threshold; } public void setLowFilter_threshold(float lowFilter_threshold) { this.lowFilter_threshold = lowFilter_threshold; getPrefs().putFloat("PawTrackerStereoBoard3.lowFilter_threshold",lowFilter_threshold); } // public int getLowFilter_radius2() { // return lowFilter_radius2; // public void setLowFilter_radius2(int lowFilter_radius2) { // this.lowFilter_radius2 = lowFilter_radius2; // getPrefs().putInt("PawTrackerStereoBoard3.lowFilter_radius2",lowFilter_radius2); // public int getLowFilter_density2() { // return lowFilter_density2; // public void setLowFilter_density2(int lowFilter_density2) { // this.lowFilter_density2 = lowFilter_density2; // getPrefs().putInt("PawTrackerStereoBoard3.lowFilter_density2",lowFilter_density2); public float getBrightness() { return brightness; } public void setBrightness(float brightness) { this.brightness = brightness; getPrefs().putFloat("PawTrackerStereoBoard3.brightness",brightness); } // public float getPlaneAngle() { // return planeAngle; // public void setPlaneAngle(float planeAngle) { // this.planeAngle = planeAngle; // getPrefs().putFloat("PawTrackerStereoBoard3.planeAngle",planeAngle); // public float getPlatformAngle() { // return platformAngle; // public void setPlatformAngle(float platformAngle) { // this.platformAngle = platformAngle; // getPrefs().putFloat("PawTrackerStereoBoard3.platformAngle",platformAngle); public void setAlpha(float alpha) { this.alpha = alpha; getPrefs().putFloat("PawTrackerStereoBoard3.alpha",alpha); } public float getAlpha() { return alpha; } public void setIntensity(float intensity) { this.intensity = intensity; getPrefs().putFloat("PawTrackerStereoBoard3.intensity",intensity); } public float getIntensity() { return intensity; } // public void setDispAvgRange(int dispAvgRange) { // this.dispAvgRange = dispAvgRange; // getPrefs().putInt("PawTrackerStereoBoard3.dispAvgRange",dispAvgRange); // public int getDispAvgRange() { // return dispAvgRange; public void setValueThreshold(float valueThreshold) { this.valueThreshold = valueThreshold; getPrefs().putFloat("PawTrackerStereoBoard3.valueThreshold",valueThreshold); } public float getValueThreshold() { return valueThreshold; } public void setGrasp_max_elevation(int grasp_max_elevation) { this.grasp_max_elevation = grasp_max_elevation; compute3DParameters(); getPrefs().putInt("PawTrackerStereoBoard3.grasp_max_elevation",grasp_max_elevation); } public int getGrasp_max_elevation() { return grasp_max_elevation; } public void setMax_finger_clusters(int max_finger_clusters) { this.max_finger_clusters = max_finger_clusters; getPrefs().putInt("PawTrackerStereoBoard3.max_finger_clusters",max_finger_clusters); } public int getMax_finger_clusters() { return max_finger_clusters; } public void setCage_distance(float cage_distance) { this.cage_distance = cage_distance; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.cage_distance",cage_distance); } public float getCage_distance() { return cage_distance; } public float getRetina_tilt_angle() { return retina_tilt_angle; } public void setRetina_tilt_angle(float retina_tilt_angle) { this.retina_tilt_angle = retina_tilt_angle; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.retina_tilt_angle",retina_tilt_angle); } public void setRetina_height(float retina_height) { this.retina_height = retina_height; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.retina_height",retina_height); } public float getRetina_height() { return retina_height; } public void setCage_door_height(float cage_door_height) { this.cage_door_height = cage_door_height; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.cage_door_height",cage_door_height); } public float getCage_door_height() { return cage_door_height; } public void setCage_height(float cage_height) { this.cage_height = cage_height; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.cage_height",cage_height); } public float getCage_height() { return cage_height; } public void setCage_width(float cage_width) { this.cage_width = cage_width; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.cage_width",cage_width); } public float getCage_width() { return cage_width; } public void setCage_platform_length(float cage_platform_length) { this.cage_platform_length = cage_platform_length; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.cage_platform_length",cage_platform_length); } public float getCage_platform_length() { return cage_platform_length; } public void setCage_door_width(float cage_door_width) { this.cage_door_width = cage_door_width; compute3DParameters(); getPrefs().putFloat("PawTrackerStereoBoard3.cage_door_width",cage_door_width); } public float getCage_door_width() { return cage_door_width; } public void setYLeftCorrection(int yLeftCorrection) { this.yLeftCorrection = yLeftCorrection; getPrefs().putInt("PawTrackerStereoBoard3.yLeftCorrection",yLeftCorrection); } public int getYLeftCorrection() { return yLeftCorrection; } public void setYRightCorrection(int yRightCorrection) { this.yRightCorrection = yRightCorrection; getPrefs().putInt("PawTrackerStereoBoard3.yRightCorrection",yRightCorrection); } public int getYRightCorrection() { return yRightCorrection; } public void setYCurveFactor(float yCurveFactor) { this.yCurveFactor = yCurveFactor; getPrefs().putFloat("PawTrackerStereoBoard3.yCurveFactor",yCurveFactor); } public float getYCurveFactor() { return yCurveFactor; } public void setColorizeFactor(float colorizeFactor) { this.colorizeFactor = colorizeFactor; getPrefs().putFloat("PawTrackerStereoBoard3.colorizeFactor",colorizeFactor); } public float getColorizeFactor() { return colorizeFactor; } public void setShadowFactor(float shadowFactor) { this.shadowFactor = shadowFactor; getPrefs().putFloat("PawTrackerStereoBoard3.shadowFactor",shadowFactor); } public float getShadowFactor() { return shadowFactor; } public void setZFactor(int zFactor) { this.zFactor = zFactor; getPrefs().putInt("PawTrackerStereoBoard3.zFactor",zFactor); } public int getZFactor() { return zFactor; } public void setValueMargin(float valueMargin) { this.valueMargin = valueMargin; getPrefs().putFloat("PawTrackerStereoBoard3.valueMargin",valueMargin); } public float getValueMargin() { return valueMargin; } public void setCorrectLeftAngle(float correctLeftAngle) { this.correctLeftAngle = correctLeftAngle; getPrefs().putFloat("PawTrackerStereoBoard3.correctLeftAngle",correctLeftAngle); } public float getCorrectLeftAngle() { return correctLeftAngle; } public void setCorrectRightAngle(float correctRightAngle) { this.correctRightAngle = correctRightAngle; getPrefs().putFloat("PawTrackerStereoBoard3.correctRightAngle",correctRightAngle); } public float getCorrectRightAngle() { return correctRightAngle; } public void setColorizePeriod(int colorizePeriod) { this.colorizePeriod = colorizePeriod; getPrefs().putInt("PawTrackerStereoBoard3.colorizePeriod",colorizePeriod); } public int getColorizePeriod() { return colorizePeriod; } public void setHighlightDecay(boolean highlightDecay){ this.highlightDecay = highlightDecay; getPrefs().putBoolean("PawTrackerStereoBoard3.highlightDecay",highlightDecay); } public boolean isHighlightDecay(){ return highlightDecay; } public void setShowZColor(boolean showZColor){ this.showZColor = showZColor; getPrefs().putBoolean("PawTrackerStereoBoard3.showZColor",showZColor); } public boolean isShowZColor(){ return showZColor; } public void setShowYColor(boolean showYColor){ this.showYColor = showYColor; getPrefs().putBoolean("PawTrackerStereoBoard3.showYColor",showYColor); } public boolean isShowYColor(){ return showYColor; } public void setShowXColor(boolean showXColor){ this.showXColor = showXColor; getPrefs().putBoolean("PawTrackerStereoBoard3.showXColor",showXColor); } public boolean isShowXColor(){ return showXColor; } public void setTrackFingers(boolean trackFingers){ this.trackFingers = trackFingers; getPrefs().putBoolean("PawTrackerStereoBoard3.trackFingers",trackFingers); } public boolean isTrackFingers(){ return trackFingers; } // public void setShowShadows(boolean showShadows){ // this.showShadows = showShadows; // getPrefs().putBoolean("PawTrackerStereoBoard3.showShadows",showShadows); // public boolean isShowShadows(){ // return showShadows; // public void setShowCorner(boolean showCorner){ // this.showCorner = showCorner; // getPrefs().putBoolean("PawTrackerStereoBoard3.showCorner",showCorner); // public boolean isShowCorner(){ // return showCorner; public void setCorrectY(boolean correctY){ this.correctY = correctY; getPrefs().putBoolean("PawTrackerStereoBoard3.correctY",correctY); } public boolean isCorrectY(){ return correctY; } public void setCube_size(int cube_size) { this.cube_size = cube_size; getPrefs().putInt("PawTrackerStereoBoard3.cube_size",cube_size); } public int getCube_size() { return cube_size; } // public void setDisparity_range(int disparity_range) { // this.disparity_range = disparity_range; // getPrefs().putInt("PawTrackerStereoBoard3.disparity_range",disparity_range); // public int getDisparity_range() { // return disparity_range; public void setNotCrossing(boolean notCrossing){ this.notCrossing = notCrossing; getPrefs().putBoolean("PawTrackerStereoBoard3.notCrossing",notCrossing); } public boolean isNotCrossing(){ return notCrossing; } public float getFinger_mix() { return finger_mix; } public void setFinger_mix(float finger_mix) { this.finger_mix = finger_mix; getPrefs().putFloat("PawTrackerStereoBoard3.finger_mix",finger_mix); } public float getExpansion_mix() { return expansion_mix; } public void setExpansion_mix(float expansion_mix) { this.expansion_mix = expansion_mix; getPrefs().putFloat("PawTrackerStereoBoard3.expansion_mix",expansion_mix); } public float getPlane_tracker_mix() { return plane_tracker_mix; } public void setPlane_tracker_mix(float plane_tracker_mix) { this.plane_tracker_mix = plane_tracker_mix; getPrefs().putFloat("PawTrackerStereoBoard3.plane_tracker_mix",plane_tracker_mix); } public float getTrackerSubsamplingDistance() { return trackerSubsamplingDistance; } public void setTrackerSubsamplingDistance(float trackerSubsamplingDistance) { this.trackerSubsamplingDistance = trackerSubsamplingDistance; getPrefs().putFloat("PawTrackerStereoBoard3.trackerSubsamplingDistance",trackerSubsamplingDistance); } public int getFinger_surround() { return finger_surround; } public void setFinger_surround(int finger_surround) { this.finger_surround = finger_surround; getPrefs().putInt("PawTrackerStereoBoard3.finger_surround",finger_surround); } public int getTracker_lifeTime() { return tracker_lifeTime; } public void setTracker_lifeTime(int tracker_lifeTime) { this.tracker_lifeTime = tracker_lifeTime; getPrefs().putInt("PawTrackerStereoBoard3.tracker_lifeTime",tracker_lifeTime); } public int getTracker_prelifeTime() { return tracker_prelifeTime; } public void setTracker_prelifeTime(int tracker_prelifeTime) { this.tracker_prelifeTime = tracker_prelifeTime; getPrefs().putInt("PawTrackerStereoBoard3.tracker_prelifeTime",tracker_prelifeTime); } public int getTracker_viable_nb_events() { return tracker_viable_nb_events; } public void setTracker_viable_nb_events(int tracker_viable_nb_events) { this.tracker_viable_nb_events = tracker_viable_nb_events; getPrefs().putInt("PawTrackerStereoBoard3.tracker_viable_nb_events",tracker_viable_nb_events); } public void setUseGroups(boolean useGroups){ this.useGroups = useGroups; getPrefs().putBoolean("PawTrackerStereoBoard3.useGroups",useGroups); } public boolean isUseGroups(){ return useGroups; } public void setGoThroughMode(boolean goThroughMode){ this.goThroughMode = goThroughMode; getPrefs().putBoolean("PawTrackerStereoBoard3.goThroughMode",goThroughMode); } public boolean isGoThroughMode(){ return goThroughMode; } public void setUseCorrections(boolean useCorrections){ this.useCorrections = useCorrections; getPrefs().putBoolean("PawTrackerStereoBoard3.useCorrections",useCorrections); } public boolean isUseCorrections(){ return useCorrections; } public float getFocal_length() { return focal_length; } public void setFocal_length(float focal_length) { this.focal_length = focal_length; getPrefs().putFloat("PawTrackerStereoBoard3.focal_length",focal_length); compute3DParameters(); } public void setRetinae_distance(float retinae_distance) { this.retinae_distance = retinae_distance; getPrefs().putFloat("PawTrackerStereoBoard3.retinae_distance",retinae_distance); compute3DParameters(); } public float getRetinae_distance() { return retinae_distance; } public void setPixel_size(float pixel_size) { this.pixel_size = pixel_size; getPrefs().putFloat("PawTrackerStereoBoard3.pixel_size",pixel_size); compute3DParameters(); } public float getPixel_size() { return pixel_size; } public void setRetina_angle(float retina_angle) { this.retina_angle = retina_angle; getPrefs().putFloat("PawTrackerStereoBoard3.retina_angle",retina_angle); compute3DParameters(); } public float getRetina_angle() { return retina_angle; } public void setRecordTrackerData(boolean recordTrackerData){ this.recordTrackerData = recordTrackerData; getPrefs().putBoolean("PawTrackerStereoBoard3.recordTrackerData",recordTrackerData); } public boolean isRecordTrackerData(){ return recordTrackerData; } public void setTrackZPlane(boolean trackZPlane){ this.trackZPlane = trackZPlane; getPrefs().putBoolean("PawTrackerStereoBoard3.trackZPlane",trackZPlane); } public boolean isTrackZPlane(){ return trackZPlane; } }
package com.ctgi.google.arraysandstrings; /** * @author Dany * * ALGORITHM: * - Get the two input strings. * - Store the first string character count in int array.(Considering ASCII values) * - iterate through the second string and then check for the character in the int array and * see if it is matching until the first string length * - If until the length of first string all character matches with the second string substring and * if the array count is zero for all character then return the substring anagram * */ public class AnagramOfFirstStringInSecondString { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(new AnagramOfFirstStringInSecondString().findAnagramSubstring("dog", "mrdhgodess")); } public String findAnagramSubstring(String str1, String str2) { if(str1==null || str2 ==null) return null; if(str1=="" || str2 == "") return null; int length1 = str1.length(); int length2 = str2.length(); int[] arrCount = new int[256]; //Considering the ASCII values for(int i=0; i<length1; i++) { char c = str1.charAt(i); arrCount[c]++; } int[] tempArr = arrCount; for(int j=0;j<length2;j++) { for(int k=j;k<length2;k++) { char ch = str2.charAt(k); if(k-j<length1) { if(tempArr[ch]>0) { tempArr[ch] if(k-j==length1-1) { if(isAnagram(tempArr)) return str2.substring(j,length1); } } else { tempArr= arrCount; break; } }else { tempArr= arrCount; break; } } } return null; } public boolean isAnagram(int[] cArr) { for(int i=0;i<cArr.length;i++) { if(cArr[i]>0) return false; } return true; } }
package com.ppm.integration.agilesdk.connector.jira; import com.hp.ppm.integration.model.WorkplanMapping; import com.hp.ppm.user.model.User; import com.ppm.integration.agilesdk.ValueSet; import com.ppm.integration.agilesdk.connector.jira.model.*; import com.ppm.integration.agilesdk.connector.jira.rest.util.exception.JIRAConnectivityExceptionHandler; import com.ppm.integration.agilesdk.connector.jira.rest.util.exception.RestRequestException; import com.ppm.integration.agilesdk.connector.jira.service.JIRAService; import com.ppm.integration.agilesdk.connector.jira.util.WorkDrivenPercentCompleteExternalTask; import com.ppm.integration.agilesdk.pm.*; import com.ppm.integration.agilesdk.provider.LocalizationProvider; import com.ppm.integration.agilesdk.provider.Providers; import com.ppm.integration.agilesdk.provider.UserProvider; import com.ppm.integration.agilesdk.ui.*; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.wink.client.ClientRuntimeException; import java.util.*; public class JIRAWorkPlanIntegration extends WorkPlanIntegration { private final Logger logger = Logger.getLogger(this.getClass()); public JIRAWorkPlanIntegration() {} @Override public List<Field> getMappingConfigurationFields(WorkPlanIntegrationContext context, ValueSet values) { final LocalizationProvider lp = Providers.getLocalizationProvider(JIRAIntegrationConnector.class); final boolean useAdminPassword = values.getBoolean(JIRAConstants.KEY_USE_ADMIN_PASSWORD_TO_MAP_TASKS, false); List<Field> fields = new ArrayList<Field>(); final JIRAService service = JIRAServiceProvider.get(values).useAdminAccount(); final Map<String, Set<String>> issueTypesPerProjectKey = service.getIssueTypesPerProject(); if (!useAdminPassword) { fields.add(new PlainText(JIRAConstants.KEY_USERNAME, "USERNAME", "", true)); fields.add(new PasswordText(JIRAConstants.KEY_PASSWORD, "PASSWORD", "", true)); fields.add(new LineBreaker()); } SelectList importSelectionSelectList = new SelectList(JIRAConstants.KEY_IMPORT_SELECTION,"IMPORT_SELECTION",JIRAConstants.IMPORT_ALL_PROJECT_ISSUES,true) .addLevel(JIRAConstants.KEY_IMPORT_SELECTION, "IMPORT_SELECTION") .addOption(new SelectList.Option(JIRAConstants.IMPORT_ALL_PROJECT_ISSUES,"IMPORT_ALL_PROJECT_ISSUES")) .addOption(new SelectList.Option(JIRAConstants.IMPORT_ONE_EPIC,"IMPORT_ONE_EPIC")) .addOption(new SelectList.Option(JIRAConstants.IMPORT_ONE_VERSION,"IMPORT_ONE_VERSION")) .addOption(new SelectList.Option(JIRAConstants.IMPORT_ONE_BOARD,"IMPORT_ONE_BOARD")); if (service.isJiraPortfolioEnabled()) { for (HierarchyLevelInfo portfolioLevel : service.getJiraPortfolioLevelsInfo()) { if (portfolioLevel.getId() <= 2) { // We don't want to display Sub-Task, Story or Epic. continue; } importSelectionSelectList.addOption( new SelectList.Option(JIRAConstants.IMPORT_PORTFOLIO_PREFIX+portfolioLevel.getId(), portfolioLevel.getTitle())); } } SelectList importGroupSelectList = new SelectList(JIRAConstants.KEY_IMPORT_GROUPS,"IMPORT_GROUPS",JIRAConstants.GROUP_EPIC,true) .addLevel(JIRAConstants.KEY_IMPORT_GROUPS, "IMPORT_GROUPS") .addOption(new SelectList.Option(JIRAConstants.GROUP_EPIC,"GROUP_EPIC")) .addOption(new SelectList.Option(JIRAConstants.GROUP_SPRINT,"GROUP_SPRINT")) .addOption(new SelectList.Option(JIRAConstants.GROUP_STATUS,"GROUP_STATUS")); if (service.isJiraPortfolioEnabled()) { importGroupSelectList.addOption(new SelectList.Option(JIRAConstants.GROUP_JIRA_PORTFOLIO_HIERARCHY,"GROUP_JIRA_PORTFOLIO_HIERARCHY")); } fields.addAll(Arrays.asList(new Field[] { new LabelText(JIRAConstants.LABEL_SELECT_WHAT_TO_IMPORT, "LABEL_SELECT_WHAT_TO_IMPORT", "Select what to import:", true), new DynamicDropdown(JIRAConstants.KEY_JIRA_PROJECT, "JIRA_PROJECT", true) { @Override public List<String> getDependencies() { return Arrays.asList(new String[] {JIRAConstants.KEY_USERNAME, JIRAConstants.KEY_PASSWORD}); } @Override public List<Option> getDynamicalOptions(ValueSet values) { if (!useAdminPassword) { service.resetUserCredentials(values).useNonAdminAccount(); } List<JIRAProject> list = new ArrayList<>(); try { list = service.getProjects(); } catch (ClientRuntimeException | RestRequestException e) { logger.error("", e); new JIRAConnectivityExceptionHandler().uncaughtException(Thread.currentThread(), e, JIRAWorkPlanIntegration.class); } catch (RuntimeException e) { logger.error("", e); new JIRAConnectivityExceptionHandler().uncaughtException(Thread.currentThread(), e, JIRAWorkPlanIntegration.class); } List<Option> optionList = new ArrayList<>(); for (JIRAProject project : list) { Option option = new Option(project.getKey(), project.getName()); optionList.add(option); } return optionList; } }, new LineBreaker(), importSelectionSelectList, new DynamicDropdown(JIRAConstants.KEY_IMPORT_SELECTION_DETAILS, "IMPORT_SELECTION_DETAILS", "", true) { @Override public List<String> getDependencies() { return Arrays.asList( new String[] {JIRAConstants.KEY_JIRA_PROJECT, JIRAConstants.KEY_IMPORT_SELECTION}); } @Override public List<Option> getDynamicalOptions(ValueSet values) { if (!useAdminPassword) { service.resetUserCredentials(values).useNonAdminAccount(); } String importSelection = values.get(JIRAConstants.KEY_IMPORT_SELECTION); String projectKey = values.get(JIRAConstants.KEY_JIRA_PROJECT); List<Option> options = new ArrayList<>(); switch (importSelection) { case JIRAConstants.IMPORT_ALL_PROJECT_ISSUES: // No extra option when importing everything, it will be ignored anyway. options.add(new Option("0", lp.getConnectorText("IMPORT_ALL_PROJECT_ISSUES"))); break; case JIRAConstants.IMPORT_ONE_EPIC: List<JIRASubTaskableIssue> epics = service.getProjectIssuesList(projectKey, JIRAConstants.JIRA_ISSUE_EPIC); for (JIRAIssue epic : epics) { Option option = new Option(epic.getKey(), epic.getName()); options.add(option); } break; case JIRAConstants.IMPORT_ONE_BOARD: List<JIRABoard> boards = service.getAllBoards(projectKey); for (JIRABoard board : boards) { Option option = new Option(board.getKey(), board.getName()); options.add(option); } break; case JIRAConstants.IMPORT_ONE_VERSION: List<JIRAVersion> versions = service.getVersions(projectKey); for (JIRAVersion version : versions) { Option option = new Option(version.getId(), version.getName()); options.add(option); } break; default: // Jira Portfolio Type then? if (importSelection.startsWith(JIRAConstants.IMPORT_PORTFOLIO_PREFIX)) { long levelId = Long.parseLong(importSelection.substring(JIRAConstants.IMPORT_PORTFOLIO_PREFIX.length())); List<JIRASubTaskableIssue> portfolioIssues = new ArrayList<>(); for (HierarchyLevelInfo portfolioLevel : service.getJiraPortfolioLevelsInfo()) { if (portfolioLevel.getId() == levelId) { portfolioIssues = service.getProjectIssuesList(projectKey, portfolioLevel.getIssueTypeIds()); break; } } for (JIRAIssue portfolioIssue : portfolioIssues) { Option option = new Option(portfolioIssue.getKey(), portfolioIssue.getName()); options.add(option); } } } return options; } }, new LineBreaker(), importGroupSelectList, new LineBreaker(), new LabelText(JIRAConstants.LABEL_ISSUES_TO_IMPORT, "SELECT_ISSUES_TYPES_TO_IMPORT", "Select issue types to import:", true)})); // List of issue types checkboxes. Set<String> allIssueTypes = new HashSet<String>(); for (Set<String> issueTypes : issueTypesPerProjectKey.values()) { allIssueTypes.addAll(issueTypes); } List<String> sortedIssueTypes = new ArrayList<String>(allIssueTypes); Collections.sort(sortedIssueTypes, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); for (final String issueType : sortedIssueTypes) { fields.add( new CheckBox(getParamNameFromIssueTypeName(issueType), issueType, "Epic".equalsIgnoreCase(issueType) || "Story".equalsIgnoreCase(issueType)) { @Override public List<String> getStyleDependencies() { return Arrays.asList(new String[] {JIRAConstants.KEY_JIRA_PROJECT, JIRAConstants.KEY_IMPORT_SELECTION}); } @Override public FieldAppearance getFieldAppearance(ValueSet values) { String projectKey = values.get(JIRAConstants.KEY_JIRA_PROJECT); String importSelection = values.get(JIRAConstants.KEY_IMPORT_SELECTION); if ((importSelection != null && importSelection.startsWith(JIRAConstants.IMPORT_PORTFOLIO_PREFIX)) || (issueTypesPerProjectKey.get(projectKey) != null && issueTypesPerProjectKey.get(projectKey).contains(issueType))) { // This issue type is enabled for this project or if picking a Jira Portfolio entity as their contents are cross projects. return new FieldAppearance("", "disabled"); } else { // This issue type is disabled for this project return new FieldAppearance("disabled", ""); } } }); } // Last options fields.addAll(Arrays.asList(new Field[] {new LineBreaker(), new LineBreaker(), new LabelText(JIRAConstants.LABEL_PROGRESS_AND_ACTUALS, "LABEL_PROGRESS_AND_ACTUALS", "Issues Progress and Actuals", true), new SelectList(JIRAConstants.KEY_PERCENT_COMPLETE,"PERCENT_COMPLETE_CHOICE",JIRAConstants.PERCENT_COMPLETE_DONE_STORY_POINTS,true) .addLevel(JIRAConstants.KEY_PERCENT_COMPLETE, "PERCENT_COMPLETE_CHOICE") .addOption(new SelectList.Option(JIRAConstants.PERCENT_COMPLETE_DONE_STORY_POINTS,"PERCENT_COMPLETE_DONE_STORY_POINTS")) .addOption(new SelectList.Option(JIRAConstants.PERCENT_COMPLETE_WORK,"PERCENT_COMPLETE_WORK")), new LineBreaker(), new SelectList(JIRAConstants.KEY_ACTUALS,"ACTUALS_CHOICE",JIRAConstants.ACTUALS_LOGGED_WORK,true) .addLevel(JIRAConstants.KEY_ACTUALS, "ACTUALS_CHOICE") .addOption(new SelectList.Option(JIRAConstants.ACTUALS_LOGGED_WORK,"ACTUALS_LOGGED_WORK")) .addOption(new SelectList.Option(JIRAConstants.ACTUALS_SP,"ACTUALS_SP")) .addOption(new SelectList.Option(JIRAConstants.ACTUALS_NO_ACTUALS,"ACTUALS_NO_ACTUALS")), new PlainText(JIRAConstants.ACTUALS_SP_RATIO, "ACTUALS_SP_RATIO", "8", false) { @Override public List<String> getStyleDependencies() { return Arrays.asList(new String[]{JIRAConstants.KEY_ACTUALS}); } @Override public FieldAppearance getFieldAppearance(ValueSet values) { String actualsChoice = values.get(JIRAConstants.KEY_ACTUALS); if (JIRAConstants.ACTUALS_SP.equals(actualsChoice)) { return new FieldAppearance("", "disabled"); } else { return new FieldAppearance("disabled", ""); } } }, new LineBreaker(), new LabelText(JIRAConstants.LABEL_TASKS_OPTIONS, "TASKS_OPTIONS", "Tasks Options:", true), new CheckBox(JIRAConstants.OPTION_INCLUDE_ISSUES_NO_GROUP, "OPTION_INCLUDE_ISSUE_NO_GROUP", true), new LineBreaker(), new CheckBox(JIRAConstants.OPTION_ADD_ROOT_TASK, "OPTION_ADD_ROOT_TASK", true), new PlainText(JIRAConstants.OPTION_ROOT_TASK_NAME, "OPTION_ROOT_TASK_NAME", Providers.getLocalizationProvider(JIRAIntegrationConnector.class).getConnectorText("WORKPLAN_ROOT_TASK_TASK_NAME"), false) { @Override public List<String> getStyleDependencies() { return Arrays.asList(new String[] {JIRAConstants.OPTION_ADD_ROOT_TASK}); } @Override public FieldAppearance getFieldAppearance(ValueSet values) { boolean isCreateRootTask = values.getBoolean(JIRAConstants.OPTION_ADD_ROOT_TASK, false); if (isCreateRootTask) { return new FieldAppearance("", "disabled"); } else { return new FieldAppearance("disabled", ""); } } }, new LineBreaker(), new SelectList(JIRAConstants.OPTION_ADD_EPIC_MILESTONES, "OPTION_ADD_EPIC_MILESTONES", "", true) { @Override public List<String> getStyleDependencies() { return Arrays.asList(new String[] {JIRAConstants.JIRA_ISSUE_EPIC}); } @Override public FieldAppearance getFieldAppearance(ValueSet values) { boolean importEpics = values.getBoolean(JIRAConstants.JIRA_ISSUE_EPIC, true); if (importEpics) { return new FieldAppearance("", "disabled"); } else { return new FieldAppearance("disabled", ""); } } }.addLevel(JIRAConstants.OPTION_ADD_EPIC_MILESTONES, "OPTION_ADD_EPIC_MILESTONES") .addOption(new SelectList.Option("", "OPTION_ADD_EPIC_MILESTONES_NO_MILESTONE")) .addOption(new SelectList.Option("MINOR", "OPTION_ADD_EPIC_MILESTONES_MINOR")).addOption( new SelectList.Option("MAJOR", "OPTION_ADD_EPIC_MILESTONES_MAJOR")) })); return fields; } private String getParamNameFromIssueTypeName(String issueTypeName) { if (issueTypeName == null) { issueTypeName = ""; } return JIRAConstants.JIRA_ISSUE_TYPE_PREFIX + issueTypeName.replace(" ", "__"); } private String getIssueTypeNameFromParamName(String paramName) { if (paramName == null) { return null; } return paramName.substring(JIRAConstants.JIRA_ISSUE_TYPE_PREFIX.length()).replace("__", " "); } @Override /** * This method is in Charge of retrieving all Jira Objects and turning them into a workplan structure to be imported in PPM. */ public ExternalWorkPlan getExternalWorkPlan(WorkPlanIntegrationContext context, final ValueSet values) { String projectKey = values.get(JIRAConstants.KEY_JIRA_PROJECT); String importSelection = values.get(JIRAConstants.KEY_IMPORT_SELECTION); String importSelectionDetails = values.get(JIRAConstants.KEY_IMPORT_SELECTION_DETAILS); String grouping = values.get(JIRAConstants.KEY_IMPORT_GROUPS); String percentCompleteType = values.get(JIRAConstants.KEY_PERCENT_COMPLETE); String actualsType = values.get(JIRAConstants.KEY_ACTUALS); int hoursPerSp = 8; try { hoursPerSp = Integer.parseInt(values.get(JIRAConstants.ACTUALS_SP_RATIO)); } catch (Exception e) { // We use default value of 8; } final boolean addRootTask = values.getBoolean(JIRAConstants.OPTION_ADD_ROOT_TASK, false); boolean includeIssuesWithNoGroup = values.getBoolean(JIRAConstants.OPTION_INCLUDE_ISSUES_NO_GROUP, false); // Following code handles backward compatibility with PPM 9.41 connector. if (JIRAConstants.KEY_ALL_EPICS.equals(values.get(JIRAConstants.KEY_IMPORT_SELECTION))) { // This key only existed in PPM 9.41 connector. It would import all epics, grouped by Epics. importSelection = JIRAConstants.IMPORT_ALL_PROJECT_ISSUES; grouping = JIRAConstants.GROUP_EPIC; includeIssuesWithNoGroup = false; percentCompleteType = JIRAConstants.PERCENT_COMPLETE_DONE_STORY_POINTS; } if (StringUtils.isBlank(grouping)) { grouping = JIRAConstants.GROUP_EPIC; } if (StringUtils.isBlank(percentCompleteType)) { percentCompleteType = JIRAConstants.PERCENT_COMPLETE_DONE_STORY_POINTS; } if (StringUtils.isBlank(importSelectionDetails)) { importSelection = JIRAConstants.IMPORT_ALL_PROJECT_ISSUES; } // End of backward compatibility code final TasksCreationContext taskContext = new TasksCreationContext(); taskContext.workplanIntegrationContext = context; taskContext.percentCompleteType = percentCompleteType; taskContext.userProvider = JIRAServiceProvider.getUserProvider(); taskContext.configValues = values; taskContext.actualsType = actualsType; taskContext.hoursPerSp = hoursPerSp; JIRAService service = JIRAServiceProvider.get(values).useAdminAccount(); // Let's get the sprints info for that project List<JIRASprint> sprints = service.getAllSprints(projectKey); final Map <String, JIRASprint> sprintsById = new LinkedHashMap<String, JIRASprint>(); for (JIRASprint sprint : sprints) { sprintsById.put(sprint.getKey(), sprint); } taskContext.sprints = sprintsById; Set<String> issueTypes = new HashSet<>(); for (String key: values.keySet()) { if (key.startsWith(JIRAConstants.JIRA_ISSUE_TYPE_PREFIX)) { if (values.getBoolean(key, false)) { issueTypes.add(getIssueTypeNameFromParamName(key)); } } } // Following code handles backward compatibility with static issue types selection if (values.getBoolean(JIRAConstants.JIRA_ISSUE_TASK, false)) { issueTypes.add(JIRAConstants.JIRA_ISSUE_TASK); } if (values.getBoolean(JIRAConstants.JIRA_ISSUE_STORY, false)) { issueTypes.add(JIRAConstants.JIRA_ISSUE_STORY); } if (values.getBoolean(JIRAConstants.JIRA_ISSUE_BUG, false)) { issueTypes.add(JIRAConstants.JIRA_ISSUE_BUG); } if (values.getBoolean(JIRAConstants.JIRA_ISSUE_EPIC, false)) { issueTypes.add(JIRAConstants.JIRA_ISSUE_EPIC); } if (values.getBoolean(JIRAConstants.JIRA_ISSUE_FEATURE, false)) { issueTypes.add(JIRAConstants.JIRA_ISSUE_FEATURE); } // End of backward compatibility code // We always want to retrieve epics if grouping tasks by Epics if (JIRAConstants.GROUP_EPIC.equalsIgnoreCase(grouping)) { issueTypes.add(JIRAConstants.JIRA_ISSUE_EPIC); } List<JIRASubTaskableIssue> issues = new ArrayList<JIRASubTaskableIssue>(); final List<JIRAEpic> selectedEpics = new ArrayList<>(); switch(importSelection) { case JIRAConstants.IMPORT_ONE_BOARD: String boardId = importSelectionDetails; issues = service.getBoardIssues(projectKey, issueTypes, boardId); break; case JIRAConstants.IMPORT_ONE_EPIC: String epicKey = importSelectionDetails; issues = service.getAllEpicIssues(projectKey, issueTypes, epicKey); break; case JIRAConstants.IMPORT_ONE_VERSION: String versionId = importSelectionDetails; issues = service.getVersionIssues(projectKey, issueTypes, versionId); break; case JIRAConstants.IMPORT_ALL_PROJECT_ISSUES: issues = service.getAllIssues(projectKey, issueTypes); break; default: // Jira Portfolio Type then? if (importSelection.startsWith(JIRAConstants.IMPORT_PORTFOLIO_PREFIX)) { String portfolioIssueKey = importSelectionDetails; issues = service.getPortfolioIssueDescendants(portfolioIssueKey, issueTypes); } } final List<ExternalTask> rootTasks = new ArrayList<ExternalTask>(); switch(grouping) { case JIRAConstants.GROUP_EPIC: // Root level is epics final List<JIRASubTaskableIssue> noEpicIssues = new ArrayList<JIRASubTaskableIssue>(); for (JIRASubTaskableIssue issue : issues) { if (JIRAConstants.JIRA_ISSUE_EPIC.equalsIgnoreCase(issue.getType())) { // Epic, add it to the root tasks final JIRAEpic epic = (JIRAEpic)issue; selectedEpics.add(epic); rootTasks.add(WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public String getName() { return epic.getFullTaskName(); } @Override public List<ExternalTask> getChildren() { List<ExternalTask> children = new ArrayList<ExternalTask>(); if (epic.hasWork()) { // Epics that will be stored as summary tasks will not have their work taken into account, so we need to create a dummy leaf task for it. final WorkDrivenPercentCompleteExternalTask epicWorkTask = convertJiraIssueToLeafExternalTask(epic, taskContext); epicWorkTask.setNameOverride("[Work]"+epicWorkTask.getName()); children.add(epicWorkTask); } children.addAll(issuesToLeafTasks(epic.getContents(), taskContext)); return children; } @Override public TaskStatus getStatus() { return epic.getExternalTaskStatus(); } @Override public Date getScheduledStart() { return epic.getContents().isEmpty() ? epic.getScheduledStart(taskContext.sprints) : getEarliestScheduledStart(getChildren()); } @Override public Date getScheduledFinish() { return epic.getContents().isEmpty() ? epic.getScheduledFinish(taskContext.sprints) : getLatestScheduledFinish(getChildren()); } @Override public Map<Integer, UserData> getUserDataFields() { Map<Integer, ExternalTask.UserData> userData = new HashMap<Integer, ExternalTask.UserData>(); // Epics can have normal story points, like any leaf task String storyPointsUserDataIndex = taskContext.configValues.get(JIRAConstants.SELECT_USER_DATA_STORY_POINTS); if (!StringUtils.isBlank(storyPointsUserDataIndex) && !"0".equals(storyPointsUserDataIndex)) { if (epic.getStoryPoints() != null) { userData.put(Integer.parseInt(storyPointsUserDataIndex), new ExternalTask.UserData(epic.getStoryPoints().toString(), epic.getStoryPoints().toString())); } } // Epics can also have aggregated Story points. String aggregatedStoryPointsUserDataIndex = taskContext.configValues.get(JIRAConstants.SELECT_USER_DATA_AGGREGATED_STORY_POINTS); if (!StringUtils.isBlank(aggregatedStoryPointsUserDataIndex) && !"0".equals(aggregatedStoryPointsUserDataIndex)) { String aggSP = String.valueOf(epic.getAggregatedStoryPoints()); userData.put(Integer.parseInt(aggregatedStoryPointsUserDataIndex), new ExternalTask.UserData(aggSP, aggSP)); } return userData; } })); } else { // Not an epic. Is it part of an Epic or not? if (isBlank(issue.getEpicKey())) { noEpicIssues.add(issue); } } } if (includeIssuesWithNoGroup && !noEpicIssues.isEmpty()) { rootTasks.add(WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public String getName() { return Providers.getLocalizationProvider(JIRAIntegrationConnector.class).getConnectorText("WORKPLAN_NO_EPIC_DEFINED_TASK_NAME"); } @Override public List<ExternalTask> getChildren() { return issuesToLeafTasks(noEpicIssues, taskContext); } @Override public Date getScheduledStart() { return getEarliestScheduledStart(getChildren()); } @Override public Date getScheduledFinish() { return getLatestScheduledFinish(getChildren()); } })); } break; case JIRAConstants.GROUP_STATUS: final Map<String, List<JIRASubTaskableIssue>> issuesByStatus = new LinkedHashMap<String, List<JIRASubTaskableIssue>>(); final List<JIRASubTaskableIssue> noStatusIssues = new ArrayList<JIRASubTaskableIssue>(); for (JIRASubTaskableIssue issue : issues) { if (isBlank(issue.getStatus())) { noStatusIssues.add(issue); if (includeIssuesWithNoGroup && JIRAConstants.JIRA_ISSUE_EPIC.equalsIgnoreCase(issue.getType())) { selectedEpics.add((JIRAEpic) issue); } continue; } if (JIRAConstants.JIRA_ISSUE_EPIC.equalsIgnoreCase(issue.getType())) { selectedEpics.add((JIRAEpic) issue); } List<JIRASubTaskableIssue> statusIssues = issuesByStatus.get(issue.getStatus()); if (statusIssues == null) { statusIssues = new ArrayList<JIRASubTaskableIssue>(); issuesByStatus.put(issue.getStatus(), statusIssues); } statusIssues.add(issue); } for (final String status : issuesByStatus.keySet()) { rootTasks.add(WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public String getName() { return status; } @Override public List<ExternalTask> getChildren() { return issuesToLeafTasks(issuesByStatus.get(status), taskContext); } @Override public Date getScheduledStart() { return getEarliestScheduledStart(getChildren()); } @Override public Date getScheduledFinish() { return getLatestScheduledFinish(getChildren()); } })); } if (includeIssuesWithNoGroup && !noStatusIssues.isEmpty()) { rootTasks.add(WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public String getName() { return Providers.getLocalizationProvider(JIRAIntegrationConnector.class).getConnectorText("WORKPLAN_NO_STATUS_DEFINED_TASK_NAME"); } @Override public List<ExternalTask> getChildren() { return issuesToLeafTasks(noStatusIssues, taskContext); } @Override public Date getScheduledStart() { return getEarliestScheduledStart(getChildren()); } @Override public Date getScheduledFinish() { return getLatestScheduledFinish(getChildren()); } })); } break; case JIRAConstants.GROUP_SPRINT: // Now let's group issues by sprints final Map<String, List<JIRASubTaskableIssue>> issuesBySprintId = new LinkedHashMap<String, List<JIRASubTaskableIssue>>(); // We initialize the Map contents to get the sprints in the right order for (String sprintId : sprintsById.keySet()) { issuesBySprintId.put(sprintId, new ArrayList<JIRASubTaskableIssue>()); } final List<JIRASubTaskableIssue> backlogIssues = new ArrayList<JIRASubTaskableIssue>(); for (JIRASubTaskableIssue issue : issues) { if (isBlank(issue.getSprintId())) { backlogIssues.add(issue); if (includeIssuesWithNoGroup && JIRAConstants.JIRA_ISSUE_EPIC.equalsIgnoreCase(issue.getType())) { selectedEpics.add((JIRAEpic) issue); } continue; } if (JIRAConstants.JIRA_ISSUE_EPIC.equalsIgnoreCase(issue.getType())) { selectedEpics.add((JIRAEpic) issue); } List<JIRASubTaskableIssue> sprintIssues = issuesBySprintId.get(issue.getSprintId()); if (sprintIssues == null) { sprintIssues = new ArrayList<JIRASubTaskableIssue>(); issuesBySprintId.put(issue.getSprintId(), sprintIssues); } sprintIssues.add(issue); } for (final String sprintId : issuesBySprintId.keySet()) { final JIRASprint sprint = sprintsById.get(sprintId); rootTasks.add(WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public String getName() { return sprint == null ? Providers.getLocalizationProvider(JIRAIntegrationConnector.class).getConnectorText("WORKPLAN_SPRINT_PREFIX_TASK_NAME") + " " + sprintId : sprint.getName(); } @Override public List<ExternalTask> getChildren() { return issuesToLeafTasks(issuesBySprintId.get(sprintId), taskContext); } @Override public Date getScheduledStart() { return (sprint == null || sprint.getStartDateAsDate() == null) ? getEarliestScheduledStart(getChildren()) : sprint.getStartDateAsDate(); } @Override public Date getScheduledFinish() { return (sprint == null || sprint.getEndDateAsDate() == null) ? getLatestScheduledFinish(getChildren()) : sprint.getEndDateAsDate(); } })); } if (includeIssuesWithNoGroup && !backlogIssues.isEmpty()) { rootTasks.add(WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public String getName() { return Providers.getLocalizationProvider(JIRAIntegrationConnector.class).getConnectorText("WORKPLAN_BACKLOG_TASK_NAME"); } @Override public List<ExternalTask> getChildren() { return issuesToLeafTasks(backlogIssues, taskContext); } @Override public Date getScheduledStart() { return getEarliestScheduledStart(getChildren()); } @Override public Date getScheduledFinish() { return getLatestScheduledFinish(getChildren()); } })); } break; case JIRAConstants.GROUP_JIRA_PORTFOLIO_HIERARCHY: // The Jira Portfolio Hierarchy is based on the "Portfolio Parent" field. // So we must first re-build the full hierarchy of tasks, not only with Epic children (Epic only), but with Portfolio Children. // Epic Children remain as it's still used as part of Jira Portfolio Hierarchy. // However, if an issue has different Epic parent & Portfolio [Epic] Parent, the Portfolio one prevails. JIRAPortfolioHierarchy hierarchy = new JIRAPortfolioHierarchy(issues, service); // Jira Portfolio allows loops at some point, so we have to check and prevent them. List<List<JIRAPortfolioHierarchy.Node>> loops = hierarchy.findLoops(); if (!loops.isEmpty()) { // Error, loop detected in Hierarchy for (final List<JIRAPortfolioHierarchy.Node>loop : loops) { rootTasks.add(new ExternalTask() { @Override public String getName() { StringBuilder errorMessage = new StringBuilder("ERROR: Loop detected in JIRA issues hierarchy: "); boolean first = true; for (JIRAPortfolioHierarchy.Node node : loop) { if (first) { first = false; } else { errorMessage.append("->"); } errorMessage.append(node.getIssue().getKey()); } return errorMessage.toString(); } }); } } else { for (JIRAPortfolioHierarchy.Node root : hierarchy.getRootNodes()) { rootTasks.add(convertNodeToExternalTask(root, taskContext)); } for (JIRAPortfolioHierarchy.Node standaloneTask : hierarchy.getStandaloneNodes()) { rootTasks.add(convertNodeToExternalTask(standaloneTask, taskContext)); } selectedEpics.addAll(hierarchy.getEpics()); } break; } if (!StringUtils.isBlank(values.get(JIRAConstants.OPTION_ADD_EPIC_MILESTONES))) { final boolean isMajorMilestone = "MAJOR".equals(values.get(JIRAConstants.OPTION_ADD_EPIC_MILESTONES)); if (!selectedEpics.isEmpty()) { rootTasks.add(WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { private List<ExternalTask> children; { children = new ArrayList<ExternalTask>(selectedEpics.size()); for (final JIRAEpic epic: selectedEpics) { final Date epicMilestoneDate = epic.getEstimatedFinishDate(taskContext.sprints); children.add(WorkDrivenPercentCompleteExternalTask.forLeafTask(new ExternalTask() { private Date milestoneDate = epicMilestoneDate; @Override public String getName() { return epic.getName(); } @Override public boolean isMilestone() { return true; } @Override public boolean isMajorMilestone() { return isMajorMilestone; } @Override public Date getScheduledStart() { return adjustStartDateTime(milestoneDate); } @Override public Double getScheduledDurationOverrideValue() { return 0d; } @Override public TaskStatus getStatus() { return epic.getExternalTaskStatus(); } @Override public Date getScheduledFinish() { return adjustStartDateTime(milestoneDate); } }, 0, 0)); } } @Override public String getName() { return Providers.getLocalizationProvider(JIRAIntegrationConnector.class).getConnectorText("EPIC_MILESTONE_TASK_NAME"); } @Override public List<ExternalTask> getChildren() { return children; } })); } } return new ExternalWorkPlan() { @Override public List<ExternalTask> getRootTasks() { if (addRootTask) { if (rootTasks.size() <= 1) { // If we already have only one root task (or no task), we don't need to add one more. return rootTasks; } ExternalTask rootTask = WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public List<ExternalTask> getChildren() { return rootTasks; } @Override public String getName() { String rootTaskName = values.get(JIRAConstants.OPTION_ROOT_TASK_NAME); if (StringUtils.isBlank(rootTaskName)) { rootTaskName = Providers.getLocalizationProvider(JIRAIntegrationConnector.class).getConnectorText("WORKPLAN_ROOT_TASK_TASK_NAME"); } return rootTaskName; } @Override public Date getScheduledStart() { return getEarliestScheduledStart(getChildren()); } @Override public Date getScheduledFinish() { return getLatestScheduledFinish(getChildren()); } }); return Arrays.asList(new ExternalTask[] {rootTask}); } else { return rootTasks; } } }; } @Override public WorkplanMapping linkTaskWithExternal(WorkPlanIntegrationContext context, WorkplanMapping workplanMapping, ValueSet values) { // A config that's too long will exceed varchar 4000 for storing config, so we'll remove all issue types that are not selected. return removeUncheckedIssuesTypesFromConfig(workplanMapping); } private WorkplanMapping removeUncheckedIssuesTypesFromConfig(WorkplanMapping workplanMapping) { Set<String> issueTypesToRemove = new HashSet<>(); // Update the display config JSon String displayConfigJson = workplanMapping.getConfigDisplayJson(); if (displayConfigJson != null) { JSONObject json = (JSONObject)JSONSerializer.toJSON(displayConfigJson); JSONArray oldConfig = json.getJSONArray("config"); JSONArray newConfig = new JSONArray(); for (int i = 0; i < oldConfig.size(); i++) { JSONObject entry = oldConfig.getJSONObject(i); String label = entry.getString("label"); String text = entry.getString("text"); if ("NO.TXT".equals(text) && !JIRAConstants.OPTION_INCLUDE_ISSUES_NO_GROUP.equals(label) && !JIRAConstants.OPTION_ADD_ROOT_TASK.equals(label)){ // Skip that issue type issueTypesToRemove.add(label); } else { newConfig.add(entry); } } json.put("config", newConfig); workplanMapping.setConfigDisplayJson(json.toString()); } // Update the real config JSon String configJson = workplanMapping.getConfigJson(); if (configJson != null) { JSONObject json = (JSONObject)JSONSerializer.toJSON(configJson); for (String issueTypeToRemove: issueTypesToRemove) { json.remove(getParamNameFromIssueTypeName(issueTypeToRemove)); } workplanMapping.setConfigJson(json.toString()); } return workplanMapping; } private ExternalTask convertNodeToExternalTask(final JIRAPortfolioHierarchy.Node node, final TasksCreationContext taskContext) { if (node.getChildren().isEmpty()) { // Leaf task. return convertJiraIssueToLeafExternalTask(node.getIssue(), taskContext); } // Summary Task. final JIRASubTaskableIssue issue = node.getIssue(); return WorkDrivenPercentCompleteExternalTask.forSummaryTask(new ExternalTask() { @Override public String getName() { return issue.getFullTaskName(); } @Override public List<ExternalTask> getChildren() { List<ExternalTask> children = new ArrayList<ExternalTask>(); if (issue.hasWork()) { // Epics that will be stored as summary tasks will not have their work taken into account, so we need to create a dummy leaf task for it. final WorkDrivenPercentCompleteExternalTask workTask = convertJiraIssueToLeafExternalTask(issue, taskContext); workTask.setNameOverride("[Work]"+workTask.getName()); children.add(workTask); } for (JIRAPortfolioHierarchy.Node child: node.getChildren()) { children.add(convertNodeToExternalTask(child, taskContext)); } return children; } @Override public TaskStatus getStatus() { return issue.getExternalTaskStatus(); } @Override public Date getScheduledStart() { return node.getChildren().isEmpty() ? issue.getScheduledStart(taskContext.sprints) : getEarliestScheduledStart(getChildren()); } @Override public Date getScheduledFinish() { return node.getChildren().isEmpty() ? issue.getScheduledFinish(taskContext.sprints) : getLatestScheduledFinish(getChildren()); } @Override public Map<Integer, UserData> getUserDataFields() { Map<Integer, ExternalTask.UserData> userData = new HashMap<Integer, ExternalTask.UserData>(); // Epics can have normal story points, like any leaf task String storyPointsUserDataIndex = taskContext.configValues.get(JIRAConstants.SELECT_USER_DATA_STORY_POINTS); if (!StringUtils.isBlank(storyPointsUserDataIndex) && !"0".equals(storyPointsUserDataIndex)) { if (issue.getStoryPoints() != null) { userData.put(Integer.parseInt(storyPointsUserDataIndex), new ExternalTask.UserData(issue.getStoryPoints().toString(), issue.getStoryPoints().toString())); } } // Epics can also have aggregated Story points. String aggregatedStoryPointsUserDataIndex = taskContext.configValues.get(JIRAConstants.SELECT_USER_DATA_AGGREGATED_STORY_POINTS); if (!StringUtils.isBlank(aggregatedStoryPointsUserDataIndex) && !"0".equals(aggregatedStoryPointsUserDataIndex)) { String aggSP = String.valueOf(node.getAggregatedStoryPoints()); userData.put(Integer.parseInt(aggregatedStoryPointsUserDataIndex), new ExternalTask.UserData(aggSP, aggSP)); } return userData; } }); } private Date getLatestScheduledFinish(List<ExternalTask> children) { Date date = null; for (ExternalTask child : children) { if (child.getScheduledFinish() == null) { continue; } if (date == null || child.getScheduledFinish().after(date)) { date = child.getScheduledFinish(); } } return date != null ? date : JIRAEntity.getDefaultFinishDate(); } private Date getEarliestScheduledStart(List<ExternalTask> children) { Date date = null; for (ExternalTask child : children) { if (child.getScheduledStart() == null) { continue; } if (date == null || child.getScheduledStart().before(date)) { date = child.getScheduledStart(); } } return date != null ? date : JIRAEntity.getDefaultStartDate(); } /** * Returns true if str is null, "", some spaces, or the string "null". * @param str * @return */ private boolean isBlank(String str) { return StringUtils.isBlank(str) || "null".equalsIgnoreCase(str); } /** * This method declares List<ExternalTask>, but we actually return a List<WorkDrivenPercentCompleteExternalTask>. */ private List<ExternalTask> issuesToLeafTasks(List<JIRASubTaskableIssue> issues, TasksCreationContext context) { List<ExternalTask> externalTasks = new ArrayList<ExternalTask>(issues.size()); for (JIRASubTaskableIssue issue : issues) { externalTasks.add(convertJiraIssueToLeafExternalTask(issue, context)); } return externalTasks; } private WorkDrivenPercentCompleteExternalTask convertJiraIssueToLeafExternalTask(final JIRASubTaskableIssue issue, final TasksCreationContext context) { // First, let's compute the work of that task double doneWork = 0d; double remainingWork = 0d; switch(context.percentCompleteType) { case JIRAConstants.PERCENT_COMPLETE_WORK: if (issue.getWork() != null) { doneWork += getNullSafeDouble(issue.getWork().getTimeSpentHours()); remainingWork += getNullSafeDouble(issue.getWork().getRemainingEstimateHours()); } // Sub Tasks can have work logged against them. if (issue.getSubTasks() != null) { for (JIRASubTask subTask: issue.getSubTasks()) { if (subTask.getWork() != null) { doneWork += getNullSafeDouble(subTask.getWork().getTimeSpentHours()); remainingWork += getNullSafeDouble(subTask.getWork().getRemainingEstimateHours()); } } } break; case JIRAConstants.PERCENT_COMPLETE_DONE_STORY_POINTS: // In story points mode, a task is either 0% or 100% complete. if (issue.isDone()) { doneWork = (issue.getStoryPoints() == null ? 0d : issue.getStoryPoints().doubleValue()); remainingWork = 0d; } else { doneWork = 0d; remainingWork = (issue.getStoryPoints() == null ? 0d : issue.getStoryPoints().doubleValue()); } // Sub Tasks don't have Story Points break; } ExternalTask task = new ExternalTask() { @Override public String getId() { return issue.getKey(); } @Override public TaskStatus getStatus() { return issue.getExternalTaskStatus(); } @Override public String getName() { // We prefix the task name with the issue type return issue.getFullTaskName(); } @Override public Date getScheduledStart() { return issue.getScheduledStart(context.sprints); } @Override public Date getScheduledFinish() { return issue.getScheduledFinish(context.sprints); } @Override public List<ExternalTaskActuals> getActuals() { return generateActuals(issue, context, getScheduledStart()); } @Override public long getOwnerId() { return issue.getAssigneePpmUserId(); } @Override public List<ExternalTask> getChildren() { // We are always generating leaf tasks with this method. return new ArrayList<ExternalTask>(); } @Override public Map<Integer, UserData> getUserDataFields() { Map<Integer, ExternalTask.UserData> userData = new HashMap<Integer, ExternalTask.UserData>(); String storyPointsUserDataIndex = context.configValues.get(JIRAConstants.SELECT_USER_DATA_STORY_POINTS); if (!StringUtils.isBlank(storyPointsUserDataIndex) && !"0".equals(storyPointsUserDataIndex)) { if (issue.getStoryPoints() != null) { userData.put(Integer.parseInt(storyPointsUserDataIndex), new ExternalTask.UserData(issue.getStoryPoints().toString(), issue.getStoryPoints().toString())); } } return userData; } }; return WorkDrivenPercentCompleteExternalTask.forLeafTask(task, doneWork, remainingWork); } private double getNullSafeDouble(Double d) { return d == null ? 0d : d.doubleValue(); } private List<ExternalTaskActuals> generateActuals(final JIRAIssue issue, TasksCreationContext context, final Date scheduledStart) { List<ExternalTaskActuals> actuals = new ArrayList<ExternalTaskActuals>(); if (ExternalTask.TaskStatus.IN_PROGRESS.equals(issue.getExternalTaskStatus())) { // Leaf Tasks that are IN_PROGRESS must always have Actual Start defined on unassigned effort actuals.add(new ExternalTaskActuals() { @Override public Date getActualStart() { return scheduledStart; } @Override public double getPercentComplete() { return 0; } @Override public long getResourceId() { return -1; } @Override public double getScheduledEffort() { return 0; } @Override public double getActualEffort() { return 0; } @Override public Double getEstimatedRemainingEffort() { return 0d; } }); } // If the issue is assigned to someone, we need that person to always appear in the actuals even if they did no work to ensure // They appear in the list of people assigned to the task. if (issue.getAssigneePpmUserId() > 0) { actuals.add(new ExternalTaskActuals() { @Override public double getPercentComplete() { return 0; } @Override public long getResourceId() { return issue.getAssigneePpmUserId(); } @Override public double getScheduledEffort() { return 0; } @Override public double getActualEffort() { return 0; } @Override public Double getEstimatedRemainingEffort() { return 0d; } }); } if (JIRAConstants.ACTUALS_NO_ACTUALS.equals(context.actualsType)) { // No Actuals! return actuals; } else if (JIRAConstants.ACTUALS_SP.equals(context.actualsType)) { // Generate Actual Hours from Story Points actuals.add(convertIssueStoryPointsToActuals(issue, context)); } else { // Default: generate Actuals from Work logged in JIRA if (issue.getWork() != null) { for (JIRAIssueWork.JIRAWorklogEntry worklog : issue.getWork().getWorklogs()) { if (worklog != null) { // These work done are considered 100% complete only if using % work complete or if using % SP done and the task is done. actuals.add(convertWorklogEntryToActuals(worklog, context, JIRAConstants.PERCENT_COMPLETE_DONE_STORY_POINTS.equals(context.percentCompleteType) ? issue.isDone() : true)); } } // Remaining Effort has a dedicated Actuals assigned to whoever the issue is assigned to. if (issue.getWork().getRemainingEstimateHours() != null && issue.getWork().getRemainingEstimateHours() > 0) { actuals.add(getRemainingEffortActuals(issue.getWork().getRemainingEstimateHours(), issue.getAssigneePpmUserId())); } } if (issue instanceof JIRASubTaskableIssue) { // Sub-tasks cannot have story points but they can have time logged against them. List<JIRASubTask> subTasks = ((JIRASubTaskableIssue)issue).getSubTasks(); if (subTasks != null) { for (JIRASubTask subTask : subTasks) { actuals.addAll(generateActuals(subTask, context, scheduledStart)); } } } } return actuals; } private ExternalTaskActuals getRemainingEffortActuals(final double remainingEstimateHours, final long assigneePpmUserId) { return new ExternalTaskActuals() { @Override public double getScheduledEffort() { return remainingEstimateHours; } @Override public Double getEstimatedRemainingEffort() { return remainingEstimateHours; } @Override public double getActualEffort() { return 0d; } @Override public double getPercentComplete() { return 0d; } @Override public long getResourceId() { return assigneePpmUserId; } }; } private ExternalTaskActuals convertIssueStoryPointsToActuals(final JIRAIssue issue, final TasksCreationContext context) { final long spEffort = issue.getStoryPoints() == null ? 0 : issue.getStoryPoints() * context.hoursPerSp; return new ExternalTaskActuals() { @Override public double getScheduledEffort() { return spEffort; } @Override public Date getActualStart() { if (ExternalTask.TaskStatus.IN_PLANNING.equals(issue.getExternalTaskStatus())) { return null; } return issue.getScheduledStart(context.sprints); } @Override public Double getEstimatedRemainingEffort() { if (issue.isDone()) { return 0d; } else { return Double.valueOf(spEffort); } } @Override public Date getActualFinish() { return issue.isDone() ? issue.getScheduledFinish(context.sprints) : null; } @Override public double getActualEffort() { return issue.isDone() ? spEffort : 0d; } @Override public double getPercentComplete() { // Each actual line from work log will be considered to be completed only if the task is done. return issue.isDone() ? 100d : 0d; } @Override public long getResourceId() { return issue.getAssigneePpmUserId(); } @Override public Date getEstimatedFinishDate() { return issue.getScheduledFinish(context.sprints); } }; } private ExternalTaskActuals convertWorklogEntryToActuals(final JIRAIssueWork.JIRAWorklogEntry worklog, final TasksCreationContext context, final boolean isTaskDone) { return new ExternalTaskActuals() { @Override public double getScheduledEffort() { return worklog.getTimeSpentHours(); } @Override public Date getActualStart() { return worklog.getDateStartedAsDate(); } @Override public Double getEstimatedRemainingEffort() { return 0d; } @Override public Date getActualFinish() { return isTaskDone ? worklog.getDateStartedAsDate() : null; } @Override public double getActualEffort() { return worklog.getTimeSpentHours(); } @Override public double getPercentComplete() { // Each actual line from work log will be considered to be completed only if the task is done. return isTaskDone ? 100d : 0d; } @Override public long getResourceId() { User user = context.userProvider.getByEmail(worklog.getAuthorEmail()); return user == null ? -1 : user.getUserId(); } @Override public Date getEstimatedFinishDate() { return worklog.getDateStartedAsDate(); } }; } /** * This will allow to have the information in PPM DB table PPMIC_WORKPLAN_MAPPINGS of what entity in JIRA is effectively linked to the PPM work plan task. * It is very useful for reporting purpose. * @since 9.42 */ public LinkedTaskAgileEntityInfo getAgileEntityInfoFromMappingConfiguration(ValueSet values) { LinkedTaskAgileEntityInfo info = new LinkedTaskAgileEntityInfo(); String importSelect = values.get(JIRAConstants.KEY_IMPORT_SELECTION); info.setProjectId(values.get(JIRAConstants.KEY_JIRA_PROJECT)); if (importSelect == null) { return info; } switch (importSelect) { case JIRAConstants.IMPORT_ALL_PROJECT_ISSUES: return info; case JIRAConstants.IMPORT_ONE_BOARD: // Technically it is NOT the sprint id but the Board ID - warning. info.setSprintId(values.get(JIRAConstants.KEY_IMPORT_SELECTION_DETAILS)); return info; case JIRAConstants.IMPORT_ONE_EPIC: info.setEpicId(values.get(JIRAConstants.KEY_IMPORT_SELECTION_DETAILS)); return info; case JIRAConstants.IMPORT_ONE_VERSION: info.setReleaseId(values.get(JIRAConstants.KEY_IMPORT_SELECTION_DETAILS)); return info; default: return info; } } private class TasksCreationContext { public String percentCompleteType; public Map<String, JIRASprint> sprints; public WorkPlanIntegrationContext workplanIntegrationContext; public UserProvider userProvider; public ValueSet configValues; public String actualsType; public int hoursPerSp; } }
package tk.adamj57.Launchpad.LChar; import java.awt.Point; public enum LChar { a(new Point[]{ createPoint(1, 4), createPoint(2, 1), createPoint(2, 3), createPoint(2, 5), createPoint(3, 1), createPoint(3, 3), createPoint(3, 5), createPoint(4, 1), createPoint(4, 3), createPoint(4, 5), createPoint(5, 1), createPoint(5, 3), createPoint(5, 4), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'a'), b(new Point[]{ createPoint(1, 0), createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(2, 2), createPoint(2, 4), createPoint(3, 2), createPoint(3, 5), createPoint(4, 2), createPoint(4, 5), createPoint(5, 2), createPoint(5, 5), createPoint(6, 3), createPoint(6, 4)}, 'b'), c(new Point[]{ createPoint(2, 3), createPoint(2, 4), createPoint(3, 2), createPoint(3, 5), createPoint(4, 2), createPoint(4, 5), createPoint(5, 2), createPoint(5, 5)}, 'c'), d(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(3, 2), createPoint(3, 5), createPoint(4, 2), createPoint(4, 5), createPoint(5, 2), createPoint(5, 4), createPoint(6, 0), createPoint(6, 1), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'd'), e(new Point[]{ createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(2, 1), createPoint(2, 3), createPoint(2, 5), createPoint(3, 1), createPoint(3, 3), createPoint(3, 5), createPoint(4, 1), createPoint(4, 3), createPoint(4, 5), createPoint(5, 1), createPoint(5, 3), createPoint(5, 5), createPoint(6, 2), createPoint(6, 3)}, 'e'), f(new Point[]{ createPoint(2, 3), createPoint(3, 1), createPoint(3, 2), createPoint(3, 3), createPoint(3, 4), createPoint(3, 5), createPoint(4, 1), createPoint(4, 3)}, 'f'), g(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(2, 7), createPoint(3, 2), createPoint(3, 5), createPoint(3, 7), createPoint(4, 3), createPoint(4, 7), createPoint(5, 2), createPoint(5, 3), createPoint(5, 4), createPoint(5, 5), createPoint(5, 6)}, 'g'), h(new Point[]{ createPoint(2, 0), createPoint(2, 1), createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 2), createPoint(4, 2), createPoint(5, 3), createPoint(5, 4), createPoint(5, 5)}, 'h'), i(new Point[]{ createPoint(4, 0), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5)}, 'i'), j(new Point[]{ createPoint(1, 7), createPoint(2, 7), createPoint(3, 2), createPoint(3, 7), createPoint(4, 0), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 6)}, 'j'), k(new Point[]{ createPoint(2, 1), createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 4), createPoint(4, 3), createPoint(4, 5), createPoint(5, 2), createPoint(5, 5)}, 'k'), l(new Point[]{createPoint(3, 0), createPoint(3, 1), createPoint(3, 2), createPoint(3, 3), createPoint(3, 4), createPoint(3, 5), createPoint(4, 5)}, 'l'), m(new Point[]{ createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(2, 2), createPoint(3, 3), createPoint(4, 3), createPoint(5, 2), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'm'), n(new Point[]{ createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 3), createPoint(4, 2), createPoint(5, 2), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'n'), o(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(3, 2), createPoint(3, 5), createPoint(4, 2), createPoint(4, 5), createPoint(5, 2), createPoint(5, 5), createPoint(6, 3), createPoint(6, 4)}, 'o'), p(new Point[]{ createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(1, 6), createPoint(1, 7), createPoint(2, 3), createPoint(2, 5), createPoint(3, 2), createPoint(3, 5), createPoint(4, 2), createPoint(4, 5), createPoint(5, 2), createPoint(5, 5), createPoint(6, 3), createPoint(6, 4)}, 'p'), q(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(3, 2), createPoint(3, 5), createPoint(4, 2), createPoint(4, 5), createPoint(5, 3), createPoint(5, 5), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5), createPoint(6, 6), createPoint(6, 7)}, 'q'), r(new Point[]{ createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 3), createPoint(4, 2), createPoint(5, 2), createPoint(6, 3)}, 'r'), s(new Point[]{ createPoint(2, 2), createPoint(2, 5), createPoint(3, 1), createPoint(3, 3), createPoint(3, 5), createPoint(4, 1), createPoint(4, 3), createPoint(4, 5), createPoint(5, 1), createPoint(5, 4)}, 's'), t(new Point[]{ createPoint(2, 2), createPoint(3, 1), createPoint(3, 2), createPoint(3, 3), createPoint(3, 4), createPoint(3, 5), createPoint(4, 2), createPoint(4, 5), createPoint(5, 2)}, 't'), u(new Point[]{ createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(3, 5), createPoint(4, 5), createPoint(5, 4), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'u'), v(new Point[]{ createPoint(1, 2), createPoint(1, 3), createPoint(2, 4), createPoint(3, 5), createPoint(4, 5), createPoint(5, 4), createPoint(6, 2), createPoint(6, 3)}, 'v'), w(new Point[]{ createPoint(0, 2), createPoint(0, 3), createPoint(1, 4), createPoint(1, 5), createPoint(2, 5), createPoint(3, 4), createPoint(4, 4), createPoint(5, 5), createPoint(6, 4), createPoint(6, 5), createPoint(7, 2), createPoint(7, 3)}, 'w'), x(new Point[]{ createPoint(1, 2), createPoint(1, 5), createPoint(2, 3), createPoint(2, 5), createPoint(3, 4), createPoint(4, 4), createPoint(5, 3), createPoint(5, 5), createPoint(6, 2), createPoint(6, 5)}, 'x'), y(new Point[]{ createPoint(1, 2), createPoint(1, 7), createPoint(2, 3), createPoint(2, 7), createPoint(3, 4), createPoint(3, 6), createPoint(4, 5), createPoint(5, 4), createPoint(6, 2), createPoint(6, 3)}, 'y'), z(new Point[]{ createPoint(2, 2), createPoint(2, 5), createPoint(3, 2), createPoint(3, 4), createPoint(3, 5), createPoint(4, 2), createPoint(4, 3), createPoint(4, 5), createPoint(5, 2), createPoint(5, 5)}, 'z'), A(new Point[]{ createPoint(1, 5), createPoint(1, 6), createPoint(2, 3), createPoint(2, 4), createPoint(3, 1), createPoint(3, 2), createPoint(3, 4), createPoint(4, 1), createPoint(4, 2), createPoint(4, 4), createPoint(5, 3), createPoint(5, 4), createPoint(6, 5), createPoint(6, 6)}, 'A'), B(new Point[]{ createPoint(2, 1), createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(2, 6), createPoint(3, 1), createPoint(3, 3), createPoint(3, 6), createPoint(4, 1), createPoint(4, 3), createPoint(4, 6), createPoint(5, 1), createPoint(5, 3), createPoint(5, 6), createPoint(6, 2), createPoint(6, 4), createPoint(6, 5)}, 'B'), C(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 6), createPoint(5, 1), createPoint(5, 6), createPoint(6, 2), createPoint(6, 5)}, 'C'), D(new Point[]{ createPoint(2, 1), createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(2, 6), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 6), createPoint(5, 1), createPoint(5, 6), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'D'), F(new Point[]{ createPoint(2, 1), createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(2, 6), createPoint(3, 1), createPoint(3, 3), createPoint(4, 1), createPoint(4, 3), createPoint(5, 1), createPoint(5, 3), createPoint(6, 1)}, 'F'), G(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 4), createPoint(4, 6), createPoint(5, 1), createPoint(5, 4), createPoint(5, 6), createPoint(6, 2), createPoint(6, 4), createPoint(6, 5)}, 'G'), H(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(1, 6), createPoint(2, 3), createPoint(3, 3), createPoint(4, 3), createPoint(5, 3), createPoint(6, 1), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5), createPoint(6, 6)}, 'H'), I(new Point[]{ createPoint(2, 1), createPoint(2, 6), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 6), createPoint(5, 1), createPoint(5, 6), createPoint(6, 1), createPoint(6, 6)}, 'I'), J(new Point[]{ createPoint(2, 5), createPoint(3, 6), createPoint(4, 1), createPoint(4, 6), createPoint(5, 1), createPoint(5, 6), createPoint(6, 1), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'J'), K(new Point[]{ createPoint(2, 1), createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(2, 6), createPoint(3, 4), createPoint(4, 3), createPoint(4, 4), createPoint(5, 2), createPoint(5, 5), createPoint(6, 1), createPoint(6, 6)}, 'K'), L(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(1, 6), createPoint(2, 6), createPoint(3, 6), createPoint(4, 6), createPoint(5, 6), createPoint(6, 6)}, 'L'), M(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(1, 6), createPoint(2, 2), createPoint(3, 3), createPoint(4, 4), createPoint(5, 3), createPoint(6, 2), createPoint(7, 1), createPoint(7, 2), createPoint(7, 3), createPoint(7, 4), createPoint(7, 5), createPoint(7, 6)}, 'M'), N(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(1, 6), createPoint(2, 2), createPoint(3, 3), createPoint(4, 4), createPoint(5, 5), createPoint(6, 1), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5), createPoint(6, 6)}, 'N'), O(new Point[]{ createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 6), createPoint(5, 1), createPoint(5, 6), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'O'), P(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(1, 6), createPoint(2, 1), createPoint(2, 3), createPoint(3, 1), createPoint(3, 3), createPoint(4, 1), createPoint(4, 3), createPoint(5, 2)}, 'P'), Q(new Point[]{ createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 6), createPoint(5, 1), createPoint(5, 6), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5), createPoint(6, 7)}, 'Q'), R(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(1, 6), createPoint(2, 1), createPoint(2, 3), createPoint(3, 1), createPoint(3, 3), createPoint(3, 4), createPoint(4, 1), createPoint(4, 3), createPoint(4, 5), createPoint(5, 2), createPoint(5, 6)}, 'R'), S(new Point[]{ createPoint(2, 2), createPoint(2, 5), createPoint(3, 1), createPoint(3, 3), createPoint(3, 6), createPoint(4, 1), createPoint(4, 4), createPoint(4, 6), createPoint(5, 1), createPoint(5, 4), createPoint(5, 6), createPoint(6, 2), createPoint(6, 5)}, 'S'), T(new Point[]{ createPoint(1, 1), createPoint(2, 1), createPoint(3, 1), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 6), createPoint(5, 1), createPoint(6, 1), createPoint(7, 1)}, 'T'), U(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(2, 6), createPoint(3, 6), createPoint(4, 6), createPoint(5, 6), createPoint(6, 1), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, 'U'), V(new Point[]{ createPoint(0, 1), createPoint(1, 2), createPoint(1, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 6), createPoint(4, 6), createPoint(5, 4), createPoint(5, 5), createPoint(6, 2), createPoint(6, 3), createPoint(7, 1)}, 'V'), W(new Point[]{ createPoint(0, 0), createPoint(0, 1), createPoint(0, 2), createPoint(0, 3), createPoint(0, 4), createPoint(0, 5), createPoint(0, 6), createPoint(1, 5), createPoint(2, 4), createPoint(3, 3), createPoint(4, 4), createPoint(5, 5), createPoint(6, 0), createPoint(6, 1), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5), createPoint(6, 6)}, 'W'), X(new Point[]{ createPoint(1, 1), createPoint(1, 6), createPoint(2, 2), createPoint(2, 5), createPoint(3, 3), createPoint(3, 4), createPoint(4, 3), createPoint(4, 4), createPoint(5, 2), createPoint(5, 5), createPoint(6, 1), createPoint(6, 6)}, 'X'), Y(new Point[]{ createPoint(1, 1), createPoint(2, 2), createPoint(3, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 6), createPoint(5, 3), createPoint(6, 2), createPoint(7, 1)}, 'Y'), Z(new Point[]{ createPoint(1, 1), createPoint(1, 6), createPoint(2, 1), createPoint(2, 5), createPoint(2, 6), createPoint(3, 1), createPoint(3, 4), createPoint(3, 6), createPoint(4, 1), createPoint(4, 3), createPoint(4, 6), createPoint(5, 1), createPoint(5, 2), createPoint(5, 6), createPoint(6, 1), createPoint(6, 6)}, 'Z'), one(new Point[]{ createPoint(3, 2), createPoint(3, 6), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 6), createPoint(5, 6)}, '1'), zero(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 6), createPoint(5, 2), createPoint(5, 5), createPoint(6, 3), createPoint(6, 4)}, '0'), two(new Point[]{ createPoint(1, 2), createPoint(1, 6), createPoint(2, 1), createPoint(2, 5), createPoint(2, 6), createPoint(3, 1), createPoint(3, 4), createPoint(3, 6), createPoint(4, 1), createPoint(4, 4), createPoint(4, 6), createPoint(5, 1), createPoint(5, 3), createPoint(5, 6), createPoint(6, 2), createPoint(6, 6)}, '2'), three(new Point[]{ createPoint(1, 2), createPoint(1, 5), createPoint(2, 1), createPoint(2, 6), createPoint(3, 1), createPoint(3, 4), createPoint(3, 6), createPoint(4, 1), createPoint(4, 4), createPoint(4, 6), createPoint(5, 1), createPoint(5, 3), createPoint(5, 6), createPoint(6, 2), createPoint(6, 5)}, '3'), four(new Point[]{ createPoint(1, 4), createPoint(1, 5), createPoint(2, 3), createPoint(2, 5), createPoint(3, 2), createPoint(3, 5), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 6), createPoint(5, 5)}, '4'), five(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 3), createPoint(1, 5), createPoint(2, 1), createPoint(2, 3), createPoint(2, 6), createPoint(3, 1), createPoint(3, 3), createPoint(3, 6), createPoint(4, 1), createPoint(4, 3), createPoint(4, 6), createPoint(5, 1), createPoint(5, 3), createPoint(5, 6), createPoint(6, 1), createPoint(6, 4), createPoint(6, 5)}, '5'), six(new Point[]{ createPoint(1, 2), createPoint(1, 3), createPoint(1, 4), createPoint(1, 5), createPoint(2, 1), createPoint(2, 3), createPoint(2, 6), createPoint(3, 1), createPoint(3, 3), createPoint(3, 6), createPoint(4, 1), createPoint(4, 3), createPoint(4, 6), createPoint(5, 1), createPoint(5, 3), createPoint(5, 6), createPoint(6, 4), createPoint(6, 5)}, '6'), seven(new Point[]{ createPoint(1, 1), createPoint(1, 6), createPoint(2, 1), createPoint(2, 5), createPoint(3, 1), createPoint(3, 4), createPoint(4, 1), createPoint(4, 3), createPoint(5, 1), createPoint(5, 2), createPoint(6, 1)}, '7'), eight(new Point[]{ createPoint(1, 2), createPoint(1, 4), createPoint(1, 5), createPoint(2, 1), createPoint(2, 3), createPoint(2, 6), createPoint(3, 1), createPoint(3, 3), createPoint(3, 6), createPoint(4, 1), createPoint(4, 3), createPoint(4, 6), createPoint(5, 1), createPoint(5, 3), createPoint(5, 6), createPoint(6, 2), createPoint(6, 4), createPoint(6, 5)}, '8'), nine(new Point[]{ createPoint(1, 2), createPoint(1, 3), createPoint(2, 1), createPoint(2, 4), createPoint(2, 6), createPoint(3, 1), createPoint(3, 4), createPoint(3, 6), createPoint(4, 1), createPoint(4, 4), createPoint(4, 6), createPoint(5, 1), createPoint(5, 4), createPoint(5, 6), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5)}, '9'), space(new Point[]{ }, ' '), exclamMark(new Point[]{ createPoint(4, 0), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 5)}, '!'), quoteMark(new Point[]{ createPoint(2, 0), createPoint(2, 1), createPoint(4, 0), createPoint(4, 1)}, '\"'), hash(new Point[]{ createPoint(1, 2), createPoint(1, 4), createPoint(2, 1), createPoint(2, 2), createPoint(2, 3), createPoint(2, 4), createPoint(2, 5), createPoint(3, 2), createPoint(3, 4), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(5, 2), createPoint(5, 4)}, ' dollar(new Point[]{ createPoint(2, 2), createPoint(2, 5), createPoint(3, 1), createPoint(3, 3), createPoint(3, 5), createPoint(4, 0), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 6), createPoint(5, 1), createPoint(5, 3), createPoint(5, 5), createPoint(6, 1), createPoint(6, 4)}, '$'), percent(new Point[]{ createPoint(0, 1), createPoint(1, 0), createPoint(1, 2), createPoint(2, 0), createPoint(2, 2), createPoint(2, 4), createPoint(3, 1), createPoint(3, 3), createPoint(4, 2), createPoint(4, 4), createPoint(5, 1), createPoint(5, 3), createPoint(5, 5), createPoint(6, 3), createPoint(6, 5), createPoint(7, 4)}, '%'), ampersand(new Point[]{ createPoint(1, 1), createPoint(1, 2), createPoint(1, 4), createPoint(2, 0), createPoint(2, 3), createPoint(2, 5), createPoint(3, 0), createPoint(3, 3), createPoint(3, 5), createPoint(4, 0), createPoint(4, 4), createPoint(5, 4), createPoint(6, 3), createPoint(6, 5)}, '&'), apostrophe(new Point[]{ createPoint(4, 0), createPoint(4, 1)}, '\''), leftBracket(new Point[]{ createPoint(2, 2), createPoint(2, 3), createPoint(3, 1), createPoint(3, 4), createPoint(4, 0), createPoint(4, 5)}, '('), rightBracket(new Point[]{ createPoint(3, 0), createPoint(3, 5), createPoint(4, 1), createPoint(4, 4), createPoint(5, 2), createPoint(5, 3)}, ')'), star(new Point[]{ createPoint(2, 0), createPoint(2, 2), createPoint(2, 4), createPoint(3, 1), createPoint(3, 2), createPoint(3, 3), createPoint(4, 0), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(5, 1), createPoint(5, 2), createPoint(5, 3), createPoint(6, 0), createPoint(6, 2), createPoint(6, 4)}, '*'), plus(new Point[]{ createPoint(2, 3), createPoint(3, 3), createPoint(4, 1), createPoint(4, 2), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(5, 3), createPoint(6, 3)}, '+'), comma(new Point[]{ createPoint(3, 6), createPoint(4, 5)}, ','), minus(new Point[]{ createPoint(3, 3), createPoint(4, 3), createPoint(5, 3)}, '-'), fullstop(new Point[]{ createPoint(4, 6)}, '.'), slash(new Point[]{ createPoint(1, 6), createPoint(2, 5), createPoint(3, 4), createPoint(4, 3), createPoint(5, 2), createPoint(6, 1)}, '/'), colon(new Point[]{ createPoint(4, 3), createPoint(4, 6)}, ':'), semicolon(new Point[]{ createPoint(3, 7), createPoint(4, 3), createPoint(4, 6)}, ';'), less_than(new Point[]{ createPoint(1, 3), createPoint(2, 3), createPoint(3, 2), createPoint(3, 4), createPoint(4, 2), createPoint(4, 4), createPoint(5, 1), createPoint(5, 5), createPoint(6, 1), createPoint(6, 5)}, '<'), equals(new Point[]{ createPoint(1, 2), createPoint(1, 4), createPoint(2, 2), createPoint(2, 4), createPoint(3, 2), createPoint(3, 4), createPoint(4, 2), createPoint(4, 4), createPoint(5, 2), createPoint(5, 4), createPoint(6, 2), createPoint(6, 4)}, '='), greater_than(new Point[]{ createPoint(1, 1), createPoint(1, 5), createPoint(2, 1), createPoint(2, 5), createPoint(3, 2), createPoint(3, 4), createPoint(4, 2), createPoint(4, 4), createPoint(5, 3), createPoint(6, 3)}, '>'), question_mark(new Point[]{ createPoint(1, 2), createPoint(2, 1), createPoint(3, 1), createPoint(4, 1), createPoint(4, 4), createPoint(4, 6), createPoint(5, 1), createPoint(5, 4), createPoint(6, 2), createPoint(6, 3)}, '?'), at_sign(new Point[]{ createPoint(1, 3), createPoint(1, 4), createPoint(2, 2), createPoint(2, 5), createPoint(3, 1), createPoint(3, 6), createPoint(4, 1), createPoint(4, 3), createPoint(4, 4), createPoint(4, 5), createPoint(4, 7), createPoint(5, 1), createPoint(5, 3), createPoint(5, 5), createPoint(5, 7), createPoint(6, 1), createPoint(6, 2), createPoint(6, 3), createPoint(6, 4), createPoint(6, 5), createPoint(6, 7)}, '@'); private Point[] pixelList; private char character; private LChar(Point[] pixelList, char character){ this.pixelList = pixelList; this.character = character; } public Point[] getPixelList(){ return pixelList; } public static char toChar(LChar lChar){ return lChar.character; } public static LChar toLChar(char character) throws UndefinedCharException{ LChar[] allValuesOfLChar = LChar.values(); for(LChar lChar : allValuesOfLChar){ if(character == LChar.toChar(lChar)){ return lChar; } } throw new UndefinedCharException(); } public static LChar[] toLChar(String stringToConvert) throws UndefinedCharException{ int stringLength = stringToConvert.length(); LChar[] lCharedString = new LChar[stringLength]; for(int i = 0; i < stringLength; i++){ lCharedString[i] = LChar.toLChar(stringToConvert.charAt(i)); } return lCharedString; } private static Point createPoint(int x, int y){ return new Point(x, y); } }
package com.intellij.ui; import com.intellij.openapi.Disposable; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupListener; import com.intellij.openapi.ui.popup.LightweightWindow; import com.intellij.openapi.ui.popup.LightweightWindowEvent; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Ref; import com.intellij.openapi.wm.impl.content.GraphicsConfig; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.components.panels.Wrapper; import com.intellij.util.Alarm; import com.intellij.util.ui.Animator; import com.intellij.util.ui.BaseButtonBehavior; import com.intellij.util.ui.TimedDeadzone; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.text.html.HTMLEditorKit; import java.awt.*; import java.awt.event.*; import java.awt.geom.GeneralPath; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.util.concurrent.CopyOnWriteArraySet; public class BalloonImpl implements Disposable, Balloon, LightweightWindow { private MyComponent myComp; private JLayeredPane myLayeredPane; private Position myPosition; private Point myTargetPoint; private boolean myHideOnFrameResize; private final Color myBorderColor; private final Color myFillColor; private final Insets myContainerInsets = new Insets(4, 4, 4, 4); private boolean myLastMoveWasInsideBalloon; private Rectangle myForcedBounds; private final AWTEventListener myAwtActivityListener = new AWTEventListener() { public void eventDispatched(final AWTEvent event) { if (myHideOnMouse && (event.getID() == MouseEvent.MOUSE_PRESSED || event.getID() == MouseEvent.MOUSE_RELEASED || event.getID() == MouseEvent.MOUSE_CLICKED)) { final MouseEvent me = (MouseEvent)event; if (isInsideBalloon(me)) return; hide(); return; } if (myClickHandler != null && event.getID() == MouseEvent.MOUSE_CLICKED) { final MouseEvent me = (MouseEvent)event; if (!(me.getComponent() instanceof CloseButton) && isInsideBalloon(me)) { myClickHandler.actionPerformed(new ActionEvent(BalloonImpl.this, ActionEvent.ACTION_PERFORMED, "click", me.getModifiersEx())); if (myCloseOnClick) { hide(); return; } } } if (myEnableCloseButton && event.getID() == MouseEvent.MOUSE_MOVED) { final MouseEvent me = (MouseEvent)event; final boolean inside = isInsideBalloon(me); final boolean moveChanged = inside != myLastMoveWasInsideBalloon; myLastMoveWasInsideBalloon = inside; if (moveChanged) { myComp.repaint(); } } if (myHideOnKey && (event.getID() == KeyEvent.KEY_PRESSED)) { final KeyEvent ke = (KeyEvent)event; if (SwingUtilities.isDescendingFrom(ke.getComponent(), myComp) || ke.getComponent() == myComp) return; hide(); } } }; private long myFadeoutTime; private Dimension myDefaultPrefSize; private ActionListener myClickHandler; private boolean myCloseOnClick; private CopyOnWriteArraySet<JBPopupListener> myListeners = new CopyOnWriteArraySet<JBPopupListener>(); private boolean myVisible; private boolean isInsideBalloon(MouseEvent me) { if (!me.getComponent().isShowing()) return true; if (SwingUtilities.isDescendingFrom(me.getComponent(), myComp) || me.getComponent() == myComp) return true; final Point mouseEventPoint = me.getPoint(); SwingUtilities.convertPointToScreen(mouseEventPoint, me.getComponent()); final Rectangle compRect = new Rectangle(myComp.getLocationOnScreen(), myComp.getSize()); if (compRect.contains(mouseEventPoint)) return true; return false; } private final ComponentAdapter myComponentListener = new ComponentAdapter() { public void componentResized(final ComponentEvent e) { if (myHideOnFrameResize) { hide(); } } }; private Animator myAnimator; private boolean myShowPointer; private boolean myDisposed; private final JComponent myContent; private final boolean myHideOnMouse; private final boolean myHideOnKey; private boolean myEnableCloseButton; private Icon myCloseButton = IconLoader.getIcon("/general/balloonClose.png"); public BalloonImpl(JComponent content, Color borderColor, Color fillColor, boolean hideOnMouse, boolean hideOnKey, boolean showPointer, boolean enableCloseButton, long fadeoutTime, boolean hideOnFrameResize, ActionListener clickHandler, boolean closeOnClick) { myBorderColor = borderColor; myFillColor = fillColor; myContent = content; myHideOnMouse = hideOnMouse; myHideOnKey = hideOnKey; myShowPointer = showPointer; myEnableCloseButton = enableCloseButton; myHideOnFrameResize = hideOnFrameResize; myClickHandler = clickHandler; myCloseOnClick = closeOnClick; myFadeoutTime = fadeoutTime; } public void show(final RelativePoint target, final Balloon.Position position) { Position pos = BELOW; switch (position) { case atLeft: pos = AT_LEFT; break; case atRight: pos = AT_RIGHT; break; case below: pos = BELOW; break; case above: pos = ABOVE; break; } show(target, pos); } private void show(RelativePoint target, Position position) { if (isVisible()) return; assert !myDisposed : "Balloon is already disposed"; assert target.getComponent().isShowing() : "Target component is not showing: " + target; final Window window = SwingUtilities.getWindowAncestor(target.getComponent()); JRootPane root = null; if (window instanceof JFrame) { root = ((JFrame)window).getRootPane(); } else if (window instanceof JDialog) { root = ((JDialog)window).getRootPane(); } else { assert false : window; } myVisible = true; myLayeredPane = root.getLayeredPane(); myPosition = position; myLayeredPane.addComponentListener(myComponentListener); final EmptyBorder border = myShowPointer ? myPosition.createBorder(this) : new EmptyBorder(getNormalInset(), getNormalInset(), getNormalInset(), getNormalInset()); myComp = new MyComponent(myContent, this, border); myTargetPoint = target.getPoint(myLayeredPane); myComp.clear(); myComp.myAlpha = 0f; for (JBPopupListener each : myListeners) { each.beforeShown(new LightweightWindowEvent(this)); } myLayeredPane.add(myComp, JLayeredPane.POPUP_LAYER); myPosition.updateLocation(this); runAnimation(true, myLayeredPane); myLayeredPane.revalidate(); myLayeredPane.repaint(); Toolkit.getDefaultToolkit().addAWTEventListener(myAwtActivityListener, MouseEvent.MOUSE_EVENT_MASK | MouseEvent.MOUSE_MOTION_EVENT_MASK | KeyEvent.KEY_EVENT_MASK); } public void show(JLayeredPane pane) { show(pane, null); } public void show(JLayeredPane pane, @Nullable Rectangle bounds) { if (bounds != null) { myForcedBounds = bounds; } show(new RelativePoint(pane, new Point(0, 0)), Balloon.Position.above); } private void runAnimation(boolean forward, final JLayeredPane layeredPane) { if (myAnimator != null) { Disposer.dispose(myAnimator); } myAnimator = new Animator("Balloon", 10, 500, false, 0, 1, forward) { public void paintNow(final float frame, final float totalFrames, final float cycle) { if (myComp.getParent() == null) return; myComp.setAlpha(frame / totalFrames); } @Override protected void paintCycleEnd() { if (myComp.getParent() == null) return; if (isForward()) { myComp.clear(); myComp.repaint(); startFadeoutTimer(); } else { layeredPane.remove(myComp); layeredPane.revalidate(); layeredPane.repaint(); } Disposer.dispose(this); } @Override public void dispose() { super.dispose(); myAnimator = null; } }; myAnimator.setTakInitialDelay(false); myAnimator.resume(); } private void startFadeoutTimer() { if (myFadeoutTime > 0) { Alarm fadeoutAlarm = new Alarm(this); fadeoutAlarm.addRequest(new Runnable() { public void run() { hide(); } }, (int)myFadeoutTime, null); } } int getArc() { return 6; } int getPointerWidth() { return 12; } int getNormalInset() { return 4; } int getShadowShift() { return 10; } int getPointerLength() { return 16; } public void hide() { Disposer.dispose(this); for (JBPopupListener each : myListeners) { each.onClosed(new LightweightWindowEvent(this)); } } public void addListener(JBPopupListener listener) { myListeners.add(listener); } public void dispose() { if (myDisposed) return; Disposer.dispose(this); myDisposed = true; Toolkit.getDefaultToolkit().removeAWTEventListener(myAwtActivityListener); if (myLayeredPane != null) { myLayeredPane.removeComponentListener(myComponentListener); runAnimation(false, myLayeredPane); } myVisible = false; onDisposed(); } protected void onDisposed() { } public boolean isVisible() { return myVisible; } public void setShowPointer(final boolean show) { myShowPointer = show; } public Icon getCloseButton() { return myCloseButton; } public void setBounds(Rectangle bounds) { myForcedBounds = bounds; if (myPosition != null) { myPosition.updateLocation(this); } } public Dimension getPreferredSize() { if (myComp != null) { return myComp.getPreferredSize(); } else { if (myDefaultPrefSize == null) { final EmptyBorder border = new EmptyBorder(getNormalInset(), getNormalInset(), getNormalInset(), getNormalInset()); final MyComponent c = new MyComponent(myContent, this, border); myDefaultPrefSize = c.getPreferredSize(); } return myDefaultPrefSize; } } public abstract static class Position { abstract EmptyBorder createBorder(final BalloonImpl balloon); public void updateLocation(final BalloonImpl balloon) { Rectangle bounds = balloon.myForcedBounds; if (bounds == null) { final Dimension size = balloon.myComp.getPreferredSize(); balloon.myComp.setSize(size); final Dimension layeredPaneSize = balloon.myLayeredPane.getSize(); Point location = balloon.myShowPointer ? getLocation(layeredPaneSize, balloon.myTargetPoint, size) : new Point(balloon.myTargetPoint.x - size.width / 2, balloon.myTargetPoint.y - size.height / 2); bounds = new Rectangle(location.x, location.y, size.width, size.height); ScreenUtil.moveToFit(bounds, new Rectangle(0, 0, layeredPaneSize.width, layeredPaneSize.height), balloon.myContainerInsets); } balloon.myComp.setBounds(bounds); } abstract Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize); void paintComponent(BalloonImpl balloon, final Rectangle bounds, final Graphics2D g, Point pointTarget) { final GraphicsConfig cfg = new GraphicsConfig(g); cfg.setAntialiasing(true); Shape shape; if (balloon.myShowPointer) { shape = getPointingShape(bounds, g, pointTarget, balloon); } else { shape = new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1, balloon.getArc(), balloon.getArc()); } g.setColor(balloon.myFillColor); g.fill(shape); g.setColor(balloon.myBorderColor); g.draw(shape); cfg.restore(); } protected abstract Shape getPointingShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon); } public static final Position BELOW = new Below(); public static final Position ABOVE = new Above(); public static final Position AT_RIGHT = new AtRight(); public static final Position AT_LEFT = new AtLeft(); private static class Below extends Position { EmptyBorder createBorder(final BalloonImpl balloon) { return new EmptyBorder(balloon.getPointerLength(), balloon.getNormalInset(), balloon.getNormalInset(), balloon.getNormalInset()); } Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize) { final Point center = UIUtil.getCenterPoint(new Rectangle(targetPoint, new Dimension(0, 0)), balloonSize); return new Point(center.x, targetPoint.y); } protected void convertBoundsToContent(final Rectangle bounds, final BalloonImpl balloon) { bounds.y += balloon.getPointerLength(); bounds.height -= balloon.getPointerLength() - 1; } protected Shape getPointingShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingUtilities.TOP); shaper.line(balloon.getPointerWidth() / 2, balloon.getPointerLength()).toRightCurve().roundRightDown().toBottomCurve().roundLeftDown() .toLeftCurve().roundLeftUp().toTopCurve().roundUpRight() .lineTo(pointTarget.x - balloon.getPointerWidth() / 2, shaper.getCurrent().y).lineTo(pointTarget.x, pointTarget.y); shaper.close(); return shaper.getShape(); } protected Shape getShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { bounds.y += balloon.getPointerLength(); bounds.height += balloon.getPointerLength(); return new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width, bounds.height, balloon.getArc(), balloon.getArc()); } } private static class Above extends Position { EmptyBorder createBorder(final BalloonImpl balloon) { return new EmptyBorder(balloon.getNormalInset(), balloon.getNormalInset(), balloon.getPointerLength(), balloon.getNormalInset()); } Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize) { final Point center = UIUtil.getCenterPoint(new Rectangle(targetPoint, new Dimension(0, 0)), balloonSize); return new Point(center.x, targetPoint.y - balloonSize.height); } protected void convertBoundsToContent(final Rectangle bounds, final BalloonImpl balloon) { bounds.height -= balloon.getPointerLength() - 1; } protected Shape getShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { bounds.y -= balloon.getPointerLength(); bounds.height -= balloon.getPointerLength(); return new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width, bounds.height, balloon.getArc(), balloon.getArc()); } @Override protected Shape getPointingShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingUtilities.BOTTOM); shaper.line(-balloon.getPointerWidth() / 2, -balloon.getPointerLength() + 1); shaper.toLeftCurve().roundLeftUp().toTopCurve().roundUpRight().toRightCurve().roundRightDown().toBottomCurve().line(0, 2) .roundLeftDown().lineTo(pointTarget.x + balloon.getPointerWidth() / 2, shaper.getCurrent().y).lineTo(pointTarget.x, pointTarget.y) .close(); return shaper.getShape(); } } private static class AtRight extends Position { EmptyBorder createBorder(final BalloonImpl balloon) { return new EmptyBorder(balloon.getNormalInset(), balloon.getPointerLength(), balloon.getNormalInset(), balloon.getNormalInset()); } Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize) { final Point center = UIUtil.getCenterPoint(new Rectangle(targetPoint, new Dimension(0, 0)), balloonSize); return new Point(targetPoint.x, center.y); } @Override protected Shape getPointingShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingUtilities.LEFT); shaper.line(balloon.getPointerLength(), -balloon.getPointerWidth() / 2).toTopCurve().roundUpRight().toRightCurve().roundRightDown() .toBottomCurve().roundLeftDown().toLeftCurve().roundLeftUp() .lineTo(shaper.getCurrent().x, pointTarget.y + balloon.getPointerWidth() / 2).lineTo(pointTarget.x, pointTarget.y).close(); return shaper.getShape(); } protected void convertBoundsToContent(final Rectangle bounds, final BalloonImpl balloon) { bounds.x += balloon.getPointerLength(); bounds.width -= balloon.getPointerLength(); } protected Shape getShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { bounds.x += balloon.getPointerLength(); bounds.width -= balloon.getPointerLength(); return new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width, bounds.height, balloon.getArc(), balloon.getArc()); } } private static class AtLeft extends Position { EmptyBorder createBorder(final BalloonImpl balloon) { return new EmptyBorder(balloon.getNormalInset(), balloon.getNormalInset(), balloon.getNormalInset(), balloon.getPointerLength()); } Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize) { final Point center = UIUtil.getCenterPoint(new Rectangle(targetPoint, new Dimension(0, 0)), balloonSize); return new Point(targetPoint.x - balloonSize.width, center.y); } protected void convertBoundsToContent(final Rectangle bounds, final BalloonImpl balloon) { bounds.width -= balloon.getPointerLength(); } @Override protected Shape getPointingShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingUtilities.RIGHT); shaper.line(-balloon.getPointerLength(), balloon.getPointerWidth() / 2); shaper.toBottomCurve().roundLeftDown().toLeftCurve().roundLeftUp().toTopCurve().roundUpRight().toRightCurve().roundRightDown() .lineTo(shaper.getCurrent().x, pointTarget.y - balloon.getPointerWidth() / 2).lineTo(pointTarget.x, pointTarget.y).close(); return shaper.getShape(); } protected Shape getShape(final Rectangle bounds, final Graphics2D g, final Point pointTarget, final BalloonImpl balloon) { bounds.width -= balloon.getPointerLength(); return new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width, bounds.height, balloon.getArc(), balloon.getArc()); } } private class CloseButton extends NonOpaquePanel { } private class MyComponent extends JPanel { private BufferedImage myImage; private float myAlpha; private final BalloonImpl myBalloon; private CloseButton myCloseRec = new CloseButton(); private BaseButtonBehavior myButton; private final Wrapper myContent; private MyComponent(JComponent content, BalloonImpl balloon, EmptyBorder shapeBorder) { setOpaque(false); setLayout(null); myBalloon = balloon; myContent = new Wrapper(content); myContent.setBorder(shapeBorder); myContent.setOpaque(false); setBorder(new EmptyBorder(balloon.getCloseButton().getIconHeight() / 3, 0, 0, balloon.getCloseButton().getIconWidth() / 3)); add(myContent); myButton = new BaseButtonBehavior(myCloseRec, TimedDeadzone.NULL) { protected void execute(MouseEvent e) { //noinspection SSBasedInspection SwingUtilities.invokeLater(new Runnable() { public void run() { myBalloon.hide(); } }); } }; add(myCloseRec); setComponentZOrder(myContent, 1); setComponentZOrder(myCloseRec, 0); } public void clear() { myImage = null; myAlpha = -1; } @Override public void doLayout() { Insets insets = getInsets(); if (insets == null) { insets = new Insets(0, 0, 0, 0); } myContent.setBounds(insets.left, insets.right, getWidth() - insets.left - insets.right, getHeight() - insets.top - insets.bottom); if (myBalloon.myEnableCloseButton) { final Icon icon = myBalloon.getCloseButton(); final Rectangle bounds = getBounds(); myCloseRec.setBounds(bounds.width - icon.getIconWidth(), 0, icon.getIconWidth(), icon.getIconHeight()); } } @Override public Dimension getPreferredSize() { return addInsets(myContent.getPreferredSize()); } @Override public Dimension getMinimumSize() { return addInsets(myContent.getMinimumSize()); } private Dimension addInsets(Dimension size) { final Insets insets = getInsets(); if (insets != null) { size.width += (insets.left + insets.right); size.height += (insets.top + insets.bottom); } return size; } @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); final Point pointTarget = SwingUtilities.convertPoint(myLayeredPane, myBalloon.myTargetPoint, this); if (myImage == null && myAlpha != -1) { myImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); myBalloon.myPosition.paintComponent(myBalloon, myContent.getBounds(), (Graphics2D)myImage.getGraphics(), pointTarget); } if (myImage != null && myAlpha != -1) { final Graphics2D g2d = (Graphics2D)g; g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, myAlpha)); g2d.drawImage(myImage, 0, 0, null); } else { myBalloon.myPosition.paintComponent(myBalloon, myContent.getBounds(), (Graphics2D)g, pointTarget); } } @Override protected void paintChildren(Graphics g) { super.paintChildren(g); if (myCloseRec.getWidth() > 0 && myBalloon.myLastMoveWasInsideBalloon) { final boolean pressed = myButton.isPressedByMouse(); myBalloon.getCloseButton().paintIcon(this, g, myCloseRec.getX() + (pressed ? 1 : 0), myCloseRec.getY() + (pressed ? 1 : 0)); } } public void setAlpha(float alpha) { myAlpha = alpha; paintImmediately(0, 0, getWidth(), getHeight()); } } private static class Shaper { private final GeneralPath myPath = new GeneralPath(); Rectangle myBounds; private final int myTargetSide; private final BalloonImpl myBalloon; public Shaper(BalloonImpl balloon, Rectangle bounds, Point targetPoint, int targetSide) { myBalloon = balloon; myBounds = bounds; myTargetSide = targetSide; start(targetPoint); } private void start(Point start) { myPath.moveTo(start.x, start.y); } public Shaper roundUpRight() { myPath.quadTo(getCurrent().x, getCurrent().y - myBalloon.getArc(), getCurrent().x + myBalloon.getArc(), getCurrent().y - myBalloon.getArc()); return this; } public Shaper roundRightDown() { myPath.quadTo(getCurrent().x + myBalloon.getArc(), getCurrent().y, getCurrent().x + myBalloon.getArc(), getCurrent().y + myBalloon.getArc()); return this; } public Shaper roundLeftUp() { myPath.quadTo(getCurrent().x - myBalloon.getArc(), getCurrent().y, getCurrent().x - myBalloon.getArc(), getCurrent().y - myBalloon.getArc()); return this; } public Shaper roundLeftDown() { myPath.quadTo(getCurrent().x, getCurrent().y + myBalloon.getArc(), getCurrent().x - myBalloon.getArc(), getCurrent().y + myBalloon.getArc()); return this; } public Point getCurrent() { return new Point((int)myPath.getCurrentPoint().getX(), (int)myPath.getCurrentPoint().getY()); } public Shaper line(final int deltaX, final int deltaY) { myPath.lineTo(getCurrent().x + deltaX, getCurrent().y + deltaY); return this; } public Shaper lineTo(final int x, final int y) { myPath.lineTo(x, y); return this; } private int getTargetDelta(int effectiveSide) { return effectiveSide == myTargetSide ? myBalloon.getPointerLength() : 0; } public Shaper toRightCurve() { myPath.lineTo((int)myBounds.getMaxX() - myBalloon.getArc() - getTargetDelta(SwingUtilities.RIGHT) - 1, getCurrent().y); return this; } public Shaper toBottomCurve() { myPath.lineTo(getCurrent().x, (int)myBounds.getMaxY() - myBalloon.getArc() - getTargetDelta(SwingUtilities.BOTTOM) - 1); return this; } public Shaper toLeftCurve() { myPath.lineTo((int)myBounds.getX() + myBalloon.getArc() + getTargetDelta(SwingUtilities.LEFT), getCurrent().y); return this; } public Shaper toTopCurve() { myPath.lineTo(getCurrent().x, (int)myBounds.getY() + myBalloon.getArc() + getTargetDelta(SwingUtilities.TOP)); return this; } public void close() { myPath.closePath(); } public Shape getShape() { return myPath; } } public static void main(String[] args) { IconLoader.activate(); final JFrame frame = new JFrame(); frame.getContentPane().setLayout(new BorderLayout()); final JPanel content = new JPanel(new BorderLayout()); frame.getContentPane().add(content, BorderLayout.CENTER); final JTree tree = new JTree(); content.add(tree); final Ref<BalloonImpl> balloon = new Ref<BalloonImpl>(); tree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (balloon.get() != null && balloon.get().isVisible()) { balloon.get().dispose(); } else { final JEditorPane pane = new JEditorPane(); pane.setBorder(new EmptyBorder(6, 6, 6, 6)); pane.setEditorKit(new HTMLEditorKit()); pane.setText(UIUtil.toHtml( "<html><body><center>Really cool balloon<br>Really fucking <a href=\\\"http://jetbrains.com\\\">big</a></center></body></html")); final Dimension size = new JLabel(pane.getText()).getPreferredSize(); pane.setEditable(false); pane.setOpaque(false); pane.setBorder(null); pane.setPreferredSize(size); balloon.set(new BalloonImpl(pane, Color.black, MessageType.ERROR.getPopupBackground(), true, true, true, true, 2000, true, null, false)); balloon.get().setShowPointer(false); if (e.isControlDown()) { balloon.get().show(new RelativePoint(e), BalloonImpl.ABOVE); } else if (e.isAltDown()) { balloon.get().show(new RelativePoint(e), BalloonImpl.BELOW); } else if (e.isMetaDown()) { balloon.get().show(new RelativePoint(e), BalloonImpl.AT_LEFT); } else { balloon.get().show(new RelativePoint(e), BalloonImpl.AT_RIGHT); } } } }); frame.setBounds(300, 300, 300, 300); frame.show(); } }
package org.helioviewer.jhv.renderable.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.ParseException; import java.util.Date; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.DropMode; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.Border; import javax.swing.border.MatteBorder; import org.helioviewer.base.datetime.TimeUtils; import org.helioviewer.base.logging.Log; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.gui.IconBank; import org.helioviewer.jhv.gui.IconBank.JHVIcon; import org.helioviewer.jhv.gui.ImageViewerGui; import org.helioviewer.jhv.gui.dialogs.model.ObservationDialogDateModel; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.LayersModel; import org.helioviewer.jhv.renderable.components.RenderableImageLayer; import org.helioviewer.viewmodel.view.AbstractView; import org.helioviewer.viewmodel.view.jp2view.JHVJPXView; @SuppressWarnings({ "serial" }) public class RenderableContainerPanel extends JPanel implements LayersListener { static final Border commonBorder = new MatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY); static final Border commonLeftBorder = new MatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY); static final Border commonRightBorder = new MatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY); private static final int ROW_HEIGHT = 20; private static final int ICON_WIDTH = 16; private static final int VISIBLEROW = 0; private static final int TITLEROW = 1; public static final int TIMEROW = 2; private static final int REMOVEROW = 3; public static final int NUMBEROFCOLUMNS = 4; private final Action addLayerAction = new AbstractAction("Add layer", IconBank.getIcon(JHVIcon.ADD)) { { putValue(SHORT_DESCRIPTION, "Add a new layer"); } /** * {@inheritDoc} */ @Override public void actionPerformed(ActionEvent arg0) { // Check the dates if possible AbstractView activeView = LayersModel.getActiveView(); if (activeView instanceof JHVJPXView) { JHVJPXView jpxView = (JHVJPXView) activeView; if (jpxView.getMaximumAccessibleFrameNumber() == jpxView.getMaximumFrameNumber()) { Date start = LayersModel.getStartDate(activeView); Date end = LayersModel.getEndDate(activeView); try { Date obsStartDate = TimeUtils.apiDateFormat.parse(ImageViewerGui.getObservationImagePane().getStartTime()); Date obsEndDate = TimeUtils.apiDateFormat.parse(ImageViewerGui.getObservationImagePane().getEndTime()); // only updates if its really necessary with a // tolerance of an hour final int tolerance = 60 * 60 * 1000; if (Math.abs(start.getTime() - obsStartDate.getTime()) > tolerance || Math.abs(end.getTime() - obsEndDate.getTime()) > tolerance) { if (ObservationDialogDateModel.getInstance().getStartDate() == null || !ObservationDialogDateModel.getInstance().isStartDateSetByUser()) { ObservationDialogDateModel.getInstance().setStartDate(start, false); } if (ObservationDialogDateModel.getInstance().getEndDate() == null || !ObservationDialogDateModel.getInstance().isEndDateSetByUser()) { ObservationDialogDateModel.getInstance().setEndDate(end, false); } } } catch (ParseException e) { // Should not happen Log.error("Cannot update observation dialog", e); } } } // Show dialog ImageViewerGui.getObservationDialog().showDialog(); } }; private final JTable grid; private final JPanel optionsPanelWrapper; public RenderableContainerPanel(final RenderableContainer renderableContainer) { this.setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.weightx = 1; gc.weighty = 0; gc.fill = GridBagConstraints.BOTH; grid = new JTable(renderableContainer); renderableContainer.addTableModelListener(grid); JScrollPane jsp = new JScrollPane(grid, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jsp.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); jsp.setPreferredSize(new Dimension(ImageViewerGui.SIDE_PANEL_WIDTH, ROW_HEIGHT * 5 + 2)); JPanel jspContainer = new JPanel(new BorderLayout()); jspContainer.setBorder(BorderFactory.createTitledBorder("")); jspContainer.add(jsp, BorderLayout.NORTH); this.add(jspContainer, gc); grid.setTableHeader(null); grid.setShowGrid(false); grid.setRowSelectionAllowed(true); grid.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); grid.setColumnSelectionAllowed(false); grid.setIntercellSpacing(new Dimension(0, 0)); grid.setRowHeight(ROW_HEIGHT); grid.setBackground(Color.white); grid.getColumnModel().getColumn(VISIBLEROW).setCellRenderer(new RenderableVisibleCellRenderer()); grid.getColumnModel().getColumn(VISIBLEROW).setPreferredWidth(ICON_WIDTH + 3); grid.getColumnModel().getColumn(VISIBLEROW).setMaxWidth(ICON_WIDTH + 3); grid.getColumnModel().getColumn(TITLEROW).setCellRenderer(new RenderableCellRenderer()); grid.getColumnModel().getColumn(TITLEROW).setPreferredWidth(80); grid.getColumnModel().getColumn(TITLEROW).setMaxWidth(80); grid.getColumnModel().getColumn(TIMEROW).setCellRenderer(new RenderableTimeCellRenderer()); grid.getColumnModel().getColumn(REMOVEROW).setCellRenderer(new RenderableRemoveCellRenderer()); grid.getColumnModel().getColumn(REMOVEROW).setPreferredWidth(ICON_WIDTH); grid.getColumnModel().getColumn(REMOVEROW).setMaxWidth(ICON_WIDTH); grid.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { handlePopup(e); } } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { handlePopup(e); } } /** * Handle with right-click menus * * @param e */ public void handlePopup(MouseEvent e) { } /** * Handle with clicks on hide/show/remove layer icons */ @Override public void mouseClicked(MouseEvent e) { int row = grid.rowAtPoint(new Point(e.getX(), e.getY())); int col = grid.columnAtPoint(new Point(e.getX(), e.getY())); Renderable renderable = (Renderable) renderableContainer.getValueAt(row, col); if (col == VISIBLEROW) { renderable.setVisible(!renderable.isVisible()); renderableContainer.fireListeners(); Displayer.display(); } if (col == TITLEROW || col == VISIBLEROW || col == TIMEROW) { if (renderable instanceof RenderableImageLayer) { LayersModel.setActiveView(((RenderableImageLayer) renderable).getMainLayerView()); } setOptionsPanel(renderable); } if (col == REMOVEROW && renderable.isDeletable()) { ((RenderableContainer) grid.getModel()).removeRow(row); Displayer.display(); } } }); grid.setDragEnabled(true); grid.setDropMode(DropMode.INSERT_ROWS); grid.setTransferHandler(new TableRowTransferHandler(grid)); optionsPanelWrapper = new JPanel(new BorderLayout()); JButton addLayerButton = new JButton(addLayerAction); addLayerButton.setBorder(null); addLayerButton.setText(null); addLayerButton.setBorderPainted(false); addLayerButton.setFocusPainted(false); addLayerButton.setContentAreaFilled(false); addLayerButton.setToolTipText("Add extra data layers"); addLayerButton.setIcon(IconBank.getIcon(JHVIcon.ADD)); JPanel addLayerButtonWrapper = new JPanel(new BorderLayout()); addLayerButtonWrapper.add(addLayerButton, BorderLayout.EAST); jspContainer.add(addLayerButtonWrapper, BorderLayout.CENTER); gc.gridy = 1; add(optionsPanelWrapper, gc); LayersModel.addLayersListener(this); } private void setOptionsPanel(Renderable renderable) { setOptionsPanel(renderable.getOptionsPanel()); } private void setOptionsPanel(Component cmp) { optionsPanelWrapper.removeAll(); if (cmp != null) optionsPanelWrapper.add(cmp, BorderLayout.CENTER); super.revalidate(); // super.repaint(); } @Override public void layerAdded(AbstractView view) { } @Override public void activeLayerChanged(AbstractView view) { if (view != null) { setOptionsPanel(view.getImageLayer()); ImageViewerGui.getRenderableContainer().fireListeners(); int index = ImageViewerGui.getRenderableContainer().getRowIndex(view.getImageLayer()); grid.getSelectionModel().setSelectionInterval(index, index); } else { JPanel jpl = new JPanel(); jpl.add(new JLabel("No layer selected")); setOptionsPanel(jpl); } } }
package com.rho.rubyext; import rhomobile.RhodesApplication; import net.rim.blackberry.api.phone.Phone; import net.rim.device.api.i18n.Locale; import net.rim.device.api.system.Display; import com.rho.BBVersionSpecific; import com.rho.RhoEmptyLogger; import com.rho.RhoLogger; import com.rho.RhodesApp; import com.xruby.runtime.builtin.ObjectFactory; import com.xruby.runtime.lang.*; import com.rho.RhoRubyHelper; import net.rim.device.api.system.DeviceInfo; public class System { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("System"); public static void initMethods(RubyClass klass){ klass.getSingletonClass().defineMethod( "get_property", new RubyOneArgMethod(){ protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block ) { try { return get_property(arg); } catch(Exception e) { LOG.ERROR("get_property failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.getSingletonClass().defineMethod( "has_network", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ) { try { return ObjectFactory.createBoolean(hasNetwork()); } catch(Exception e) { LOG.ERROR("has_network failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.getSingletonClass().defineMethod( "get_locale", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ) { try { return ObjectFactory.createString(getLocale()); } catch(Exception e) { LOG.ERROR("get_locale failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.getSingletonClass().defineMethod( "get_screen_width", new RubyNoArgMethod() { protected RubyValue run(RubyValue receiver, RubyBlock block) { try { return ObjectFactory.createInteger(getScreenWidth()); } catch(Exception e) { LOG.ERROR("get_screen_width failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.getSingletonClass().defineMethod( "get_screen_height", new RubyNoArgMethod() { protected RubyValue run(RubyValue receiver, RubyBlock block) { try { return ObjectFactory.createInteger(getScreenHeight()); } catch(Exception e) { LOG.ERROR("get_screen_height failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.getSingletonClass().defineMethod( "set_push_notification", new RubyTwoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block ) { try { String url = arg1 != RubyConstant.QNIL ? arg1.toStr() : ""; String params = arg2 != RubyConstant.QNIL ? arg2.toStr() : ""; RhodesApp.getInstance().setPushNotification(url, params); return RubyConstant.QNIL; } catch(Exception e) { LOG.ERROR("set_push_notification failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.getSingletonClass().defineMethod( "set_screen_rotation_notification", new RubyTwoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block ) { try { String url = arg1 != RubyConstant.QNIL ? arg1.toStr() : ""; String params = arg2 != RubyConstant.QNIL ? arg2.toStr() : ""; RhodesApp.getInstance().setScreenRotationNotification(url, params); return RubyConstant.QNIL; } catch(Exception e) { LOG.ERROR("set_screen_rotation_notification failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.getSingletonClass().defineMethod("exit", new RubyNoArgMethod() { protected RubyValue run(RubyValue receiver, RubyBlock block) { RhodesApplication.getInstance().close(); return RubyConstant.QNIL; } }); } //@RubyLevelMethod(name="get_property", module=true) private static RubyValue get_property(RubyValue arg) { String strPropName = arg.toStr(); if ( strPropName.equalsIgnoreCase("platform") ) { RhoRubyHelper helper = new RhoRubyHelper(); return ObjectFactory.createString( helper.getPlatform() ); } if ( strPropName.equalsIgnoreCase("has_network") ) return ObjectFactory.createBoolean(hasNetwork()); if ( strPropName.equalsIgnoreCase("locale") ) return ObjectFactory.createString(getLocale()); if ( strPropName.equalsIgnoreCase("screen_width") ) return ObjectFactory.createInteger(getScreenWidth()); if ( strPropName.equalsIgnoreCase("screen_height") ) return ObjectFactory.createInteger(getScreenHeight()); if ( strPropName.equalsIgnoreCase("ppi_x")) return ObjectFactory.createFloat(getScreenPpiX()); if ( strPropName.equalsIgnoreCase("ppi_y")) return ObjectFactory.createFloat(getScreenPpiY()); if ( strPropName.equalsIgnoreCase("has_camera") ) return ObjectFactory.createBoolean(hasCamera()); if ( strPropName.equalsIgnoreCase("phone_number") ) return ObjectFactory.createString(Phone.getDevicePhoneNumber(true)); if ( strPropName.equalsIgnoreCase("device_id") ) return ObjectFactory.createString(new Integer( DeviceInfo.getDeviceId() ).toString()); if ( strPropName.equalsIgnoreCase("full_browser") ) return ObjectFactory.createBoolean(rhomobile.RhodesApplication.isFullBrowser()); if ( strPropName.equalsIgnoreCase("device_name") ) return ObjectFactory.createString(DeviceInfo.getDeviceName()); if ( strPropName.equalsIgnoreCase("os_version") ) return ObjectFactory.createString(DeviceInfo.getSoftwareVersion()); return RubyConstant.QNIL; } public static String getLocale() { Locale loc = Locale.getDefault(); String lang = loc != null ? loc.getLanguage() : "en"; return lang; } public static boolean hasCamera() { return DeviceInfo.hasCamera(); } public static boolean hasNetwork() { /*if ((RadioInfo.getActiveWAFs() & RadioInfo.WAF_WLAN) != 0) { if (CoverageInfo.isCoverageSufficient( CoverageInfo.COVERAGE_CARRIER,RadioInfo.WAF_WLAN, false) || CoverageInfo.isCoverageSufficient( CoverageInfo.COVERAGE_MDS,RadioInfo.WAF_WLAN, false) || CoverageInfo.isCoverageSufficient( COVERAGE_BIS_B,RadioInfo.WAF_WLAN, false)) return true; } if (CoverageInfo.isOutOfCoverage()) return false; */ int nStatus = net.rim.device.api.system.RadioInfo.getNetworkService(); boolean hasGPRS = ( nStatus & net.rim.device.api.system.RadioInfo.NETWORK_SERVICE_DATA) != 0; boolean hasWifi = BBVersionSpecific.isWifiActive(); LOG.INFO("hasGPRS : " + hasGPRS + "; Wifi: " + hasWifi); boolean bRes = hasGPRS || hasWifi; return bRes; } public static int getScreenHeight() { return Display.getHeight(); } public static int getScreenWidth() { return Display.getWidth(); } public static double getScreenPpiX() { // Convert PPM (Pixels Per Meter) to PPI (Pixels Per Inch) int ppm = Display.getHorizontalResolution(); double retval = (ppm*25.4)/1000; return retval; } public static double getScreenPpiY() { // Convert PPM (Pixels Per Meter) to PPI (Pixels Per Inch) int ppm = Display.getVerticalResolution(); double retval = (ppm*25.4)/1000; return retval; } }
package org.voovan.tools; import org.voovan.tools.reflect.TReflect; import java.text.ParseException; import java.util.*; public class TObject { /** * * JDK 1.8 , * * @param <T> * @param obj * @return */ @SuppressWarnings("unchecked") public static <T> T cast(Object obj){ return TObject.cast(obj); } /** * * @param <T> * @param source * @param defValue null * @return null source null defValue */ public static <T>T nullDefault(T source,T defValue){ return source!=null?source:defValue; } /** * List * @param objs List * @return List */ @SuppressWarnings("rawtypes") public static List asList(Object ...objs){ List result = new ArrayList(); for(Object o : objs) { result.add(o); } return result; } /** * Map * @param objs Map. :key1,value1,key2,value2..... * @return Map */ @SuppressWarnings("rawtypes") public static Map asMap(Object ...objs){ Map<Object,Object> map = new LinkedHashMap<Object,Object>(); for(int i=1;i<objs.length;i+=2){ map.put(objs[i-1], objs[i]); } return map; } /** * map null * @param source map * @param withEmptyString * @return map null map */ public static Map removeMapNullValue(Map source, boolean withEmptyString) { if (source == null) { return null; } for (Iterator<?> it = source.values().iterator(); it.hasNext(); ) { Object obj = it.next(); if (obj == null) { it.remove(); } if (obj instanceof String && withEmptyString) { if (TString.isNullOrEmpty((String) obj)) { it.remove(); } } } return source; } /** * map null * @param source map * @return map null map */ public static Map removeMapNullValue(Map source) { return removeMapNullValue(source, true); } /** * Map List * @param map Map * @return Value list */ public static List<?> mapValueToList(Map<?,?> map){ ArrayList<Object> result = new ArrayList<Object>(); for(Map.Entry<?,?> entry : map.entrySet()){ result.add(entry.getValue()); } return result; } /** * Map List * @param map Map * @return key list */ public static List<?> mapKeyToList(Map<?,?> map){ ArrayList<Object> result = new ArrayList<Object>(); for(Map.Entry<?,?> entry : map.entrySet()){ result.add(entry.getKey()); } return result; } /** * Map * key , 1 * value * @param objs * @param <T> * @return Map [, ] */ public static <T> Map<String, T> arrayToMap(T[] objs){ Map<String ,T> arrayMap = new LinkedHashMap<String ,T>(); for(int i=0;i<objs.length;i++){ arrayMap.put(Integer.toString(i+1), objs[i]); } return arrayMap; } /** * Collection Map * key * value * @param objs Collection * @param <T> * @return Map [, ] */ public static <T> Map<String, T> collectionToMap(Collection<T> objs){ Map<String ,T> arrayMap = new LinkedHashMap<String ,T>(); int i = 0; for(T t : objs){ arrayMap.put(Integer.toString(++i), t); } return arrayMap; } /** * * @param firstArray * @param firstArrayLength * @param lastArray * @param lastArrayLength * @return */ public static Object[] arrayConcat(Object[] firstArray,int firstArrayLength, Object[] lastArray,int lastArrayLength) { if (lastArray.length == 0) return firstArray; Object[] target = new Object[firstArrayLength + lastArrayLength]; System.arraycopy(firstArray, 0, target, 0, firstArrayLength); System.arraycopy(lastArrayLength, 0, target, firstArrayLength, lastArrayLength); return target; } /** * * @param source * @param mark * @return */ public static int indexOfArray(Object[] source, Object mark){ for(int i=0;i<source.length;i++){ Object item = source[i]; if(item.equals(mark)){ return i; } } return -1; } /** * * @param source * @param mark * @return */ public static int indexOfArray(Object[] source, Object[] mark){ if(source.length == 0){ return -1; } if(source.length < mark.length){ return -1; } int index = -1; int i = 0; int j = 0; while(i <= (source.length - mark.length + j ) ){ if(!source[i].equals(mark[j]) ){ if(i == (source.length - mark.length + j )){ break; } int pos = -1; for(int p = mark.length-1 ; p >= 0; p if(mark[p] == source[i+mark.length-j]){ pos = p ; } } if( pos== -1){ i = i + mark.length + 1 - j; j = 0 ; }else{ i = i + mark.length - pos - j; j = 0; } }else{ if(j == (mark.length - 1)){ i = i - j + 1 ; j = 0; index = i-j - 1; break; }else{ i++; j++; } } } return index; } /** * * @param obj * @param <T> * @return * @throws ReflectiveOperationException * @throws ParseException */ public static <T> T clone(T obj) throws ReflectiveOperationException, ParseException { Map dataMap = TReflect.getMapfromObject(obj); return (T)TReflect.getObjectFromMap(obj.getClass(),dataMap, false); } }
package ca.corefacility.bioinformatics.irida.model; import java.util.Date; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import org.hibernate.envers.Audited; /** * OAuth2 token for communicating with a {@link RemoteAPI} for a given * {@link User} * * @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca> * */ @Entity @Table(name = "remote_api_token", uniqueConstraints = @UniqueConstraint(columnNames = { "user_id", "remote_api_id" }, name = "UK_remote_api_token_user")) @Audited public class RemoteAPIToken { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull private String tokenString; @NotNull private Date expiryDate; @ManyToOne @JoinColumn(name = "remote_api_id") @NotNull RemoteAPI remoteApi; @ManyToOne @JoinColumn(name = "user_id") @NotNull User user; public RemoteAPIToken() { } public RemoteAPIToken(String tokenString, RemoteAPI remoteApi, Date expiryDate) { super(); this.tokenString = tokenString; this.remoteApi = remoteApi; this.expiryDate = expiryDate; } /** * @return the id */ public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the tokenString */ public String getTokenString() { return tokenString; } /** * @param tokenString * the tokenString to set */ public void setTokenString(String tokenString) { this.tokenString = tokenString; } /** * @return the remoteApi */ public RemoteAPI getRemoteApi() { return remoteApi; } /** * @param remoteApi * the remoteApi to set */ public void setRemoteApi(RemoteAPI remoteApi) { this.remoteApi = remoteApi; } /** * @return the user */ public User getUser() { return user; } /** * @param user * the user to set */ public void setUser(User user) { this.user = user; } @Override public String toString() { return "RemoteAPIToken [tokenString=" + tokenString + ", remoteApi=" + remoteApi + ", user=" + user + "]"; } /** * Get the date that this token expires * * @return */ public Date getExpiryDate() { return expiryDate; } /** * Set the date that this token expires * * @param expiryDate */ public void setExpiryDate(Date expiryDate) { this.expiryDate = expiryDate; } /** * Test if this token has expired * * @return true if this token has expired */ public boolean isExpired() { return (new Date()).after(expiryDate); } /** * Hashcode using remoteAPI and tokenString */ @Override public int hashCode() { return Objects.hash(remoteApi, tokenString); } /** * Equals method using remoteAPI and tokenString */ @Override public boolean equals(Object other) { if (other instanceof RemoteAPIToken) { RemoteAPIToken p = (RemoteAPIToken) other; return Objects.equals(remoteApi, p.remoteApi) && Objects.equals(tokenString, p.tokenString); } return false; } }
package co.nubetech.crux.server.aggregate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Stack; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.coprocessor.BaseEndpointCoprocessor; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.ipc.ProtocolSignature; import org.apache.log4j.Logger; import co.nubetech.crux.model.Alias; import co.nubetech.crux.model.ColumnAlias; import co.nubetech.crux.model.GroupBys; import co.nubetech.crux.model.Report; import co.nubetech.crux.model.ReportDesign; import co.nubetech.crux.model.ReportDesignFunction; import co.nubetech.crux.model.RowAlias; import co.nubetech.crux.server.functions.Conversion; import co.nubetech.crux.server.functions.CruxFunction; import co.nubetech.crux.util.CruxException; public class GroupingAggregationImpl extends BaseEndpointCoprocessor implements GroupingAggregationProtocol{ private final static Logger logger = Logger.getLogger(GroupingAggregationImpl.class); /** * We are here * means that the caller has already decided that * the server needs to be executed * which means at least one of the design functions * is an aggregate */ @Override public List<List> getAggregates(Scan scan, Report report) throws CruxException{ List<List> returnList = new ArrayList<List>(); try { //understand the report //see what is the group by //get the designs //for each design //get the col or row alias and the function to be applied. //create list of functions to be applied. Collection<ReportDesign> designs = report.getDesigns(); List<Stack<CruxFunction>> functions = getFunctions(report); GroupBys groupBys = report.getGroupBys(); //open the scan //get values of data for each group by //put in hash //hash key group by objects, hash value List of function applied values. //we are keeping everything in memory, as we are assuming that final report holds less data //we are going to be dealing with preaggregated data only, umm..lets see.. //may have to revise this InternalScanner scanner = ((RegionCoprocessorEnvironment) getEnvironment()) .getRegion().getScanner(scan); if (groupBys == null) { //just simple function application, but an aggregate is possibly lurking in somewhere //without a groupby ..ouch int index = 0; byte[] value = null; List<KeyValue> results = new ArrayList<KeyValue>(); for (ReportDesign design: designs) { //get each value and apply functions Stack<CruxFunction> designFn = functions.get(index++); boolean hasMoreRows = false; do { hasMoreRows = scanner.next(results); //convert and apply //see if the design is on row or column alias Alias alias = getAlias(design); value = getValue(results, alias, report); } while (hasMoreRows); } } //group bys are not null else { } } catch(Exception e) { throw new CruxException("Error processing aggregates " + e); } return returnList; } /** * This is not the most optimized pience of code * we should go to the byte buffers * lets clean this later once the functionality works end to end * @param results * @param alias * @return */ protected byte[] getValue(List<KeyValue> results, Alias alias, Report report) { byte[] value = null; if (alias instanceof RowAlias) { value = results.get(0).getKey(); } else { ColumnAlias colAlias = (ColumnAlias) alias; String family = colAlias.getColumnFamily(); String qualifier = colAlias.getQualifier(); byte[] familyBytes = family.getBytes(); byte[] qualifierBytes = qualifier.getBytes(); for (KeyValue kv: results) { if (kv.getFamily().equals(familyBytes)) { if (kv.getQualifier().equals(qualifierBytes)) { value = kv.getValue(); break; } } } } return value; } protected Alias getAlias(ReportDesign design) { Alias alias = design.getRowAlias(); if (alias == null) { alias = design.getColumnAlias(); } return alias; } protected List<Stack<CruxFunction>> getFunctions(Report report) throws CruxException{ List<Stack<CruxFunction>> aggregators = new ArrayList<Stack<CruxFunction>>(); try { for (ReportDesign design: report.getDesigns()) { logger.debug("Finding functions for design: " + design); Collection<ReportDesignFunction> functions = design.getReportDesignFunctionList(); Stack<CruxFunction> functionStack = new Stack<CruxFunction>(); if (functions != null) { for (ReportDesignFunction function: functions) { logger.debug("Creating function class for " + function); functionStack.push((CruxFunction) Class.forName(function.getFunction().getFunctionClass()). newInstance()); } } aggregators.add(functionStack); } } catch(Exception e) { e.printStackTrace(); throw new CruxException("Unable to generate the functions " + e); } return aggregators; } }
package codemining.cpp.codeutils; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map.Entry; import java.util.SortedMap; import java.util.logging.Logger; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.AbstractFileFilter; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.exception.ExceptionUtils; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTArrayModifier; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier.IASTEnumerator; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTInitializer; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.IASTPointerOperator; import org.eclipse.cdt.core.dom.ast.IASTProblem; import org.eclipse.cdt.core.dom.ast.IASTStatement; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IASTTypeId; import org.eclipse.cdt.core.dom.ast.c.ICASTDesignator; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCapture; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateParameter; import org.eclipse.cdt.internal.core.dom.parser.ASTAmbiguousNode; import org.eclipse.core.runtime.CoreException; import codemining.languagetools.IAstAnnotatedTokenizer; import codemining.languagetools.ITokenizer; import codemining.util.SettingsLoader; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * C/C++ AST Annotated Tokenizer * * @author Miltos Allamanis <m.allamanis@ed.ac.uk> * */ public abstract class AbstractCdtASTAnnotatedTokenizer implements IAstAnnotatedTokenizer { private static class TokenDecorator extends ASTVisitor { final SortedMap<Integer, FullToken> baseTokens; final SortedMap<Integer, AstAnnotatedToken> annotatedTokens; public static final String NONE = "NONE"; public TokenDecorator(final SortedMap<Integer, FullToken> baseTokens) { super(true); this.baseTokens = baseTokens; annotatedTokens = Maps.newTreeMap(); } SortedMap<Integer, AstAnnotatedToken> getAnnotatedTokens( final IASTNode node) { annotatedTokens.putAll(Maps.transformValues(baseTokens, new Function<FullToken, AstAnnotatedToken>() { @Override public AstAnnotatedToken apply(final FullToken input) { return new AstAnnotatedToken(input, NONE, NONE); } })); node.accept(this); return annotatedTokens; } public void preVisit(final IASTNode node) { final IASTFileLocation fileLocation = node.getFileLocation(); if (fileLocation == null) { return; // TODO: Is this right? This happens when we have a // macro problem } final int fromPosition = fileLocation.getNodeOffset(); final int endPosition = fromPosition + fileLocation.getNodeLength(); final String nodeType = node.getClass().getSimpleName(); final String parentType; if (node.getParent() != null) { parentType = node.getParent().getClass().getSimpleName(); } else { parentType = "NONE"; } final SortedMap<Integer, FullToken> nodeTokens = baseTokens.subMap( fromPosition, endPosition); for (final Entry<Integer, FullToken> token : nodeTokens.entrySet()) { if (token.getValue().token.startsWith("WS_")) { annotatedTokens.put( token.getKey(), new AstAnnotatedToken(new FullToken(token .getValue().token, token.getValue().tokenType), null, null)); } else { annotatedTokens.put( token.getKey(), new AstAnnotatedToken(new FullToken(token .getValue().token, token.getValue().tokenType), nodeType, parentType)); } } } @Override public int visit(final ASTAmbiguousNode astAmbiguousNode) { preVisit(astAmbiguousNode); return super.visit(astAmbiguousNode); } @Override public int visit(final IASTArrayModifier arrayModifier) { preVisit(arrayModifier); return super.visit(arrayModifier); } @Override public int visit(final IASTDeclaration declaration) { preVisit(declaration); return super.visit(declaration); } @Override public int visit(final IASTDeclarator declarator) { preVisit(declarator); return super.visit(declarator); } @Override public int visit(final IASTDeclSpecifier declSpec) { preVisit(declSpec); return super.visit(declSpec); } @Override public int visit(final IASTEnumerator enumerator) { preVisit(enumerator); return super.visit(enumerator); } @Override public int visit(final IASTExpression expression) { preVisit(expression); return super.visit(expression); } @Override public int visit(final IASTInitializer initializer) { preVisit(initializer); return super.visit(initializer); } @Override public int visit(final IASTName name) { preVisit(name); return super.visit(name); } @Override public int visit(final IASTParameterDeclaration parameterDeclaration) { preVisit(parameterDeclaration); return super.visit(parameterDeclaration); } @Override public int visit(final IASTPointerOperator ptrOperator) { preVisit(ptrOperator); return super.visit(ptrOperator); } @Override public int visit(final IASTProblem problem) { preVisit(problem); return super.visit(problem); } @Override public int visit(final IASTStatement statement) { preVisit(statement); return super.visit(statement); } @Override public int visit(final IASTTranslationUnit tu) { preVisit(tu); return super.visit(tu); } @Override public int visit(final IASTTypeId typeId) { preVisit(typeId); return super.visit(typeId); } @Override public int visit(final ICASTDesignator designator) { preVisit(designator); return super.visit(designator); } @Override public int visit(final ICPPASTBaseSpecifier baseSpecifier) { preVisit(baseSpecifier); return super.visit(baseSpecifier); } @Override public int visit(final ICPPASTCapture capture) { preVisit(capture); return super.visit(capture); } @Override public int visit(final ICPPASTNamespaceDefinition namespaceDefinition) { preVisit(namespaceDefinition); return super.visit(namespaceDefinition); } @Override public int visit(final ICPPASTTemplateParameter templateParameter) { preVisit(templateParameter); return super.visit(templateParameter); } } private static final long serialVersionUID = -3086123070064967257L; public final ITokenizer baseTokenizer; private static final Logger LOGGER = Logger .getLogger(AbstractCdtASTAnnotatedTokenizer.class.getName()); final Class<? extends AbstractCdtAstExtractor> astExtractorClass; private final String codeIncludePath; public AbstractCdtASTAnnotatedTokenizer( final Class<? extends AbstractCdtAstExtractor> extractorClass, final String baseIncludePath) { astExtractorClass = extractorClass; try { final Class<? extends ITokenizer> tokenizerClass = (Class<? extends ITokenizer>) Class .forName(SettingsLoader.getStringSetting("baseTokenizer", "codemining.cpp.codeutils.CDTTokenizer")); baseTokenizer = tokenizerClass.newInstance(); } catch (final ClassNotFoundException e) { LOGGER.severe(ExceptionUtils.getFullStackTrace(e)); throw new IllegalArgumentException(e); } catch (final InstantiationException e) { LOGGER.severe(ExceptionUtils.getFullStackTrace(e)); throw new IllegalArgumentException(e); } catch (final IllegalAccessException e) { LOGGER.severe(ExceptionUtils.getFullStackTrace(e)); throw new IllegalArgumentException(e); } codeIncludePath = baseIncludePath; } public AbstractCdtASTAnnotatedTokenizer(final ITokenizer base, final Class<? extends AbstractCdtAstExtractor> extractorClass, final String baseIncludePath) { astExtractorClass = extractorClass; baseTokenizer = base; codeIncludePath = baseIncludePath; } /* * (non-Javadoc) * * @see codemining.languagetools.ITokenizer#fullTokenListWithPos(char[]) */ @Override public SortedMap<Integer, FullToken> fullTokenListWithPos(final char[] code) { throw new NotImplementedException(); } @Override public List<AstAnnotatedToken> getAnnotatedTokenListFromCode( final char[] code) { final List<AstAnnotatedToken> tokens = Lists.newArrayList(); for (final Entry<Integer, AstAnnotatedToken> token : getAnnotatedTokens( code).entrySet()) { tokens.add(token.getValue()); } return tokens; } @Override public List<AstAnnotatedToken> getAnnotatedTokenListFromCode( final File codeFile) throws IOException { // TODO Get ast through the file return getAnnotatedTokenListFromCode(FileUtils.readFileToString( codeFile).toCharArray()); } @Override public SortedMap<Integer, AstAnnotatedToken> getAnnotatedTokens( final char[] code) { try { final AbstractCdtAstExtractor ex = astExtractorClass.newInstance(); final IASTTranslationUnit cu = ex.getAST(code, codeIncludePath); final SortedMap<Integer, FullToken> baseTokens = baseTokenizer .fullTokenListWithPos(code); final TokenDecorator dec = new TokenDecorator(baseTokens); return dec.getAnnotatedTokens(cu); } catch (final CoreException ce) { LOGGER.severe("Failed to get annotated tokens, because " + ExceptionUtils.getFullStackTrace(ce)); } catch (final InstantiationException e) { LOGGER.severe("Failed to get annotated tokens, because " + ExceptionUtils.getFullStackTrace(e)); } catch (final IllegalAccessException e) { LOGGER.severe("Failed to get annotated tokens, because " + ExceptionUtils.getFullStackTrace(e)); } return null; } @Override public ITokenizer getBaseTokenizer() { return baseTokenizer; } /* * (non-Javadoc) * * @see codemining.languagetools.ITokenizer#getFileFilter() */ @Override public AbstractFileFilter getFileFilter() { return baseTokenizer.getFileFilter(); } /* * (non-Javadoc) * * @see codemining.languagetools.ITokenizer#getIdentifierType() */ @Override public String getIdentifierType() { return baseTokenizer.getIdentifierType(); } /* * (non-Javadoc) * * @see * codemining.languagetools.ITokenizer#getTokenFromString(java.lang.String) */ @Override public FullToken getTokenFromString(final String token) { throw new IllegalArgumentException( "ASTAnnotatedTokenizer cannot return a token from a single string."); } /* * (non-Javadoc) * * @see codemining.languagetools.ITokenizer#getTokenListFromCode(char[]) */ @Override public List<FullToken> getTokenListFromCode(final char[] code) { final List<FullToken> tokens = Lists.newArrayList(); for (final Entry<Integer, AstAnnotatedToken> token : getAnnotatedTokens( code).entrySet()) { final AstAnnotatedToken annotatedToken = token.getValue(); tokens.add(new FullToken(annotatedToken.token.token + "_i:" + annotatedToken.tokenAstNode + "_p:" + annotatedToken.parentTokenAstNode, annotatedToken.token.tokenType)); } return tokens; } @Override public List<FullToken> getTokenListFromCode(final File codeFile) throws IOException { return getTokenListFromCode(FileUtils.readFileToString(codeFile) .toCharArray()); } /* * (non-Javadoc) * * @see codemining.languagetools.ITokenizer#tokenListFromCode(char[]) */ @Override public List<String> tokenListFromCode(final char[] code) { final List<String> tokens = Lists.newArrayList(); for (final Entry<Integer, AstAnnotatedToken> token : getAnnotatedTokens( code).entrySet()) { tokens.add(token.getValue().token.token); } return tokens; } @Override public List<String> tokenListFromCode(final File codeFile) throws IOException { // TODO get ast from file return tokenListFromCode(FileUtils.readFileToString(codeFile) .toCharArray()); } /* * (non-Javadoc) * * @see codemining.languagetools.ITokenizer#tokenListWithPos(char[]) */ @Override public SortedMap<Integer, String> tokenListWithPos(final char[] code) { final SortedMap<Integer, String> tokens = Maps.newTreeMap(); for (final Entry<Integer, AstAnnotatedToken> token : getAnnotatedTokens( code).entrySet()) { tokens.put(token.getKey(), token.getValue().token.token); } return tokens; } @Override public SortedMap<Integer, FullToken> tokenListWithPos(final File file) throws IOException { return fullTokenListWithPos(FileUtils.readFileToString(file) .toCharArray()); } }
package com.lothrazar.cyclic.block.collectfluid; import javax.annotation.Nullable; import com.lothrazar.cyclic.base.BlockBase; import com.lothrazar.cyclic.registry.ContainerScreenRegistry; import com.lothrazar.cyclic.registry.TileRegistry; import com.lothrazar.cyclic.util.UtilStuff; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.client.gui.ScreenManager; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.state.StateContainer; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.client.registry.ClientRegistry; public class BlockFluidCollect extends BlockBase { public BlockFluidCollect(Properties properties) { super(properties.hardnessAndResistance(1.8F)); this.setHasGui(); } @Override @OnlyIn(Dist.CLIENT) public void registerClient() { ClientRegistry.bindTileEntityRenderer(TileRegistry.collector_fluid, RenderFluidCollect::new); ScreenManager.registerFactory(ContainerScreenRegistry.collector_fluid, ScreenFluidCollect::new); } @Override public boolean hasTileEntity(BlockState state) { return true; } @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) { return new TileFluidCollect(); } @Override public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, @Nullable LivingEntity entity, ItemStack stack) { if (entity != null) { world.setBlockState(pos, state.with(BlockStateProperties.HORIZONTAL_FACING, UtilStuff.getFacingFromEntityHorizontal(pos, entity)), 2); } } @Override protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) { builder.add(BlockStateProperties.HORIZONTAL_FACING).add(LIT); } }
package com.ning.http.client.providers.netty; import com.ning.http.client.ConnectionsPool; import org.jboss.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; /** * A simple implementation of {@link com.ning.http.client.ConnectionsPool} based on a {@link java.util.concurrent.ConcurrentHashMap} */ public class NettyConnectionsPool implements ConnectionsPool<String, Channel> { private final static Logger log = LoggerFactory.getLogger(NettyConnectionsPool.class); private final ConcurrentHashMap<String, ConcurrentLinkedQueue<IdleChannel>> connectionsPool = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IdleChannel>>(); private final ConcurrentHashMap<Channel, IdleChannel> channel2IdleChannel = new ConcurrentHashMap<Channel, IdleChannel>(); private final AtomicBoolean isClosed = new AtomicBoolean(false); private final Timer idleConnectionDetector = new Timer(); private final boolean sslConnectionPoolEnabled; private final int maxTotalConnections; private final int maxConnectionPerHost; private final long maxIdleTime; public NettyConnectionsPool(NettyAsyncHttpProvider provider) { this.maxTotalConnections = provider.getConfig().getMaxTotalConnections(); this.maxConnectionPerHost = provider.getConfig().getMaxConnectionPerHost(); this.sslConnectionPoolEnabled = provider.getConfig().isSslConnectionPoolEnabled(); this.maxIdleTime = provider.getConfig().getIdleConnectionInPoolTimeoutInMs(); this.idleConnectionDetector.schedule(new IdleChannelDetector(), maxIdleTime, maxIdleTime); } private static class IdleChannel { final String uri; final Channel channel; final long start; IdleChannel(String uri, Channel channel) { this.uri = uri; this.channel = channel; this.start = System.currentTimeMillis(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof IdleChannel)) return false; IdleChannel that = (IdleChannel) o; if (channel != null ? !channel.equals(that.channel) : that.channel != null) return false; return true; } @Override public int hashCode() { return channel != null ? channel.hashCode() : 0; } } private class IdleChannelDetector extends TimerTask { @Override public void run() { try { if (isClosed.get()) return; List<IdleChannel> channelsInTimeout = new ArrayList<IdleChannel>(); long currentTime = System.currentTimeMillis(); for (IdleChannel idleChannel : channel2IdleChannel.values()) { long age = currentTime - idleChannel.start; if (age > maxIdleTime) { // store in an unsynchronized list to minimize the impact on the ConcurrentHashMap. channelsInTimeout.add(idleChannel); } } long endConcurrentLoop = System.currentTimeMillis(); for (IdleChannel idleChannel : channelsInTimeout) { Object attachment = idleChannel.channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment(); if (attachment != null) { if (NettyResponseFuture.class.isAssignableFrom(attachment.getClass())) { NettyResponseFuture<?> future = (NettyResponseFuture<?>) attachment; if (!future.isDone() && !future.isCancelled()) { log.debug("Future not in appropriate state %s\n", future); continue; } } } if (remove(idleChannel)) { log.debug("Closing Idle Channel {}", idleChannel.channel); close(idleChannel.channel); } } log.trace(String.format("%d channel open, %d idle channels closed (times: 1st-loop=%d, 2nd-loop=%d).\n", connectionsPool.size(), channelsInTimeout.size(), endConcurrentLoop - currentTime, System.currentTimeMillis() - endConcurrentLoop)); } catch (Throwable t) { log.error("uncaught exception!", t); } } } /** * {@inheritDoc} */ public boolean offer(String uri, Channel channel) { if (isClosed.get()) return false; if (!sslConnectionPoolEnabled && uri.startsWith("https")) { return false; } log.debug("Adding uri: {} for channel {}", uri, channel); channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(new NettyAsyncHttpProvider.DiscardEvent()); ConcurrentLinkedQueue<IdleChannel> idleConnectionForHost = connectionsPool.get(uri); if (idleConnectionForHost == null) { ConcurrentLinkedQueue<IdleChannel> newPool = new ConcurrentLinkedQueue<IdleChannel>(); idleConnectionForHost = connectionsPool.putIfAbsent(uri, newPool); if (idleConnectionForHost == null) idleConnectionForHost = newPool; } boolean added; int size = idleConnectionForHost.size(); if (maxConnectionPerHost == -1 || size < maxConnectionPerHost) { IdleChannel idleChannel = new IdleChannel(uri, channel); added = idleConnectionForHost.add(idleChannel); if (channel2IdleChannel.put(channel, idleChannel) != null) { log.error("Bas, this channel entry already exists in the connections pool!"); } } else { log.debug("Maximum number of requests per host reached {} for {}", maxConnectionPerHost, uri); added = false; } return added; } /** * {@inheritDoc} */ public Channel poll(String uri) { if (!sslConnectionPoolEnabled && uri.startsWith("https")) { return null; } IdleChannel idleChannel = null; ConcurrentLinkedQueue<IdleChannel> idleConnectionForHost = connectionsPool.get(uri); if (idleConnectionForHost != null) { boolean poolEmpty = false; while (!poolEmpty && idleChannel == null) { if (idleConnectionForHost.size() > 0) { idleChannel = idleConnectionForHost.poll(); if (idleChannel != null) channel2IdleChannel.remove(idleChannel.channel); } if (idleChannel == null) { poolEmpty = true; } else if (!idleChannel.channel.isConnected() || !idleChannel.channel.isOpen()) { idleChannel = null; log.trace("Channel not connected or not opened!"); } } } return idleChannel != null ? idleChannel.channel : null; } private boolean remove(IdleChannel pooledChannel) { if (pooledChannel == null || isClosed.get()) return false; boolean isRemoved = false; ConcurrentLinkedQueue<IdleChannel> pooledConnectionForHost = connectionsPool.get(pooledChannel.uri); if (pooledConnectionForHost != null) { isRemoved = pooledConnectionForHost.remove(pooledChannel); } isRemoved |= channel2IdleChannel.remove(pooledChannel.channel) != null; return isRemoved; } /** * {@inheritDoc} */ public boolean removeAll(Channel channel) { return !isClosed.get() && remove(channel2IdleChannel.get(channel)); } /** * {@inheritDoc} */ public boolean canCacheConnection() { if (!isClosed.get() && maxTotalConnections != -1 && channel2IdleChannel.size() >= maxTotalConnections) { return false; } else { return true; } } /** * {@inheritDoc} */ public void destroy() { if (isClosed.getAndSet(true)) return; // stop timer idleConnectionDetector.cancel(); idleConnectionDetector.purge(); for (Channel channel : channel2IdleChannel.keySet()) { close(channel); } connectionsPool.clear(); channel2IdleChannel.clear(); } private void close(Channel channel) { try { channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(new NettyAsyncHttpProvider.DiscardEvent()); channel.close(); } catch (Throwable t) { // noop } } public final String toString() { return String.format("NettyConnectionPool: {pool-size: %d}", channel2IdleChannel.size()); } }
package com.tealcube.minecraft.bukkit.chatterbox; import com.tealcube.minecraft.bukkit.TextUtils; import com.tealcube.minecraft.bukkit.chatterbox.titles.GroupData; import com.tealcube.minecraft.bukkit.chatterbox.titles.PlayerData; import com.tealcube.minecraft.bukkit.config.MasterConfiguration; import com.tealcube.minecraft.bukkit.config.SmartConfiguration; import com.tealcube.minecraft.bukkit.config.SmartYamlConfiguration; import com.tealcube.minecraft.bukkit.config.VersionedConfiguration; import com.tealcube.minecraft.bukkit.config.VersionedSmartYamlConfiguration; import com.tealcube.minecraft.bukkit.facecore.apache.validator.routines.UrlValidator; import com.tealcube.minecraft.bukkit.facecore.logging.PluginLogger; import com.tealcube.minecraft.bukkit.facecore.plugin.FacePlugin; import com.tealcube.minecraft.bukkit.hilt.HiltItemStack; import com.tealcube.minecraft.bukkit.shade.fanciful.FancyMessage; import com.tealcube.minecraft.bukkit.shade.google.common.base.Splitter; import net.milkbowl.vault.chat.Chat; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.RegisteredServiceProvider; import se.ranzdo.bukkit.methodcommand.CommandHandler; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Level; public class ChatterboxPlugin extends FacePlugin implements Listener { private Chat chat; private UrlValidator validator; private MasterConfiguration settings; private VersionedSmartYamlConfiguration groupsYaml; private SmartConfiguration dataYaml; private Map<UUID, PlayerData> playerDataMap = new HashMap<>(); private Map<String, GroupData> groupDataMap = new HashMap<>(); private PluginLogger debugPrinter; @Override public void enable() { debugPrinter = new PluginLogger(this); VersionedSmartYamlConfiguration configYaml = new VersionedSmartYamlConfiguration( new File(getDataFolder(), "config.yml"), getResource("config.yml"), VersionedConfiguration.VersionUpdateType.BACKUP_AND_UPDATE); if (configYaml.update()) { getLogger().info("Updating config.yml..."); debug("Updating config.yml..."); } groupsYaml = new VersionedSmartYamlConfiguration( new File(getDataFolder(), "groups.yml"), getResource("groups.yml"), VersionedConfiguration.VersionUpdateType.BACKUP_AND_UPDATE); if (groupsYaml.update()) { getLogger().info("Updating groups.yml..."); debug("Updating groups.yml..."); } dataYaml = new SmartYamlConfiguration(new File(getDataFolder(), "data.yml")); loadGroupData(groupsYaml); loadPlayerData(dataYaml); settings = MasterConfiguration.loadFromFiles(configYaml); if (!setupChat()) { getServer().getPluginManager().disablePlugin(this); return; } getServer().getPluginManager().registerEvents(this, this); validator = new UrlValidator(); CommandHandler commandHandler = new CommandHandler(this); commandHandler.registerCommands(new TitleCommand(this)); Bukkit.getScheduler().runTaskTimer(this, new Runnable() { @Override public void run() { saveGroupData(groupsYaml); savePlayerData(dataYaml); } }, 20L * 600, 20L * 600); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent event) { PlayerData playerData = getPlayerDataMap().get(event.getPlayer().getUniqueId()); if (playerData == null) { playerData = new PlayerData(event.getPlayer().getUniqueId()); playerData.setTitle(settings.getString("config.default-title")); playerData.setTitleGroup(getTitleGroup(event.getPlayer())); } getPlayerDataMap().put(event.getPlayer().getUniqueId(), playerData); } private void savePlayerData(SmartConfiguration configuration) { for (String key : configuration.getKeys(true)) { configuration.set(key, null); } for (Map.Entry<UUID, PlayerData> entry : playerDataMap.entrySet()) { configuration.set("titles." + entry.getKey().toString() + ".title", entry.getValue().getTitle()); configuration.set("titles." + entry.getKey().toString() + ".title-group", entry.getValue().getTitleGroup()); configuration.set("titles." + entry.getKey().toString() + ".ignore-list", entry.getValue().getIgnoreList()); } configuration.save(); } private void saveGroupData(SmartConfiguration configuration) { for (String key : configuration.getKeys(true)) { if (key.equals("version")) { continue; } configuration.set(key, null); } for (Map.Entry<String, GroupData> entry : groupDataMap.entrySet()) { configuration.set("groups." + entry.getKey() + ".titles", entry.getValue().getTitles()); configuration.set("groups." + entry.getKey() + ".title-color", TextUtils.convertTag(entry.getValue() .getTitleColor())); configuration.set("groups." + entry.getKey() + ".chat-color", TextUtils.convertTag(entry.getValue() .getChatColor())); configuration.set("groups." + entry.getKey() + ".rank-description", entry.getValue().getRankDescription()); configuration.set("groups." + entry.getKey() + ".title-description", entry.getValue().getTitleDescription()); configuration.set("groups." + entry.getKey() + ".weight", entry.getValue().getWeight()); } } private void loadPlayerData(SmartConfiguration configuration) { playerDataMap.clear(); if (!configuration.isConfigurationSection("titles")) { return; } ConfigurationSection titlesSection = configuration.getConfigurationSection("titles"); Map<UUID, PlayerData> data = new HashMap<>(); for (String key : titlesSection.getKeys(false)) { ConfigurationSection titleSection = titlesSection.getConfigurationSection(key); UUID uuid = UUID.fromString(key); PlayerData playerData = new PlayerData(uuid); playerData.setTitle(titleSection.getString("title")); playerData.setTitleGroup(titleSection.getString("title-group")); playerData.setIgnoreList(titleSection.getStringList("ignore-list")); data.put(uuid, playerData); } debug("Loaded players: " + data.size()); playerDataMap.putAll(data); } private void loadGroupData(SmartConfiguration configuration) { groupDataMap.clear(); if (!configuration.isConfigurationSection("groups")) { return; } ConfigurationSection groupsSection = configuration.getConfigurationSection("groups"); Map<String, GroupData> data = new HashMap<>(); for (String key : groupsSection.getKeys(false)) { ConfigurationSection groupSection = groupsSection.getConfigurationSection(key); GroupData groupData = new GroupData(key); groupData.setTitleColor(TextUtils.convertTag(groupSection.getString("title-color"))); groupData.setChatColor(TextUtils.convertTag(groupSection.getString("chat-color"))); groupData.setRankDescription(groupSection.getStringList("rank-description")); groupData.setTitleDescription(groupSection.getStringList("title-description")); groupData.setWeight(groupSection.getInt("weight")); groupData.setTitles(groupSection.getStringList("titles")); data.put(key, groupData); } debug("Loaded groups: " + data.size()); groupDataMap.putAll(data); } private boolean setupChat() { RegisteredServiceProvider<Chat> chatProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.chat.Chat.class); if (chatProvider != null) { chat = chatProvider.getProvider(); } return (chat != null); } public void debug(String... messages) { debug(Level.INFO, messages); } public void debug(Level level, String... messages) { if (debugPrinter != null && (settings == null || settings.getBoolean("config.debug", false))) { debugPrinter.log(level, Arrays.asList(messages)); } } @Override public void disable() { saveGroupData(groupsYaml); savePlayerData(dataYaml); } @EventHandler(priority = EventPriority.HIGHEST) public void onAsyncPlayerChat(AsyncPlayerChatEvent event) { if (event.isCancelled()) { return; } event.setCancelled(true); Player player = event.getPlayer(); Set<Player> receivers = event.getRecipients(); String message = event.getMessage(); String newFormat = formatMessage(player, message); GroupData group = getGroupData(player); List<String> splitMessage = Splitter.on(" ").splitToList(newFormat); FancyMessage messageParts = new FancyMessage(""); ChatColor color = ChatColor.GRAY; String title = playerDataMap.containsKey(player.getUniqueId()) ? playerDataMap.get(player.getUniqueId()) .getTitle() : settings.getString("config.default-title"); for (int i = 0; i < splitMessage.size(); i++) { if (i == 2) { color = ChatColor.getByChar(splitMessage.get(i).substring(1, 2)); } String s = splitMessage.get(i); String str = ChatColor.stripColor(s); if (str.equalsIgnoreCase(player.getDisplayName() + ":")) { String lev = ChatColor.WHITE + player.getName() + " - Level " + player.getLevel(); String[] rankDesc = TextUtils.color(group.getRankDescription()).toArray( new String[group.getRankDescription().size()]); String[] titleDesc = TextUtils.color(group.getTitleDescription()).toArray( new String[group.getTitleDescription().size()]); messageParts.then(s).tooltip(concat(concat(lev, rankDesc), titleDesc)); } else if (str.equalsIgnoreCase(title)) { messageParts.then(TextUtils.findFirstColor(s) + "[" + s + "]").tooltip(concat(group .getRankDescription(), group.getTitleDescription())); } else if (str.startsWith("{")) { if (str.equalsIgnoreCase("{hand}") || str.equalsIgnoreCase("{item}") || str.equalsIgnoreCase("{link}")) { ItemStack hand = player.getEquipment().getItemInHand(); HiltItemStack hHand = (hand != null && hand.getType() != Material.AIR) ? new HiltItemStack(hand) : null; if (hHand != null) { if (hHand.getName().contains("\u00A7")) { messageParts.then(hHand.getName().substring(0, 2) + "[Item]").itemTooltip(hHand); } else { messageParts.then("[Item]").itemTooltip(hHand); } } else { messageParts.then("nothing"); } } else if (str.equalsIgnoreCase("{helmet}") || str.equalsIgnoreCase("{head}") || str.equalsIgnoreCase ("{hat}")) { ItemStack helmet = player.getEquipment().getHelmet(); HiltItemStack hHelmet = (helmet != null && helmet.getType() != Material.AIR) ? new HiltItemStack(helmet) : null; if (hHelmet != null) { if (hHelmet.getName().contains("\u00A7")) { messageParts.then(hHelmet.getName().substring(0, 2) + "[Item]").itemTooltip(hHelmet); } else { messageParts.then("[Item]").itemTooltip(hHelmet); } } else { messageParts.then("nothing"); } } else if (str.equalsIgnoreCase("{chestplate}") || str.equalsIgnoreCase("{chest}") || str .equalsIgnoreCase("{body}")) { ItemStack chest = player.getEquipment().getChestplate(); HiltItemStack hChest = (chest != null && chest.getType() != Material.AIR) ? new HiltItemStack(chest) : null; if (hChest != null) { if (hChest.getName().contains("\u00A7")) { messageParts.then(hChest.getName().substring(0, 2) + "[Item]").itemTooltip(hChest); } else { messageParts.then("[Item]").itemTooltip(hChest); } } else { messageParts.then("nothing"); } } else if (str.equalsIgnoreCase("{leggings}") || str.equalsIgnoreCase("{legs}") || str.equalsIgnoreCase ("{pants}")) { ItemStack leggings = player.getEquipment().getLeggings(); HiltItemStack hLeggings = (leggings != null && leggings.getType() != Material.AIR) ? new HiltItemStack(leggings) : null; if (hLeggings != null) { if (hLeggings.getName().contains("\u00A7")) { messageParts.then(hLeggings.getName().substring(0, 2) + "[Item]").itemTooltip(hLeggings); } else { messageParts.then("[Item]").itemTooltip(hLeggings); } } else { messageParts.then("nothing"); } } else if (str.equalsIgnoreCase("{boots}") || str.equalsIgnoreCase("{feet}") || str.equalsIgnoreCase ("{shoes}")) { ItemStack boots = player.getEquipment().getBoots(); HiltItemStack hBoots = (boots != null && boots.getType() != Material.AIR) ? new HiltItemStack(boots) : null; if (hBoots != null) { if (hBoots.getName().contains("\u00A7")) { messageParts.then(hBoots.getName().substring(0, 2) + "[Item]").itemTooltip(hBoots); } else { messageParts.then("[Item]").itemTooltip(hBoots); } } else { messageParts.then("nothing"); } } } else if (validator.isValid(str)) { messageParts.then("[Link]").color(ChatColor.AQUA).link(str).tooltip(str); } else if (validator.isValid("http://" + str)) { messageParts.then("[Link]").color(ChatColor.AQUA).link("http: } else { messageParts.then(TextUtils.color(color + s)); } if (i != splitMessage.size() - 1) { messageParts.then(" "); } } messageParts.send(Bukkit.getConsoleSender()); for (Player receiver : receivers) { PlayerData playerData = getPlayerDataMap().get(receiver.getUniqueId()); if (playerData == null) { continue; } if (playerData.getIgnoreList().contains(player.getName())) { continue; } messageParts.send(receiver); } } public Map<UUID, PlayerData> getPlayerDataMap() { return playerDataMap; } public Map<String, GroupData> getGroupDataMap() { return groupDataMap; } private GroupData getGroupData(Player player) { GroupData group = null; for (Map.Entry<String, GroupData> entry : groupDataMap.entrySet()) { if (!player.hasPermission("easytitles.group." + entry.getKey())) { continue; } if (group == null) { group = entry.getValue(); continue; } if (entry.getValue().getWeight() > group.getWeight()) { group = entry.getValue(); } } return group; } private String formatMessage(Player player, String message) { GroupData group = getGroupData(player); String title = playerDataMap.containsKey(player.getUniqueId()) ? playerDataMap.get(player.getUniqueId()) .getTitle() : settings.getString("config.default-title"); String template = settings.getString("config.format"); return TextUtils.args(template, new String[][]{ {"%name%", player.getDisplayName()}, {"%message%", message}, {"%title-color%", group.getTitleColor() + ""}, {"%chatcolor%", group.getChatColor() + ""}, {"%title%", title} }); } @SafeVarargs private final List<String> concat(List<String>... strings) { List<String> ret = new ArrayList<>(); for (List<String> list : strings) { ret.addAll(list); } return ret; } private String[] concat(String string, String[] strings) { int size = strings.length + 1; String[] ret = new String[size]; ret[0] = string; System.arraycopy(strings, 0, ret, 1, strings.length); return ret; } private String[] concat(String[] strings, String string) { int size = strings.length + 1; String[] ret = new String[size]; System.arraycopy(strings, 0, ret, 0, strings.length); ret[strings.length] = string; return ret; } private String[] concat(String[]... strings) { int size = 0; for (String[] array : strings) { size += array.length; } String[] ret = new String[size]; int counter = 0; for (String[] array : strings) { for (String string : array) { ret[counter++] = string; } } return ret; } private String getTitleGroup(Player player) { String titleGroup = ""; int lastWeight = 0; for (Map.Entry<String, GroupData> entry : getGroupDataMap().entrySet()) { if (player.hasPermission("easytitles.group." + entry.getKey()) && entry.getValue().getWeight() > lastWeight) { titleGroup = entry.getKey(); lastWeight = entry.getValue().getWeight(); } } return titleGroup; } }
package com.zero_x_baadf00d.play.module.aws.s3; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ClientOptions; import com.amazonaws.services.s3.model.AmazonS3Exception; import play.Configuration; import play.Logger; import play.inject.ApplicationLifecycle; import javax.inject.Inject; import javax.inject.Singleton; import java.util.concurrent.CompletableFuture; /** * Implementation of {@code AmazonS3Module}. * * @author Thibault Meyer * @version 16.03.16 * @since 16.03.13 */ @Singleton public class AmazonS3ModuleImpl implements AmazonS3Module { /** * @since 16.03.13 */ private static final String AWS_S3_BUCKET = "aws.s3.bucket"; /** * @since 16.03.13 */ private static final String AWS_ENDPOINT = "aws.s3.endpoint"; /** * @since 16.03.13 */ private static final String AWS_WITHPATHSTYLE = "aws.s3.pathstyle"; /** * @since 16.03.13 */ private static final String AWS_ACCESS_KEY = "aws.access.key"; /** * @since 16.03.13 */ private static final String AWS_SECRET_KEY = "aws.secret.key"; /** * Handle on the S3 API client. * * @since 16.03.13 */ private final AmazonS3Client amazonS3; /** * Name of the S3 bucket to use. * * @since 16.03.13 */ private final String s3Bucket; /** * Create a simple instance of {@code S3Module}. * * @param lifecycle The application life cycle * @param configuration The application configuration * @since 16.03.13 */ @Inject public AmazonS3ModuleImpl(final ApplicationLifecycle lifecycle, final Configuration configuration) { final String accessKey = configuration.getString(AmazonS3ModuleImpl.AWS_ACCESS_KEY); final String secretKey = configuration.getString(AmazonS3ModuleImpl.AWS_SECRET_KEY); this.s3Bucket = configuration.getString(AmazonS3ModuleImpl.AWS_S3_BUCKET); if ((accessKey != null) && (secretKey != null) && (this.s3Bucket != null)) { final AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); this.amazonS3 = new AmazonS3Client(awsCredentials); this.amazonS3.setEndpoint(configuration.getString(AmazonS3ModuleImpl.AWS_ENDPOINT)); if (configuration.getBoolean(AmazonS3ModuleImpl.AWS_WITHPATHSTYLE, false)) { this.amazonS3.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); } try { this.amazonS3.createBucket(this.s3Bucket); } catch (AmazonS3Exception e) { if (e.getErrorCode().compareTo("BucketAlreadyOwnedByYou") != 0 && e.getErrorCode().compareTo("AccessDenied") != 0) { throw e; } } finally { Logger.info("Using S3 Bucket: " + this.s3Bucket); } } else { throw new RuntimeException("S3Module is not properly configured"); } lifecycle.addStopHook(() -> CompletableFuture.completedFuture(null)); } @Override public AmazonS3Client getService() { return this.amazonS3; } @Override public String getBucketName() { return this.s3Bucket; } }
package de.swm.nis.logicaldecoding.tracktable; import java.sql.SQLException; import java.sql.Types; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Future; import org.postgresql.util.PGobject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Repository; import com.google.common.base.Joiner; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.WKBWriter; import de.swm.nis.logicaldecoding.parser.domain.Cell; import de.swm.nis.logicaldecoding.parser.domain.DmlEvent; /** * This class publishes changes into an audit table. * Old an new Values of the whole object record are stored in JSONB objects. * @author Schmidt.Sebastian2 * */ @Repository public class TrackTablePublisher { private static final Logger log = LoggerFactory.getLogger(TrackTablePublisher.class); @Autowired private JdbcTemplate template; @Value("${tracktable.schemaname}") private String schemaname; @Value("${tracktable.tablename}") private String tableName; @Value("${tracktable.commitTimestampColumn:commit_ts}") private String commitTimestampColumnName; @Value("${tracktable.transactionIdColumn:transaction_id}") private String txIdColumnName; @Value("${tracktable.jsonOldValuesColumn:oldvalues}") private String jsonOldValuesColumnName; @Value("${tracktable.jsonNewValuesColumn:newvalues}") private String jsonNewValuesColumName; @Value("${tracktable.metaInfoColumn:metadata}") private String metadataColumnName; @Value("${tracktable.regionColumn:region}") private String regionColumnName; @Value("${tracktable.tableColumn:tablename}") private String tableColumnName; @Value("${tracktable.schemaColumn:schemaname}") private String schemaColumnName; @Value("${tracktable.transactionTypeColumn:type}") private String transactionTypeColumnName; @Value("#{'${tracktable.metainfo.searchpatterns}'.split(',')}") private List<String> metaInfoSearchPatterns; @Value("${postgresql.epsgCode}") private int epsgCode; @Value("${pointObjects.miniumSize}") private double minSize=0.00001f; @Value("${pointObjects.buffer}") private double bufferSize=0.0001f; @Async public Future<String> publish(Collection<DmlEvent> events) { log.info("Publishing " + events.size()+" change metadata to track table"); for(DmlEvent event:events) { publish(event); } return new AsyncResult<String>("success"); } public void publish(DmlEvent event) { String metadata = extractMetadata(event); String changedTableSchema = event.getSchemaName(); String changedTableName = event.getTableName(); String type = event.getType().toString(); Long transactionId = event.getTransactionId(); PGobject timestamp = getTimestamp(event); PGobject oldjson = getJsonOldValues(event); PGobject newjson = getJsonNewValues(event); Object[] params; String sql; int[] types; Envelope envelope = event.getEnvelope(); if (! envelope.isNull()) { //expand if necessasry if (envelope.getHeight() < minSize && envelope.getWidth() < minSize) { envelope.expandBy(bufferSize); } //Transform Bounding Box of the change into WKB GeometryFactory geomFactory = new GeometryFactory(new PrecisionModel(), epsgCode); WKBWriter wkbWriter = new WKBWriter(2, true); byte[] wkb = wkbWriter.write(geomFactory.toGeometry(envelope)); params = new Object[]{wkb, type, changedTableSchema, changedTableName, transactionId, timestamp, metadata, oldjson, newjson}; types = new int[] {Types.BINARY, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BIGINT, Types.OTHER, Types.VARCHAR, Types.OTHER, Types.OTHER}; sql = "INSERT INTO "+schemaname + "." + tableName + "("+regionColumnName +", "+transactionTypeColumnName + ", "+schemaColumnName+", "+tableColumnName+", "+txIdColumnName +", "+commitTimestampColumnName+", "+metadataColumnName+", "+jsonOldValuesColumnName+", "+jsonNewValuesColumName +") VALUES (?,?,?,?,?,?,?,?,?)"; } else { //geometry is null, do not include it in SQL insert statement params = new Object[]{type, changedTableSchema, changedTableName, transactionId, timestamp, metadata, oldjson, newjson}; types = new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BIGINT, Types.OTHER, Types.VARCHAR, Types.OTHER, Types.OTHER}; sql = "INSERT INTO "+schemaname + "." + tableName + "(" +transactionTypeColumnName + ", "+schemaColumnName+", "+tableColumnName+", "+txIdColumnName +", "+commitTimestampColumnName+", "+metadataColumnName+", "+jsonOldValuesColumnName+", "+jsonNewValuesColumName +") VALUES (?,?,?,?,?,?,?,?)"; } template.update(sql, params,types); } private String extractMetadata(DmlEvent event) { switch(event.getType()) { case delete: { return extractMetadata(event.getOldValues()); } default: { return extractMetadata(event.getNewValues()); } } } private String extractMetadata(Collection<Cell> cells) { List<String> parts = new ArrayList<String>(); for (Cell cell:cells) { for (String pattern:metaInfoSearchPatterns) { if (cell.getName().startsWith(pattern) || cell.getName().endsWith(pattern)) { parts.add(new String(cell.getName() + ": " + cell.getValue())); } } } return Joiner.on(", ").join(parts); } private PGobject getJsonOldValues(DmlEvent event) { if ((event.getType() == DmlEvent.Type.delete) || (event.getType() == DmlEvent.Type.update)) { return getJsonObject(event.getOldValues()); } else { return null; } } private PGobject getJsonNewValues(DmlEvent event) { if ((event.getType() == DmlEvent.Type.insert) || (event.getType() == DmlEvent.Type.update)) { return getJsonObject(event.getNewValues()); } else { return null; } } private PGobject getJsonObject(List<Cell> cells) { List<String> parts = new ArrayList<String>(); for (Cell cell:cells) { parts.add(cell.getJson()); } PGobject pgobject = new PGobject(); pgobject.setType("jsonb"); try { pgobject.setValue("{" + Joiner.on(", ").join(parts) + "}"); } catch (SQLException e) { log.error("Error while setting JSONB of changed Objects into SQL PGobject type:", e); } return pgobject; } private PGobject getTimestamp(DmlEvent event) { PGobject timestamp = new PGobject(); timestamp.setType("timestamp"); try { ZonedDateTime time = event.getCommitTime(); if (time == null) { timestamp.setValue("1970-01-01T00:00:00+00:00"); return timestamp; } timestamp.setValue(time.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); } catch (SQLException e) { log.error("Error while setting Timestamp SQL PGobject type:", e); } return timestamp; } }
package de.tuberlin.dima.schubotz.fse.mappers; import java.util.Arrays; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.common.collect.HashMultiset; import de.tuberlin.dima.schubotz.fse.types.QueryTuple; import de.tuberlin.dima.schubotz.fse.types.ResultTuple; import de.tuberlin.dima.schubotz.fse.types.SectionTuple; import de.tuberlin.dima.schubotz.utils.TFIDFHelper; import eu.stratosphere.api.java.functions.FlatMapFunction; import eu.stratosphere.configuration.Configuration; import eu.stratosphere.util.Collector; public class QuerySectionMatcher extends FlatMapFunction<SectionTuple,ResultTuple> { /** * Split for tex and keywords */ final String STR_SPLIT; final HashMultiset<String> latexDocsMultiset; final HashMultiset<String> keywordDocsMultiset; Collection<QueryTuple> queries; final Integer numDocs; double latexScore = 0; double keywordScore = 0; double finalScore =0.; private static Log LOG = LogFactory.getLog(QuerySectionMatcher.class); private boolean debug; public QuerySectionMatcher (String STR_SPLIT, HashMultiset<String> latexDocsMultiset, HashMultiset<String> keywordDocsMultiset, Integer numDocs, boolean debug) { this.STR_SPLIT = STR_SPLIT; this.latexDocsMultiset = latexDocsMultiset; this.keywordDocsMultiset = keywordDocsMultiset; this.numDocs = numDocs; this.debug = debug; } @Override public void open(Configuration parameters) { queries = getRuntimeContext().getBroadcastVariable("Queries"); } /** * The core method of the MapFunction. Takes an element from the input data set and transforms * it into another element. * * @param in The input value. * @return The value produced by the map function from the input value. * @throws Exception This method may throw exceptions. Throwing an exception will cause the operation * to fail and may trigger recovery. */ @Override public void flatMap(SectionTuple in,Collector<ResultTuple> out) { HashMultiset<String> queryLatex; HashMultiset<String> queryKeywords; //Construct set of term frequencies for latex and keywords HashMultiset<String> sectionLatex = HashMultiset.create(Arrays.asList(in.getLatex().split(STR_SPLIT))); HashMultiset<String> sectionKeywords = HashMultiset.create(Arrays.asList(in.getKeywords().split(STR_SPLIT))); if (sectionLatex.isEmpty() && sectionKeywords.isEmpty()) { return; } //Loop through queries and calculate tfidf scores for (QueryTuple query : queries) { if (in.getID().contains("5478_1_6") && query.getID().contains("Math-1")) { //DEBUG changer debug = true; } else { debug = false; } if (LOG.isDebugEnabled() && debug) { LOG.debug(query.toString()); LOG.debug(in.toString()); LOG.debug(Arrays.asList(in.getLatex().split(STR_SPLIT))); } if (!sectionLatex.isEmpty()) { queryLatex = HashMultiset.create(Arrays.asList(query.getLatex().split(STR_SPLIT))); latexScore = TFIDFHelper.calculateTFIDFScore(queryLatex, sectionLatex, latexDocsMultiset, numDocs, debug); } else { latexScore = 0.; } if (!sectionKeywords.isEmpty()) { queryKeywords = HashMultiset.create(Arrays.asList(query.getKeywords().split(STR_SPLIT))); keywordScore = TFIDFHelper.calculateTFIDFScore(queryKeywords, sectionKeywords, keywordDocsMultiset, numDocs, debug); } else { keywordScore = 0.; } finalScore = (keywordScore/6.36) + latexScore; //TODO why is keywordScore and/or latexScore producing NaN? if( Double.isNaN( finalScore )) { if (LOG.isWarnEnabled() ) { LOG.warn("NaN hit! Latex: " + Double.toString(latexScore) + " Keyword: " + Double.toString(keywordScore)); } finalScore = 0; } out.collect( new ResultTuple( query.getID(), in.getID(), finalScore ) ); } } }
package hudson.plugins.octopusdeploy; import com.octopusdeploy.api.data.SelectedPackage; import com.octopusdeploy.api.data.DeploymentProcessTemplate; import com.octopusdeploy.api.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.*; import jenkins.model.*; import hudson.*; import hudson.FilePath.FileCallable; import hudson.model.*; import hudson.remoting.VirtualChannel; import hudson.scm.*; import hudson.tasks.*; import hudson.util.*; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.json.*; import org.apache.commons.lang.StringUtils; import org.jenkinsci.remoting.RoleChecker; import org.kohsuke.stapler.*; import org.kohsuke.stapler.export.*; /** * Creates a release and optionally deploys it. */ public class OctopusDeployReleaseRecorder extends Recorder implements Serializable { /** * The project name as defined in Octopus. */ private final String project; public String getProject() { return project; } /** * The release version as defined in Octopus. */ private final String releaseVersion; public String getReleaseVersion() { return releaseVersion; } /** * Are there release notes for this release? */ private final boolean releaseNotes; public boolean getReleaseNotes() { return releaseNotes; } /** * Where are the release notes located? */ private final String releaseNotesSource; public String getReleaseNotesSource() { return releaseNotesSource; } public boolean isReleaseNotesSourceFile() { return "file".equals(releaseNotesSource); } public boolean isReleaseNotesSourceScm() { return "scm".equals(releaseNotesSource); } /** * The Tenant to use for a deploy to in Octopus. */ private final String tenant; public String getTenant() { return tenant; } private final String channel; public String getChannel() { return channel; } /** * Write a link back to the originating Jenkins build to the * Octopus release notes? */ private final boolean releaseNotesJenkinsLinkback; public boolean getJenkinsUrlLinkback() { return releaseNotesJenkinsLinkback; } /** * The file that the release notes are in. */ private final String releaseNotesFile; public String getReleaseNotesFile() { return releaseNotesFile; } /** * If we are deploying, should we wait for it to complete? */ private final boolean waitForDeployment; public boolean getWaitForDeployment() { return waitForDeployment; } /** * The environment to deploy to, if we are deploying. */ private final String environment; public String getEnvironment() { return environment; } /** * Should this release be deployed right after it is created? */ private final boolean deployThisRelease; @Exported public boolean getDeployThisRelease() { return deployThisRelease; } /** * All packages needed to create this new release. */ private final List<PackageConfiguration> packageConfigs; @Exported public List<PackageConfiguration> getPackageConfigs() { return packageConfigs; } /** * Default package version to use for required packages that are not * specified in the Package Configurations */ private final String defaultPackageVersion; @Exported public String getDefaultPackageVersion() { return defaultPackageVersion; } // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public OctopusDeployReleaseRecorder( String project, String releaseVersion, boolean releaseNotes, String releaseNotesSource, String releaseNotesFile, boolean deployThisRelease, String environment, String tenant, String channel, boolean waitForDeployment, List<PackageConfiguration> packageConfigs, boolean jenkinsUrlLinkback, String defaultPackageVersion) { this.project = project.trim(); this.releaseVersion = releaseVersion.trim(); this.releaseNotes = releaseNotes; this.releaseNotesSource = releaseNotesSource; this.releaseNotesFile = releaseNotesFile.trim(); this.deployThisRelease = deployThisRelease; this.packageConfigs = packageConfigs; this.environment = environment.trim(); this.tenant = tenant.trim(); this.channel = channel.trim(); this.waitForDeployment = waitForDeployment; this.releaseNotesJenkinsLinkback = jenkinsUrlLinkback; this.defaultPackageVersion = defaultPackageVersion; } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { boolean success = true; Log log = new Log(listener); if (Result.FAILURE.equals(build.getResult())) { log.info("Not creating a release due to job being in FAILED state."); return success; } logStartHeader(log); // todo: getting from descriptor is ugly. refactor? getDescriptorImpl().setGlobalConfiguration(); OctopusApi api = getDescriptorImpl().api; VariableResolver resolver = build.getBuildVariableResolver(); EnvVars envVars; try { envVars = build.getEnvironment(listener); } catch (Exception ex) { log.fatal(String.format("Failed to retrieve environment variables for this project '%s' - '%s'", project, ex.getMessage())); return false; } EnvironmentVariableValueInjector envInjector = new EnvironmentVariableValueInjector(resolver, envVars); // NOTE: hiding the member variables of the same name with their env-injected equivalents String project = envInjector.injectEnvironmentVariableValues(this.project); String releaseVersion = envInjector.injectEnvironmentVariableValues(this.releaseVersion); String releaseNotesFile = envInjector.injectEnvironmentVariableValues(this.releaseNotesFile); String environment = envInjector.injectEnvironmentVariableValues(this.environment); String tenant = envInjector.injectEnvironmentVariableValues(this.tenant); String channel = envInjector.injectEnvironmentVariableValues(this.channel); String defaultPackageVersion = envInjector.injectEnvironmentVariableValues(this.defaultPackageVersion); com.octopusdeploy.api.data.Project p = null; try { p = api.getProjectsApi().getProjectByName(project); } catch (Exception ex) { log.fatal(String.format("Retrieving project name '%s' failed with message '%s'", project, ex.getMessage())); success = false; } if (p == null) { log.fatal("Project was not found."); success = false; } com.octopusdeploy.api.data.Channel c = null; if (channel != null && !channel.isEmpty()) { try { c = api.getChannelsApi().getChannelByName(p.getId(), channel); } catch (Exception ex) { log.fatal(String.format("Retrieving channel name '%s' from project '%s' failed with message '%s'", channel, project, ex.getMessage())); success = false; } if (c == null) { log.fatal("Channel was not found."); success = false; } } // Check packageVersion String releaseNotesContent = ""; // Prepend Release Notes with Jenkins URL? // Do this regardless if Release Notes are specified if (releaseNotesJenkinsLinkback) { final String buildUrlVar = "${BUILD_URL}"; // Use env vars String resolvedBuildUrlVar = envInjector.injectEnvironmentVariableValues(buildUrlVar); releaseNotesContent = String.format("Created by: <a href=\"%s\">%s</a>%n", resolvedBuildUrlVar, resolvedBuildUrlVar); } if (releaseNotes) { if (isReleaseNotesSourceFile()) { try { releaseNotesContent += getReleaseNotesFromFile(build, releaseNotesFile); } catch (Exception ex) { log.fatal(String.format("Unable to get file contents from release ntoes file! - %s", ex.getMessage())); success = false; } } else if (isReleaseNotesSourceScm()) { releaseNotesContent += getReleaseNotesFromScm(build); } else { log.fatal(String.format("Bad configuration: if using release notes, should have source of file or scm. Found '%s'", releaseNotesSource)); success = false; } } if (!success) { // Early exit return success; } Set<SelectedPackage> selectedPackages = null; List<PackageConfiguration> combinedPackageConfigs = getCombinedPackageList(p.getId(), packageConfigs, defaultPackageVersion, log); if (combinedPackageConfigs != null && !combinedPackageConfigs.isEmpty()) { selectedPackages = new HashSet<SelectedPackage>(); for (PackageConfiguration pc : combinedPackageConfigs) { selectedPackages.add(new SelectedPackage( envInjector.injectEnvironmentVariableValues(pc.getPackageName()), envInjector.injectEnvironmentVariableValues(pc.getPackageVersion()))); } } try { // Sanitize the release notes in preparation for JSON releaseNotesContent = JSONSanitizer.getInstance().sanitize(releaseNotesContent); String results = api.getReleasesApi().createRelease(p.getId(), releaseVersion, c.getId(), releaseNotesContent, selectedPackages); JSONObject json = (JSONObject)JSONSerializer.toJSON(results); String urlSuffix = json.getJSONObject("Links").getString("Web"); String url = getDescriptorImpl().octopusHost; if (url.endsWith("/")) { url = url.substring(0, url.length() - 2); } log.info("Release created: \n\t" + url + urlSuffix); build.addAction(new BuildInfoSummary(BuildInfoSummary.OctopusDeployEventType.Release, url + urlSuffix)); } catch (Exception ex) { log.fatal("Failed to create release: " + ex.getMessage()); success = false; } if (success && deployThisRelease) { OctopusDeployDeploymentRecorder deployment = new OctopusDeployDeploymentRecorder(project, releaseVersion, environment, tenant, "", waitForDeployment); success = deployment.perform(build, launcher, listener); } return success; } private DescriptorImpl getDescriptorImpl() { return ((DescriptorImpl)getDescriptor()); } /** * Write the startup header for the logs to show what our inputs are. * @param log The logger */ private void logStartHeader(Log log) { log.info("Started Octopus Release"); log.info("======================="); log.info("Project: " + project); log.info("Release Version: " + releaseVersion); if (channel != null && !channel.isEmpty()) { log.info("Channel: " + channel); } log.info("Include Release Notes?: " + releaseNotes); if (releaseNotes) { log.info("\tRelease Notes Source: " + releaseNotesSource); log.info("\tRelease Notes File: " + releaseNotesFile); } log.info("Deploy this Release?: " + deployThisRelease); if (deployThisRelease) { log.info("\tEnvironment: " + environment); log.info("\tWait for Deployment: " + waitForDeployment); } if (packageConfigs == null || packageConfigs.isEmpty()) { log.info("Package Configurations: none"); } else { log.info("Package Configurations:"); for (PackageConfiguration pc : packageConfigs) { log.info("\t" + pc.getPackageName() + "\tv" + pc.getPackageVersion()); } } log.info("======================="); } /** * Gets a package list that is a combination of the default packages (taken from the Octopus template) * and the packages selected. Selected package version overwrite the default package version for a given package * @param projectId * @param selectedPackages * @param defaultPackageVersion * @return A list that combines the default packages and selected packages */ private List<PackageConfiguration> getCombinedPackageList(String projectId, List<PackageConfiguration> selectedPackages, String defaultPackageVersion, Log log) { List<PackageConfiguration> combinedList = new ArrayList<PackageConfiguration>(); //Get all selected package names for easier lookup later Set<String> selectedNames = new HashSet<String>(); if (selectedPackages != null) { for (PackageConfiguration pkgConfig : selectedPackages) { selectedNames.add(pkgConfig.getPackageName()); } //Start with the selected packages combinedList.addAll(selectedPackages); } DeploymentProcessTemplate defaultPackages = null; //If not default version specified, ignore all default packages try { defaultPackages = this.getDescriptorImpl().api.getDeploymentsApi().getDeploymentProcessTemplateForProject(projectId); } catch (Exception ex) { //Default package retrieval unsuccessful log.info(String.format("Could not retrieve default package list for project id: %s. No default packages will be used", projectId)); } if (defaultPackages != null) { for (SelectedPackage selPkg : defaultPackages.getSteps()) { String name = selPkg.getStepName(); //Only add if it was not a selected package if (!selectedNames.contains(name)) { //Get the default version, if not specified, warn if (defaultPackageVersion != null && !defaultPackageVersion.isEmpty()) { combinedList.add(new PackageConfiguration(name, defaultPackageVersion)); log.info(String.format("Using default version (%s) of package %s", defaultPackageVersion, name)); } else { log.error(String.format("Required package %s not included because package is not in Package Configuration list and no default package version defined", name)); } } } } return combinedList; } /** * Return the release notes contents from a file. * @param build our build * @return string contents of file * @throws IOException if there was a file read io problem * @throws InterruptedException if the action for reading was interrupted */ private String getReleaseNotesFromFile(AbstractBuild build, String releaseNotesFilename) throws IOException, InterruptedException { FilePath path = new FilePath(build.getWorkspace(), releaseNotesFilename); return path.act(new ReadFileCallable()); } /** * This callable allows us to read files from other nodes - ie. Jenkins slaves. */ private static final class ReadFileCallable implements FileCallable<String> { public final static String ERROR_READING = "<Error Reading File>"; @Override public String invoke(File f, VirtualChannel channel) { try { return StringUtils.join(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8), "\n"); } catch (IOException ex) { return ERROR_READING; } } @Override public void checkRoles(RoleChecker rc) throws SecurityException { } } /** * Attempt to load release notes info from SCM. * @param build the jenkins build * @return release notes as a single string */ private String getReleaseNotesFromScm(AbstractBuild build) { StringBuilder notes = new StringBuilder(); AbstractProject project = build.getProject(); AbstractBuild lastSuccessfulBuild = (AbstractBuild)project.getLastSuccessfulBuild(); AbstractBuild currentBuild = null; if (lastSuccessfulBuild == null) { AbstractBuild lastBuild = (AbstractBuild)project.getLastBuild(); currentBuild = lastBuild; } else { currentBuild = lastSuccessfulBuild.getNextBuild(); } if (currentBuild != null) { while (currentBuild != build) { String currBuildNotes = convertChangeSetToString(currentBuild); if (!currBuildNotes.isEmpty()) { notes.append(currBuildNotes); } currentBuild = currentBuild.getNextBuild(); } // Also include the current build String currBuildNotes = convertChangeSetToString(build); if (!currBuildNotes.isEmpty()) { notes.append(currBuildNotes); } } return notes.toString(); } /** * Convert a build's change set to a string, each entry on a new line * @param build The build to poll changesets from * @return The changeset as a string */ private String convertChangeSetToString(AbstractBuild build) { StringBuilder allChangeNotes = new StringBuilder(); if (build != null) { ChangeLogSet<? extends ChangeLogSet.Entry> changeSet = build.getChangeSet(); for (Object item : changeSet.getItems()) { ChangeLogSet.Entry entry = (ChangeLogSet.Entry) item; allChangeNotes.append(entry.getMsg()).append("\n"); } } return allChangeNotes.toString(); } /** * Descriptor for {@link OctopusDeployReleaseRecorder}. Used as a singleton. * The class is marked as public so that it can be accessed from views. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { private String octopusHost = ""; private String apiKey = ""; private boolean loadedConfig; private OctopusApi api; private static final String PROJECT_RELEASE_VALIDATION_MESSAGE = "Project must be set to validate release."; public DescriptorImpl() { load(); } @Override public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } @Override public String getDisplayName() { return "OctopusDeploy Release"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws Descriptor.FormException { save(); return true; } /** * Loads the OctopusDeployPlugin descriptor and pulls configuration from it * for API Key, and Host. */ private void setGlobalConfiguration() { // NOTE - This method is not being called from the constructor due // to a circular dependency issue on startup if (!loadedConfig) { updateGlobalConfiguration(); } } public void updateGlobalConfiguration() { Jenkins jenkinsInstance = Jenkins.getInstance(); if (jenkinsInstance != null) { OctopusDeployPlugin.DescriptorImpl descriptor = (OctopusDeployPlugin.DescriptorImpl) jenkinsInstance.getDescriptor(OctopusDeployPlugin.class); apiKey = descriptor.getApiKey(); octopusHost = descriptor.getOctopusHost(); } api = new OctopusApi(octopusHost, apiKey); loadedConfig = true; } /** * Check that the project field is not empty and represents an actual project. * @param project The name of the project. * @return FormValidation message if not ok. */ public FormValidation doCheckProject(@QueryParameter String project) { setGlobalConfiguration(); project = project.trim(); OctopusValidator validator = new OctopusValidator(api); return validator.validateProject(project); } /** * Check that the Channel field is either not set (default) or set to a real channel. * @param channel release channel. * @param project The name of the project. * @return Ok if not empty, error otherwise. */ public FormValidation doCheckChannel(@QueryParameter String channel, @QueryParameter String project) { setGlobalConfiguration(); channel = channel.trim(); project = project.trim(); OctopusValidator validator = new OctopusValidator(api); return validator.validateChannel(channel, project); } /** * Check that the releaseVersion field is not empty. * @param releaseVersion release version. * @param project The name of the project. * @return Ok if not empty, error otherwise. */ public FormValidation doCheckReleaseVersion(@QueryParameter String releaseVersion, @QueryParameter String project) { setGlobalConfiguration(); releaseVersion = releaseVersion.trim(); if (project == null || project.isEmpty()) { return FormValidation.warning(PROJECT_RELEASE_VALIDATION_MESSAGE); } com.octopusdeploy.api.data.Project p; try { p = api.getProjectsApi().getProjectByName(project); if (p == null) { return FormValidation.warning(PROJECT_RELEASE_VALIDATION_MESSAGE); } } catch (Exception ex) { return FormValidation.warning(PROJECT_RELEASE_VALIDATION_MESSAGE); } OctopusValidator validator = new OctopusValidator(api); return validator.validateRelease(releaseVersion, p.getId(), OctopusValidator.ReleaseExistenceRequirement.MustNotExist); } /** * Check that the releaseNotesFile field is not empty. * @param releaseNotesFile The path to the release notes file, relative to the WS. * @return Ok if not empty, error otherwise. */ public FormValidation doCheckReleaseNotesFile(@QueryParameter String releaseNotesFile) { if (releaseNotesFile.isEmpty()) { return FormValidation.error("Please provide a project notes file."); } return FormValidation.ok(); } /** * Check that the environment field is not empty, and represents a real environment. * @param environment The name of the environment. * @return FormValidation message if not ok. */ public FormValidation doCheckEnvironment(@QueryParameter String environment) { setGlobalConfiguration(); environment = environment.trim(); OctopusValidator validator = new OctopusValidator(api); return validator.validateEnvironment(environment); } /** * Data binding that returns all possible environment names to be used in the environment autocomplete. * @return ComboBoxModel */ public ComboBoxModel doFillEnvironmentItems() { setGlobalConfiguration(); ComboBoxModel names = new ComboBoxModel(); try { Set<com.octopusdeploy.api.data.Environment> environments = api.getEnvironmentsApi().getAllEnvironments(); for (com.octopusdeploy.api.data.Environment env : environments) { names.add(env.getName()); } } catch (Exception ex) { Logger.getLogger(OctopusDeployReleaseRecorder.class.getName()).log(Level.SEVERE, "Filling environments combo failed!", ex); } return names; } /** * Data binding that returns all possible tenant names to be used in the tenant autocomplete. * @return ComboBoxModel */ public ComboBoxModel doFillTenantItems() { setGlobalConfiguration(); ComboBoxModel names = new ComboBoxModel(); try { Set<com.octopusdeploy.api.data.Tenant> tenants = api.getTenantsApi().getAllTenants(); for (com.octopusdeploy.api.data.Tenant ten : tenants) { names.add(ten.getName()); } } catch (Exception ex) { Logger.getLogger(OctopusDeployDeploymentRecorder.class.getName()).log(Level.SEVERE, null, ex); } return names; } /** * Data binding that returns all possible project names to be used in the project autocomplete. * @return ComboBoxModel */ public ComboBoxModel doFillProjectItems() { setGlobalConfiguration(); ComboBoxModel names = new ComboBoxModel(); try { Set<com.octopusdeploy.api.data.Project> projects = api.getProjectsApi().getAllProjects(); for (com.octopusdeploy.api.data.Project proj : projects) { names.add(proj.getName()); } } catch (Exception ex) { Logger.getLogger(OctopusDeployReleaseRecorder.class.getName()).log(Level.SEVERE, "Filling projects combo failed!", ex); } return names; } /** * Data binding that returns all possible channels names to be used in the channel autocomplete. * @param project the project name * @return ComboBoxModel */ public ComboBoxModel doFillChannelItems(@QueryParameter String project) { setGlobalConfiguration(); ComboBoxModel names = new ComboBoxModel(); if (project != null && !project.isEmpty()) { try { com.octopusdeploy.api.data.Project p = api.getProjectsApi().getProjectByName(project); if (p != null) { Set<com.octopusdeploy.api.data.Channel> channels = api.getChannelsApi().getChannelsByProjectId(p.getId()); for (com.octopusdeploy.api.data.Channel channel : channels) { names.add(channel.getName()); } } } catch (Exception ex) { Logger.getLogger(OctopusDeployReleaseRecorder.class.getName()).log(Level.SEVERE, "Filling Channel combo failed!", ex); } } return names; } } }
package info.u_team.u_team_core.intern.updatechecker; import com.google.gson.*; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.*; import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion; /** * Update API<br> * -> Update parser * * @author HyCraftHD * @date 21.10.2017 * */ public class UpdateParser { private UpdateResult result = null; private String modid; public UpdateParser(String modid, String data) { this.modid = modid; parse(data); } private void parse(String data) { JsonElement element = new JsonParser().parse(data); JsonElement versionelement = element.getAsJsonObject().get(ForgeVersion.mcVersion); if (versionelement == null || versionelement.isJsonNull()) { result = new UpdateResult(); } else { check(versionelement.getAsJsonObject().get("version").getAsString(), versionelement.getAsJsonObject().get("download").getAsString()); } } private void check(String newversion, String download) { ModContainer container = Loader.instance().getIndexedModList().get(modid); if (container == null) { throw new NullPointerException("Modcontainer for modid could not be found."); } String currentversion = container.getVersion(); DefaultArtifactVersion currentversionartifact = new DefaultArtifactVersion(currentversion); DefaultArtifactVersion newversionartifact = new DefaultArtifactVersion(newversion); if (currentversionartifact.compareTo(newversionartifact) < 0) { result = new UpdateResult(newversion, download); } else { result = new UpdateResult(); } } public UpdateResult getResult() { return result; } }