answer
stringlengths 17
10.2M
|
|---|
package org.oep.pong;
import java.util.Random;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.Toast;
/**
* This class is the main viewing window for the Pong game. All the game's
* logic takes place within this class as well.
* @author OEP
*
*/
public class PongView extends View implements OnTouchListener, OnKeyListener, OnCompletionListener {
/** Debug tag */
private static final String TAG = "PongView";
protected static final int FPS = 30;
/**
* This is mostly deprecated but kept around if the need
* to add more game states comes around.
*/
private State mCurrentState = State.Running;
private State mLastState = State.Stopped;
public static enum State { Running, Stopped}
/** Flag that marks this view as initialized */
private boolean mInitialized = false;
/** Starts a new round when set to true */
private boolean mNewRound = true;
/** Shows the title screen when set to true */
private boolean mShowTitle = true;
/** Keeps the game thread alive */
private boolean mContinue = true;
/** Mutes sounds when true */
private boolean mMuted = false;
/** Red player paddle bounds */
private Rect mRedPaddleRect = new Rect();
/** Blue player paddle bounds */
private Rect mBluePaddleRect = new Rect();
/** Touch boxes for various functions. These are assigned in initialize() */
private Rect mRedTouchBox, mBlueTouchBox, mPauseTouchBox;
/** Last x-coordinate of red player's touch */
private float mRedLastTouch = 0;
/** Last x-coordinate of blue player's touch */
private float mBlueLastTouch = 0;
/** Red player's lives */
private int mRedLives;
/** Blue player's lives */
private int mBlueLives;
/** Flag to indicate the human-ness of red */
private boolean mRedIsPlayer = false;
/** Flag to indicate the human-ness of blue */
private boolean mBlueIsPlayer = false;
/** Timestamp of the last frame created */
private long mLastFrame = 0;
/** Speed of the paddles */
private int mPaddleSpeed = 2;
protected Ball mBall = new Ball();
/** Random number generator */
private static final Random RNG = new Random();
/** Paint object */
private final Paint mPaint = new Paint();
/** Thickness of the paddle */
private static final int PADDLE_THICKNESS = 10;
/** Width of the paddle */
private static final int PADDLE_WIDTH = 40;
/** Padding for touch zones and paddles */
private static final int PADDING = 3;
/** Scrollwheel sensitivity */
private static final int SCROLL_SENSITIVITY = 80;
/** Redraws the screen according to FPS */
private RefreshHandler mRedrawHandler = new RefreshHandler();
/** Tone for a wall hit */
private MediaPlayer mWallHit;
/** Tone for a paddle hit */
private MediaPlayer mPaddleHit;
/** Tone for when the ball is missed */
private MediaPlayer mMissTone;
/** Tone for when a game is won */
private MediaPlayer mWinTone;
/**
* An overloaded class that repaints this view in a separate thread.
* Calling PongView.update() should initiate the thread.
* @author OEP
*
*/
class RefreshHandler extends Handler {
@Override
public void handleMessage(Message msg) {
PongView.this.update();
PongView.this.invalidate(); // Mark the view as 'dirty'
}
public void sleep(long delay) {
this.removeMessages(0);
this.sendMessageDelayed(obtainMessage(0), delay);
}
}
/**
* Creates a new PongView within some context
* @param context
* @param attrs
*/
public PongView(Context context, AttributeSet attrs) {
super(context, attrs);
initPongView();
}
public PongView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPongView();
}
/**
* The main loop. Call this to update the game state.
*/
public void update() {
if(getHeight() == 0 || getWidth() == 0) {
mRedrawHandler.sleep(1000 / FPS);
return;
}
if(!mInitialized) {
nextRound();
newGame();
mInitialized = true;
}
long now = System.currentTimeMillis();
if(gameRunning() && mCurrentState != State.Stopped) {
if(now - mLastFrame >= 1000 / FPS) {
if(mNewRound) {
nextRound();
mNewRound = false;
}
doGameLogic();
}
}
// We will take this much time off of the next update() call to normalize for
// CPU time used updating the game state.
if(mContinue) {
long diff = System.currentTimeMillis() - now;
mRedrawHandler.sleep(Math.max(0, (1000 / FPS) - diff) );
}
}
/**
* All of the game's logic (per game iteration) is in this function.
* Given some initial game state, it computes the next game state.
*/
private void doGameLogic() {
float py = mBall.y;
mBall.move();
// Shake it up if it appears to not be moving vertically
if(py == mBall.y) {
mBall.randomAngle();
}
// Do some basic paddle AI
if(!mRedIsPlayer)
doAI(mRedPaddleRect, mBluePaddleRect);
else
movePaddleTorward(mRedPaddleRect, 8 * mPaddleSpeed, mRedLastTouch);
if(!mBlueIsPlayer)
doAI(mBluePaddleRect, mRedPaddleRect);
else
movePaddleTorward(mBluePaddleRect, 8 * mPaddleSpeed, mBlueLastTouch);
// See if all is lost
if(mBall.y >= getHeight()) {
mNewRound = true;
mBlueLives = Math.max(0, mBlueLives - 1);
if(mBlueLives != 0 || mShowTitle) playSound(mMissTone);
else playSound(mWinTone);
}
else if (mBall.y <= 0) {
mNewRound = true;
mRedLives = Math.max(0, mRedLives - 1);
if(mRedLives != 0 || mShowTitle) playSound(mMissTone);
else playSound(mWinTone);
}
handleBounces();
}
protected void handleBounces() {
// Handle bouncing off of a wall
if(mBall.x <= Ball.RADIUS || mBall.x >= getWidth() - Ball.RADIUS) {
mBall.bounceWall();
if(mBall.x == Ball.RADIUS)
mBall.x++;
else
mBall.x
}
// Bouncing off the paddles
if(mBall.goingUp() && mBall.collides(mRedPaddleRect) ) {
mBall.bouncePaddle(mRedPaddleRect);
increaseDifficulty();
}
else if(mBall.goingDown() && mBall.collides(mBluePaddleRect)) {
mBall.bouncePaddle(mBluePaddleRect);
increaseDifficulty();
}
}
/**
* Moves the paddle toward a specific x-coordinate without overshooting it.
* @param r, the Rect object to move.
* @param speed, the speed at which the paddle moves at maximum.
* @param x, the x-coordinate to move to.
*/
private void movePaddleTorward(Rect r, int speed, float x) {
int dx = (int) Math.abs(r.centerX() - x);
if(x < r.centerX()) {
r.offset( (dx > speed) ? -speed : -dx, 0);
}
else if(x > r.centerX()) {
r.offset( (dx > speed) ? speed : dx, 0);
}
}
/**
* A generalized Pong AI player. Takes a Rect object and a Ball, computes where the ball will
* be when ball.y == rect.y, and tries to move toward that x-coordinate. If the ball is moving
* straight it will try to clip the ball with the edge of the paddle.
* @param cpu
*/
private void doAI(Rect cpu, Rect opp) {
Ball ball = new Ball(mBall);
// Special case: move torward the center if the ball is blinking
if(mBall.serving()) {
movePaddleTorward(cpu, mPaddleSpeed, getWidth() / 2);
return;
}
// Something is wrong if vy = 0.. let's wait until things fix themselves
if(ball.vy == 0) return;
// Y-Distance from ball to Rect 'cpu'
float cpuDist = Math.abs(ball.y - cpu.centerY());
// Y-Distance to opponent.
float oppDist = Math.abs( ball.y - opp.centerY() );
// Distance between two paddles.
float paddleDistance = Math.abs(cpu.centerY() - opp.centerY());
// Is the ball coming at us?
boolean coming = (cpu.centerY() < ball.y && ball.vy < 0)
|| (cpu.centerY() > ball.y && ball.vy > 0);
// Total amount of x-distance the ball covers
float total = ((((coming) ? cpuDist : oppDist + paddleDistance)) / Math.abs(ball.vy)) * Math.abs( ball.vx );
// Playable width of the stage
float playWidth = getWidth() - 2 * Ball.RADIUS;
float wallDist = (ball.goingLeft()) ? ball.x - Ball.RADIUS : playWidth - ball.x + Ball.RADIUS;
// Effective x-translation left over after first bounce
float remains = (total - wallDist) % playWidth;
// Bounces the ball will incur
int bounces = (int) ((total) / playWidth);
boolean left = (bounces % 2 == 0) ? !ball.goingLeft() : ball.goingLeft();
float prediction = getWidth() / 2;
// Now we need to compute the final x. That's all that matters.
if(bounces == 0) {
prediction = ball.x + total * Math.signum(ball.vx);
}
else if(left) {
prediction = Ball.RADIUS + remains;
}
else { // The ball is going right...
prediction = (Ball.RADIUS + playWidth) - remains;
}
/*if(cpu == mBluePaddleRect) {
projx = (int) prediction;
projy = mBluePaddleRect.centerY();
Log.d(TAG, "Distance to blue: " + oppDist);
Log.d(TAG, "Distance to red: " + cpuDist);
Log.d(TAG, "Distance from red to blue: " + paddleDistance);
Log.d(TAG, String.format("Ball V: <%f, %f>\n", ball.vx, ball.vy));
Log.d(TAG, String.format("Ball P: <%f, %f>\n", ball.x, ball.y));
Log.d(TAG, "Total x-dist: " + total);
Log.d(TAG, "Total wall-dist: " + wallDist);
Log.d(TAG, "Total playWidth: " + playWidth);
Log.d(TAG, "Total remains: " + remains);
Log.d(TAG, "Bounces: " + bounces);
Log.d(TAG, "Prediction: " + prediction);
System.currentTimeMillis();
}*/
// Try to give it a little kick if vx = 0
int salt = (int) (System.currentTimeMillis() / 10000);
Random r = new Random((long) (cpu.centerY() + ball.vx + ball.vy + salt));
prediction += r.nextInt(2 * PADDLE_WIDTH - (PADDLE_WIDTH / 5)) - PADDLE_WIDTH + (PADDLE_WIDTH / 10);
movePaddleTorward(cpu, mPaddleSpeed, prediction);
}
/**
* Knocks up the framerate a bit to keep it difficult.
*/
private void increaseDifficulty() {
mBall.speed++;
}
/**
* Set the state, start a new round, start the loop if needed.
* @param next, the next state
*/
public void setMode(State next) {
mCurrentState = next;
nextRound();
update();
}
/**
* Set the paddles to their initial states and as well the ball.
*/
private void initPongView() {
setOnTouchListener(this);
setOnKeyListener(this);
setFocusable(true);
resetPaddles();
resetBall();
mWallHit = loadSound(R.raw.wall);
mPaddleHit = loadSound(R.raw.paddle);
mMissTone = loadSound(R.raw.ballmiss);
mWinTone = loadSound(R.raw.wintone);
// Grab the muted preference
Context ctx = this.getContext();
SharedPreferences settings = ctx.getSharedPreferences(Pong.DB_PREFS, 0);
mMuted = settings.getBoolean(Pong.PREF_MUTED, mMuted);
}
/**
* Reset the paddles/touchboxes/framespersecond/ballcounter for the next round.
*/
private void nextRound() {
mRedTouchBox = new Rect(0,0,getWidth(),getHeight() / 8);
mBlueTouchBox = new Rect(0, 7 * getHeight() / 8, getWidth(), getHeight());
int min = Math.min(getWidth() / 4, getHeight() / 4);
int xmid = getWidth() / 2;
int ymid = getHeight() / 2;
mPauseTouchBox = new Rect(xmid - min, ymid - min, xmid + min, ymid + min);
realignPaddles();
resetBall();
mBall.speed = Ball.SPEED;
mBall.pause();
}
private void realignPaddles() {
mRedPaddleRect.top = mRedTouchBox.bottom + PADDING;
mRedPaddleRect.bottom = mRedPaddleRect.top + PADDLE_THICKNESS;
mBluePaddleRect.bottom = mBlueTouchBox.top - PADDING;
mBluePaddleRect.top = mBluePaddleRect.bottom - PADDLE_THICKNESS;
}
/**
* Reset paddles to an initial state.
*/
private void resetPaddles() {
mRedPaddleRect.top = PADDING;
mRedPaddleRect.bottom = PADDING + PADDLE_THICKNESS;
mBluePaddleRect.top = getHeight() - PADDING - PADDLE_THICKNESS;
mBluePaddleRect.bottom = getHeight() - PADDING;
mBluePaddleRect.left = mRedPaddleRect.left = getWidth() / 2 - PADDLE_WIDTH;
mBluePaddleRect.right = mRedPaddleRect.right = getWidth() / 2 + PADDLE_WIDTH;
mRedLastTouch = getWidth() / 2;
mBlueLastTouch = getWidth() / 2;
}
/**
* Reset ball to an initial state
*/
private void resetBall() {
mBall.x = getWidth() / 2;
mBall.y = getHeight() / 2;
mBall.randomAngle();
mBall.pause();
}
protected float bound(float x, float low, float hi) {
return Math.max(low, Math.min(x, hi));
}
/**
* Use for keeping track of a position.
* @author pkilgo
*
*/
class Point {
private int x, y;
Point() {
x = 0; y = 0;
}
Point(int x, int y) {
this.x = x; this.y = y;
}
public int getX() { return x; }
public int getY() { return y ; }
public void set(double d, double e) { this.x = (int) d; this.y = (int) e; }
public void translate(int i, int j) { this.x += i; this.y += j; }
@Override
public String toString() {
return "Point: (" + x + ", " + y + ")";
}
}
public void onSizeChanged(int w, int h, int ow, int oh) {
mPaddleSpeed = Math.max(1, w / 160);
}
/**
* Paints the game!
*/
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Context context = getContext();
// Draw the paddles / touch boundaries
mPaint.setStyle(Style.FILL);
mPaint.setColor(Color.RED);
canvas.drawRect(mRedPaddleRect, mPaint);
if(gameRunning() && mRedIsPlayer && mCurrentState == State.Running)
canvas.drawLine(mRedTouchBox.left, mRedTouchBox.bottom, mRedTouchBox.right, mRedTouchBox.bottom, mPaint);
// Draw Blue's stuff
mPaint.setColor(Color.BLUE);
canvas.drawRect(mBluePaddleRect, mPaint);
if(gameRunning() && mBlueIsPlayer && mCurrentState == State.Running)
canvas.drawLine(mBlueTouchBox.left, mBlueTouchBox.top, mBlueTouchBox.right, mBlueTouchBox.top, mPaint);
// Draw ball stuff
mPaint.setStyle(Style.FILL);
mPaint.setColor(Color.WHITE);
mBall.draw(canvas);
// If either is a not a player, blink and let them know they can join in!
// This blinks with the ball.
if(!mShowTitle && mBall.serving()) {
String join = context.getString(R.string.join_in);
int joinw = (int) mPaint.measureText(join);
if(!mRedIsPlayer) {
mPaint.setColor(Color.RED);
canvas.drawText(join, getWidth() / 2 - joinw / 2, mRedTouchBox.centerY(), mPaint);
}
if(!mBlueIsPlayer) {
mPaint.setColor(Color.BLUE);
canvas.drawText(join, getWidth() / 2 - joinw / 2, mBlueTouchBox.centerY(), mPaint);
}
}
// Show where the player can touch to pause the game
if(!mShowTitle && mBall.serving()) {
String pause = context.getString(R.string.pause);
int pausew = (int) mPaint.measureText(pause);
mPaint.setColor(Color.GREEN);
mPaint.setStyle(Style.STROKE);
canvas.drawRect(mPauseTouchBox, mPaint);
canvas.drawText(pause, getWidth() / 2 - pausew / 2, getHeight() / 2, mPaint);
}
// Paint a PAUSED message
if(gameRunning() && mCurrentState == State.Stopped) {
String s = context.getString(R.string.paused);
int width = (int) mPaint.measureText(s);
int height = (int) (mPaint.ascent() + mPaint.descent());
mPaint.setColor(Color.WHITE);
canvas.drawText(s, getWidth() / 2 - width / 2, getHeight() / 2 - height / 2, mPaint);
}
// Draw a 'lives' counter
if(!mShowTitle) {
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Style.FILL_AND_STROKE);
for(int i = 0; i < mRedLives; i++) {
canvas.drawCircle(Ball.RADIUS + PADDING + i * (2 * Ball.RADIUS + PADDING),
PADDING + Ball.RADIUS,
Ball.RADIUS,
mPaint);
}
for(int i = 0; i < mBlueLives; i++) {
canvas.drawCircle(Ball.RADIUS + PADDING + i * (2 * Ball.RADIUS + PADDING),
getHeight() - PADDING - Ball.RADIUS,
Ball.RADIUS,
mPaint);
}
}
// Announce the winner!
if(!gameRunning()) {
mPaint.setColor(Color.GREEN);
String s = "You both lose";
if(mBlueLives == 0) {
s = context.getString(R.string.red_wins);
mPaint.setColor(Color.RED);
}
else if(mRedLives == 0) {
s = context.getString(R.string.blue_wins);
mPaint.setColor(Color.BLUE);
}
int width = (int) mPaint.measureText(s);
int height = (int) (mPaint.ascent() + mPaint.descent());
canvas.drawText(s, getWidth() / 2 - width / 2, getHeight() / 2 - height / 2, mPaint);
}
// Draw the Title text
if(mShowTitle) {
Bitmap image = BitmapFactory.decodeResource(context.getResources(), R.drawable.pong);
canvas.drawBitmap(image, getWidth() / 2 - image.getWidth() / 2,
getHeight() / 2 - image.getHeight() / 2, mPaint);
String prompt = context.getString(R.string.menu_prompt);
mPaint.setColor(Color.WHITE);
int nextLine = 3 * getHeight() / 4;
int w = (int) mPaint.measureText(prompt);
canvas.drawText(prompt, getWidth() / 2 - w / 2, nextLine, mPaint);
}
}
/**
* Touching is the method of movement. Touching the touchscreen, that is.
* A player can join in simply by touching where they would in a normal
* game.
*/
public boolean onTouch(View v, MotionEvent mo) {
if(v != this || !gameRunning() || mShowTitle) return false;
// We want to support multiple touch and single touch
InputHandler handle = InputHandler.getInstance();
// Loop through all the pointers that we detected and
// process them as normal touch events.
for(int i = 0; i < handle.getTouchCount(mo); i++) {
int tx = (int) handle.getX(mo, i);
int ty = (int) handle.getY(mo, i);
// Bottom paddle moves when we are playing in one or two player mode and the touch
// was in the lower quartile of the screen.
if(mBlueIsPlayer && mBlueTouchBox.contains(tx,ty)) {
mBlueLastTouch = tx;
}
else if(mRedIsPlayer && mRedTouchBox.contains(tx,ty)) {
mRedLastTouch = tx;
}
else if(mo.getAction() == MotionEvent.ACTION_DOWN && mPauseTouchBox.contains(tx, ty)) {
if(mCurrentState != State.Stopped) {
mLastState = mCurrentState;
mCurrentState = State.Stopped;
}
else {
mCurrentState = mLastState;
mLastState = State.Stopped;
}
}
// In case a player wants to join in...
if(mo.getAction() == MotionEvent.ACTION_DOWN) {
if(!mBlueIsPlayer && mBlueTouchBox.contains(tx,ty)) {
mBlueIsPlayer = true;
}
else if(!mRedIsPlayer && mRedTouchBox.contains(tx,ty)) {
mRedIsPlayer = true;
}
}
}
return true;
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
if(!gameRunning() || mShowTitle) return false;
if(mBlueIsPlayer == false) {
mBlueIsPlayer = true;
mBlueLastTouch = mBluePaddleRect.centerX();
}
switch(event.getAction()) {
case MotionEvent.ACTION_MOVE:
mBlueLastTouch = Math.max(0, Math.min(getWidth(), mBlueLastTouch + SCROLL_SENSITIVITY * event.getX()));
break;
}
return true;
}
/**
* Reset the lives, paddles and the like for a new game.
*/
public void newGame() {
mRedLives = 3;
mBlueLives = 3;
resetPaddles();
nextRound();
resumeLastState();
}
/**
* This is kind of useless as well.
*/
private void resumeLastState() {
if(mLastState == State.Stopped && mCurrentState == State.Stopped) {
mCurrentState = State.Running;
}
else if(mCurrentState != State.Stopped) {
// Do nothing
}
else if(mLastState != State.Stopped) {
mCurrentState = mLastState;
mLastState = State.Stopped;
}
}
public boolean gameRunning() {
return mShowTitle || (mRedLives > 0 && mBlueLives > 0);
}
public void setShowTitle(boolean b) {
mShowTitle = b;
}
public void pause() {
if(!mShowTitle) {
mLastState = mCurrentState;
mCurrentState = State.Stopped;
}
}
public boolean titleShowing() {
return mShowTitle;
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
public void setPlayerControl(boolean red, boolean blue) {
mRedIsPlayer = red;
mBlueIsPlayer = blue;
}
public void onCompletion(MediaPlayer mp) {
mp.seekTo(0);
}
public void resume() {
mContinue = true;
update();
}
public void stop() {
mContinue = false;
}
public void toggleMuted() {
this.setMuted(!mMuted);
}
public void setMuted(boolean b) {
// Set the in-memory flag
mMuted = b;
// Grab a preference editor
Context ctx = this.getContext();
SharedPreferences settings = ctx.getSharedPreferences(Pong.DB_PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
// Save the value
editor.putBoolean(Pong.PREF_MUTED, b);
editor.commit();
// Output a toast to the user
int rid = (mMuted) ? R.string.sound_disabled : R.string.sound_enabled;
Toast.makeText(ctx, rid, Toast.LENGTH_SHORT).show();
}
/**
* Put yer resources in year and we'll release em!
*/
public void releaseResources() {
mWallHit.release();
mPaddleHit.release();
mWinTone.release();
mMissTone.release();
}
private MediaPlayer loadSound(int rid) {
MediaPlayer mp = MediaPlayer.create(getContext(), rid);
mp.setOnCompletionListener(this);
return mp;
}
private void playSound(MediaPlayer mp) {
if(mMuted == true) return;
if(!mp.isPlaying()) {
mp.setVolume(0.2f, 0.2f);
mp.start();
}
}
class Ball {
public float x, y, xp, yp, vx, vy;
public float speed = SPEED;
protected double mAngle;
protected boolean mNextPointKnown = false;
protected int mCounter = 0;
public Ball() {
findVector();
}
public Ball(Ball other) {
x = other.x;
y = other.y;
xp = other.xp;
yp = other.yp;
vx = other.vx;
vy = other.vy;
speed = other.speed;
mAngle = other.mAngle;
}
protected void findVector() {
vx = (float) (speed * Math.cos(mAngle));
vy = (float) (speed * Math.sin(mAngle));
}
public boolean goingUp() {
return mAngle >= Math.PI;
}
public boolean goingDown() {
return !goingUp();
}
public boolean goingLeft() {
return mAngle <= 3 * Math.PI / 2 && mAngle > Math.PI / 2;
}
public boolean goingRight() {
return !goingLeft();
}
public double getAngle() {
return mAngle;
}
public boolean serving() {
return mCounter > 0;
}
public void pause() {
mCounter = 60;
}
public void move() {
if(mCounter <= 0) {
x = keepX(x + vx);
y += vy;
}
else {
mCounter
}
}
public void randomAngle() {
setAngle( 2 * Math.PI * RNG.nextDouble() );
}
public void setAngle(double angle) {
mAngle = angle % (2 * Math.PI);
mAngle = boundAngle(mAngle);
findVector();
}
public void draw(Canvas canvas) {
if((mCounter / 10) % 2 == 1 || mCounter == 0)
canvas.drawCircle(x, y, Ball.RADIUS, mPaint);
}
/**
* Tells us if the ball collides with a rectangle.
* @param r, the rectangle
* @return true if the ball is colliding, false if not
*/
public boolean collides(Rect r) {
return x >= r.left && x <= r.right &&
y >= r.top - RADIUS && y <= r.bottom + RADIUS;
}
/**
* Method bounces the ball across a vertical axis. Seriously it's that easy.
* Math failed me when figuring this out so I guessed instead.
*/
public void bouncePaddle(Rect r) {
double angle;
// up-right case
if(mAngle >= Math.PI) {
angle = 4 * Math.PI - mAngle;
}
// down-left case
else {
angle = 2 * Math.PI - mAngle;
}
angle %= (2 * Math.PI);
angle = salt(angle, r);
normalize(r);
setAngle(angle);
}
/**
* Bounce the ball off a horizontal axis.
*/
public void bounceWall() {
setAngle(3 * Math.PI - mAngle);
}
protected double salt(double angle, Rect paddle) {
int cx = paddle.centerX();
double halfWidth = paddle.width() / 2;
double change = 0.0;
if(goingUp()) change = SALT * ((cx - x) / halfWidth);
else change = SALT * ((x - cx) / halfWidth);
return boundAngle(angle, change);
}
/**
* Normalizes a ball's position after it has hit a paddle.
* @param r The paddle the ball has hit.
*/
protected void normalize(Rect r) {
// Quit if the ball is outside the width of the paddle
if(x < r.left || x > r.right) {
return;
}
// Case if ball is above the paddle
if(y < r.top) {
y = Math.min(y, r.top - Ball.RADIUS);
}
else if(y > r.bottom) {
y = Math.max(y, r.bottom + Ball.RADIUS);
}
}
/**
* Bounds sum of <code>angle</code> and <code>angleChange</code> to the side of the
* unit circle that <code>angle</code> is on.
* @param angle The initial angle.
* @param angleChange Amount to add to angle.
* @return bounded angle sum
*/
protected double boundAngle(double angle, double angleChange) {
return boundAngle(angle + angleChange, angle >= Math.PI);
}
protected double boundAngle(double angle) {
return boundAngle(angle, angle >= Math.PI);
}
/**
* Bounds an angle in radians to a subset of the top
* or bottom part of the unit circle.
* @param angle The angle in radians to bound.
* @param top Flag which indicates if we should bound to the top or not.
* @return the bounded angle
*/
protected double boundAngle(double angle, boolean top) {
if(top) {
return Math.max(Math.PI + BOUND, Math.min(2 * Math.PI - BOUND, angle));
}
return Math.max(BOUND, Math.min(Math.PI - BOUND, angle));
}
/**
* Given it a coordinate, it transforms it into a proper x-coordinate for the ball.
* @param x, the x-coord to transform
* @return
*/
protected float keepX(float x) {
return bound(x, Ball.RADIUS, getWidth() - Ball.RADIUS);
}
public static final double BOUND = Math.PI / 9;
public static final float SPEED = 4.0f;
public static final int RADIUS = 4;
public static final double SALT = 4 * Math.PI / 9;
}
}
|
package polyglot.main;
import java.io.File;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.StringTokenizer;
import polyglot.frontend.ExtensionInfo;
/**
* This object encapsulates various polyglot options.
*/
public class Options {
public static Options global;
/**
* Back pointer to the extension that owns this options
*/
protected ExtensionInfo extension = null;
/*
* Fields for storing values for options.
*/
public int error_count = 100;
public Collection source_path; // List[String]
public File output_directory;
public String default_classpath;
public String default_output_classpath;
public String classpath;
public String output_classpath;
public String bootclasspath = null;
public boolean assertions = false;
public boolean compile_command_line_only = false;
public String[] source_ext = null; // e.g., java, jl, pj
public String output_ext = "java"; // java, by default
public boolean output_stdout = false; // whether to output to stdout
public String post_compiler;
// compiler to run on java output file
public int output_width = 80;
public boolean fully_qualified_names = false;
/** Inject type information in serialized form into output file? */
public boolean serialize_type_info = true;
/** Dump the AST after the following passes? */
public Set dump_ast = new HashSet();
/** Pretty-print the AST after the following passes? */
public Set print_ast = new HashSet();
/** Disable the following passes? */
public Set disable_passes = new HashSet();
/** keep output files */
public boolean keep_output_files = true;
/** Directly output code from possibly ambiguous ast nodes */
public boolean output_ambiguous_nodes = false;
/**
* Constructor
*/
public Options(ExtensionInfo extension) {
this.extension = extension;
setDefaultValues();
}
/**
* Set default values for options
*/
public void setDefaultValues() {
String default_bootpath = System.getProperty("sun.boot.class.path");
if (default_bootpath == null) {
default_bootpath = System.getProperty("java.home") +
File.separator + "jre" +
File.separator + "lib" +
File.separator + "rt.jar";
}
default_classpath = System.getProperty("java.class.path") +
File.pathSeparator + default_bootpath;
classpath = default_classpath;
default_output_classpath = System.getProperty("java.class.path");
output_classpath = default_output_classpath;
String java_home = System.getProperty("java.home");
String current_dir = System.getProperty("user.dir");
source_path = new LinkedList();
source_path.add(new File(current_dir));
output_directory = new File(current_dir);
// First try: $JAVA_HOME/../bin/javac
// This should work with JDK 1.2 and 1.3
// If not found, try: $JAVA_HOME/bin/javac
// This should work for JDK 1.1.
// If neither found, assume "javac" is in the path.
post_compiler = java_home + File.separator + ".." + File.separator +
"bin" + File.separator + "javac";
if (! new File(post_compiler).exists()) {
post_compiler = java_home + File.separator +
"bin" + File.separator + "javac";
if (! new File(post_compiler).exists()) {
post_compiler = "javac";
}
}
}
/**
* Parse the command line
*
* @throws UsageError if the usage is incorrect.
*/
public void parseCommandLine(String args[], Set source) throws UsageError {
if(args.length < 1) {
throw new UsageError("No command line arguments given");
}
for(int i = 0; i < args.length; ) {
try {
int ni = parseCommand(args, i, source);
if (ni == i) {
throw new UsageError("illegal option -- " + args[i]);
}
i = ni;
}
catch (ArrayIndexOutOfBoundsException e) {
throw new UsageError("missing argument");
}
}
if (source.size() < 1) {
throw new UsageError("must specify at least one source file");
}
}
/**
* Parse a command
* @return the next index to process. i.e., if calling this method
* processes two commands, then the return value should be index+2
*/
protected int parseCommand(String args[], int index, Set source)
throws UsageError, Main.TerminationException {
int i = index;
if (args[i].equals("-h") ||
args[i].equals("-help") ||
args[i].equals("--help")) {
throw new UsageError("", 0);
}
else if (args[i].equals("-version")) {
StringBuffer sb = new StringBuffer();
if (extension != null) {
sb.append(extension.compilerName() +
" version " + extension.version() + "\n");
}
sb.append("Polyglot compiler toolkit version " +
new polyglot.ext.jl.Version());
throw new Main.TerminationException(sb.toString(), 0);
}
else if (args[i].equals("-d"))
{
i++;
output_directory = new File(args[i]);
i++;
}
else if (args[i].equals("-classpath") ||
args[i].equals("-cp")) {
i++;
classpath = args[i] + System.getProperty("path.separator") +
default_classpath;
output_classpath = args[i] + System.getProperty("path.separator") +
default_output_classpath;
i++;
}
else if (args[i].equals("-bootclasspath")) {
i++;
bootclasspath = args[i];
i++;
}
else if (args[i].equals("-sourcepath"))
{
i++;
StringTokenizer st = new StringTokenizer(args[i], File.pathSeparator);
while(st.hasMoreTokens())
{
File f = new File(st.nextToken());
if (f != null && !source_path.contains(f))
source_path.add(f);
}
i++;
}
else if (args[i].equals("-commandlineonly"))
{
i++;
compile_command_line_only = true;
}
else if (args[i].equals("-preferclassfiles"))
{
i++;
ignore_mod_times = true;
}
else if (args[i].equals("-assert"))
{
i++;
assertions = true;
}
else if (args[i].equals("-fqcn"))
{
i++;
fully_qualified_names = true;
}
else if (args[i].equals("-c"))
{
post_compiler = null;
i++;
}
else if (args[i].equals("-errors"))
{
i++;
try {
error_count = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {}
i++;
}
else if (args[i].equals("-w"))
{
i++;
try {
output_width = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {}
i++;
}
else if (args[i].equals("-post"))
{
i++;
post_compiler = args[i];
i++;
}
else if (args[i].equals("-stdout"))
{
i++;
output_stdout = true;
}
else if (args[i].equals("-sx"))
{
i++;
if (source_ext == null) {
source_ext = new String[] { args[i] };
}
else {
String[] s = new String[source_ext.length+1];
System.arraycopy(source_ext, 0, s, 0, source_ext.length);
s[s.length-1] = args[i];
source_ext = s;
}
i++;
}
else if (args[i].equals("-ox"))
{
i++;
output_ext = args[i];
i++;
}
else if (args[i].equals("-noserial"))
{
i++;
serialize_type_info = false;
}
else if (args[i].equals("-dump"))
{
i++;
String pass_name = args[i];
dump_ast.add(pass_name);
i++;
}
else if (args[i].equals("-print"))
{
i++;
String pass_name = args[i];
print_ast.add(pass_name);
i++;
}
else if (args[i].equals("-disable"))
{
i++;
String pass_name = args[i];
disable_passes.add(pass_name);
i++;
}
else if (args[i].equals("-nooutput"))
{
i++;
keep_output_files = false;
output_width = 1000; // we do not keep the output files, so
// set the output_width to a large number
// to reduce the time spent pretty-printing
}
else if (args[i].equals("-v") || args[i].equals("-verbose"))
{
i++;
Report.addTopic("verbose", 1);
}
else if (args[i].equals("-report")) {
i++;
String report_option = args[i];
StringTokenizer st = new StringTokenizer(args[i], "=");
String topic = ""; int level = 0;
if (st.hasMoreTokens()) topic = st.nextToken();
if (st.hasMoreTokens()) {
try {
level = Integer.parseInt(st.nextToken());
}
catch (NumberFormatException e) {}
}
Report.addTopic(topic, level);
i++;
}
else if (args[i].equals("-outputamb")) {
output_ambiguous_nodes = true;
i++;
}
else if (!args[i].startsWith("-")) {
source.add(args[i]);
File f = new File(args[i]).getParentFile();
if (f != null && !source_path.contains(f))
source_path.add(f);
i++;
}
return i;
}
/**
* Print usage information
*/
public void usage(PrintStream out) {
out.println("usage: " + extension.compilerName() + " [options] " +
"<source-file>." + extension.fileExtensions()[0] + " ...");
out.println("where [options] includes:");
usageForFlag(out, "@<file>", "read options from <file>");
usageForFlag(out, "-d <directory>", "output directory");
usageForFlag(out, "-assert", "recognize the assert keyword");
usageForFlag(out, "-sourcepath <path>", "source path");
usageForFlag(out, "-bootclasspath <path>",
"path for bootstrap class files");
usageForFlag(out, "-ext <extension>", "use language extension");
usageForFlag(out, "-extclass <ext-class>", "use language extension");
usageForFlag(out, "-commandlineonly", "only compile files named on the command-line (may also require -c)");
usageForFlag(out, "-preferclassfiles", "prefer class files to source files even if the source is newer");
usageForFlag(out, "-fqcn", "use fully-qualified class names");
usageForFlag(out, "-sx <ext>", "set source extension");
usageForFlag(out, "-ox <ext>", "set output extension");
usageForFlag(out, "-errors <num>", "set the maximum number of errors");
usageForFlag(out, "-w <num>",
"set the maximum width of the .java output files");
usageForFlag(out, "-dump <pass>", "dump the ast after pass <pass>");
usageForFlag(out, "-print <pass>",
"pretty-print the ast after pass <pass>");
usageForFlag(out, "-disable <pass>", "disable pass <pass>");
// usageForFlag(out, "-scramble [seed]", "scramble the ast (for testing)");
usageForFlag(out, "-noserial", "disable class serialization");
usageForFlag(out, "-nooutput", "delete output files after compilation");
usageForFlag(out, "-c", "compile only to .java");
usageForFlag(out, "-outputamb", "allow generating code from ambiguous nodes");
usageForFlag(out, "-post <compiler>",
"run javac-like compiler after translation");
usageForFlag(out, "-v -verbose", "print verbose debugging information");
usageForFlag(out, "-report <topic>=<level>",
"print verbose debugging information about " +
"topic at specified verbosity");
StringBuffer allowedTopics = new StringBuffer("Allowed topics: ");
for (Iterator iter = Report.topics.iterator(); iter.hasNext(); ) {
allowedTopics.append(iter.next().toString());
if (iter.hasNext()) {
allowedTopics.append(", ");
}
}
usageSubsection(out, allowedTopics.toString());
usageForFlag(out, "-version", "print version info");
usageForFlag(out, "-h", "print this message");
}
/**
* The maximum width of a line when printing usage information. Used
* by <code>usageForFlag</code> and <code>usageSubsection</code>.
*/
protected int USAGE_SCREEN_WIDTH = 76;
/**
* The number of spaces from the left that the descriptions for flags will
* be displayed. Used
* by <code>usageForFlag</code>.
*/
protected int USAGE_FLAG_WIDTH = 27;
/**
* The number of spaces to indent a subsection of usage information.
* Used by <code>usageSubsection</code>.
*/
protected int USAGE_SUBSECTION_INDENT = 8;
/** Ignore source and class file modification times when compiling; always prefer the class file. */
public boolean ignore_mod_times;
/**
* Output a flag and a description of its usage in a nice format. This
* makes it easier for extensions to output their usage in a consistent
* format.
*
* @param out output PrintStream
* @param flag
* @param description description of the flag.
*/
protected void usageForFlag(PrintStream out, String flag, String description) {
out.print(" ");
out.print(flag);
// cur is where the cursor is on the screen.
int cur = flag.length() + 2;
// print space to get up to indentation level
if (cur < USAGE_FLAG_WIDTH) {
printSpaces(out, USAGE_FLAG_WIDTH - cur);
}
else {
// the flag is long. Get a new line before printing the
// description.
out.println();
printSpaces(out, USAGE_FLAG_WIDTH);
}
cur = USAGE_FLAG_WIDTH;
// break up the description.
StringTokenizer st = new StringTokenizer(description);
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (cur + s.length() > USAGE_SCREEN_WIDTH) {
out.println();
printSpaces(out, USAGE_FLAG_WIDTH);
cur = USAGE_FLAG_WIDTH;
}
out.print(s);
cur += s.length();
if (st.hasMoreTokens()) {
if (cur + 1 > USAGE_SCREEN_WIDTH) {
out.println();
printSpaces(out, USAGE_FLAG_WIDTH);
cur = USAGE_FLAG_WIDTH;
}
else {
out.print(" ");
cur++;
}
}
}
out.println();
}
/**
* Output a section of text for usage information. This text will be
* displayed indented a certain amount from the left, controlled by
* the field <code>USAGE_SUBSECTION_INDENT</code>
*
* @param out the output PrintStream
* @param text the text to output.
*/
protected void usageSubsection(PrintStream out, String text) {
// print space to get up to indentation level
printSpaces(out, USAGE_SUBSECTION_INDENT);
// cur is where the cursor is on the screen.
int cur = USAGE_SUBSECTION_INDENT;
// break up the description.
StringTokenizer st = new StringTokenizer(text);
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (cur + s.length() > USAGE_SCREEN_WIDTH) {
out.println();
printSpaces(out, USAGE_SUBSECTION_INDENT);
cur = USAGE_SUBSECTION_INDENT;
}
out.print(s);
cur += s.length();
if (st.hasMoreTokens()) {
if (cur + 1 > USAGE_SCREEN_WIDTH) {
out.println();
printSpaces(out, USAGE_SUBSECTION_INDENT);
cur = USAGE_SUBSECTION_INDENT;
}
else {
out.print(' ');
cur++;
}
}
}
out.println();
}
/**
* Utility method to print a number of spaces to a PrintStream.
* @param out output PrintStream
* @param n number of spaces to print.
*/
protected static void printSpaces(PrintStream out, int n) {
while (n
out.print(' ');
}
}
public String constructFullClasspath() {
StringBuffer fullcp = new StringBuffer();
if (bootclasspath != null) {
fullcp.append(bootclasspath);
}
fullcp.append(classpath);
return fullcp.toString();
}
public String constructPostCompilerClasspath() {
return output_directory + File.pathSeparator
+ "." + File.pathSeparator
+ output_classpath;
}
}
|
package org.mskcc.portal.servlet;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import org.owasp.validator.html.PolicyException;
import org.apache.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.ArrayList;
/**
* Generates Plots via RServe.
*
* @author Anders Jacobsen, Ethan Cerami.
*/
public class PlotServlet extends HttpServlet {
private static Logger logger = Logger.getLogger(PlotServlet.class);
public static final String SKIN = "skin";
public static final String SKIN_COL_GROUP = "skin_col_gp";
public static final String LEGEND_POS = "legendPos";
public static final String SKIN_NORMALS = "skin_normals";
public static final int PLOT_WIDTH = 600;
public static final int PLOT_HEIGHT = 600;
private static final String UNDEFINED = "undefined";
private static ServletXssUtil servletXssUtil;
private static RConnection c;
/**
* Initializes the servlet.
*
* @throws ServletException Serlvet Init Error.
*/
public void init() throws ServletException {
super.init();
try {
c = new RConnection();
servletXssUtil = ServletXssUtil.getInstance();
} catch (PolicyException e) {
throw new ServletException (e);
} catch (RserveException e) {
throw new ServletException (e);
}
}
/**
* Servlet is being taken out of service.
*/
public void destroy() {
// close RConnection
if (c != null) {
c.close();
}
}
/**
* Processes GET Request.
*
* @param req Http Servlet Request.
* @param res http Servlet Response.
* @throws ServletException Servlet Error.
* @throws IOException IO Error.
*/
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
try {
// Get All Parameters Safely
Pattern p = Pattern.compile(",");
// TODO: Later: ACCESS CONTROL: change to cancer study, etc.
String cancerTypeId = servletXssUtil.getCleanInput(req, QueryBuilder.CANCER_STUDY_ID);
String[] genesList = p.split(servletXssUtil.getCleanInput(req, QueryBuilder.GENE_LIST));
String[] geneticProfilesList = p.split
(servletXssUtil.getCleanInput(req, QueryBuilder.GENETIC_PROFILE_IDS));
String skin = servletXssUtil.getCleanInput(req, SKIN);
String caseSetId = servletXssUtil.getCleanInput(req, QueryBuilder.CASE_SET_ID);
String caseIds = servletXssUtil.getCleanInput(req, QueryBuilder.CASE_IDS);
String format = servletXssUtil.getCleanInput(req, QueryBuilder.FORMAT);
String skinColGroup = servletXssUtil.getCleanInput(req, SKIN_COL_GROUP);
String skinNormals = servletXssUtil.getCleanInput(req, SKIN_NORMALS);
String legendPos = servletXssUtil.getCleanInput(req, LEGEND_POS);
if (format == null || !format.equals("pdf")) {
format = "png"; // default is png
}
// Split Gene List
String genes = "";
for (String s : genesList) {
genes += "'" + s + "',";
}
genes = genes.substring(0, genes.length() - 1);
String geneticProfiles = "";
for (String s : geneticProfilesList) {
geneticProfiles += "'" + s + "',";
}
geneticProfiles = geneticProfiles.substring(0, geneticProfiles.length() - 1);
if (format.equals("pdf")) {
res.setContentType("application/pdf");
} else {
res.setContentType("image/png");
}
String tmpfile = "tmp" + String.valueOf(System.currentTimeMillis() + "." + format);
// Must use Cairo Library, so that we can generate Images without GUI
StringBuffer plot = new StringBuffer("library(cgdsr);\n");
plot.append("library(Cairo);\n");
if (format.equals("png")) {
plot.append("Cairo(width=" + PLOT_WIDTH + ", height="
+ PLOT_HEIGHT + ", file='" + tmpfile + "', type='" + format + "', units=\"px\")\n");
} else {
plot.append("pdf(width=6, height=6, file='" + tmpfile + "')\n");
}
String currentUrl = req.getRequestURL().toString();
String localHost = "127.0.0.1";
logger.debug("Current URL is: " + currentUrl);
// locate host name to replace
int startOfHostname = currentUrl.indexOf("
int endOfHostname = currentUrl.indexOf(":", startOfHostname);
// port not included in url
if (endOfHostname == -1) {
endOfHostname = currentUrl.indexOf("/", startOfHostname);
// we need to append port number
localHost += ":38080";
}
String hostname = currentUrl.substring(startOfHostname, endOfHostname);
String cgdsUrl = currentUrl.replaceAll("plot.(do|pdf)", "");
cgdsUrl = cgdsUrl.replace(hostname, localHost);
logger.debug("Web API URL is: " + cgdsUrl);
plot.append ("c = CGDS('" + cgdsUrl + "',TRUE);\n");
if (caseSetId != null && !caseSetId.equals("-1")) {
plot.append (String.format("plot(c, '%s', c(%s), c(%s), '%s', skin='%s' ",
cancerTypeId, genes, geneticProfiles, caseSetId, skin));
} else {
ArrayList <String> caseList = new ArrayList<String>();
for (String currentCase : caseIds.split("[\\s,]+")) {
currentCase = currentCase.trim();
if (currentCase.length() > 0) {
caseList.add(currentCase);
}
}
StringBuffer caseBuffer = new StringBuffer();
for (int i=0; i<caseList.size(); i++) {
caseBuffer.append ("\"" + caseList.get(i) + "\"");
if (i < caseList.size() -1) {
caseBuffer.append (",");
}
}
plot.append (String.format("plot(c, '%s', c(%s), c(%s), cases=c(%s), skin='%s' ",
cancerTypeId, genes, geneticProfiles, caseBuffer.toString(), skin));
}
if (skinColGroup != null && !skinColGroup.equals(UNDEFINED)) {
plot.append (", skin.col.gp=c(");
if (skinColGroup.contains(",")) {
String colGroups [] = skinColGroup.split(",");
for (int i=0; i<colGroups.length; i++) {
plot.append ("'" + colGroups[i] +"'");
if (i < colGroups.length -1) {
plot.append (",");
}
}
}
else {
plot.append ("'" + skinColGroup + "'");
}
plot.append (")");
}
if (skinNormals != null) {
plot.append (", skin.normals='" + skinNormals + "'");
}
if (legendPos != null) {
plot.append (", legend.pos='" + legendPos + "'");
}
plot.append (");\n");
plot.append ("dev.off();\n");
logger.debug("Call to R Follows:");
logger.debug(plot.toString());
// open device
c.parseAndEval(plot.toString());
// There is no I/O API in REngine because it's actually more efficient to use R for this
// we limit the file size to 1MB which should be sufficient and we delete the file as well
REXP xp = c.parseAndEval("r=readBin('" + tmpfile
+ "','raw',1024*1024); unlink('" + tmpfile + "'); r;");
// now this is pretty boring AWT stuff - create an image from the data and display it ...
byte[] imageBytes = xp.asBytes();
res.setContentLength(imageBytes.length);
res.getOutputStream().write(imageBytes);
} catch (Exception e) {
// In the event of an exception, redirect to the Plot NA Image.
logger.error(e);
res.sendRedirect("images/plots_na.png");
}
}
}
|
import java.util.*;
public class PuzzleMain {
public static void main(String[] args) {
boolean verbose = false;
if(args.length == 0) {
System.out.println("Usage:");
System.out.println("java PuzzleMain IMGS [-v]");
System.out.println(" IMGS: directory to look for .png puzzle pieces");
System.out.println(" -v: verbose if flag is present");
} else {
//TODO: check for valid directory here
if(args.length == 2) {
if(!args[1].equals("-v")) {
System.out.println("Unrecognized flag \"" + args[1] + "\"... run with no params for help");
return;
} else {
verbose = true;
System.out.println("Running verbose...");
}
} else if(args.length > 2) {
System.out.println("Too many flags detected... run with no params for help");
return;
}
}
}
}
|
package com.main;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.RepaintManager;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import com.maths.Calculator;
/**
* Builds the main window
*
* @author Group 12
* @version 2.1
*
*/
public class Visualizer extends JFrame implements ActionListener,KeyListener,
MenuListener,MouseListener,MouseWheelListener,MouseMotionListener, FocusListener{
public static int CARTESIAN2D_STATE=0;
public static int CARTESIAN3D_STATE=2;
public static int POLAR2D_STATE=1;
public static int VISUALIZATION_STATE=CARTESIAN2D_STATE;
//public static int VISUALIZATION_STATE=POLAR2D_STATE;
String VERSION="Math Graphics 2.1.0 ";
JPanel center=null;
JPanel bottom=null;
Graphics2D graphics2D;
JButton draw=null;
JButton more=null;
JButton less=null;
JButton calculateIntegral=null;
//size of the display panel
public static int HEIGHT=500;
public static int WIDTH=800;
private Calculator calc;
public static int BUTTOMBORDER=100;
public static int UPBORDER=40;
public static int LEFTBORDER=0;
public static int RIGHTBORDER=150;
private JPanel right;
public JTextField displayedFunction;
public JTextField displayedA;
public JTextField displayedB;
private JPanel up;
public static Color LINE_COLOR=Color.BLUE;
public static Color LINE_2_COLOR=Color.GREEN;
public static Color LINE_3D_COLOR=Color.LIGHT_GRAY;
public static Color AXIS_COLOR=Color.BLACK;
public static Color BACKGROUND_COLOR=new Color( 255,236,139);
public static Color PANEL_COLOR=new Color( 205,190,112);
private JButton displayDerivative;
public static boolean isDerivativeDisplay;
private JMenuBar jmb;
private JMenuItem jmt1;
private JMenuItem jmt3;
private JMenuItem jmt2;
private JMenuItem jmt4;
private JMenu jm;
private boolean redrawAfterMenu=false;
private JMenu jm2;
private JMenuItem jmt21;
private JMenuItem jmt22;
private Properties p;
private JMenu jm3;
private JMenuItem jmt31;
private JMenuItem jmt23;
public DigitTextField displayedA2;
public DigitTextField displayedB2;
private JMenu jm4;
private JMenuItem jmt41;
static boolean start=true;
JFileChooser fc = new JFileChooser();
private JLabel screenPoint;
private int xPressed;
private int yPressed;
private File currentDirectory=null;
private BufferedImage buf=null;
private JMenuItem jmt42;
//constructor
public Visualizer(){
loadProperties();
center=new JPanel();
center.addMouseWheelListener(this);
setLocation(20,20);
setTitle(VERSION);
setSize(LEFTBORDER+WIDTH+RIGHTBORDER,UPBORDER+HEIGHT+BUTTOMBORDER);
Container container = getContentPane();
setLayout(null);
center.setBounds(LEFTBORDER,UPBORDER,WIDTH,HEIGHT);
center.addMouseListener(this);
center.addMouseMotionListener(this);
add(center);
calc=new Calculator(WIDTH,HEIGHT);
calc.setY0(250);
calc.setX0(50);
if(VISUALIZATION_STATE==CARTESIAN2D_STATE)
{
buildUpPanel();
buildRightPanel();
buildBottomPanel();
}
else if(VISUALIZATION_STATE==POLAR2D_STATE)
{
buildPolarUpPanel();
buildPolarRightPanel();
buildBottomPanel();
}
else if(VISUALIZATION_STATE==CARTESIAN3D_STATE)
{
build3DUpPanel();
build3DRightPanel();
buildBottomPanel();
}
buildMenuBar();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//override to avoid a tricky paint problem
RepaintManager.setCurrentManager(
new RepaintManager(){
public void paintDirtyRegions() {
super.paintDirtyRegions();
if(redrawAfterMenu ) {draw();redrawAfterMenu=false;}
}
}
);
setInitColors(p);
center.setBackground(BACKGROUND_COLOR);
up.setBackground(PANEL_COLOR);
bottom.setBackground(PANEL_COLOR);
right.setBackground(PANEL_COLOR);
setVisible(true);
}
/**
* Creates the menu bar at the top of the screen
*/
private void buildMenuBar() {
jmb=new JMenuBar();
jm=new JMenu("Do");
jm.addMenuListener(this);
jmt1=new JMenuItem("Exit");
jmt1.addActionListener(this);
jmt2=new JMenuItem("Draw");
jmt2.addActionListener(this);
jmt3=new JMenuItem("Integral");
jmt3.addActionListener(this);
jmt4=new JMenuItem("Show DF");
jmt4.addActionListener(this);
jm.add(jmt2);
jm.add(jmt3);
jm.add(jmt4);
jm.addSeparator();
jm.add(jmt1);
jmb.add(jm);
jm2=new JMenu("Visualization");
jm2.addMenuListener(this);
jmt21=new JMenuItem("Cartesian 2D");
jmt21.addActionListener(this);
jm2.add(jmt21);
jmt22 = new JMenuItem("Polar 2D");
jmt22.addActionListener(this);
jm2.add(jmt22);
jmt23 = new JMenuItem("Cartesian 3D");
jmt23.addActionListener(this);
jm2.add(jmt23);
jm2.addMenuListener(this);
jmb.add(jm2);
jm3=new JMenu("Colors");
jm3.addMenuListener(this);
jmt31=new JMenuItem("Change colors");
jmt31.addActionListener(this);
jm3.add(jmt31);
jmb.add(jm3);
jm4=new JMenu("Save");
jm4.addMenuListener(this);
jmt41=new JMenuItem("Save image");
jmt41.addActionListener(this);
jm4.add(jmt41);
jmt42=new JMenuItem("Export data");
jmt42.addActionListener(this);
jm4.add(jmt42);
jmb.add(jm4);
setJMenuBar(jmb);
}
/**
* Builds the bottom panel below the graph
*/
private void buildBottomPanel() {
draw=new JButton("<html><body><u>D</u>raw</body</html>");
draw.addActionListener(this);
draw.setBounds(100,2,100,20);
more=new JButton("+");
more.addActionListener(this);
more.setBounds(210,2,50,20);
less=new JButton("-");
less.addActionListener(this);
less.setBounds(280,2,50,20);
bottom=new JPanel();
bottom.setLayout(null);
bottom.add(draw);
bottom.add(less);
bottom.add(more);
JLabel moves=new JLabel("arrow up,down,left,right to move axis ");
moves.setBounds(350,2,300,20);
bottom.add(moves);
JLabel lscreenpoint = new JLabel();
lscreenpoint.setText("Position x,y: ");
lscreenpoint.setBounds(650,2,100,20);
bottom.add(lscreenpoint);
screenPoint=new JLabel();
screenPoint.setText(",");
screenPoint.setBounds(750,2,100,20);
bottom.add(screenPoint);
bottom.setBounds(0,UPBORDER+HEIGHT,LEFTBORDER+WIDTH+RIGHTBORDER,BUTTOMBORDER);
add(bottom);
draw.addKeyListener(this);
less.addKeyListener(this);
more.addKeyListener(this);
}
/**
* Builds the top panel above the graph
*/
private void buildUpPanel() {
up=new JPanel();
up.setLayout(null);
up.setBounds(0,0,LEFTBORDER+WIDTH+RIGHTBORDER,UPBORDER);
add(up);
JLabel flabel = new JLabel("Displayed function: y=");
flabel.setBounds(5,5,130,20);
up.add(flabel);
displayedFunction=new FunctionTextField();
displayedFunction.addKeyListener(this);
//displayedFunction.setEditable(false);
displayedFunction.setBounds(140,5,400,20);
displayedFunction.addFocusListener(this);
up.add(displayedFunction);
displayedFunction.setText(calc.DISPLAYED_FUNCTION);
}
/**
* Builds the top panel for the Polar2D display
*/
private void buildPolarUpPanel() {
up=new JPanel();
up.setLayout(null);
up.setBounds(0,0,LEFTBORDER+WIDTH+RIGHTBORDER,UPBORDER);
add(up);
JLabel flabel = new JLabel("Displayed function: r(theta)=");
flabel.setBounds(5,5,160,20);
up.add(flabel);
displayedFunction=new FunctionTextField();
displayedFunction.addKeyListener(this);
//displayedFunction.setEditable(false);
displayedFunction.setBounds(170,5,400,20);
displayedFunction.addFocusListener(this);
up.add(displayedFunction);
displayedFunction.setText(calc.DISPLAYED_FUNCTION);
}
/**
* Builds the top panel for the 3D display
*/
private void build3DUpPanel() {
up=new JPanel();
up.setLayout(null);
up.setBounds(0,0,LEFTBORDER+WIDTH+RIGHTBORDER,UPBORDER);
add(up);
JLabel flabel = new JLabel("Displayed function: z(x,y)=");
flabel.setBounds(5,5,150,20);
up.add(flabel);
displayedFunction=new FunctionTextField();
displayedFunction.addKeyListener(this);
//displayedFunction.setEditable(false);
displayedFunction.setBounds(160,5,400,20);
displayedFunction.addFocusListener(this);
up.add(displayedFunction);
displayedFunction.setText(calc.DISPLAYED_FUNCTION);
}
/**
* Builds the right panel for 3D display
*/
private void build3DRightPanel() {
right=new JPanel();
right.setLayout(null);
right.setBounds(LEFTBORDER+WIDTH,UPBORDER,RIGHTBORDER,HEIGHT);
JLabel rlabel = new JLabel("Coord. ranges:");
rlabel.setBounds(5,60,100,20);
right.add(rlabel);
JLabel alabel = new JLabel("ax:");
alabel.setBounds(5,90,20,20);
right.add(alabel);
displayedA=new DigitTextField();
displayedA.addKeyListener(this);
//displayedA.setEditable(false);
displayedA.setBounds(35,90,70,20);
right.add(displayedA);
JLabel blabel = new JLabel("bx:");
blabel.setBounds(5,120,20,20);
right.add(blabel);
add(right);
displayedB=new DigitTextField();
displayedB.addKeyListener(this);
//displayedB.setEditable(false);
displayedB.setBounds(35,120,70,20);
right.add(displayedB);
displayedA.setText(""+calc.a);
displayedB.setText(""+calc.b);
JLabel a2label = new JLabel("ay:");
a2label.setBounds(5,150,20,20);
right.add(a2label);
displayedA2=new DigitTextField();
displayedA2.addKeyListener(this);
//displayedA.setEditable(false);
displayedA2.setBounds(35,150,70,20);
right.add(displayedA2);
JLabel b2label = new JLabel("by:");
b2label.setBounds(5,180,20,20);
right.add(b2label);
displayedB2=new DigitTextField();
displayedB2.addKeyListener(this);
//displayedB.setEditable(false);
displayedB2.setBounds(35,180,70,20);
right.add(displayedB2);
displayedA2.setText(""+calc.a2);
displayedB2.setText(""+calc.b2);
}
/**
* Builds the right panel for Cartesian 2D display
*/
private void buildRightPanel() {
right=new JPanel();
right.setLayout(null);
right.setBounds(LEFTBORDER+WIDTH,UPBORDER,RIGHTBORDER,HEIGHT);
JLabel rlabel = new JLabel("Displayed range:");
rlabel.setBounds(5,60,100,20);
right.add(rlabel);
JLabel alabel = new JLabel("a:");
alabel.setBounds(5,90,20,20);
right.add(alabel);
displayedA=new DigitTextField();
displayedA.addKeyListener(this);
//displayedA.setEditable(false);
displayedA.setBounds(35,90,70,20);
right.add(displayedA);
JLabel blabel = new JLabel("b:");
blabel.setBounds(5,120,20,20);
right.add(blabel);
add(right);
displayedB=new DigitTextField();
displayedB.addKeyListener(this);
//displayedB.setEditable(false);
displayedB.setBounds(35,120,70,20);
right.add(displayedB);
calculateIntegral=new JButton("Integral");
calculateIntegral.setBounds(5,150,100,20);
calculateIntegral.addActionListener(this);
right.add(calculateIntegral);
displayDerivative=new JButton("Show DF");
displayDerivative.setBounds(5,180,100,20);
displayDerivative.addActionListener(this);
right.add(displayDerivative);
displayedA.setText(""+calc.a);
displayedB.setText(""+calc.b);
}
/**
* Build right panel for Polar2D display
*/
private void buildPolarRightPanel() {
right=new JPanel();
right.setLayout(null);
right.setBounds(LEFTBORDER+WIDTH,UPBORDER,RIGHTBORDER,HEIGHT);
JLabel rlabel = new JLabel("Displayed range:");
rlabel.setBounds(5,60,100,20);
right.add(rlabel);
JLabel alabel = new JLabel("theta1:");
alabel.setBounds(5,90,40,20);
right.add(alabel);
displayedA=new DigitTextField();
displayedA.addKeyListener(this);
//displayedA.setEditable(false);
displayedA.setBounds(50,90,60,20);
right.add(displayedA);
JLabel blabel = new JLabel("theta2:");
blabel.setBounds(5,120,40,20);
right.add(blabel);
add(right);
displayedB=new DigitTextField();
displayedB.addKeyListener(this);
//displayedB.setEditable(false);
displayedB.setBounds(50,120,60,20);
right.add(displayedB);
displayedA.setText(""+calc.a);
displayedB.setText(""+calc.b);
}
/**
* Build the graph panel and draw the graph
*/
public void draw(){
draw(getGraphics2D());
}
public void draw(Graphics2D graphics2D){
try{
Graphics2D g2=(Graphics2D) buf.getGraphics();
clean(g2);
readRange();
g2.setColor(AXIS_COLOR);
if(VISUALIZATION_STATE==CARTESIAN2D_STATE || VISUALIZATION_STATE==POLAR2D_STATE){
calc.drawy0axis(g2,getWIDTH(),getHEIGHT());
calc.drawX0axis(g2,getWIDTH(),getHEIGHT());
}
g2.setColor(LINE_COLOR);
if(VISUALIZATION_STATE==CARTESIAN2D_STATE){
calc.draw(g2,getWIDTH(),getHEIGHT());
if(isDerivativeDisplay){
g2.setColor(LINE_2_COLOR);
calc.drawDerivative(g2,getWIDTH(),getHEIGHT());
}
}
else if(VISUALIZATION_STATE==CARTESIAN3D_STATE){
calc.draw3D(buf);
}
else if(VISUALIZATION_STATE==POLAR2D_STATE){
calc.drawPolar(g2,getWIDTH(),getHEIGHT());
}
calc.setRecalculate(true);
graphics2D.drawImage(buf,0,0,WIDTH,HEIGHT,null);
}
catch (Exception e) {
e.printStackTrace();
error("Error in parsing function,please read the README.TXT !");
displayedFunction.setText("0");
return;
}
}
/**
* Read the range values for a and b
*/
private void readRange() {
double a=Double.parseDouble(displayedA.getText());
calc.a=a;
double b=Double.parseDouble(displayedB.getText());
calc.b=b;
if(VISUALIZATION_STATE==CARTESIAN3D_STATE){
double a2=Double.parseDouble(displayedA2.getText());
calc.a2=a2;
double b2=Double.parseDouble(displayedB2.getText());
calc.b2=b2;
}
calc.DISPLAYED_FUNCTION=displayedFunction.getText();
draw.requestFocus(true);
}
/**
* To redraw the graph if the panel is moved or iconified
*
**/
public void paint(Graphics arg0) {
super.paint(arg0);
draw();
}
public void update(Graphics arg0) {
calc.setRecalculate(false);
super.update(arg0);
}
/* (non-Javadoc)
* @see java.awt.Component#repaint()
*/
public void repaint() {
super.repaint();
}
/**
* Clear the graph
*/
private void clean(Graphics2D g2d) {
g2d.setColor(center.getBackground());
g2d.fillRect(0,0,getWIDTH(),getHEIGHT());
}
/**
* Draw the axes
*/
public void initialize() {
graphics2D=(Graphics2D) center.getGraphics();
buf=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
}
/**
*Loads saved properties from the "mathgraphics.properties"
*file
*/
public void loadProperties(){
p=new Properties();
try {
p.load(new FileInputStream("mathgraphics.properties"));
} catch (Exception e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0) {
Object o=arg0.getSource();
if(o==draw || o==jmt2 )
draw();
else if (o==more){
zoom(+1);
}
else if (o==less){
zoom(-1);
}
else if (o==calculateIntegral ||o==jmt3){
calculateIntegral();
}
else if (o==displayDerivative || o==jmt4){
isDerivativeDisplay=!isDerivativeDisplay;
if(isDerivativeDisplay)
{ displayDerivative.setText("No DF");
jmt4.setText("No DF");
}
else {
displayDerivative.setText("Show DF");
jmt4.setText("Show DF");
}
draw();
}
else if (o==jmt1) exit();
else if(o==jmt21) {
VISUALIZATION_STATE=CARTESIAN2D_STATE;
calc.DISPLAYED_FUNCTION="sin(x)";
calc.setY0(250);
calc.setX0(50);
displayedFunction.setText(calc.DISPLAYED_FUNCTION);
remove(up);
remove(right);
buildUpPanel();
buildRightPanel();
jmt3.setVisible(true);
jmt4.setVisible(true);
setColors(p);
repaint();
}
else if(o==jmt22) {
VISUALIZATION_STATE=POLAR2D_STATE;
calc.DISPLAYED_FUNCTION="2";
calc.setY0(250);
calc.setX0(250);
displayedFunction.setText(calc.DISPLAYED_FUNCTION);
remove(up);
remove(right);
buildPolarUpPanel();
buildPolarRightPanel();
jmt3.setVisible(false);
jmt4.setVisible(false);
setColors(p);
repaint();
}
else if(o==jmt23) {
VISUALIZATION_STATE=CARTESIAN3D_STATE;
calc.DISPLAYED_FUNCTION="sin(x+y)";
calc.setY0(250);
calc.setX0(250);
displayedFunction.setText(calc.DISPLAYED_FUNCTION);
remove(up);
remove(right);
build3DUpPanel();
build3DRightPanel();
jmt3.setVisible(false);
jmt4.setVisible(false);
setColors(p);
repaint();
}
else if(o==jmt31){
selectColors();
}
else if(o==jmt41){
saveImage();
}
else if(o==jmt42){
exportData();
}
}
/**
* Saves the graph image
*/
private void saveImage() {
fc.setDialogType(JFileChooser.SAVE_DIALOG);
if(currentDirectory!=null)
fc.setCurrentDirectory(currentDirectory);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
currentDirectory=fc.getCurrentDirectory();
File file = fc.getSelectedFile();
saveImage(file);
}
}
/**
* Save image to a specified file
* @param file name of file the image is saved to
*/
private void saveImage(File file) {
//drawFace();
BufferedImage buf=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
try {
Graphics2D bufGraphics=(Graphics2D)buf.getGraphics();
draw(bufGraphics);
ImageIO.write(buf,"jpg",file);
} catch (Exception e) {
e.printStackTrace();
}
}
private void exportData() {
Object fun=null;
if(VISUALIZATION_STATE==CARTESIAN2D_STATE || VISUALIZATION_STATE==POLAR2D_STATE){
fun=calc.getFunction();
}
else if(VISUALIZATION_STATE==CARTESIAN3D_STATE){
fun=calc.getFunction3D();
}
ExportDataPanel edp=new ExportDataPanel(fun);
}
/**
* Creates a colorpanel and sets the colors
*/
private void selectColors() {
Colorpanel cp=new Colorpanel(p);
setColors(p);
}
/**
* Sets the background colors and gets the initial colors
* from setInitColors()
* @param p2 color properties
*/
private void setColors(Properties p2) {
setInitColors(p2);
center.setBackground(BACKGROUND_COLOR);
up.setBackground(PANEL_COLOR);
bottom.setBackground(PANEL_COLOR);
right.setBackground(PANEL_COLOR);
repaint();
}
/**
* Set the initial colors
* @param p2 color properties
*/
private void setInitColors(Properties p2) {
if(p2.getProperty("BACKGROUND_COLOR")!=null){
BACKGROUND_COLOR=Colorpanel.buildColor(p2.getProperty("BACKGROUND_COLOR"));
}
else{
p2.setProperty("BACKGROUND_COLOR",Colorpanel.decomposeColor(BACKGROUND_COLOR));
}
if(p2.getProperty("PANEL_COLOR")!=null){
PANEL_COLOR=Colorpanel.buildColor(p2.getProperty("PANEL_COLOR"));
}
else{
p2.setProperty("PANEL_COLOR",Colorpanel.decomposeColor(PANEL_COLOR));
}
if(p2.getProperty("LINE_COLOR")!=null){
LINE_COLOR=Colorpanel.buildColor(p2.getProperty("LINE_COLOR"));
}
else{
p2.setProperty("LINE_COLOR",Colorpanel.decomposeColor(LINE_COLOR));
}
if(p2.getProperty("LINE_2_COLOR")!=null){
LINE_2_COLOR=Colorpanel.buildColor(p2.getProperty("LINE_2_COLOR"));
}
else{
p2.setProperty("LINE_2_COLOR",Colorpanel.decomposeColor(LINE_2_COLOR));
}
if(p2.getProperty("AXIS_COLOR")!=null){
AXIS_COLOR=Colorpanel.buildColor(p2.getProperty("AXIS_COLOR"));
}
else{
p2.setProperty("AXIS_COLOR",Colorpanel.decomposeColor(AXIS_COLOR));
}
if(p2.getProperty("LINE_3D_COLOR")!=null){
LINE_3D_COLOR=Colorpanel.buildColor(p2.getProperty("LINE_3D_COLOR"));
}
else{
p2.setProperty("LINE_3D_COLOR",Colorpanel.decomposeColor(LINE_3D_COLOR));
}
}
/**
* Exit the program
*/
private void exit() {
dispose();
System.exit(0);
}
/**
* Zoom in on the graph
*/
private void zoom(int i) {
calc.zoom(i);
double alfa=1.0;
if(i>0){
alfa=0.5;
}
else {
alfa=2.0;
}
int dx=(int) ((WIDTH/2-calc.x0)*(1-1.0/alfa));
int dy=(int) ((HEIGHT/2-calc.y0)*(1-1.0/alfa));
calc.moveCenter(dx,dy);
draw();
}
/**
* @return Returns the g2.
*/
public Graphics2D getGraphics2D() {
return graphics2D;
}
/**
* @param g2 The g2 to set.
*/
public void setGraphics2D(Graphics2D g2) {
this.graphics2D = g2;
}
/**
* @return Returns the hEIGHT.
*/
public int getHEIGHT() {
return HEIGHT;
}
/**
* @param height The hEIGHT to set.
*/
public void setHEIGHT(int height) {
HEIGHT = height;
}
/**
* @return Returns the wIDTH.
*/
public int getWIDTH() {
return WIDTH;
}
/**
* @param width The wIDTH to set.
*/
public void setWIDTH(int width) {
WIDTH = width;
}
public void keyTyped(KeyEvent arg0) {
}
public void keyPressed(KeyEvent arg0) {
int code =arg0.getKeyCode();
if(code==KeyEvent.VK_LEFT && !displayedFunction.hasFocus())
left(+1);
else if(code==KeyEvent.VK_RIGHT && !displayedFunction.hasFocus() )
left(-1);
else if(code==KeyEvent.VK_UP)
up(-1);
else if(code==KeyEvent.VK_DOWN )
up(+1);
else if(code==KeyEvent.VK_D)
draw();
else if(code==KeyEvent.VK_PLUS && !displayedFunction.hasFocus())
zoom(-1);
else if(code==KeyEvent.VK_MINUS && !displayedFunction.hasFocus())
zoom(+1);
}
public void keyReleased(KeyEvent arg0) {
}
/**
* Move up/down
*/
private void up(int signum) {
calc.up(signum);
draw();
}
/**
* Move left/right
*/
private void left(int signum) {
calc.left(signum);
draw();
}
/**
* Calculate integral under the range obtained
* from readRange()
*/
private void calculateIntegral() {
readRange();
Integralpanel ip=new Integralpanel(calc);
}
/**
* @param string
*/
public void error(String string) {
JOptionPane.showMessageDialog(null,string,"Error",JOptionPane.ERROR_MESSAGE);
}
public void menuSelected(MenuEvent arg0) {
redrawAfterMenu=false;
}
public void menuDeselected(MenuEvent arg0) {
redrawAfterMenu=true;
}
public void menuCanceled(MenuEvent arg0) {
}
public void mouseClicked(MouseEvent arg0) {
Point point = arg0.getPoint();
movetToCenter(point.x,point.y);
/*int BORDER_LIMIT=50;
Point point = arg0.getPoint();
if(point.y<BORDER_LIMIT) up(-1);
if(point.y>pannel.getHeight()-BORDER_LIMIT) up(+1);
if(point.x<BORDER_LIMIT) left(+1);
if(point.x>pannel.getWidth()-BORDER_LIMIT) left(-1);*/
}
private void movetToCenter(int x, int y) {
calc.moveCenter(WIDTH/2-x,HEIGHT/2-(HEIGHT-y));
draw();
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
xPressed = arg0.getX();
yPressed = arg0.getY();
}
public void mouseReleased(MouseEvent arg0) {
int x = arg0.getX();
int y = arg0.getY();
if(x-xPressed!=0 || -y+yPressed!=0 ){
calc.drag(x-xPressed,-y+yPressed);
draw();
}
}
public void mouseWheelMoved(MouseWheelEvent arg0) {
int pix=arg0.getUnitsToScroll();
if(pix>0) up(+1);
else up(-1);
}
public void mouseDragged(MouseEvent arg0) {
}
public void mouseMoved(MouseEvent arg0) {
Point p=arg0.getPoint();
if(VISUALIZATION_STATE==CARTESIAN2D_STATE || VISUALIZATION_STATE==POLAR2D_STATE )
screenPoint.setText(calc.invertX((int)p.getX())+" ; "+calc.invertY((int)p.getY(),HEIGHT));
else
screenPoint.setText("");
}
@Override
public void focusGained(FocusEvent arg0) {
Object obj = arg0.getSource();
}
@Override
public void focusLost(FocusEvent arg0) {
Object obj = arg0.getSource();
}
}
|
package VASSAL.build.module.map;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.Map;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.command.Command;
import VASSAL.configure.Configurer;
import VASSAL.configure.ConfigurerFactory;
import VASSAL.configure.IconConfigurer;
import VASSAL.configure.SingleChildInstance;
import VASSAL.configure.StringArrayConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.LaunchButton;
/**
* Controls the zooming in/out of a {@link Map} window.
*
* @author Joel Uckelman
*/
public class Zoomer extends AbstractConfigurable implements GameComponent {
protected Map map;
@Deprecated protected double zoom = 1.0;
@Deprecated protected int zoomLevel = 0;
@Deprecated protected int zoomStart = 1;
@Deprecated protected double[] zoomFactor;
@Deprecated protected int maxZoom = 4;
protected LaunchButton zoomInButton;
protected LaunchButton zoomPickButton;
protected LaunchButton zoomOutButton;
protected ZoomMenu zoomMenu;
protected State state;
// the default zoom levels are powers of 1.6
protected static final double[] defaultZoomLevels = new double[] {
1.0/1.6/1.6,
1.0/1.6,
1.0,
1.6
};
protected static final int defaultInitialZoomLevel = 2;
/**
* Stores the state information for the {@link Zoomer}. This class
* exists to keep the <code>Zoomer</code> data separate from the
* <code>Zoomer</code> GUI.
*
* <p>Predefined zoom levels are stored in <code>levels</code>. If we are
* in a predefined zoom level, then <code>custom == -1</code> and
* <code>levels[cur]</code> is the current zoom factor. If we are in
* a user-defined zoom level, then <code>custom</code> is the current
* zoom factor and <code>cur</code> is the greatest value such that
* {@code custom < level[cur]}}.</p>
*
* @author Joel Uckelman
* @since 3.1.0
*/
protected static class State {
private double custom;
private final double[] levels;
private int cur;
private final int initial;
public State(double[] levels, int initial) {
this.levels = levels;
Arrays.sort(this.levels);
cur = this.initial = initial;
custom = -1;
}
public State(Collection<Double> l, int initial) {
levels = new double[l.size()];
int i = 0;
for (Double d : l) levels[i++] = d;
Arrays.sort(levels);
cur = this.initial = initial;
custom = -1;
}
public double getZoom() {
return custom < 0 ? levels[cur] : custom;
}
public void setZoom(double z) {
cur = Arrays.binarySearch(levels, z);
if (cur < 0) {
// if z is not a level, set cur to the next level > z
cur = -cur-1;
// check whether we are close to a level
if (cur < levels.length && Math.abs(z - levels[cur]) < 0.005) {
custom = -1;
}
else if (cur > 0 && Math.abs(z - levels[cur-1]) < 0.005) {
--cur;
custom = -1;
}
else {
custom = z;
}
}
else {
// custom is negative when we are in a predefined zoom level
custom = -1;
}
}
public int getLevel() {
return cur;
}
public void setLevel(int l) {
cur = l;
custom = -1;
}
public int getInitialLevel() {
return initial;
}
public int getLevelCount() {
return levels.length;
}
public boolean atLevel() {
return custom < 0;
}
public void lowerLevel() {
if (custom >= 0) custom = -1;
--cur;
}
public void higherLevel() {
if (custom < 0) ++cur;
else custom = -1;
}
public boolean hasLowerLevel() {
return cur > 0;
}
public boolean hasHigherLevel() {
return custom < 0 ? cur < levels.length-1 : cur < levels.length;
}
public List<Double> getLevels() {
final ArrayList<Double> l = new ArrayList<Double>(levels.length);
for (double d : levels) l.add(d);
return l;
}
}
public Zoomer() {
state = new State(defaultZoomLevels, defaultInitialZoomLevel);
ActionListener zoomIn = new ActionListener() {
public void actionPerformed(ActionEvent e) {
zoomIn();
}
};
ActionListener zoomOut = new ActionListener() {
public void actionPerformed(ActionEvent e) {
zoomOut();
}
};
zoomMenu = new ZoomMenu();
ActionListener zoomPick = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (zoomPickButton.isShowing()) {
zoomMenu.show(zoomPickButton, 0, zoomPickButton.getHeight());
}
}
};
zoomPickButton = new LaunchButton(null, PICK_TOOLTIP, PICK_BUTTON_TEXT,
ZOOM_PICK, PICK_ICON_NAME, zoomPick);
zoomPickButton.setAttribute(PICK_TOOLTIP,
Resources.getString("Zoomer.zoom_select")); //$NON-NLS-1$
zoomPickButton.setAttribute(PICK_ICON_NAME, PICK_DEFAULT_ICON);
zoomInButton = new LaunchButton(null, IN_TOOLTIP, IN_BUTTON_TEXT,
ZOOM_IN, IN_ICON_NAME, zoomIn);
zoomInButton.setAttribute(IN_TOOLTIP,
Resources.getString("Zoomer.zoom_in")); //$NON-NLS-1$
zoomInButton.setAttribute(IN_ICON_NAME, IN_DEFAULT_ICON);
zoomOutButton = new LaunchButton(null, OUT_TOOLTIP, OUT_BUTTON_TEXT,
ZOOM_OUT, OUT_ICON_NAME, zoomOut);
zoomOutButton.setAttribute(OUT_TOOLTIP,
Resources.getString("Zoomer.zoom_out")); //$NON-NLS-1$
zoomOutButton.setAttribute(OUT_ICON_NAME, OUT_DEFAULT_ICON);
setConfigureName(null);
}
protected void init() {
zoomInButton.setEnabled(state.hasHigherLevel());
zoomPickButton.setEnabled(true);
zoomOutButton.setEnabled(state.hasLowerLevel());
zoomMenu.initZoomItems();
}
public static String getConfigureTypeName() {
return "Zoom capability";
}
public String[] getAttributeNames() {
return new String[]{
ZOOM_START,
ZOOM_LEVELS,
IN_TOOLTIP,
IN_BUTTON_TEXT,
IN_ICON_NAME,
ZOOM_IN,
PICK_TOOLTIP,
PICK_BUTTON_TEXT,
PICK_ICON_NAME,
ZOOM_PICK,
OUT_TOOLTIP,
OUT_BUTTON_TEXT,
OUT_ICON_NAME,
ZOOM_OUT
};
}
public String[] getAttributeDescriptions() {
return new String[]{
"",
"Preset zoom levels: ",
"Zoom in tooltip text: ",
"Zoom in button text: ",
"Zoom in Icon: ",
"Zoom in hotkey: ",
"Zoom select tooltip text",
"Zoom select button text",
"Zoom select Icon",
"Zoom select hotkey",
"Zoom out tooltip text: ",
"Zoom out button text: ",
"Zoom out Icon: ",
"Zoom out hotkey: "
};
}
public Class<?>[] getAttributeTypes() {
return new Class<?>[]{
null, // ZOOM_START is handled by the LevelConfigurer
LevelConfig.class,
String.class,
String.class,
InIconConfig.class,
KeyStroke.class,
String.class,
String.class,
PickIconConfig.class,
KeyStroke.class,
String.class,
String.class,
OutIconConfig.class,
KeyStroke.class
};
}
public static class InIconConfig implements ConfigurerFactory {
public Configurer getConfigurer(AutoConfigurable c,
String key, String name) {
return new IconConfigurer(key, name, IN_DEFAULT_ICON);
}
}
public static class PickIconConfig implements ConfigurerFactory {
public Configurer getConfigurer(AutoConfigurable c,
String key, String name) {
return new IconConfigurer(key, name, PICK_DEFAULT_ICON);
}
}
public static class OutIconConfig implements ConfigurerFactory {
public Configurer getConfigurer(AutoConfigurable c,
String key, String name) {
return new IconConfigurer(key, name, OUT_DEFAULT_ICON);
}
}
public static class LevelConfig implements ConfigurerFactory {
public Configurer getConfigurer(AutoConfigurable c,
String key, String name) {
return new LevelConfigurer((Zoomer) c, key, name);
}
}
/**
* The {@link Configurer} for {@link #ZOOM_LEVELS} and {@link #ZOOM_START}.
*
* @author Joel Uckelman
* @since 3.1.0
*/
protected static class LevelConfigurer extends Configurer {
private Zoomer z;
private JPanel panel;
private LevelModel model;
private JList levelList;
private JButton addButton;
private JButton removeButton;
private JButton initialButton;
private JTextField levelField;
public LevelConfigurer(final Zoomer z, String key, String name) {
super(key, name);
this.z = z;
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
final Box leftBox = Box.createVerticalBox();
final Box addBox = Box.createHorizontalBox();
// Add button
addButton = new JButton(Resources.getString(Resources.ADD));
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { addLevel(); }
});
addButton.setEnabled(false);
addBox.add(addButton);
levelField = new JTextField(8);
levelField.setMaximumSize(new Dimension(
Integer.MAX_VALUE, levelField.getPreferredSize().height));
// validator for the level entry field
levelField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) { }
public void insertUpdate(DocumentEvent e) { validate(); }
public void removeUpdate(DocumentEvent e) { validate(); }
private final String pattern =
"^(\\d*[1-9]\\d*(/\\d*[1-9]\\d*|\\.\\d*)?|0*\\.\\d*[1-9]\\d*)$";
private void validate() {
// valid entries match the pattern and aren't already in the list
final String text = levelField.getText();
addButton.setEnabled(text.matches(pattern) &&
!z.state.getLevels().contains(parseLevel(text)));
}
});
// rely on addButton to do the validation
levelField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (addButton.isEnabled()) addLevel();
}
});
addBox.add(levelField);
leftBox.add(addBox);
final Box buttonBox = Box.createHorizontalBox();
// Remove button
removeButton = new JButton(Resources.getString(Resources.REMOVE));
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// get the zoom level index to be removed
final int rm_level = levelList.getSelectedIndex();
final List<Double> l = z.state.getLevels();
final int new_init;
if (rm_level == z.state.getInitialLevel()) {
// we're deleting the initial level; keep it the same position
new_init = Math.min(rm_level, z.state.getLevelCount()-2);
l.remove(rm_level);
}
else {
// find the new index of the old initial level
final Double old_init_val = l.get(z.state.getInitialLevel());
l.remove(rm_level);
new_init = l.indexOf(old_init_val);
}
// adjust the state
z.state = new State(l, new_init);
z.init();
model.updateModel();
// adjust the selection
levelList.setSelectedIndex(
Math.max(Math.min(rm_level, l.size()-1), 0));
updateButtons();
}
});
buttonBox.add(removeButton);
// Set Initial button
initialButton = new JButton("Set Initial");
initialButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// set the new initial scale level
final int i = levelList.getSelectedIndex();
z.state = new State(z.state.getLevels(), i);
z.init();
model.updateModel();
updateButtons();
}
});
buttonBox.add(initialButton);
leftBox.add(buttonBox);
final JLabel explanation =
new JLabel("An '*' indicates the initial zoom level.");
explanation.setAlignmentX(JLabel.CENTER_ALIGNMENT);
leftBox.add(
Box.createVerticalStrut(explanation.getPreferredSize().height));
leftBox.add(explanation);
leftBox.add(
Box.createVerticalStrut(explanation.getPreferredSize().height));
// level list
model = new LevelModel();
levelList = new JList(model);
levelList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
levelList.setSelectedIndex(0);
levelList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) { updateButtons(); }
});
final JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
pane.setLeftComponent(leftBox);
pane.setRightComponent(new JScrollPane(levelList));
panel.add(pane);
panel.setBorder(new TitledBorder(name));
updateButtons();
}
/**
* Parse a <code>String</code> to a <code>double</code>.
* Accepts fractions as "n/d".
*/
protected double parseLevel(String text) {
final String[] s = text.split("/");
try {
return s.length > 1 ?
Double.parseDouble(s[0])/Double.parseDouble(s[1]) :
Double.parseDouble(s[0]);
}
catch (NumberFormatException ex) {
// should not happen, text already validated
ErrorDialog.bug(ex);
}
return 0.0;
}
/**
* Add a level to the level list. This method expects that the
* intput has already been validated.
*/
protected void addLevel() {
// get the initial scale level
final List<Double> l = z.state.getLevels();
final Double old_init_val = l.get(z.state.getInitialLevel());
// add the new scale level
final double new_level_val = parseLevel(levelField.getText());
l.add(new_level_val);
Collections.sort(l);
// find the initial scale index
final int new_init = l.indexOf(old_init_val);
// adjust the state
z.state = new State(l, new_init);
z.init();
model.updateModel();
// adjust the selection
final int new_level = l.indexOf(new_level_val);
levelList.setSelectedIndex(new_level);
levelField.setText("");
updateButtons();
}
/**
* Ensures that the buttons are properly en- or disabled.
*/
protected void updateButtons() {
removeButton.setEnabled(z.state.getLevelCount() > 1);
initialButton.setEnabled(
levelList.getSelectedIndex() != z.state.getInitialLevel());
}
/**
* A {@link ListModel} built on the {@link State}.
*/
protected class LevelModel extends AbstractListModel {
private static final long serialVersionUID = 1L;
public void updateModel() {
fireContentsChanged(this, 0, z.state.getLevelCount()-1);
}
public Object getElementAt(int i) {
return z.state.getLevels().get(i) +
(z.state.getInitialLevel() == i ? " *" : "");
}
public int getSize() {
return z.state.getLevelCount();
}
}
@Override
public Component getControls() {
return panel;
}
@Override
public void setValue(Object o) {
}
@Override
public void setValue(String s) {
}
@Override
public String getValueString() {
return null;
}
}
protected static final String ZOOM_START = "zoomStart"; //$NON-NLS-1$
protected static final String ZOOM_LEVELS = "zoomLevels"; //$NON-NLS-1$
protected static final String ZOOM_IN = "zoomInKey"; //$NON-NLS-1$
protected static final String IN_TOOLTIP = "inTooltip"; //$NON-NLS-1$
protected static final String IN_BUTTON_TEXT = "inButtonText"; //$NON-NLS-1$
protected static final String IN_ICON_NAME = "inIconName"; //$NON-NLS-1$
protected static final String IN_DEFAULT_ICON = "/images/zoomIn.gif"; //$NON-NLS-1$
protected static final String ZOOM_PICK = "zoomPickKey"; //$NON-NLS-1$
protected static final String PICK_TOOLTIP = "pickTooltip"; //$NON-NLS-1$
protected static final String PICK_BUTTON_TEXT = "pickButtonText"; //$NON-NLS-1$
protected static final String PICK_ICON_NAME = "pickIconName"; //$NON-NLS-1$
protected static final String PICK_DEFAULT_ICON = "/images/zoom.png"; //$NON-NLS-1$
protected static final String ZOOM_OUT = "zoomOutKey"; //$NON-NLS-1$
protected static final String OUT_TOOLTIP = "outTooltip"; //$NON-NLS-1$
protected static final String OUT_BUTTON_TEXT = "outButtonText"; //$NON-NLS-1$
protected static final String OUT_ICON_NAME = "outIconName"; //$NON-NLS-1$
protected static final String OUT_DEFAULT_ICON = "/images/zoomOut.gif"; //$NON-NLS-1$
public void addTo(Buildable b) {
GameModule.getGameModule().getGameState().addGameComponent(this);
map = (Map) b;
validator = new SingleChildInstance(map, getClass());
map.setZoomer(this);
map.getToolBar().add(zoomInButton);
map.getToolBar().add(zoomPickButton);
map.getToolBar().add(zoomOutButton);
}
public String getAttributeValueString(String key) {
if (ZOOM_START.equals(key)) {
// Notes:
// 1. ZOOM_START is one-based, not zero-based.
// 2. The levels in state run from zoomed out to zoomed in,
// while the levels coming from outside Zoomer run from
// zoomed in to zoomed out. Hence we reverse the initial
// zoom level being returned here.
return String.valueOf(state.getLevelCount() - state.getInitialLevel());
}
else if (ZOOM_LEVELS.equals(key)) {
final List<Double> levels = state.getLevels();
final String[] s = new String[levels.size()];
for (int i = 0; i < s.length; ++i) {
s[i] = levels.get(i).toString();
}
return StringArrayConfigurer.arrayToString(s);
}
else if (zoomInButton.getAttributeValueString(key) != null) {
return zoomInButton.getAttributeValueString(key);
}
else if (zoomPickButton.getAttributeValueString(key) != null) {
return zoomPickButton.getAttributeValueString(key);
}
else {
return zoomOutButton.getAttributeValueString(key);
}
}
public void setAttribute(String key, Object val) {
if (ZOOM_START.equals(key)) {
if (val instanceof String) {
val = new Integer((String) val);
}
if (val != null) {
// Notes:
// 1. ZOOM_START is one-based, not zero-based.
// 2. The levels in state run from zoomed out to zoomed in,
// while the levels coming from outside Zoomer run from
// zoomed in to zoomed out. Hence we reverse the initial
// zoom level being set here.
final List<Double> levels = state.getLevels();
final int initial =
Math.max(0, Math.min(levels.size()-1, levels.size()-(Integer) val));
state = new State(levels, initial);
if (deprecatedFactor > 0 && deprecatedMax > 0) {
state = new State(levels, initial-1);
// zero these so this block is run only once
deprecatedFactor = 0.0;
deprecatedMax = 0;
}
init();
}
}
else if (ZOOM_LEVELS.equals(key)) {
if (val instanceof String) {
val = StringArrayConfigurer.stringToArray((String) val);
}
if (val != null) {
// dump into a set to remove duplicates
final HashSet<Double> levels = new HashSet<Double>();
for (String s : (String[]) val) {
levels.add(Double.valueOf(s));
}
state = new State(levels,
Math.min(state.getInitialLevel(), levels.size()-1));
init();
}
}
else if (FACTOR.equals(key)) { // deprecated key
if (val instanceof String) {
val = new Double((String) val);
}
if (val != null) {
deprecatedFactor = (Double) val;
if (deprecatedFactor > 0 && deprecatedMax > 0) {
adjustStateForFactorAndMax();
}
}
}
else if (MAX.equals(key)) { // deprecated key
if (val instanceof String) {
val = new Integer((String) val);
}
if (val != null) {
deprecatedMax = (Integer) val;
if (deprecatedFactor > 0 && deprecatedMax > 0) {
adjustStateForFactorAndMax();
}
}
}
else {
// FIXME: does having this as an extremal case cause weird behavior for
// unrecognized keys?
zoomInButton.setAttribute(key, val);
zoomPickButton.setAttribute(key, val);
zoomOutButton.setAttribute(key, val);
}
}
// begin deprecated keys
private static final String FACTOR = "factor"; //$NON-NLS-1$
private static final String MAX = "max"; //$NON-NLS-1$
private int deprecatedMax = -1;
private double deprecatedFactor = -1.0;
private void adjustStateForFactorAndMax() {
final double[] levels = new double[deprecatedMax+1];
for (int i = 0; i < levels.length; ++i)
levels[i] = Math.pow(deprecatedFactor, -(i-1));
state = new State(levels, state.getInitialLevel());
init();
}
// end deprecated keys
public Class[] getAllowableConfigureComponents() {
return new Class[0];
}
public void removeFrom(Buildable b) {
map = (Map) b;
map.setZoomer(null);
map.getToolBar().remove(zoomInButton);
map.getToolBar().remove(zoomPickButton);
map.getToolBar().remove(zoomOutButton);
}
public double getZoomFactor() {
return state.getZoom();
}
protected Point getMapCenter() {
final Rectangle r = map.getView().getVisibleRect();
return map.mapCoordinates(new Point(r.x + r.width/2, r.y + r.height/2));
}
protected void updateZoomer(Point center) {
zoomInButton.setEnabled(state.hasHigherLevel());
zoomOutButton.setEnabled(state.hasLowerLevel());
zoomMenu.updateZoom();
final Dimension d = map.getPreferredSize();
map.getView().setBounds(0,0,d.width,d.height); // calls revalidate()
map.centerAt(center);
map.repaint(true);
}
public void setZoomLevel(int l) {
final Point center = getMapCenter();
state.setLevel(l);
updateZoomer(center);
}
public void setZoomFactor(double z) {
final Point center = getMapCenter();
state.setZoom(z);
updateZoomer(center);
}
public void zoomIn() {
if (state.hasHigherLevel()) {
final Point center = getMapCenter();
state.higherLevel();
updateZoomer(center);
}
}
public void zoomOut() {
if (state.hasLowerLevel()) {
final Point center = getMapCenter();
state.lowerLevel();
updateZoomer(center);
}
}
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Map.htm", "Zoom"); //$NON-NLS-1$ //$NON-NLS-2$
}
public void setup(boolean gameStarting) {
if (!gameStarting) {
zoomInButton.setEnabled(state.hasHigherLevel());
zoomOutButton.setEnabled(state.hasLowerLevel());
}
zoomPickButton.setEnabled(gameStarting);
}
public Command getRestoreCommand() {
return null;
}
/**
* The menu which displays zoom levels.
*
* @author Joel Uckelman
* @since 3.1.0
*/
protected class ZoomMenu extends JPopupMenu implements ActionListener {
protected final JRadioButtonMenuItem other;
protected final JPopupMenu.Separator sep;
protected final ButtonGroup bg;
private static final String OTHER = "Other...";
private static final String FIT_WIDTH = "Fit Width";
private static final String FIT_HEIGHT = "Fit Height";
private static final String FIT_VISIBLE = "Fit Visible";
private static final long serialVersionUID = 1L;
public ZoomMenu() {
super();
sep = new JPopupMenu.Separator();
add(sep);
bg = new ButtonGroup();
other = new JRadioButtonMenuItem(
Resources.getString("Zoomer.ZoomMenu.other"));
other.setActionCommand(OTHER);
other.addActionListener(this);
bg.add(other);
add(other);
addSeparator();
final JMenuItem fw = new JMenuItem(
Resources.getString("Zoomer.ZoomMenu.fit_width"));
fw.setActionCommand(FIT_WIDTH);
fw.addActionListener(this);
add(fw);
final JMenuItem fh = new JMenuItem(
Resources.getString("Zoomer.ZoomMenu.fit_height"));
fh.setActionCommand(FIT_HEIGHT);
fh.addActionListener(this);
add(fh);
final JMenuItem fv = new JMenuItem(
Resources.getString("Zoomer.ZoomMenu.fit_visible"));
fv.setActionCommand(FIT_VISIBLE);
fv.addActionListener(this);
add(fv);
}
public void initZoomItems() {
while (getComponent(0) != sep) remove(0);
final List<Double> levels = state.getLevels();
for (int i = 0; i < levels.size(); ++i) {
final String zs = Long.toString(Math.round(levels.get(i)*100)) + "%";
final JMenuItem item = new JRadioButtonMenuItem(zs);
item.setActionCommand(Integer.toString(i));
item.addActionListener(this);
bg.add(item);
insert(item, 0);
}
((JRadioButtonMenuItem) getComponent(
state.getLevelCount() - state.getLevel() - 1)).setSelected(true);
}
public void actionPerformed(ActionEvent a) {
try {
setZoomLevel(Integer.parseInt(a.getActionCommand()));
return;
}
catch (NumberFormatException e) {
}
final String cmd = a.getActionCommand();
if (OTHER.equals(cmd)) {
final ZoomDialog dialog = new ZoomDialog((Frame)
SwingUtilities.getAncestorOfClass(Frame.class, map.getView()),
Resources.getString("Zoomer.ZoomDialog.title"), true);
dialog.setVisible(true);
final double z = dialog.getResult()/100.0;
if (z > 0 && z != state.getZoom()) {
setZoomFactor(z);
}
}
// FIXME: should be map.getSize() for consistency?
else if (FIT_WIDTH.equals(cmd)) {
final Dimension vd = map.getView().getVisibleRect().getSize();
final Dimension md = map.mapSize();
setZoomFactor(vd.getWidth()/md.getWidth());
}
else if (FIT_HEIGHT.equals(cmd)) {
final Dimension vd = map.getView().getVisibleRect().getSize();
final Dimension md = map.mapSize();
setZoomFactor(vd.getHeight()/md.getHeight());
}
else if (FIT_VISIBLE.equals(cmd)) {
final Dimension vd = map.getView().getVisibleRect().getSize();
final Dimension md = map.mapSize();
setZoomFactor(Math.min(vd.getWidth()/md.getWidth(),
vd.getHeight()/md.getHeight()));
}
else {
// this should not happen!
assert false;
}
}
public void updateZoom() {
if (state.atLevel()) {
((JRadioButtonMenuItem) getComponent(
state.getLevelCount() - state.getLevel() - 1)).setSelected(true);
}
else {
other.setSelected(true);
}
}
}
/**
* The dialog for setting custom zoom levels.
*
* @author Joel Uckelman
* @since 3.1.0
*/
protected class ZoomDialog extends JDialog
implements ActionListener,
ChangeListener {
protected double result;
protected final JSpinner ratioNumeratorSpinner;
protected final JSpinner ratioDenominatorSpinner;
protected final JSpinner percentSpinner;
protected final SpinnerNumberModel ratioNumeratorModel;
protected final SpinnerNumberModel ratioDenominatorModel;
protected final SpinnerNumberModel percentModel;
protected final JButton okButton;
private static final long serialVersionUID = 1L;
public ZoomDialog(Frame owner, String title, boolean modal) {
super(owner, title, modal);
final int hsep = 5;
final JPanel controlsPane = new JPanel(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
final Insets linset = new Insets(0, 0, 11, 11);
final Insets dinset = new Insets(0, 0, 0, 0);
final JLabel ratioLabel = new JLabel(
Resources.getString("Zoomer.ZoomDialog.zoom_ratio"));
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
c.insets = linset;
c.anchor = GridBagConstraints.LINE_START;
controlsPane.add(ratioLabel, c);
final Box ratioBox = new Box(BoxLayout.X_AXIS);
ratioLabel.setLabelFor(ratioBox);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1;
c.weighty = 0;
c.insets = dinset;
c.anchor = GridBagConstraints.LINE_START;
controlsPane.add(ratioBox, c);
ratioNumeratorModel = new SpinnerNumberModel(1, 1, 256, 1);
ratioNumeratorSpinner = new JSpinner(ratioNumeratorModel);
ratioNumeratorSpinner.addChangeListener(this);
ratioBox.add(ratioNumeratorSpinner);
ratioBox.add(Box.createHorizontalStrut(hsep));
final JLabel ratioColon = new JLabel(":");
ratioBox.add(ratioColon);
ratioBox.add(Box.createHorizontalStrut(hsep));
ratioDenominatorModel = new SpinnerNumberModel(1, 1, 256, 1);
ratioDenominatorSpinner = new JSpinner(ratioDenominatorModel);
ratioDenominatorSpinner.addChangeListener(this);
ratioBox.add(ratioDenominatorSpinner);
final JLabel percentLabel = new JLabel(
Resources.getString("Zoomer.ZoomDialog.zoom_percent"));
c.gridx = 0;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.insets = linset;
c.anchor = GridBagConstraints.LINE_START;
controlsPane.add(percentLabel, c);
final Box percentBox = new Box(BoxLayout.X_AXIS);
c.gridx = 1;
c.gridy = 1;
c.weightx = 1;
c.weighty = 0;
c.insets = dinset;
c.anchor = GridBagConstraints.LINE_START;
controlsPane.add(percentBox, c);
percentModel =
new SpinnerNumberModel(state.getZoom()*100.0, 0.39, 25600.0, 10.0);
percentSpinner = new JSpinner(percentModel);
percentLabel.setLabelFor(percentSpinner);
percentSpinner.addChangeListener(this);
percentBox.add(percentSpinner);
updateRatio();
percentBox.add(Box.createHorizontalStrut(hsep));
final JLabel percentSign = new JLabel("%");
percentBox.add(percentSign);
// buttons
final Box buttonBox = new Box(BoxLayout.X_AXIS);
buttonBox.add(Box.createHorizontalGlue());
okButton = new JButton(Resources.getString("General.ok"));
okButton.addActionListener(this);
getRootPane().setDefaultButton(okButton);
buttonBox.add(okButton);
buttonBox.add(Box.createHorizontalStrut(hsep));
final JButton cancelButton = new JButton(
Resources.getString("General.cancel"));
cancelButton.addActionListener(this);
buttonBox.add(cancelButton);
final Dimension okDim = okButton.getPreferredSize();
final Dimension cancelDim = cancelButton.getPreferredSize();
final Dimension buttonDimension = new Dimension(
Math.max(okDim.width, cancelDim.width),
Math.max(okDim.height, cancelDim.height));
okButton.setPreferredSize(buttonDimension);
cancelButton.setPreferredSize(buttonDimension);
final JComponent contentPane = (JComponent) getContentPane();
contentPane.setBorder(new EmptyBorder(12, 12, 11, 11));
contentPane.setLayout(new BorderLayout(0, 11));
contentPane.add(controlsPane, BorderLayout.CENTER);
contentPane.add(buttonBox, BorderLayout.PAGE_END);
setResizable(false);
pack();
}
public double getResult() {
return result;
}
public void actionPerformed(ActionEvent e) {
result = e.getSource() == okButton ?
percentModel.getNumber().doubleValue() : 0.0;
setVisible(false);
}
public void stateChanged(ChangeEvent e) {
if (e.getSource() == ratioNumeratorSpinner ||
e.getSource() == ratioDenominatorSpinner) {
updatePercent();
}
else if (e.getSource() == percentSpinner) {
updateRatio();
}
}
private void updatePercent() {
// disconnect listener to prevent circularity
percentSpinner.removeChangeListener(this);
percentModel.setValue(new Double(
ratioNumeratorModel.getNumber().doubleValue() /
ratioDenominatorModel.getNumber().doubleValue() * 100.0));
percentSpinner.addChangeListener(this);
}
private void updateRatio() {
// Warning: Heavy maths ahead!
// This algorithm borrowed from gimpzoommodel.c in LIBGIMP:
// for a discussion of calculating continued fractions by convergeants.
double z = percentModel.getNumber().doubleValue() / 100.0;
// we want symmetric behavior, so find reciprocal when zooming out
boolean swapped = false;
if (z < 1.0) {
z = 1.0/z;
swapped = true;
}
// calculate convergeants
int p0 = 1;
int q0 = 0;
int p1 = (int)Math.floor(z);
int q1 = 1;
int p2;
int q2;
double r = z - p1;
double next_cf;
while (Math.abs(r) >= 0.0001 &&
Math.abs((double)p1/q1 - z) > 0.0001) {
r = 1.0/r;
next_cf = Math.floor(r);
p2 = (int)(next_cf * p1 + p0);
q2 = (int)(next_cf * q1 + q0);
// We limit the numerator and denominator to be 256 or less,
// and also exclude absurd ratios like 170:171.
if (p2 > 256 || q2 > 256 || (p2 > 1 && q2 > 1 && p2 * q2 > 200))
break;
// remember the last two fractions
p0 = p1;
p1 = p2;
q0 = q1;
q1 = q2;
r -= next_cf;
}
z = (double)p1/q1;
// hard upper and lower bounds for zoom ratio
if (z > 256.0) {
p1 = 256;
q1 = 1;
}
else if (z < 1.0/256.0) {
p1 = 1;
q1 = 256;
}
if (swapped) {
final int tmp = p1;
p1 = q1;
q1 = tmp;
}
// disconnect listeners to prevent circularity
ratioNumeratorSpinner.removeChangeListener(this);
ratioDenominatorSpinner.removeChangeListener(this);
ratioNumeratorModel.setValue(new Integer(p1));
ratioDenominatorModel.setValue(new Integer(q1));
ratioNumeratorSpinner.addChangeListener(this);
ratioDenominatorSpinner.addChangeListener(this);
}
}
}
|
package org.epics.pvmanager;
/**
* Called by the ChannelHandler once a write is completed.
*
* @author carcassi
*/
public interface ChannelWriteCallback {
/**
* Called when a write is completed. If completed without error,
* the argument is null.
*
* @param ex the exception if the write failed, null otherwise
*/
public void channelWritten(Exception ex);
}
|
package jp.ac.kansai_u.kutc.firefly.packetcam;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity
{
private Camera camera;
private OverLayView overlay;
private boolean mIsTake = false;
// FlashONOFF
private boolean status = false;
// INOUT
private boolean inoutstatus = false;
// heightwidth
Size picSize = null;
// Size preSize = null;
private static String FOLDER_PATH = null;
private static final String TAG = "MainActivity";
private boolean switchEffect=false;
@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
getWindow ().addFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature (Window.FEATURE_NO_TITLE);
setContentView (R.layout.activity_main);
SurfaceView surfaceView = (SurfaceView) findViewById (R.id.surfaceView1);
final SurfaceHolder holder = surfaceView.getHolder ();
holder.addCallback (surfaceListener);
// 3.0Android
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
holder.setType (SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
overlay = new OverLayView (this);
FrameLayout flame = (FrameLayout) findViewById (R.id.frameLayout1);
flame.addView (overlay);
// addContentView (overlay, new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// Button flashBtn = (Button) findViewById (R.id.button1);
// flashBtn.setOnClickListener (new OnClickListener ()
// @Override
// public void onClick (View arg0)
// // TODO
// if (status == false)
// Camera.Parameters parameters = camera.getParameters ();
// parameters.setFlashMode (Camera.Parameters.FLASH_MODE_ON);
// camera.setParameters (parameters);
// status = true;
// else
// Camera.Parameters parameters = camera.getParameters ();
// parameters.setFlashMode (Camera.Parameters.FLASH_MODE_OFF);
// camera.setParameters (parameters);
// status = false;
// Button resolutionBtn = (Button) findViewById (R.id.button3);
// resolutionBtn.setOnClickListener (new OnClickListener ()
// @Override
// public void onClick (View v)
// final List <Size> supportedPictureSize = camera.getParameters ().getSupportedPictureSizes ();
// List <Size> supportedPreviewSize = camera.getParameters ().getSupportedPreviewSizes ();
// int numPicItem = supportedPictureSize.size ();
// // int numPreItem = supportedPreviewSize.size();
// String[] picHeight = new String[numPicItem];
// String[] picWidth = new String[numPicItem];
// final String[] pic = new String[numPicItem];
// // // String[] preHeight = new String[numPreItem];
// // // String[] preWidth = new String[numPreItem];
// // // final String[] pre = new String[numPreItem];
// for (int i = 0; i < supportedPictureSize.size (); i++)
// picSize = supportedPictureSize.get (i);
// picHeight[i] = String.valueOf (picSize.height);
// picWidth[i] = String.valueOf (picSize.width);
// // preSize = supportedPreviewSize.get(i);
// // preHeight[i] = String.valueOf(preSize.height);
// // preWidth[i] = String.valueOf(preSize.width);
// // pic[i] = "Height: " + picHeight[i] + "Width: "
// // + picWidth[i];
// pic[i] = "Width : " + picWidth[i] + "Height : " + picHeight[i];
// // pic[i] = "PicHeight: " + picHeight[i] + "PicWidth: " +
// // picWidth[i] + "\n"
// // + "PreHeight: " + preHeight[i] + "PreWidth: " +
// // preWidth[i];
// AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this);
// builder.setTitle ("");
// builder.setItems (pic, new DialogInterface.OnClickListener ()
// public void onClick (DialogInterface dialog, int which)
// Camera.Parameters parameter = camera.getParameters ();
// picSize = supportedPictureSize.get (which);
// parameter.setPictureSize (picSize.width, picSize.height);
// // parameter.setPreviewSize(preSize.width,
// // preSize.height);
// camera.setParameters (parameter);
// builder.show ();
ImageButton INOUTBtn = (ImageButton) findViewById (R.id.inout);
INOUTBtn.setOnClickListener (new OnClickListener ()
{
@TargetApi (Build.VERSION_CODES.GINGERBREAD)
public void onClick (View v)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD)
{
return;
}
int numberOfCameras = Camera.getNumberOfCameras ();
Toast.makeText (MainActivity.this, "NumberOfCameras :" + numberOfCameras, Toast.LENGTH_SHORT).show ();
if (numberOfCameras == 1)
{
Toast.makeText (MainActivity.this, "Camera", Toast.LENGTH_SHORT).show ();
return;
}
if (camera != null)
{
camera.release ();
}
if (!inoutstatus)
{
camera = Camera.open (1);
inoutstatus = true;
}
else
{
camera = Camera.open (0);
inoutstatus = false;
}
try
{
camera.setPreviewDisplay (holder);
Camera.Parameters param = camera.getParameters();
List <Size> previewSizes = camera.getParameters().getSupportedPreviewSizes();
Size size = previewSizes.get (0);
param.setPreviewSize (size.width, size.height);
camera.setParameters (param);
holder.setFixedSize (size.width, size.height);
}
catch (Exception e)
{
e.printStackTrace ();
}
camera.startPreview ();
}
});
ImageButton shutterBtn = (ImageButton) findViewById(R.id.shutter);
shutterBtn.setOnClickListener (new OnClickListener()
{
@Override
public void onClick (View v)
{
if (camera != null)
{
if (!mIsTake)
{
Toast.makeText (MainActivity.this, "", Toast.LENGTH_SHORT).show();
mIsTake = true;
camera.autoFocus (mAutoFocusListener);
}
}
}
});
// TODO: B Z
ImageButton settingBtn = (ImageButton) findViewById (R.id.setting);
settingBtn.setOnClickListener (new OnClickListener()
{
@Override
public void onClick (View v)
{
CharSequence[] conf = { "", "", "" };
final AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this);
builder.setTitle ("");
builder.setItems (conf, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
if (which == 0)
{
CharSequence[] conf1 = { "", "" };
AlertDialog.Builder builder1 = new AlertDialog.Builder (MainActivity.this);
builder1.setTitle ("");
builder1.setItems (conf1, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
if (which == 0)
{
}
if (which == 1)
{
}
}
});
builder1.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
//To change body of implemented methods use File | Settings | File Templates.
builder.show();
}
});
builder1.show ();
}
if (which == 1)
{
final List <Size> supportedPictureSize = camera.getParameters ().getSupportedPictureSizes ();
int numPicItem = supportedPictureSize.size ();
String[] picHeight = new String[numPicItem];
String[] picWidth = new String[numPicItem];
final String[] pic = new String[numPicItem];
for (int i = 0; i < supportedPictureSize.size (); i++)
{
picSize = supportedPictureSize.get (i);
picHeight[i] = String.valueOf (picSize.height);
picWidth[i] = String.valueOf (picSize.width);
int gcd = GetGCD.getGCD (picSize.width, picSize.height);
String aspWidth = String.valueOf (picSize.width / gcd);
String aspHeight = String.valueOf (picSize.height / gcd);
pic[i] = picWidth[i] + " : " + picHeight[i] + "" + aspWidth + " " + aspHeight + "";
}
AlertDialog.Builder builder2 = new AlertDialog.Builder (MainActivity.this);
builder2.setTitle ("");
builder2.setItems (pic, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
Camera.Parameters parameter = camera.getParameters ();
picSize = supportedPictureSize.get (which);
Toast.makeText (MainActivity.this, "" + pic[which] + "", Toast.LENGTH_SHORT).show ();
parameter.setPictureSize (picSize.width, picSize.height);
camera.setParameters (parameter);
}
});
builder2.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
//To change body of implemented methods use File | Settings | File Templates.
builder.show();
}
});
builder2.show();
}
if (which == 2)
{
CharSequence[] conf3 = { "", "", "OFF" };
AlertDialog.Builder builder3 = new AlertDialog.Builder (MainActivity.this);
builder3.setTitle ("");
builder3.setItems (conf3, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
if (which == 0)
{
Camera.Parameters parameters = camera.getParameters ();
parameters.setFlashMode (Camera.Parameters.FLASH_MODE_ON);
camera.setParameters (parameters);
Toast.makeText (MainActivity.this, "Flash", Toast.LENGTH_SHORT).show ();
}
if (which == 1)
{
Camera.Parameters parameters = camera.getParameters ();
parameters.setFlashMode (Camera.Parameters.FLASH_MODE_AUTO);
camera.setParameters (parameters);
Toast.makeText (MainActivity.this, "Flash", Toast.LENGTH_SHORT).show();
}
if (which == 2)
{
// OFF
Camera.Parameters parameters = camera.getParameters ();
parameters.setFlashMode (Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters (parameters);
Toast.makeText (MainActivity.this, "FlashOFF", Toast.LENGTH_SHORT).show();
}
}
});
builder3.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
//To change body of implemented methods use File | Settings | File Templates.
builder.show();
}
});
builder3.show ();
}
}
});
builder.show ();
}
});
final ImageButton effectBtn = (ImageButton) findViewById(R.id.effect);
effectBtn.setOnClickListener (new OnClickListener()
{
@Override
public void onClick (View v)
{
if (!switchEffect){
effectBtn.setImageResource(R.drawable.effect_on);
switchEffect=true;
}else{
effectBtn.setImageResource(R.drawable.effect_off);
switchEffect=false;
}
}
});
// surfaceView.setOnTouchListener (new OnTouchListener ()
// @Override
// public boolean onTouch (View v, MotionEvent event)
// if (event.getAction () == MotionEvent.ACTION_DOWN)
// if (camera != null)
// if (!mIsTake)
// Toast.makeText (MainActivity.this, "", Toast.LENGTH_SHORT).show ();
// mIsTake = true;
// camera.autoFocus (mAutoFocusListener);
// return true;
}
private SurfaceHolder.Callback surfaceListener = new SurfaceHolder.Callback ()
{
/**
* SurfaceView
*/
public void surfaceCreated (SurfaceHolder holder)
{
camera = Camera.open ();
try
{
camera.setPreviewDisplay (holder);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
/**
* SurfaceView
*/
public void surfaceDestroyed (SurfaceHolder holder)
{
camera.release ();
camera = null;
}
/**
* SurfaceView
*/
public void surfaceChanged (SurfaceHolder holder, int format, int width, int height)
{
/**
* startPreview
*/
try
{
Camera.Parameters parameters = camera.getParameters ();
// Size size = getOptimalPreviewSize (parameters);
List <Size> previewSizes = camera.getParameters ().getSupportedPreviewSizes ();
Size size = previewSizes.get (0);
parameters.setPreviewSize (size.width, size.height);
camera.setParameters (parameters);
holder.setFixedSize (size.width, size.height);
// List <Size> supportedSizes =
// Reflect.getSuportedPreviewSizes(parameters);
// if (supportedSizes != null && supportedSizes.size() > 0)
// Log.d(TAG, "supportedSizeIsNotNull");
// Size size = supportedSizes.get(0);
// Log.d(TAG, "sizeHeight = " + size.height + "sizeWidth = " +
// size.width);
// parameters.setPreviewSize(size.width, size.height);
// camera.setParameters(parameters);
camera.startPreview ();
}
catch (Exception e)
{
e.printStackTrace ();
String a = e.getMessage ();
Log.d (TAG, a);
}
}
};
private Size getOptimalPreviewSize (Parameters params)
{
Size optimalSize = null;
List <Size> sizes = params.getSupportedPreviewSizes ();
float horizontalViewAngle = params.getHorizontalViewAngle ();
float verticalViewAngle = params.getVerticalViewAngle ();
double targetRatio = (double) horizontalViewAngle / verticalViewAngle;
double minDiff = Double.MAX_VALUE;
for (Size size : sizes)
{
double ratio = (double) size.width / size.height;
double tempDiff = Math.abs (targetRatio - ratio);
if (tempDiff <= minDiff)
{
minDiff = tempDiff;
optimalSize = size;
}
}
return optimalSize;
}
private Camera.AutoFocusCallback mAutoFocusListener = new Camera.AutoFocusCallback ()
{
@Override
public void onAutoFocus (boolean success, Camera camera)
{
camera.takePicture (null, null, pictureListener);
}
};
private Camera.ShutterCallback shutterListener = new Camera.ShutterCallback ()
{
public void onShutter ()
{
if (camera != null)
{
if (!mIsTake)
{
Toast.makeText (MainActivity.this, "", Toast.LENGTH_SHORT).show ();
mIsTake = true;
camera.autoFocus (mAutoFocusListener);
}
}
}
};
private Camera.PictureCallback pictureListener = new Camera.PictureCallback ()
{
public void onPictureTaken (byte[] data, Camera camera)
{
if (data == null)
{
return;
}
if (!createFolder ())
{
Toast.makeText (MainActivity.this, "failure", Toast.LENGTH_SHORT).show ();
}
else
{
Toast.makeText (MainActivity.this, "Success", Toast.LENGTH_SHORT).show ();
}
Toast.makeText (MainActivity.this, "totalMemory" + String.valueOf (Runtime.getRuntime ().totalMemory ()), Toast.LENGTH_LONG).show ();
Toast.makeText (MainActivity.this, "maxMemory" + String.valueOf (Runtime.getRuntime ().maxMemory ()), Toast.LENGTH_LONG).show ();
Toast.makeText (MainActivity.this, "freeMemory" + String.valueOf (Runtime.getRuntime ().freeMemory ()), Toast.LENGTH_LONG).show ();
Log.d (TAG, "totalMemory" + String.valueOf (Runtime.getRuntime ().totalMemory ()));
Log.d (TAG, "maxMemory" + String.valueOf (Runtime.getRuntime ().maxMemory ()));
Log.d (TAG, "freeMemory" + String.valueOf (Runtime.getRuntime ().freeMemory ()));
try
{
// createBitmap
BitmapFactory.Options options = new BitmapFactory.Options ();
options.inPurgeable = true;
// Bitmap cameraBitmap = BitmapFactory.decodeByteArray(data, 0,
// data.length, null);
Bitmap cameraBitmap = BitmapFactory.decodeByteArray (data, 0, data.length, options);
// view
Bitmap overlayBitmap = overlay.getDrawingCache ();
Bitmap offBitmap = Bitmap.createBitmap (cameraBitmap.getWidth (), cameraBitmap.getHeight (), Bitmap.Config.ARGB_8888);
Canvas offScreen = new Canvas (offBitmap);
offScreen.drawBitmap (cameraBitmap, null, new Rect (0, 0, cameraBitmap.getWidth (), cameraBitmap.getHeight ()), null);
offScreen.drawBitmap (overlayBitmap, null, new Rect (0, 0, cameraBitmap.getWidth (), cameraBitmap.getHeight ()), null);
// offBitmap
Calendar cal = Calendar.getInstance ();
SimpleDateFormat sf = new SimpleDateFormat ("yyyyMMdd_HHmmss");
String imgPath = FOLDER_PATH + File.separator + sf.format (cal.getTime ()) + ".jpg";
FileOutputStream fos;
fos = new FileOutputStream (imgPath, true);
// fos.write (data);
offBitmap.compress (CompressFormat.JPEG, 100, fos);
fos.close ();
// Android
registAndroidDB (imgPath);
}
catch (Exception e)
{
Toast.makeText (MainActivity.this, e.getMessage (), Toast.LENGTH_SHORT).show ();
}
catch (OutOfMemoryError e)
{
Log.d (TAG, "OutOfMemory");
Toast.makeText (MainActivity.this, ",", Toast.LENGTH_SHORT).show ();
}
camera.startPreview ();
mIsTake = false;
}
};
/**
*
*
* @return truefalse
*/
private boolean createFolder ()
{
String status = Environment.getExternalStorageState ();
if (!isSdCardMounted (status))
{
Toast.makeText (this, "SD", Toast.LENGTH_SHORT).show ();
return false;
}
String SD_PATH = Environment.getExternalStorageDirectory ().getPath ();
FOLDER_PATH = SD_PATH + File.separator + getString (R.string.app_name);
File file = new File (FOLDER_PATH);
try
{
if (!file.exists ())
{
file.mkdirs ();
}
}
catch (Exception e)
{
e.printStackTrace ();
return false;
}
return true;
}
/**
* SD
*
* @param status
* Environment.getExternalStorageStateString
* @return true, false
*/
private boolean isSdCardMounted (String status)
{
return status.equals (Environment.MEDIA_MOUNTED);
}
/**
* Android
*
* @param path
*
*/
private void registAndroidDB (String path)
{
ContentValues values = new ContentValues ();
ContentResolver contentResolver = MainActivity.this.getContentResolver ();
values.put (Images.Media.MIME_TYPE, "image/jpeg");
values.put ("_data", path);
contentResolver.insert (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
// TODO: B Z
@Override
public boolean dispatchKeyEvent (KeyEvent event)
{
int nowZoom;
Camera.Parameters parameter;
List <Size> previewSizes = camera.getParameters ().getSupportedPreviewSizes ();
switch (event.getAction ())
{
case KeyEvent.ACTION_DOWN:
switch (event.getKeyCode ())
{
case KeyEvent.KEYCODE_VOLUME_UP:
parameter = camera.getParameters ();
nowZoom = parameter.getZoom ();
if (nowZoom < parameter.getMaxZoom ())
{
parameter.setZoom (nowZoom + 1);
}
camera.setParameters (parameter);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
parameter = camera.getParameters ();
nowZoom = parameter.getZoom ();
if (nowZoom > 0)
{
parameter.setZoom (nowZoom - 1);
}
camera.setParameters (parameter);
return true;
case KeyEvent.KEYCODE_MENU:
CharSequence[] conf = { "", "", "" };
AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this);
builder.setTitle ("");
builder.setItems (conf, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
if (which == 0)
{
CharSequence[] conf1 = { "", "" };
AlertDialog.Builder builder1 = new AlertDialog.Builder (MainActivity.this);
builder1.setTitle ("");
builder1.setItems (conf1, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
if (which == 0)
{
}
if (which == 1)
{
}
}
});
builder1.show ();
}
if (which == 1)
{
final List <Size> supportedPictureSize = camera.getParameters ().getSupportedPictureSizes ();
int numPicItem = supportedPictureSize.size ();
String[] picHeight = new String[numPicItem];
String[] picWidth = new String[numPicItem];
final String[] pic = new String[numPicItem];
for (int i = 0; i < supportedPictureSize.size (); i++)
{
picSize = supportedPictureSize.get (i);
picHeight[i] = String.valueOf (picSize.height);
picWidth[i] = String.valueOf (picSize.width);
int gcd = GetGCD.getGCD (picSize.width, picSize.height);
String aspWidth = String.valueOf (picSize.width / gcd);
String aspHeight = String.valueOf (picSize.height / gcd);
pic[i] = picWidth[i] + " : " + picHeight[i] + "" + aspWidth + " " + aspHeight + "";
}
AlertDialog.Builder builder2 = new AlertDialog.Builder (MainActivity.this);
builder2.setTitle ("");
builder2.setItems (pic, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
Camera.Parameters parameter = camera.getParameters ();
picSize = supportedPictureSize.get (which);
Toast.makeText (MainActivity.this, "" + pic[which] + "", Toast.LENGTH_SHORT).show ();
parameter.setPictureSize (picSize.width, picSize.height);
camera.setParameters (parameter);
}
});
builder2.show ();
}
if (which == 2)
{
CharSequence[] conf3 = { "", "", "OFF" };
AlertDialog.Builder builder3 = new AlertDialog.Builder (MainActivity.this);
builder3.setTitle ("");
builder3.setItems (conf3, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int which)
{
if (which == 0)
{
Camera.Parameters parameters = camera.getParameters ();
parameters.setFlashMode (Camera.Parameters.FLASH_MODE_ON);
camera.setParameters (parameters);
Toast.makeText (MainActivity.this, "Flash", Toast.LENGTH_SHORT).show ();
}
if (which == 1)
{
Camera.Parameters parameters = camera.getParameters ();
parameters.setFlashMode (Camera.Parameters.FLASH_MODE_AUTO);
camera.setParameters (parameters);
Toast.makeText (MainActivity.this, "Flash", Toast.LENGTH_SHORT).show();
}
if (which == 2)
{
// OFF
Camera.Parameters parameters = camera.getParameters ();
parameters.setFlashMode (Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters (parameters);
Toast.makeText (MainActivity.this, "FlashOFF", Toast.LENGTH_SHORT).show();
}
}
});
builder3.show ();
}
}
});
builder.show ();
return true;
default:
break;
}
break;
case KeyEvent.ACTION_UP:
switch (event.getKeyCode ())
{
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
return true;
default:
break;
}
default:
break;
}
return super.dispatchKeyEvent (event);
}
@Override
public boolean onCreateOptionsMenu (Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater ().inflate (R.menu.main, menu);
return true;
}
}
|
package org.pwsafe.passwordsafeswt;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.pwsafe.lib.exception.PasswordSafeException;
import org.pwsafe.lib.file.PwsFile;
import org.pwsafe.lib.file.PwsFileFactory;
import org.pwsafe.lib.file.PwsRecord;
import org.pwsafe.lib.file.PwsRecordV1;
import org.pwsafe.lib.file.PwsRecordV2;
import org.pwsafe.passwordsafeswt.action.AboutAction;
import org.pwsafe.passwordsafeswt.action.AddRecordAction;
import org.pwsafe.passwordsafeswt.action.ChangeSafeCombinationAction;
import org.pwsafe.passwordsafeswt.action.ClearClipboardAction;
import org.pwsafe.passwordsafeswt.action.CopyPasswordAction;
import org.pwsafe.passwordsafeswt.action.CopyUsernameAction;
import org.pwsafe.passwordsafeswt.action.DeleteRecordAction;
import org.pwsafe.passwordsafeswt.action.EditRecordAction;
import org.pwsafe.passwordsafeswt.action.ExitAppAction;
import org.pwsafe.passwordsafeswt.action.ExportToTextAction;
import org.pwsafe.passwordsafeswt.action.ExportToXMLAction;
import org.pwsafe.passwordsafeswt.action.HelpAction;
import org.pwsafe.passwordsafeswt.action.ImportFromTextAction;
import org.pwsafe.passwordsafeswt.action.ImportFromXMLAction;
import org.pwsafe.passwordsafeswt.action.MRUFileAction;
import org.pwsafe.passwordsafeswt.action.NewFileAction;
import org.pwsafe.passwordsafeswt.action.OpenFileAction;
import org.pwsafe.passwordsafeswt.action.OptionsAction;
import org.pwsafe.passwordsafeswt.action.SaveFileAction;
import org.pwsafe.passwordsafeswt.action.SaveFileAsAction;
import org.pwsafe.passwordsafeswt.action.ViewAsListAction;
import org.pwsafe.passwordsafeswt.action.ViewAsTreeAction;
import org.pwsafe.passwordsafeswt.action.VisitPasswordSafeWebsiteAction;
import org.pwsafe.passwordsafeswt.dialog.StartupDialog;
import org.pwsafe.passwordsafeswt.dto.PwsEntryDTO;
import org.pwsafe.passwordsafeswt.listener.TableColumnSelectionAdaptor;
import org.pwsafe.passwordsafeswt.listener.ViewerDoubleClickListener;
import org.pwsafe.passwordsafeswt.model.PasswordTableContentProvider;
import org.pwsafe.passwordsafeswt.model.PasswordTableLabelProvider;
import org.pwsafe.passwordsafeswt.model.PasswordTableSorter;
import org.pwsafe.passwordsafeswt.model.PasswordTreeContentProvider;
import org.pwsafe.passwordsafeswt.model.PasswordTreeLabelProvider;
import org.pwsafe.passwordsafeswt.preference.DisplayPreferences;
import org.pwsafe.passwordsafeswt.preference.MiscPreferences;
import org.pwsafe.passwordsafeswt.preference.SecurityPreferences;
import org.pwsafe.passwordsafeswt.util.UserPreferences;
import org.pwsafe.passwordsafeswt.xml.XMLDataParser;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import com.swtdesigner.SWTResourceManager;
/**
* A port of PasswordSafe to JFace. This is the main class that is launched from
* the commandline.
*
* @author Glen Smith
*/
public class PasswordSafeJFace extends ApplicationWindow {
private ImportFromXMLAction importFromXMLAction;
private ExportToXMLAction exportToXMLAction;
private OptionsAction optionsAction;
private TreeViewer treeViewer;
private Tree tree;
private HelpAction helpAction;
private AboutAction aboutAction;
private ChangeSafeCombinationAction changeSafeCombinationAction;
private VisitPasswordSafeWebsiteAction visitPasswordSafeWebsiteAction;
private ExitAppAction exitAppAction;
private TableViewer tableViewer;
private NewFileAction newFileAction;
private DeleteRecordAction deleteRecordAction;
private EditRecordAction editRecordAction;
private AddRecordAction addRecordAction;
private ClearClipboardAction clearClipboardAction;
private CopyPasswordAction copyPasswordAction;
private CopyUsernameAction copyUsernameAction;
private SaveFileAsAction saveFileAsAction;
private SaveFileAction saveFileAction;
private OpenFileAction openFileAction;
private ViewAsListAction viewAsListAction;
private ViewAsTreeAction viewAsTreeAction;
private ExportToTextAction exportToTextAction;
private ImportFromTextAction importFromTextAction;
private Table table;
private TrayItem trayItem;
private StackLayout stackLayout;
private Composite composite;
private static final Log log = LogFactory.getLog(PasswordSafeJFace.class);
public static final String APP_NAME = "PasswordSafeSWT";
private static PasswordSafeJFace app;
private PwsFile pwsFile;
private static final String DISPLAY_AS_LIST_PREF = "display.as.list";
private static final String V1_GROUP_PLACEHOLDER = "UntitledGroup";
/**
* Constructor.
*/
public PasswordSafeJFace() {
super(null);
app = this;
createActions();
addToolBar(SWT.FLAT | SWT.WRAP);
addMenuBar();
addStatusLine();
setEditMenusEnabled(false);
}
private void displayOpeningDialog() {
StartupDialog sd = new StartupDialog(getShell(), UserPreferences.getInstance().getMRUFiles());
boolean allDone = false;
while (!allDone) {
String result = (String) sd.open();
if (result == StartupDialog.CANCEL || result == null) {
// they cancelled or clicked the close button on the dialog
exitApplication();
return;
} else if (result == StartupDialog.OPEN_FILE) {
try {
openFile(sd.getFilename(), sd.getPassword());
allDone = true;
} catch (Exception e) {
displayErrorDialog("Error Opening File", "Invalid Password or File Error", e);
allDone = false;
}
} else if (result == StartupDialog.NEW_FILE) {
newFileAction.run();
if (getPwsFile() != null)
allDone = true;
} else if (result == StartupDialog.OPEN_OTHER) {
openFileAction.run();
allDone = true;
}
}
setupStatusMessage();
}
private void startOpeningDialogThread(final Shell shell) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
displayOpeningDialog();
}
});
}
/**
* Returns a singleton handle to the app for making business logic calls.
*
* @return a handle to a singleton of this class
*/
public static PasswordSafeJFace getApp() {
return app;
}
/**
* On platforms where a tray is supported, installs the event handlers for
* showing and hiding the tray.
*/
private void setupTrayItem() {
Image image = SWTResourceManager.getImage(PasswordSafeJFace.class,
"/org/pwsafe/passwordsafeswt/images/cpane.ico");
final Tray tray = getShell().getDisplay().getSystemTray();
if (tray == null) {
if (log.isInfoEnabled())
log.info("The system tray is not available");
} else {
if (log.isDebugEnabled())
log.debug("Setting up System Tray");
trayItem = new TrayItem(tray, SWT.NONE);
trayItem.setVisible(false);
trayItem.setToolTipText(PasswordSafeJFace.APP_NAME);
trayItem.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event event) {
getShell().setVisible(true);
getShell().setMinimized(false);
trayItem.setVisible(false);
}
});
final Menu menu = new Menu(getShell(), SWT.POP_UP);
MenuItem trayRestore = new MenuItem(menu, SWT.PUSH);
trayRestore.setText("Restore");
trayRestore.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
getShell().setVisible(true);
getShell().setMinimized(false);
trayItem.setVisible(false);
}
});
new MenuItem(menu, SWT.SEPARATOR);
MenuItem trayExit = new MenuItem(menu, SWT.PUSH);
trayExit.setText("Exit");
trayExit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
new ExitAppAction().run();
}
});
trayItem.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
menu.setVisible(true);
}
});
trayItem.setImage(image);
getShell().addShellListener(new ShellAdapter() {
public void shellIconified(ShellEvent e) {
if (trayItem != null
&& UserPreferences.getInstance().getBoolean(DisplayPreferences.SHOW_ICON_IN_SYSTEM_TRAY)) {
if (log.isDebugEnabled())
log.debug("Shrinking to tray");
trayItem.setVisible(true);
getShell().setVisible(false);
}
if (UserPreferences.getInstance().getBoolean(SecurityPreferences.CLEAR_CLIPBOARD_ON_MIN)) {
clearClipboardAction.run();
}
}
});
}
}
/**
* @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new FillLayout(SWT.VERTICAL));
composite = new Composite(container, SWT.NONE);
stackLayout = new StackLayout();
composite.setLayout(stackLayout);
tableViewer = new TableViewer(composite, SWT.FULL_SELECTION | SWT.BORDER);
tableViewer.addDoubleClickListener(new ViewerDoubleClickListener());
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setMenu(createPopupMenu(table));
tableViewer.setContentProvider(new PasswordTableContentProvider());
tableViewer.setLabelProvider(new PasswordTableLabelProvider());
tableViewer.setInput(new Object());
tableViewer.setSorter(new PasswordTableSorter());
final TableColumn tableColumn = new TableColumn(table, SWT.NONE);
tableColumn.setWidth(100);
tableColumn.setText("Title");
tableColumn.addSelectionListener(new TableColumnSelectionAdaptor(tableViewer, 1));
final TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE);
tableColumn_1.setWidth(100);
tableColumn_1.setText("User Name");
tableColumn_1.addSelectionListener(new TableColumnSelectionAdaptor(tableViewer, 2));
final TableColumn tableColumn_2 = new TableColumn(table, SWT.NONE);
tableColumn_2.setWidth(100);
tableColumn_2.setText("Notes");
tableColumn_2.addSelectionListener(new TableColumnSelectionAdaptor(tableViewer, 3));
if (UserPreferences.getInstance().getBoolean(DisplayPreferences.SHOW_PASSWORD_IN_LIST)) {
final TableColumn tableColumn_3 = new TableColumn(table, SWT.NONE);
tableColumn_3.setWidth(100);
tableColumn_3.setText("Password");
tableColumn_3.addSelectionListener(new TableColumnSelectionAdaptor(tableViewer, 4));
}
// Sort on first column
PasswordTableSorter pts = (PasswordTableSorter) tableViewer.getSorter();
pts.sortOnColumn(1);
treeViewer = new TreeViewer(composite, SWT.BORDER);
treeViewer.setLabelProvider(new PasswordTreeLabelProvider());
treeViewer.setContentProvider(new PasswordTreeContentProvider());
treeViewer.setSorter(new ViewerSorter());
treeViewer.addDoubleClickListener(new ViewerDoubleClickListener());
tree = treeViewer.getTree();
tree.setHeaderVisible(true);
tree.setMenu(createPopupMenu(tree));
treeViewer.setInput(new Object());
final TreeColumn treeColumn = new TreeColumn(tree, SWT.CENTER);
treeColumn.setText("Title");
// treeColumn.addSelectionListener(new TreeColumnSelectionAdaptor(treeViewer, 1));
final TreeColumn treeColumn_1 = new TreeColumn(tree, SWT.LEFT);
treeColumn_1.setText("User Name");
// treeColumn_1.addSelectionListener(new TreeColumnSelectionAdaptor(treeViewer, 2));
final TreeColumn treeColumn_2 = new TreeColumn(tree, SWT.LEFT);
treeColumn_2.setText("Notes");
// treeColumn_2.addSelectionListener(new TreeColumnSelectionAdaptor(treeViewer, 3));
if (UserPreferences.getInstance().getBoolean(DisplayPreferences.SHOW_PASSWORD_IN_LIST)) {
final TreeColumn treeColumn_3 = new TreeColumn(tree, SWT.LEFT);
treeColumn_3.setText("Password");
// treeColumn_3.addSelectionListener(new TreeColumnSelectionAdaptor(treeViewer, 4));
}
TreeColumn[] columns = tree.getColumns();
for (int i = 0; i < columns.length; i++) {
columns[i].setWidth(100);
columns[i].setMoveable(true);
}
if (UserPreferences.getInstance().getBoolean(DISPLAY_AS_LIST_PREF)) {
showListView();
viewAsListAction.setChecked(true);
viewAsTreeAction.setChecked(false);
} else {
showTreeView();
viewAsTreeAction.setChecked(true);
viewAsListAction.setChecked(false);
}
composite.layout();
setupTrayItem();
return container;
}
/**
* Creates the JFace actions that will be used for menus and toolbars.
*/
private void createActions() {
newFileAction = new NewFileAction();
openFileAction = new OpenFileAction();
saveFileAction = new SaveFileAction();
saveFileAsAction = new SaveFileAsAction();
exportToTextAction = new ExportToTextAction();
importFromTextAction = new ImportFromTextAction();
exitAppAction = new ExitAppAction();
copyUsernameAction = new CopyUsernameAction();
copyPasswordAction = new CopyPasswordAction();
clearClipboardAction = new ClearClipboardAction();
addRecordAction = new AddRecordAction();
editRecordAction = new EditRecordAction();
deleteRecordAction = new DeleteRecordAction();
viewAsListAction = new ViewAsListAction();
viewAsTreeAction = new ViewAsTreeAction();
visitPasswordSafeWebsiteAction = new VisitPasswordSafeWebsiteAction();
changeSafeCombinationAction = new ChangeSafeCombinationAction();
aboutAction = new AboutAction();
helpAction = new HelpAction();
optionsAction = new OptionsAction();
exportToXMLAction = new ExportToXMLAction();
importFromXMLAction = new ImportFromXMLAction();
}
/**
* @see org.eclipse.jface.window.ApplicationWindow#createMenuManager()
*/
protected MenuManager createMenuManager() {
MenuManager result = new MenuManager("menu");
final MenuManager menuManagerFile = new MenuManager("File");
result.add(menuManagerFile);
menuManagerFile.add(newFileAction);
menuManagerFile.add(openFileAction);
menuManagerFile.add(new Separator());
String[] mruFiles = UserPreferences.getInstance().getMRUFiles();
if (mruFiles != null && mruFiles.length > 0) {
for (int i = 0; i < mruFiles.length; i++) {
String fileName = mruFiles[i];
String menuItem = "&" + (i + 1) + " " + new File(fileName).getName();
IAction nextMRUAction = new MRUFileAction(fileName, menuItem);
menuManagerFile.add(nextMRUAction);
}
menuManagerFile.add(new Separator());
}
menuManagerFile.add(saveFileAction);
menuManagerFile.add(saveFileAsAction);
menuManagerFile.add(new Separator());
final MenuManager menuManagerExportTo = new MenuManager("Export To");
menuManagerFile.add(menuManagerExportTo);
menuManagerExportTo.add(exportToTextAction);
menuManagerExportTo.add(exportToXMLAction);
final MenuManager menuManagerImportFrom = new MenuManager("Import From");
menuManagerFile.add(menuManagerImportFrom);
menuManagerImportFrom.add(importFromTextAction);
menuManagerImportFrom.add(importFromXMLAction);
menuManagerFile.add(new Separator());
menuManagerFile.add(exitAppAction);
final MenuManager menuManagerEdit = new MenuManager("Edit");
result.add(menuManagerEdit);
menuManagerEdit.add(addRecordAction);
menuManagerEdit.add(editRecordAction);
menuManagerEdit.add(deleteRecordAction);
menuManagerEdit.add(new Separator());
menuManagerEdit.add(copyPasswordAction);
menuManagerEdit.add(copyUsernameAction);
menuManagerEdit.add(clearClipboardAction);
final MenuManager menuManagerView = new MenuManager("View");
result.add(menuManagerView);
menuManagerView.add(viewAsListAction);
menuManagerView.add(viewAsTreeAction);
final MenuManager menuManagerManage = new MenuManager("Manage");
result.add(menuManagerManage);
menuManagerManage.add(changeSafeCombinationAction);
menuManagerManage.add(new Separator());
menuManagerManage.add(optionsAction);
final MenuManager menuManagerHelp = new MenuManager("Help");
result.add(menuManagerHelp);
menuManagerHelp.add(helpAction);
menuManagerHelp.add(new Separator());
menuManagerHelp.add(visitPasswordSafeWebsiteAction);
menuManagerHelp.add(new Separator());
menuManagerHelp.add(aboutAction);
return result;
}
/**
* Creates the popup (right click) menu for the given control.
*
* @param ctl
* the control to add the popup to
* @return the created menu
*/
protected Menu createPopupMenu(Control ctl) {
final MenuManager menuListPopup = new MenuManager("ListPopup");
menuListPopup.createContextMenu(ctl);
menuListPopup.add(copyPasswordAction);
menuListPopup.add(copyUsernameAction);
menuListPopup.add(new Separator());
menuListPopup.add(addRecordAction);
menuListPopup.add(editRecordAction);
menuListPopup.add(deleteRecordAction);
return menuListPopup.getMenu();
}
/**
* @see org.eclipse.jface.window.ApplicationWindow#createToolBarManager(int)
*/
protected ToolBarManager createToolBarManager(int style) {
ToolBarManager toolBarManager = new ToolBarManager(style);
toolBarManager.add(newFileAction);
toolBarManager.add(openFileAction);
toolBarManager.add(saveFileAction);
toolBarManager.add(new Separator());
toolBarManager.add(copyUsernameAction);
toolBarManager.add(copyPasswordAction);
toolBarManager.add(clearClipboardAction);
toolBarManager.add(new Separator());
toolBarManager.add(addRecordAction);
toolBarManager.add(editRecordAction);
toolBarManager.add(deleteRecordAction);
toolBarManager.add(new Separator());
toolBarManager.add(helpAction);
return toolBarManager;
}
/**
* @see org.eclipse.jface.window.ApplicationWindow#createStatusLineManager()
*/
protected StatusLineManager createStatusLineManager() {
StatusLineManager statusLineManager = new StatusLineManager();
statusLineManager.setMessage("http://passwordsafe.sf.net");
return statusLineManager;
}
/**
* Updates the status bar with the supplied text.
*
* @param statusMsg
* the message to display in the status bar
*/
public void setStatusMessage(String statusMsg) {
getStatusLineManager().setMessage(statusMsg);
}
public void setupStatusMessage() {
final PwsFile pwsf = getPwsFile();
if (pwsf != null && pwsf.getRecordCount() > 0) {
if (UserPreferences.getInstance().getBoolean(MiscPreferences.DOUBLE_CLICK_COPIES_TO_CLIPBOARD)) {
setStatusMessage("Double Click on entry to copy password");
} else {
setStatusMessage("Double Click to edit entry");
}
} else {
setStatusMessage("http://passwordsafe.sf.net");
}
}
/**
* Main program entry point.
*
* @param args
* commandline args that are passed in
*/
public static void main(String args[]) {
log.info("PasswordSafe starting...");
log.info("java.library.path is: [" + System.getProperty("java.library.path") + "]");
try {
PasswordSafeJFace window = new PasswordSafeJFace();
window.setBlockOnOpen(true);
window.open();
SWTResourceManager.dispose();
Display.getCurrent().dispose();
} catch (Exception e) {
log.error("Error Starting PasswordSafe", e);
}
log.info("PasswordSafe terminating...");
}
/**
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(PasswordSafeJFace.APP_NAME);
newShell.setImage(SWTResourceManager.getImage(PasswordSafeJFace.class,
"/org/pwsafe/passwordsafeswt/images/cpane.ico"));
startOpeningDialogThread(newShell);
}
/**
* @see org.eclipse.jface.window.Window#getInitialSize()
*/
protected Point getInitialSize() {
return new Point(425, 375);
}
/**
* Create a brand new empty safe.
*
* @param password the password for the new safe
*/
public void newFile(String password) {
getShell().setText(PasswordSafeJFace.APP_NAME + " - <Untitled>");
PwsFile newFile = PwsFileFactory.newFile();
newFile.setPassphrase(password);
this.setPwsFile(newFile);
}
/**
* Opens a new safe from the filesystem.
*
* @throws Exception
* if bad things happen during open
*/
public void openFile(String fileName, String password) throws Exception {
PwsFile file = PwsFileFactory.loadFile(fileName, password);
getShell().setText(PasswordSafeJFace.APP_NAME + " - " + fileName);
setPwsFile(file);
if (true) // TODO (!openedFromMRU)
UserPreferences.getInstance().setMostRecentFilename(fileName);
}
/**
* Save the current safe.
*
* @throws IOException
* if bad things happen during save
*/
public void saveFile() throws IOException {
PwsFile file = getPwsFile();
String fileName = file.getFilename();
if (fileName == null) {
saveFileAsAction.run();
} else {
file.save();
}
}
/**
* Saves the current safe under a new filename.
*
* @throws IOException
*/
public void saveFileAs(String newFilename) throws IOException {
getPwsFile().setFilename(newFilename);
getPwsFile().save();
getShell().setText(PasswordSafeJFace.APP_NAME + " - " + newFilename);
UserPreferences.getInstance().setMostRecentFilename(newFilename);
}
/**
* Sets the passphrase for the open safe.
*
* @param the
* new password for the safe
*/
public void setPassphrase(String newPassword) {
if (newPassword != null)
getPwsFile().setPassphrase(newPassword);
}
/**
* Copy field to clipboard.
*
* @param cb
* handle to the clipboard
* @param recordToCopy
* the pwsafe record to copy
* @param fieldToCopy
* the field in that record to copy
*/
public void copyToClipboard(Clipboard cb, PwsRecord recordToCopy, int fieldToCopy) {
if (recordToCopy != null) {
String valueToCopy = null;
valueToCopy = recordToCopy.getField(fieldToCopy).getValue().toString();
if (valueToCopy != null) {
cb.setContents(new Object[]{valueToCopy}, new Transfer[]{TextTransfer.getInstance()});
log.debug("Copied to clipboard");
}
}
}
/**
* Locates the selected record in the underlying tree or table control.
*
* @return the selected record
*/
public PwsRecord getSelectedRecord() {
PwsRecord recordToCopy = null;
if (stackLayout.topControl == tree) {
if (tree.getSelectionCount() == 1) {
TreeItem ti = tree.getSelection()[0];
Object treeData = ti.getData();
if (treeData != null && treeData instanceof PwsRecord) { // must be a left, not a group entry
recordToCopy = (PwsRecord) treeData;
}
}
} else {
if (table.getSelectionCount() == 1) {
TableItem ti = table.getSelection()[0];
recordToCopy = (PwsRecord) ti.getData();
}
}
return recordToCopy;
}
/**
* Edits the selected record in a new dialog.
*/
public void editRecord(PwsEntryDTO newEntry) {
PwsRecord selectedRecord = getSelectedRecord();
if (log.isDebugEnabled())
log.debug("Dialog has been edited, updating safe");
newEntry.toPwsRecord(selectedRecord);
updateViewers();
}
/**
* Adds a new record to the safe in a new dialog.
*/
public void addRecord(PwsEntryDTO newEntry) {
if (log.isDebugEnabled())
log.debug("Dialog has created new record, updating safe");
PwsRecord newRecord = getPwsFile().newRecord();
newEntry.toPwsRecord(newRecord);
try {
getPwsFile().add(newRecord);
saveOnUpdateOrEditCheck();
} catch (PasswordSafeException e) {
displayErrorDialog("Add Entry Error", "Error Adding Entry", e);
}
updateViewers();
}
/**
* If the user has set "Save on Update or Edit", we save the file
* immediately.
*
*/
private void saveOnUpdateOrEditCheck() {
if (UserPreferences.getInstance().getBoolean(MiscPreferences.SAVE_IMMEDIATELY_ON_EDIT)) {
if (log.isDebugEnabled())
log.debug("Save on Edit option active. Saving database.");
saveFileAction.run();
}
}
/**
* Prompts the user to save the current file, if it has been modified.
* @return <code>true</code> if the user cancels the action which triggered the
* call to this method, <code>false</code> if the save was successful or ignored.
*/
public boolean saveAppIfDirty() {
boolean cancelled = false;
if (isDirty()) {
int style = SWT.APPLICATION_MODAL | SWT.YES | SWT.NO | SWT.CANCEL;
MessageBox messageBox = new MessageBox(getShell(), style);
messageBox.setText("Save Changes");
messageBox
.setMessage("Do you want to save changes to the password list?");
int result = messageBox.open();
if (result == SWT.YES) {
try {
saveFile();
} catch (IOException e1) {
displayErrorDialog("Error Saving Safe", e1.getMessage(), e1);
cancelled = true;
}
} else if (result == SWT.CANCEL) {
cancelled = true;
}
}
return cancelled;
}
/**
* Deletes the selected record in the tree or table.
*
*/
public void deleteRecord() {
PwsRecord selectedRec = getSelectedRecord();
selectedRec.delete();
saveOnUpdateOrEditCheck();
updateViewers();
}
/**
* Has the current safe been modified.
*
* @return true if the safe has been modified
*/
public boolean isDirty() {
if (getPwsFile() != null) {
return getPwsFile().isModified();
}
return false;
}
/**
* Returns the currently loaded pwsafe file.
*
* @return Returns the pwsFile.
*/
public PwsFile getPwsFile() {
return pwsFile;
}
/**
* Sets the currently load pwsafe file.
*
* @param pwsFile
* The pwsFile to set.
*/
public void setPwsFile(PwsFile pwsFile) {
this.pwsFile = pwsFile;
updateViewers();
setEditMenusEnabled(true);
}
/**
* Perform necessary shutdown operations, regardless of how the user
* exited the application.
*
*/
private void tidyUpOnExit() {
if (UserPreferences.getInstance().getBoolean(SecurityPreferences.CLEAR_CLIPBOARD_ON_MIN)) {
clearClipboardAction.run();
}
UserPreferences.getInstance().setString(DISPLAY_AS_LIST_PREF, Boolean.toString(stackLayout.topControl == table));
try {
UserPreferences.getInstance().savePreferences();
} catch (IOException e) {
displayErrorDialog("Error Saving User Preferences", "Error encountered saving your user preferences: " + e.getMessage(), e);
}
}
/**
* Exit the app.
*
*/
public void exitApplication() {
tidyUpOnExit();
getShell().dispose();
}
/**
* Set the list view as the topmost view.
*/
public void showListView() {
stackLayout.topControl = table;
composite.layout();
}
/**
* Set the table view as the topmost view.
*/
public void showTreeView() {
stackLayout.topControl = tree;
composite.layout();
}
/**
* Returns whether the treeview is the active view.
*
* @return true if the treeview is showing, false otherwise
*/
public boolean isTreeViewShowing() {
return (stackLayout.topControl == tree);
}
public String getSelectedTreeGroup() {
if (stackLayout.topControl == tree) {
if (tree.getSelectionCount() == 1) {
TreeItem ti = tree.getSelection()[0];
if (ti.getItemCount() > 0) {
return ti.getText();
} else {
// we're in a leaf node
if (ti.getParentItem() != null) {
return ti.getParentItem().getText();
} else {
return ""; // empty root element
}
}
}
}
return null;
}
/**
* Refresh the tree and table.
*
*/
public void updateViewers() {
tableViewer.setInput(getPwsFile());
//tableViewer.refresh();
treeViewer.setInput(getPwsFile());
treeViewer.refresh();
}
/**
* Turns on or off the edit record menus (add/edit/delete) and save/as
* menus.
*
* @param enabled
* true to enable the menus, false otherwise
*/
private void setEditMenusEnabled(boolean enabled) {
this.addRecordAction.setEnabled(enabled);
this.editRecordAction.setEnabled(enabled);
this.deleteRecordAction.setEnabled(enabled);
this.saveFileAction.setEnabled(enabled);
this.saveFileAsAction.setEnabled(enabled);
}
/**
* Exports the contents of the password safe to tab separated file.
*
* @param filename
* full path to output file
* @throws FileNotFoundException
*/
public void exportToText(String filename) {
FileWriter fw = null;
try {
fw = new FileWriter(filename);
Iterator iter = getPwsFile().getRecords();
CSVWriter csvWriter = new CSVWriter(fw, '\t');
while (iter.hasNext()) {
PwsRecord nextRecord = (PwsRecord) iter.next();
List nextEntry = new ArrayList();
if (nextRecord instanceof PwsRecordV1) {
nextEntry.add(V1_GROUP_PLACEHOLDER);
nextEntry.add(nextRecord.getField(PwsRecordV1.TITLE).getValue().toString());
nextEntry.add(nextRecord.getField(PwsRecordV1.USERNAME).getValue().toString());
nextEntry.add(nextRecord.getField(PwsRecordV1.PASSWORD).getValue().toString());
} else {
nextEntry.add(nextRecord.getField(PwsRecordV2.GROUP).getValue().toString());
nextEntry.add(nextRecord.getField(PwsRecordV2.TITLE).getValue().toString());
nextEntry.add(nextRecord.getField(PwsRecordV2.USERNAME).getValue().toString());
nextEntry.add(nextRecord.getField(PwsRecordV2.PASSWORD).getValue().toString());
}
String[] nextLine = (String[])nextEntry.toArray(new String[0]);
csvWriter.writeNext(nextLine);
}
} catch (IOException ioe) {
displayErrorDialog("Error Exporting", "Error writing to text file", ioe);
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
log.warn("Could not close output text file", e);
}
}
}
}
public void importFromText(String filename) {
File theFile = new File(filename);
if (!theFile.exists()) {
throw new RuntimeException("Could not locate CSV source file: [" + filename + "]");
}
Reader fileReader = null;
try {
fileReader = new FileReader(theFile);
CSVReader csvReader = new CSVReader(fileReader, '\t');
String[] nextLine;
PwsFile pwsFile = getPwsFile();
while ((nextLine = csvReader.readNext()) != null) {
PwsRecord newRecord = pwsFile.newRecord();
PwsEntryDTO entry = new PwsEntryDTO();
if (!nextLine[0].equals(V1_GROUP_PLACEHOLDER)) {
entry.setGroup(nextLine[0]);
}
entry.setTitle(nextLine[1]);
entry.setUsername(nextLine[2]);
entry.setPassword(nextLine[3]);
entry.toPwsRecord(newRecord);
pwsFile.add(newRecord);
}
} catch (Exception e) {
throw new RuntimeException("Could not process text file: [" + filename + "]", e);
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
log.warn("Could not close import text file", e);
}
}
}
this.updateViewers();
}
/**
* Import an XML file into the current passwordsafe.
*
* @param filename
* the name of the file
* @throws PasswordSafeException
*/
public void importFromXML(String filename) throws PasswordSafeException {
File theFile = new File(filename);
if (!theFile.exists()) {
throw new RuntimeException("Could not locate XML source file: [" + filename + "]");
}
BufferedInputStream bis;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
bis = new BufferedInputStream(new FileInputStream(filename));
} catch (FileNotFoundException e) {
throw new RuntimeException("Could not open file", e);
}
String utf8String;
try {
int c;
while ((c = bis.read()) != -1) {
baos.write(c);
}
byte[] utf8Bytes = baos.toByteArray();
utf8String = new String(utf8Bytes, "UTF-8");
char header = utf8String.charAt(0);
if (header > 255) {
utf8String = utf8String.substring(1); // skip utf leading char
}
} catch (Exception ioe) {
throw new RuntimeException("IO Issues reading XML source file", ioe);
} finally
{
try
{
bis.close();
} catch (IOException e)
{
log.warn("BufferedInputStream.close()", e);
}
}
XMLDataParser xdp = new XMLDataParser();
PwsEntryDTO[] entries = xdp.parse(utf8String);
if (entries != null && entries.length > 0) {
PwsFile pwsFile = getPwsFile();
for (int i = 0; i < entries.length; i++) {
PwsEntryDTO nextEntry = entries[i];
PwsRecord newRecord = pwsFile.newRecord();
nextEntry.toPwsRecord(newRecord);
pwsFile.add(newRecord);
}
this.updateViewers();
}
}
/**
* Export the current safe to the name file in XML format.
*
* @param filename
* the filename to export to
* @throws IOException
*/
public void exportToXML(String filename) throws IOException {
PwsFile pwsFile = getPwsFile();
if (pwsFile != null) {
List entryList = new ArrayList();
for (Iterator iter = pwsFile.getRecords(); iter.hasNext();) {
PwsEntryDTO nextDTO = PwsEntryDTO.fromPwsRecord((PwsRecord) iter.next());
entryList.add(nextDTO);
}
XMLDataParser xdp = new XMLDataParser();
String xmlOutput = xdp.convertToXML((PwsEntryDTO[]) entryList.toArray(new PwsEntryDTO[0]));
DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename));
// output the UTF-8 BOM byte by byte directly to the stream
dos.write(239); // 0xEF
dos.write(187); // 0xBB
dos.write(191); // 0xBF
dos.write(xmlOutput.getBytes());
dos.close();
}
}
/**
* Display error dialog and log error.
*
* @param title
* the title of the dialog
* @param message
* the message to display
* @param e
* the exception that caused the problem.
*/
public void displayErrorDialog(String title, String message, Exception e) {
MessageBox mb = new MessageBox(getShell(), SWT.ICON_ERROR);
mb.setText(title);
mb.setMessage(message);
mb.open();
log.error(message, e);
}
/**
*
* @see org.eclipse.jface.window.Window#handleShellCloseEvent()
*/
protected void handleShellCloseEvent() {
boolean cancelled = saveAppIfDirty();
if (cancelled) {
setReturnCode(OK);
} else {
tidyUpOnExit();
super.handleShellCloseEvent();
}
}
}
|
package vista;
import java.awt.Color;
import java.awt.Desktop;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class VentanaPrincipal extends javax.swing.JFrame {
private int numeroPuerto = 5000;
private String servidor= "192.168.0.102";
private int id;
private int puertoPHP;
private int puertoSQL;
private String ip;
public VentanaPrincipal() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButtonIniciar = new javax.swing.JButton();
jButtonDetener = new javax.swing.JButton();
url = new javax.swing.JLabel();
jlabelSQL = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("App [ID:?]");
setLocation(new java.awt.Point(100, 100));
setMinimumSize(new java.awt.Dimension(235, 150));
setResizable(false);
getContentPane().setLayout(new java.awt.FlowLayout());
jLabel1.setFont(new java.awt.Font("Consolas", 1, 48)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 0, 0));
jLabel1.setText("App");
getContentPane().add(jLabel1);
jButtonIniciar.setText("Iniciar");
jButtonIniciar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonIniciarActionPerformed(evt);
}
});
getContentPane().add(jButtonIniciar);
jButtonDetener.setText("Detener");
jButtonDetener.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDetenerActionPerformed(evt);
}
});
getContentPane().add(jButtonDetener);
getContentPane().add(url);
getContentPane().add(jlabelSQL);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIniciarActionPerformed
try {
// Se intenta conectar, retorna IOException en caso que no pueda
Socket socket = new Socket(servidor, numeroPuerto);
// Stream para e/s, se crea primero la salida
ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream entrada = new ObjectInputStream(socket.getInputStream());
salida.writeObject("Dame server");
String response = (String) entrada.readObject();
System.out.println(response);
ip = socket.getInetAddress().getHostAddress();
id = Integer.parseInt(response.substring(response.lastIndexOf("?") + 1));
puertoPHP = Integer.parseInt(response.substring(0, response.indexOf("?")));
puertoSQL = Integer.parseInt(response.substring(response.indexOf("?") + 1, response.lastIndexOf("?")));
System.out.println("ID: " + id);
System.out.println("IP: " + ip);
System.out.println("PHP: " + puertoPHP);
System.out.println("SQL: " + puertoSQL);
jLabel1.setForeground(Color.green);
entrada.close();
salida.close();
socket.close();
Desktop.getDesktop().browse(new URI("http://" + ip + ":" + puertoPHP + "/phpmyadmin"));
url.setText("http://" + ip + ":" + puertoPHP + "/phpmyadmin");
jlabelSQL.setText("PuertoSQL: " + puertoSQL);
this.setTitle("App [ID:" + id + "]");
} catch (IOException ex) {
System.out.println("(LOG) [ERROR] No se pudo contactar al servidor");
Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButtonIniciarActionPerformed
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed
try {
// Se intenta conectar, retorna IOException en caso que no pueda
Socket socket = new Socket(servidor, numeroPuerto);
// Stream para e/s, se crea primero la salida
ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream entrada = new ObjectInputStream(socket.getInputStream());
salida.writeObject("Mata server" + id);
jLabel1.setForeground(Color.red);
entrada.close();
salida.close();
socket.close();
url.setText("");
jlabelSQL.setText("");
this.setTitle("App [ID:?]");
} catch (IOException ex) {
System.out.println("(LOG) [ERROR] No se pudo contactar al servidor");
Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButtonDetenerActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VentanaPrincipal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonDetener;
private javax.swing.JButton jButtonIniciar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jlabelSQL;
private javax.swing.JLabel url;
// End of variables declaration//GEN-END:variables
}
|
package com.facebook.react;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_START;
import static com.facebook.react.bridge.ReactMarkerConstants.PROCESS_CORE_REACT_PACKAGE_END;
import static com.facebook.react.bridge.ReactMarkerConstants.PROCESS_CORE_REACT_PACKAGE_START;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMarker;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.module.annotations.ReactModuleList;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.core.ExceptionsManagerModule;
import com.facebook.react.modules.core.Timing;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.HeadlessJsTaskSupportModule;
import com.facebook.react.modules.debug.SourceCodeModule;
import com.facebook.react.modules.deviceinfo.DeviceInfoModule;
import com.facebook.react.modules.systeminfo.AndroidInfoModule;
import com.facebook.react.uimanager.UIImplementationProvider;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.systrace.Systrace;
import java.util.Collections;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.facebook.react.bridge.ReactMarkerConstants.*;
/**
* This is the basic module to support React Native. The debug modules are now in DebugCorePackage.
*/
@ReactModuleList(
// WARNING: If you modify this list, ensure that the list below in method
// getReactModuleInfoByInitialization is also updated
nativeModules = {
AndroidInfoModule.class,
DeviceEventManagerModule.class,
DeviceInfoModule.class,
ExceptionsManagerModule.class,
HeadlessJsTaskSupportModule.class,
SourceCodeModule.class,
Timing.class,
UIManagerModule.class,
})
/* package */ class CoreModulesPackage extends TurboReactPackage implements ReactPackageLogger {
private final ReactInstanceManager mReactInstanceManager;
private final DefaultHardwareBackBtnHandler mHardwareBackBtnHandler;
private final boolean mLazyViewManagersEnabled;
private final int mMinTimeLeftInFrameForNonBatchedOperationMs;
CoreModulesPackage(
ReactInstanceManager reactInstanceManager,
DefaultHardwareBackBtnHandler hardwareBackBtnHandler,
@Nullable UIImplementationProvider uiImplementationProvider,
boolean lazyViewManagersEnabled,
int minTimeLeftInFrameForNonBatchedOperationMs) {
mReactInstanceManager = reactInstanceManager;
mHardwareBackBtnHandler = hardwareBackBtnHandler;
mLazyViewManagersEnabled = lazyViewManagersEnabled;
mMinTimeLeftInFrameForNonBatchedOperationMs = minTimeLeftInFrameForNonBatchedOperationMs;
}
/**
* This method is overridden, since OSS does not run the annotation processor to generate {@link
* CoreModulesPackage$$ReactModuleInfoProvider} class. Here we check if it exists. If it does not
* exist, we generate one manually in {@link
* CoreModulesPackage#getReactModuleInfoByInitialization()} and return that instead.
*/
@Override
public ReactModuleInfoProvider getReactModuleInfoProvider() {
try {
Class<?> reactModuleInfoProviderClass =
Class.forName("com.facebook.react.CoreModulesPackage$$ReactModuleInfoProvider");
return (ReactModuleInfoProvider) reactModuleInfoProviderClass.newInstance();
} catch (ClassNotFoundException e) {
// In OSS case, the annotation processor does not run. We fall back on creating this byhand
Class<? extends NativeModule>[] moduleList =
new Class[] {
AndroidInfoModule.class,
DeviceEventManagerModule.class,
DeviceInfoModule.class,
ExceptionsManagerModule.class,
HeadlessJsTaskSupportModule.class,
SourceCodeModule.class,
Timing.class,
UIManagerModule.class
};
final Map<String, ReactModuleInfo> reactModuleInfoMap = new HashMap<>();
for (Class<? extends NativeModule> moduleClass : moduleList) {
ReactModule reactModule = moduleClass.getAnnotation(ReactModule.class);
reactModuleInfoMap.put(
reactModule.name(),
new ReactModuleInfo(
reactModule.name(),
moduleClass.getName(),
reactModule.canOverrideExistingModule(),
reactModule.needsEagerInit(),
reactModule.hasConstants(),
reactModule.isCxxModule(),
false));
}
return new ReactModuleInfoProvider() {
@Override
public Map<String, ReactModuleInfo> getReactModuleInfos() {
return reactModuleInfoMap;
}
};
} catch (InstantiationException e) {
throw new RuntimeException(
"No ReactModuleInfoProvider for CoreModulesPackage$$ReactModuleInfoProvider", e);
} catch (IllegalAccessException e) {
throw new RuntimeException(
"No ReactModuleInfoProvider for CoreModulesPackage$$ReactModuleInfoProvider", e);
}
}
@Override
public NativeModule getModule(String name, ReactApplicationContext reactContext) {
switch (name) {
case AndroidInfoModule.NAME:
return new AndroidInfoModule(reactContext);
case DeviceEventManagerModule.NAME:
return new DeviceEventManagerModule(reactContext, mHardwareBackBtnHandler);
case ExceptionsManagerModule.NAME:
return new ExceptionsManagerModule(mReactInstanceManager.getDevSupportManager());
case HeadlessJsTaskSupportModule.NAME:
return new HeadlessJsTaskSupportModule(reactContext);
case SourceCodeModule.NAME:
return new SourceCodeModule(reactContext);
case Timing.NAME:
return new Timing(reactContext, mReactInstanceManager.getDevSupportManager());
case UIManagerModule.NAME:
return createUIManager(reactContext);
case DeviceInfoModule.NAME:
return new DeviceInfoModule(reactContext);
default:
throw new IllegalArgumentException(
"In CoreModulesPackage, could not find Native module for " + name);
}
}
private UIManagerModule createUIManager(final ReactApplicationContext reactContext) {
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_START);
Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "createUIManagerModule");
try {
if (mLazyViewManagersEnabled) {
UIManagerModule.ViewManagerResolver resolver =
new UIManagerModule.ViewManagerResolver() {
@Override
public @Nullable ViewManager getViewManager(String viewManagerName) {
return mReactInstanceManager.createViewManager(viewManagerName);
}
@Override
public List<String> getViewManagerNames() {
return mReactInstanceManager.getViewManagerNames();
}
};
return new UIManagerModule(
reactContext, resolver, mMinTimeLeftInFrameForNonBatchedOperationMs);
} else {
return new UIManagerModule(
reactContext,
mReactInstanceManager.getOrCreateViewManagers(reactContext),
mMinTimeLeftInFrameForNonBatchedOperationMs);
}
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_END);
}
}
@Override
public void startProcessPackage() {
ReactMarker.logMarker(PROCESS_CORE_REACT_PACKAGE_START);
}
@Override
public void endProcessPackage() {
ReactMarker.logMarker(PROCESS_CORE_REACT_PACKAGE_END);
}
}
|
package com.anthony.shakeitoff;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.hardware.Camera;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Calendar;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity implements SensorEventListener {
public static final String TAG = "MainActivity";
private ShakeListener mShaker;
private boolean useFrontComera = false;
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
//checks the direction of spinning
private SensorManager cSensorManager;
private boolean canSpin = false;
private boolean spinDir = false;
private float currentDegree = 0f;
private float startDegree = 0f;
private float prevDegree = 0f;
private int prevTime = 0;
TextView tvHeading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// make the app fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
// set up camera preview
preview = (SurfaceView)findViewById(R.id.preview);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//Text view that will tell the user what degree for testing
tvHeading = (TextView) findViewById(R.id.tvHeading);
//initialize your android device sensor capabilities
cSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// set up the shake listener and back button for after picture taken
final ImageButton backButton = (ImageButton)findViewById(R.id.back_button);
final ImageButton swapCameraButton = (ImageButton)findViewById(R.id.swap_camera_button);
backButton.setEnabled(false);
swapCameraButton.setEnabled(true);
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() { takePicture(); }
});
backButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (camera != null && cameraConfigured && !inPreview) startPreview();
backButton.setEnabled(false);
swapCameraButton.setEnabled(true);
}
}
);
swapCameraButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (camera != null) { camera.release(); camera = null; }
useFrontComera = !useFrontComera;
camera = openCamera(useFrontComera);
inPreview = false; startPreview();
}
}
);
}
@Override
public void onResume() {
super.onResume();
cSensorManager.registerListener(this, cSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
mShaker.resume();
camera = openCamera(useFrontComera);
startPreview();
}
@Override
public void onPause() {
stopPreview();
camera.release(); camera = null;
mShaker.pause();
cSensorManager.unregisterListener(this);
super.onPause();
}
// get the largest preview size (by area) that still fits inside the layout
private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null || size.width * size.height > result.width * result.height)
result = size;
}
}
return result;
}
private boolean cameraConfigured = false;
private boolean inPreview = false;
private void initPreview(int width, int height) {
if (camera != null && previewHolder.getSurface() != null) {
try { camera.setPreviewDisplay(previewHolder); }
catch (Throwable t) { Log.e(TAG, "Exception in setPreviewDisplay()", t); }
if (!cameraConfigured) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height, parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
camera.setParameters(parameters);
cameraConfigured = true;
}
}
}
}
private void startPreview() {
if (cameraConfigured && camera != null && !inPreview) {
camera.startPreview(); inPreview = true;
}
}
private void stopPreview() {
if (cameraConfigured && camera != null && inPreview) {
inPreview = false; camera.stopPreview();
}
}
SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {}
public void surfaceDestroyed(SurfaceHolder holder) {}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // recreate the preview when the screen dimensions change
initPreview(width, height);
startPreview();
}
};
private Camera openCamera(boolean frontCamera) {
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, cameraInfo);
if ((frontCamera && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ||
(!frontCamera && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) {
try { cam = Camera.open(i); }
catch (RuntimeException e) { Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage()); }
}
}
return cam;
}
//MOD FUNCTIONS ARE REQUIRED IN ORDER TO WORK WITH DEGREES
/*private float modDeg(float deg){
deg = deg % 360;
if(deg < 0){
deg = deg + 360;
}
return deg;
}*/
private boolean suckit = false;
private boolean detectRoll = false;
private boolean[] checkpointsR = new boolean[4];
private boolean fullRollTurn = false;
private void setDetectRoll(boolean detectRoll){
this.detectRoll = detectRoll;
}
private boolean areAllTrue(boolean[] array){
for(boolean b : array)
if (!b)
return false;
return true;
}
private void detectingRoll(){
setDetectRoll(true);
for(int i = 0; i < 4; i++){
if((currentDegree > 90 * i && currentDegree < 90 * (i + 1))){
checkpointsR[i] = true;
}
}
if(areAllTrue(checkpointsR) && currentDegree > 0 && currentDegree > 45){
fullRollTurn = true;
//reset checkpoints
for(int i = 0; i < 4; i++){
checkpointsR[i] = false;
}
}
}
@Override
public void onSensorChanged(SensorEvent event){
float degree = Math.round(event.values[0]);
Calendar c = Calendar.getInstance();
int curSeconds = c.get(Calendar.SECOND);
if((prevDegree > degree - 5) && (prevDegree < degree + 5)) {
if (prevTime + 1 < curSeconds) {
canSpin = true;
}
}
else {
prevDegree = degree;
}
if(canSpin){
detectingRoll();
}
if(fullRollTurn){
suckit = true;
canSpin = false;
takePicture();
fullRollTurn = false;
}
tvHeading.setText("Heading: " + Float.toString(degree) + "canSpin" + canSpin + "circle: " + suckit);
//I don't know why this is here so im commenting it out
currentDegree = degree;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy){
//not in use
}
private void takePicture() { // takes a picture and stops the image preview
if (camera != null && cameraConfigured && inPreview) {
inPreview = false;
camera.takePicture(null, null, pictureSaver); // take picture with JPEG callback
final ImageButton backButton = (ImageButton)findViewById(R.id.back_button);
backButton.setEnabled(true);
final ImageButton swapCameraButton = (ImageButton)findViewById(R.id.swap_camera_button);
swapCameraButton.setEnabled(false);
}
}
private Camera.PictureCallback pictureSaver = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// To be safe, you should check that the SDCard is mounted using Environment.getExternalStorageState() before doing this.
// This location works best if you want the created images to be shared between applications and persist after your app has been uninstalled.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ShakeItOff");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Error creating picture directory");
return;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
File pictureFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
// add the picture to the gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(pictureFile);
mediaScanIntent.setData(contentUri);
MainActivity.this.sendBroadcast(mediaScanIntent);
}
};
}
|
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.StorageContainerForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.StorageContainerBizLogic;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.SpecimenClass;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.StorageType;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.logger.Logger;
public class StorageContainerAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
* Initializes the various fields in StorageContainer.jsp Page.
* */
protected ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
StorageContainerForm storageContainerForm = (StorageContainerForm) form;
// set the menu selection
request.setAttribute(Constants.MENU_SELECTED, "7" );
Logger.out.info("Add New Attribute in StorageContainerAction:"+request.getAttribute(Constants.SUBMITTED_FOR));
//List of keys used in map of ActionForm
List key = new ArrayList();
key.add("StorageContainerDetails:i_parameterName");
key.add("StorageContainerDetails:i_parameterValue");
//Gets the map from ActionForm
Map map = storageContainerForm.getValues();
//Calling DeleteRow of BaseAction class
MapDataParser.deleteRow(key,map,request.getParameter("status"));
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Add/Edit Institute Page.
request.setAttribute(Constants.OPERATION, operation);
//Sets the activityStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
//Sets the isContainerFullList attribute to be used in the StorageContainer Add/Edit Page.
request.setAttribute(Constants.IS_CONTAINER_FULL_LIST, Constants.IS_CONTAINER_FULL_VALUES );
StorageContainerBizLogic bizLogic = (StorageContainerBizLogic)BizLogicFactory.getInstance().getBizLogic(Constants.STORAGE_CONTAINER_FORM_ID);
/*String []displayField = {"type"};
String valueField = "systemIdentifier";
List list = bizLogic.getList(StorageType.class.getName(),displayField, valueField, false);
request.setAttribute(Constants.STORAGETYPELIST, list);*/
//Populating the Site Array
String []siteDisplayField = {"name"};
String valueField = "systemIdentifier";
List list = bizLogic.getList(Site.class.getName(),siteDisplayField, valueField, true);
request.setAttribute(Constants.SITELIST,list);
//populating collection protocol list.
List list1=bizLogic.retrieve(CollectionProtocol.class.getName());
List collectionProtocolList=getCollectionProtocolList(list1);
request.setAttribute(Constants.PROTOCOL_LIST, collectionProtocolList);
//Gets the Storage Type List and sets it in request
List list2=bizLogic.retrieve(StorageType.class.getName());
List storageTypeListWithAny=getStorageTypeList(list2,true);
request.setAttribute(Constants.HOLDS_LIST1, storageTypeListWithAny);
List StorageTypeListWithoutAny=getStorageTypeList(list2,false);
request.setAttribute(Constants.STORAGETYPELIST, StorageTypeListWithoutAny);
//Gets the Specimen Class Type List and sets it in request
List list3=bizLogic.retrieve(SpecimenClass.class.getName());
List specimenClassTypeList = getSpecimenClassTypeList(list3);
//Collections.sort(specimenClassTypeList);
request.setAttribute(Constants.HOLDS_LIST2, specimenClassTypeList);
boolean isOnChange = false;
boolean typeChange = false;
String type_name="";
String site_name="";
String str = request.getParameter("isOnChange");
if(str!=null && str.equals("true"))
{
isOnChange = true;
}
str = request.getParameter("typeChange");
if(str!=null && str.equals("true"))
{
typeChange = true;
}
Logger.out.info("Onchange parameter in StorageContainerAction:"+isOnChange);
/*if(operation.equals(Constants.ADD))
{
storageContainerForm.setHoldsStorageTypeIds(new long[]{1});
storageContainerForm.setHoldsSpecimenClassTypeIds(new long[]{1});
}*/
// Mandar : code for Addnew Storage Type data 23-Jan-06
String storageTypeID = (String)request.getAttribute(Constants.ADD_NEW_STORAGE_TYPE_ID);
if(storageTypeID != null && storageTypeID.trim().length() > 0 )
{
Logger.out.debug(">>>>>>>>>>><<<<<<<<<<<<<<<<>>>>>>>>>>>>> ST : "+ storageTypeID );
storageContainerForm.setTypeId(Long.parseLong(storageTypeID) );
}
// -- 23-Jan-06 end
// Mandar : code for Addnew Site data 24-Jan-06
String siteID = (String)request.getAttribute(Constants.ADD_NEW_SITE_ID);
if(siteID != null && siteID.trim().length() > 0 )
{
Logger.out.debug(">>>>>>>>>>><<<<<<<<<<<<<<<<>>>>>>>>>>>>> ToSite ID in Distribution Action : "+ siteID );
storageContainerForm.setSiteId(Long.parseLong(siteID));
}
// -- 24-Jan-06 end
if(isOnChange || request.getAttribute(Constants.SUBMITTED_FOR)!=null)
{
long typeSelected=-1;
String selectedType = String.valueOf(storageContainerForm.getTypeId());
Logger.out.debug(">>>>>>>>>>><<<<<<<<<<<<<<<<>>>>>>>>>>>>> ST : "+ selectedType );
if(selectedType != null && !selectedType.equals("-1"))
{
typeSelected = Long.parseLong(selectedType);
list = bizLogic.retrieve(StorageType.class.getName(),valueField,new Long(typeSelected));
if(!list.isEmpty())
{
StorageType type = (StorageType)list.get(0);
if(type.getDefaultTempratureInCentigrade()!= null)
storageContainerForm.setDefaultTemperature(type.getDefaultTempratureInCentigrade().toString() );
storageContainerForm.setOneDimensionCapacity(type.getDefaultStorageCapacity().getOneDimensionCapacity().intValue());
storageContainerForm.setTwoDimensionCapacity(type.getDefaultStorageCapacity().getTwoDimensionCapacity().intValue());
storageContainerForm.setOneDimensionLabel(type.getOneDimensionLabel());
storageContainerForm.setTwoDimensionLabel(Utility.toString(type.getTwoDimensionLabel()));
type_name=type.getType();
Logger.out.debug("Type Name:"+type_name);
// If operation is add opeartion then set the holds list according to storage type selected.
if(operation!=null && typeChange && operation.equals(Constants.ADD))
{
long[] defHoldsStorageTypeList=getDefaultHoldStorageTypeList(type);
if(defHoldsStorageTypeList!=null)
{
storageContainerForm.setHoldsStorageTypeIds(defHoldsStorageTypeList);
}
long[] defHoldsSpecimenClassTypeList=getDefaultHoldsSpecimenClasstypeList(type);
if(defHoldsSpecimenClassTypeList!=null)
{
storageContainerForm.setHoldsSpecimenClassTypeIds(defHoldsSpecimenClassTypeList);
}
}
}
}
else
{
request.setAttribute("storageType", null);
storageContainerForm.setDefaultTemperature("");
storageContainerForm.setOneDimensionCapacity(0);
storageContainerForm.setTwoDimensionCapacity(0);
storageContainerForm.setOneDimensionLabel("Dimension One");
storageContainerForm.setTwoDimensionLabel("Dimension Two");
type_name="";
}
int startNumber = 1;
if(storageContainerForm.getCheckedButton() == 1)
{
Logger.out.debug("storageContainerForm.getSiteId()......................."+storageContainerForm.getSiteId());
Logger.out.debug("storageContainerForm.getTypeId()......................."+storageContainerForm.getTypeId());
list = bizLogic.retrieve(Site.class.getName(),valueField,new Long(storageContainerForm.getSiteId()));
if(!list.isEmpty())
{
Site site = (Site)list.get(0);
site_name=site.getName();
Logger.out.debug("Site Name :"+site_name);
}
}
else
{
Logger.out.debug("Long.parseLong(request.getParameter(parentContainerId)......................."+request.getParameter("parentContainerId"));
Logger.out.debug("storageContainerForm.getTypeId()......................."+storageContainerForm.getTypeId());
list = bizLogic.retrieve(StorageContainer.class.getName(),valueField,new Long(request.getParameter("parentContainerId")));
if(!list.isEmpty())
{
StorageContainer container = (StorageContainer)list.get(0);
site_name=container.getSite().getName();
Logger.out.debug("Site Name :"+site_name);
}
}
Logger.out.debug("Start Number : " + startNumber);
storageContainerForm.setStartNumber(String.valueOf(startNumber));
//Getting the next container number.
String containerNumber="";
if(operation.equals(Constants.ADD))
{
containerNumber=String.valueOf(bizLogic.getNextContainerName());
}
else
{
containerNumber=String.valueOf(storageContainerForm.getSystemIdentifier());
}
if(!type_name.equals("")&& !site_name.equals(""))
{
if(storageContainerForm.getContainerName().equals(""))
{
//generating the default container name
storageContainerForm.setContainerName(site_name+"_"+type_name+"_"+containerNumber);
}
}
}
String reqPath = request.getParameter(Constants.REQ_PATH);
if (reqPath != null)
{
request.setAttribute(Constants.REQ_PATH, reqPath);
}
return mapping.findForward((String)request.getParameter(Constants.PAGEOF));
}
/* This function gets the list of all collection protocols as argument and
* create a list in which nameValueBean is stored with Title and Identifier of Collection Protocol.
* and returns this list
*/
private List getCollectionProtocolList(List list)
{
List collectionProtocolList=new ArrayList();
Iterator cpItr=list.iterator();
while(cpItr.hasNext())
{
CollectionProtocol cp=(CollectionProtocol)cpItr.next();
collectionProtocolList.add(new NameValueBean(cp.getTitle(),cp.getSystemIdentifier()));
}
Collections.sort(collectionProtocolList);
collectionProtocolList.add(0,new NameValueBean("Any","-1"));
return collectionProtocolList;
}
/* this Function gets the list of all storage types as argument and
* create a list in which nameValueBean is stored with Type and Identifier of storage type.
* and returns this list
*/
private List getStorageTypeList(List list,boolean includeAny)
{
NameValueBean typeAny=null;
List storageTypeList=new ArrayList();
Iterator typeItr=list.iterator();
while(typeItr.hasNext())
{
StorageType type=(StorageType)typeItr.next();
if(type.getSystemIdentifier().longValue()==1)
{
typeAny=new NameValueBean(type.getType(),type.getSystemIdentifier());
}
else
{
storageTypeList.add(new NameValueBean(type.getType(),type.getSystemIdentifier()));
}
}
Collections.sort(storageTypeList);
if(includeAny)
{
storageTypeList.add(0,typeAny);
}
else
{
storageTypeList.add(0,new NameValueBean(Constants.SELECT_OPTION,"-1"));
}
return storageTypeList;
}
/* this Function gets the list of all Specimen Class Types as argument and
* create a list in which nameValueBean is stored with Name and Identifier of specimen Class Type.
* and returns this list
*/
private List getSpecimenClassTypeList(List list)
{
List specimenClassTypeList=new ArrayList();
NameValueBean specimenClassAny=null;
Iterator specimentypeItr=list.iterator();
while(specimentypeItr.hasNext())
{
SpecimenClass specimenClass=(SpecimenClass)specimentypeItr.next();
if(specimenClass.getSystemIdentifier().longValue()==1)
{
specimenClassAny=new NameValueBean(specimenClass.getName(),specimenClass.getSystemIdentifier());
}
else
{
specimenClassTypeList.add(new NameValueBean(specimenClass.getName(),specimenClass.getSystemIdentifier()));
}
}
Collections.sort(specimenClassTypeList);
specimenClassTypeList.add(0,specimenClassAny);
return specimenClassTypeList;
}
/* this function finds out the storage type holds list for a storage type given
* and sets the container's storage type holds list
* */
private long[] getDefaultHoldStorageTypeList(StorageType type)
{
//Populating the storage type-id array
Logger.out.info("Storage type size:"+type.getStorageTypeCollection().size());
Collection storageTypeCollection = type.getStorageTypeCollection();
if(storageTypeCollection != null)
{
long holdsStorageTypeList[] = new long[storageTypeCollection.size()];
int i=0;
Iterator it = storageTypeCollection.iterator();
while(it.hasNext())
{
StorageType holdStorageType = (StorageType)it.next();
holdsStorageTypeList[i] = holdStorageType.getSystemIdentifier().longValue();
i++;
}
return holdsStorageTypeList;
}
return null;
}
/* this function finds out the specimen class holds list for a storage type given
* and sets the container's specimen class holds list
* */
private long[] getDefaultHoldsSpecimenClasstypeList(StorageType type)
{
//Populating the specimen class type-id array
Logger.out.info("Specimen class type size:"+type.getSpecimenClassCollection().size());
Collection specimenClassTypeCollection = type.getSpecimenClassCollection();
if(specimenClassTypeCollection != null)
{
long holdsSpecimenClassList[] = new long[specimenClassTypeCollection.size()];
int i=0;
Iterator it = specimenClassTypeCollection.iterator();
while(it.hasNext())
{
SpecimenClass specimenClass = (SpecimenClass)it.next();
holdsSpecimenClassList[i] = specimenClass.getSystemIdentifier().longValue();
i++;
}
return holdsSpecimenClassList;
}
return null;
}
}
|
package edu.wustl.catissuecore.tag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import edu.wustl.catissuecore.actionForm.ViewSpecimenSummaryForm;
import edu.wustl.catissuecore.bean.GenericSpecimen;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.util.global.ApplicationProperties;
/**
* This tag will accept the list of specimens and display them in
* editable or readonly mode.
*
* @author mandar_deshmukh
*
*/
public class GenericSpecimenDetailsTag extends TagSupport
{
private static final long serialVersionUID = 1234567890L;
// data type list used to display different types of data.
private final String dataListTypes[] = {"Parent","Aliquot","Derived"};
public static final String [] COLUMN_NAMES = {
"Parent",
"Label",
"Barcode",
"Type",
"Quantity",
"Concentration",
"Location",
"Collected",
"Class",
"Tissue Site",
"Tissue Side",
"Pathological Status"
};
public static final String [] COLUMN_LABELS = {
"specimen.label",
"specimen.barcode",
"specimen.subType",
"anticipatorySpecimen.Quantity",
"anticipatorySpecimen.Concentration",
"anticipatorySpecimen.Location",
"anticipatorySpecimen.Collected",
"specimen.type",
"specimen.tissueSite",
"specimen.tissueSide",
"specimen.pathologicalStatus"
};
private String displayColumnListName = "";
private String columnHeaderListName = "";
private String dataListName = "";
private String isReadOnly = "";
private String formName = "";
private String dataListType = "";
private String columnListName = "";
private List columnList = null; // List containing column names
private List columnHeaderList = null;
private List displayColumnList = null; // List of columns to show. If name not present hide the column.
private List dataList = null;
private boolean showParentId = false;
private String elementPrefixPart1="";
ViewSpecimenSummaryForm specimenSummaryForm = null;
public GenericSpecimenDetailsTag()
{
super();
}
public String getColumnHeaderListName() {
return columnHeaderListName;
}
public void setColumnHeaderListName(String columnHeaderListName) {
this.columnHeaderListName = columnHeaderListName;
}
public String getDataListName() {
return dataListName;
}
public void setDataListName(String dataListName) {
this.dataListName = dataListName;
}
public String getDisplayColumnListName() {
return displayColumnListName;
}
public void setDisplayColumnListName(String displayColumnListName) {
this.displayColumnListName = displayColumnListName;
}
public String getIsReadOnly() {
return isReadOnly;
}
public void setIsReadOnly(String isReadOnly) {
this.isReadOnly = isReadOnly;
}
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
public String getDataListType() {
return dataListType;
}
public void setDataListType(String dataListType) {
this.dataListType = dataListType;
}
public String getColumnListName() {
return columnListName;
}
public void setColumnListName(String columnListName) {
this.columnListName = columnListName;
}
/**
* A call back function, which gets executed by JSP runtime when opening tag for this
* custom tag is encountered.
*/
public int doStartTag() throws JspException
{
try
{
JspWriter out = pageContext.getOut();
out.print("");
if(validateTagAttributes() )
{
initialiseElements();
if(validateLists())
{
out.print(generateHeaderForDisplay());
out.print(generateRowOutput());
}
else
{
out.print("<b>Column header list is not matching with the display column list.</b>");
}
}
else
{
out.print("<b>Some of the attributes of the tag are missing or are not proper.</b>");
}
}
catch(IOException ioe)
{
throw new JspTagException("Error:IOException while writing to the user");
}
return SKIP_BODY;
}
/**
* A call back function
*/
public int doEndTag() throws JspException
{
displayColumnListName = "";
columnHeaderListName = "";
dataListName = "";
isReadOnly = "";
formName = "";
dataListType = "";
columnList = null;
columnHeaderList = null;
displayColumnList = null;
dataList = null;
showParentId = false;
elementPrefixPart1="";
specimenSummaryForm = null;
return EVAL_PAGE;
}
/* method to validate the given values for the attributes.
* Returns true if all required attributes are in proper valid format. Otherwise returns false.
*/
private boolean validateTagAttributes()
{
boolean result = true;
ServletRequest request = pageContext.getRequest();
ActionErrors errors = (ActionErrors)request.getAttribute(Globals.ERROR_KEY);
if(errors == null)
{
errors = new ActionErrors();
}
if(columnHeaderListName == null || columnHeaderListName.trim().length()<1)
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("Column Header List Name is null or empty"));
result = false;
}
if(isReadOnly == null || isReadOnly.trim().length()<1)
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("DisplayOnly parameter is null or empty"));
result = false;
}
else if(!Constants.TRUE.equalsIgnoreCase(isReadOnly))
{
if(formName == null || formName.trim().length()<1)
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("Form name is null or empty"));
result = false;
}
}
if(dataListName == null || dataListName.trim().length()<1)
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("Data List Name is null or empty"));
result = false;
}
if(dataListType == null || dataListType.trim().length()<1)
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("Data List Type is null or empty"));
result = false;
}
else if(!isListDataTypeOK())
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("Data List Type is invalid"));
result = false;
}
if(displayColumnListName == null || displayColumnListName.trim().length()<1)
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("Display Column List Name is null or empty"));
result = false;
}
request.setAttribute(Globals.ERROR_KEY,errors);
return result;
}
private void initialiseElements()
{
ServletRequest request = pageContext.getRequest();
specimenSummaryForm = (ViewSpecimenSummaryForm)request.getAttribute(formName);
columnHeaderList = (List)request.getAttribute(columnHeaderListName);
dataList = (List)request.getAttribute(dataListName);
displayColumnList = (List)request.getAttribute(displayColumnListName);
columnList = (List)request.getAttribute(columnListName);
if(columnHeaderList == null || columnHeaderList.isEmpty())
{
columnHeaderList = new ArrayList();
if(dataListType.equalsIgnoreCase(dataListTypes[0]))
columnHeaderList.add("");
else
columnHeaderList.add("anticipatorySpecimen.Parent");
for(int i=0;i< GenericSpecimenDetailsTag.COLUMN_LABELS.length; i++)
columnHeaderList.add(GenericSpecimenDetailsTag.COLUMN_LABELS[i]);
}
if(!dataListType.equalsIgnoreCase(dataListTypes[0]))
{
showParentId = true;
}
if(displayColumnList == null || displayColumnList.isEmpty())
{
displayColumnList = new ArrayList();
setFixedColumnsList(displayColumnList);
}
if(columnList == null || columnList.isEmpty())
{
columnList = new ArrayList();
setFixedColumnsList(columnList);
}
}
private boolean isListDataTypeOK()
{
boolean result = false;
for(int cnt=0;cnt<dataListTypes.length; cnt++)
{
if(dataListType.equalsIgnoreCase(dataListTypes[cnt]))
{
if(dataListTypes[0].equalsIgnoreCase(dataListTypes[cnt]))
elementPrefixPart1 = "specimen[";
else
elementPrefixPart1 = dataListTypes[cnt].toLowerCase().trim()+"[";
result = true;
}
}
return result;
}
private List getDataList()
{
List l = new ArrayList();
//setting the data list to be used to display the specimens.
if(dataList == null || dataList.isEmpty())
{
if(specimenSummaryForm != null)
{
if(dataListType.equalsIgnoreCase(dataListTypes[0]))
l = specimenSummaryForm.getSpecimenList();
else if(dataListType.equalsIgnoreCase(dataListTypes[1]))
l = specimenSummaryForm.getAliquotList();
else if(dataListType.equalsIgnoreCase(dataListTypes[2]))
l = specimenSummaryForm.getDerivedList();
}
}
else // get the list from ViewSpecimenSummaryForm based on list type
{
l = dataList;
}
return l;
}
private String getFormattedValue(Object obj)
{
String str = "";
if(obj == null || obj.toString().trim().length() == 0)
{
str = "";
}
else
str = obj.toString();
return str;
}
private String getFormattedValue(Object obj, int space)
{
String str = getFormattedValue(obj);
return (str.trim().length()>0 ? str : " ");
}
private String generateHeaderForDisplay() //throws IOException
{
StringBuffer sb = new StringBuffer();
sb.append("<tr>");
for(int cnt=0;cnt < columnHeaderList.size(); cnt++ )
{
if(((String)columnHeaderList.get(cnt)).trim().length()>0)
sb.append("<th class=\"formSerialNumberLabelForTable\" scope=\"col\">"+ApplicationProperties.getValue((String)columnHeaderList.get(cnt))+"</th>");
else
sb.append("<th class=\"formSerialNumberLabelForTable\" scope=\"col\"> </th>");
}
sb.append("</tr>");
String output =sb.toString();
return output;
}
private boolean validateLists()
{
boolean result = true;
ServletRequest request = pageContext.getRequest();
ActionErrors errors = (ActionErrors)request.getAttribute(Globals.ERROR_KEY);
if(errors == null)
{
errors = new ActionErrors();
}
if(columnHeaderList.size() != displayColumnList.size())
{
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("Column Header List is not matching the Display Column List."));
result = false;
}
request.setAttribute(Globals.ERROR_KEY,errors);
return result;
}
private void setFixedColumnsList(List list)
{
if(list == null){list = new ArrayList();}
for(int i=0;i< GenericSpecimenDetailsTag.COLUMN_NAMES.length; i++)
list.add(GenericSpecimenDetailsTag.COLUMN_NAMES[i]);
}
/*
* Method to generate row output for generic specimen
*/
private String generateRowOutput() throws IOException
{
StringBuffer sb = new StringBuffer();
sb.append("");
List specimenList = getDataList();
for(int counter=0; counter<specimenList.size(); counter++)
{
GenericSpecimen specimen = (GenericSpecimen)specimenList.get(counter);
if(Constants.TRUE.equalsIgnoreCase(isReadOnly) || specimen.getReadOnly() == true)
{
addReadOnlyRow(sb, counter, specimen);
}
else
addEditableRow(sb, counter, specimen);
} // outer most loop for specimenList
sb.append("");
String output =sb.toString();
return output;
}
private void addEditableRow(StringBuffer sb,int counter,GenericSpecimen specimen)
{
sb.append("<tr>");
StringBuffer hiddenElements = new StringBuffer();
hiddenElements.append("");
String elementNamePrefix = elementPrefixPart1+counter+"].";
for(int columnCounter=0; columnCounter<columnList.size(); columnCounter++)
{
if(displayColumnList.contains(columnList.get(columnCounter))) // show element
{
sb.append(getElement(columnCounter,specimen, elementNamePrefix));
} // end of show element
else // start of hide element
{
getHiddenElement(columnCounter,hiddenElements, specimen, elementNamePrefix);
} // end of hide element
}
sb.append("<td width='0'>");
sb.append(hiddenElements.toString());
addRemainingSpecimenElements(sb, elementNamePrefix, specimen);
sb.append("</td>");
sb.append("</tr>");
}
private void getHiddenElement(int counter, StringBuffer hiddenFields, GenericSpecimen specimen, String elementNamePrefix)
{
String nameValue[] = getElementAt( counter, specimen, elementNamePrefix);
if(nameValue.length > 2)
{
for(int i=0; i<nameValue.length; i+=2)
hiddenFields.append("<input type=\"hidden\" name=\""+nameValue[i]+"\" value=\""+nameValue[i+1]+"\">");
}
else
hiddenFields.append("<input type=\"hidden\" name=\""+nameValue[0]+"\" value=\""+nameValue[1]+"\">");
}
private String getElement(int counter, GenericSpecimen specimen, String elementNamePrefix)
{
String nameValue[] = getElementAt( counter, specimen, elementNamePrefix);
StringBuffer sb = new StringBuffer() ;
if(GenericSpecimenDetailsTag.COLUMN_NAMES[0].equalsIgnoreCase(columnList.get(counter).toString()))
{
if(showParentId == false)
{
nameValue[1] = getFormattedValue(specimen.getUniqueIdentifier());
createParentRadioComponent(sb, nameValue);
}
else
{createTextComponent(sb, nameValue, "formFieldSized10");}
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[1].equalsIgnoreCase(columnList.get(counter).toString()))
{
if(specimenSummaryForm.getShowLabel() == true)
{
createTextComponent(sb, nameValue, "formFieldSized10");
}
else{createEmptyCell(sb);}
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[2].equalsIgnoreCase(columnList.get(counter).toString()))
{
if(specimenSummaryForm.getShowbarCode() == true)
{
createTextComponent(sb, nameValue, "formFieldSized10");
}
else{createEmptyCell(sb);}
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[3].equalsIgnoreCase(columnList.get(counter).toString()))
{
createTextComponent(sb, nameValue, "formFieldSized10");
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[4].equalsIgnoreCase(columnList.get(counter).toString()))
{
createTextComponent(sb, nameValue, "formFieldSized3");
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[5].equalsIgnoreCase(columnList.get(counter).toString()))
{
createTextComponent(sb, nameValue, "formFieldSized3");
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[6].equalsIgnoreCase(columnList.get(counter).toString()))
{
//if(specimen.getStorageContainerForSpecimen()!= null && specimen.getStorageContainerForSpecimen().equalsIgnoreCase("Virtual"))
//if((specimen.getStorageContainerForSpecimen()!= null && "Virtual".equalsIgnoreCase(specimen.getStorageContainerForSpecimen())) || (getFormattedValue(specimen.getSelectedContainerName()).trim().length() ==0))
if(specimen.getStorageContainerForSpecimen()!= null && "Virtual".equalsIgnoreCase(specimen.getStorageContainerForSpecimen()))
{
createVirtualStorageComponent( sb, nameValue);
}
else
{
createStorageComponent(sb, nameValue, specimen);
}
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[7].equalsIgnoreCase(columnList.get(counter).toString()))
{
createCollectedComponent(sb, nameValue, "getElement");
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[8].equalsIgnoreCase(columnList.get(counter).toString()))
{
createTextComponent(sb, nameValue, "formFieldSized10");
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[9].equalsIgnoreCase(columnList.get(counter).toString()))
{
createTextComponent(sb, nameValue, "formFieldSized10");
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[10].equalsIgnoreCase(columnList.get(counter).toString()))
{
createTextComponent(sb, nameValue, "formFieldSized10");
// return sb.toString();
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[11].equalsIgnoreCase(columnList.get(counter).toString()))
{
createTextComponent(sb, nameValue, "formFieldSized10");
// return sb.toString();
}
return sb.toString();
}
private String[] getElementAt(int counter, GenericSpecimen specimen, String elementNamePrefix)
{
String s[] = new String[2] ;
if(GenericSpecimenDetailsTag.COLUMN_NAMES[0].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"parentName"; s[1] =getFormattedValue(specimen.getParentName()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[1].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"displayName"; s[1] =getFormattedValue(specimen.getDisplayName()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[2].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"barCode"; s[1] =getFormattedValue(specimen.getBarCode()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[3].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"type"; s[1] =getFormattedValue(specimen.getType()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[4].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"quantity"; s[1] =getFormattedValue(specimen.getQuantity()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[5].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"concentration"; s[1] =getFormattedValue(specimen.getConcentration()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[6].equalsIgnoreCase(columnList.get(counter).toString()))
{
//if((specimen.getStorageContainerForSpecimen()!= null && specimen.getStorageContainerForSpecimen().equalsIgnoreCase("Virtual")) || (getFormattedValue(specimen.getSelectedContainerName()).trim().length() ==0))
if((specimen.getStorageContainerForSpecimen()!= null && "Virtual".equalsIgnoreCase(specimen.getStorageContainerForSpecimen())))
{
s[0] = elementNamePrefix+"storageContainerForSpecimen"; s[1] =getFormattedValue(specimen.getStorageContainerForSpecimen());
}
else
{
s = new String[8];
s[0] = elementNamePrefix+"selectedContainerName"; s[1] =getFormattedValue(specimen.getSelectedContainerName());
s[2] = elementNamePrefix+"positionDimensionOne"; s[3] =getFormattedValue(specimen.getPositionDimensionOne());
s[4] = elementNamePrefix+"positionDimensionTwo"; s[5] =getFormattedValue(specimen.getPositionDimensionTwo());
s[6] = elementNamePrefix+"containerId"; s[7] =getFormattedValue(specimen.getContainerId());
}
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[7].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"checkedSpecimen"; s[1] =getFormattedValue(specimen.getCheckedSpecimen()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[8].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"className"; s[1] =getFormattedValue(specimen.getClassName()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[9].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"tissueSite"; s[1] =getFormattedValue(specimen.getTissueSite()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[10].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"tissueSide"; s[1] =getFormattedValue(specimen.getTissueSide()); }
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[11].equalsIgnoreCase(columnList.get(counter).toString()))
{ s[0] = elementNamePrefix+"pathologicalStatus"; s[1] =getFormattedValue(specimen.getPathologicalStatus()); }
return s;
}
private void createTextComponent(StringBuffer sb, String[] nameValue, String styleClass)
{
sb.append("<td class=\"dataCellText\" >");
sb.append("<input type=\"text\" name=\""+nameValue[0]+"\" value=\""+nameValue[1]+"\" class=\""+styleClass+"\">");
sb.append("</td>");
}
private void createStorageComponent(StringBuffer sb, String[] nameValue, GenericSpecimen specimen)
{
sb.append("<td class=\"dataCellText\" >");
sb.append(getFormattedValue(specimen.getStorageContainerForSpecimen(),1));
String specimenId = getFormattedValue(specimen.getUniqueIdentifier());
String specimenClass = getFormattedValue(specimen.getClassName());
Long collectionProtocolId = specimen.getCollectionProtocolId();
String containerId = "containerId_"+specimenId;
String selectedContainerName = "selectedContainerName_"+specimenId;
String positionDimensionOne = "positionDimensionOne_"+specimenId;
String positionDimensionTwo = "positionDimensionTwo_"+specimenId;
String specimenClassName = (String)specimenClass;
String cpId = getFormattedValue(collectionProtocolId);
String functionCall="showMap('" + selectedContainerName + "','"+
positionDimensionOne +"','"
+ positionDimensionTwo +"','"
+containerId +"','"+
specimenClassName +"','"+
cpId +"')" ;
sb.append("<table style=\"font-size:1em\" size=\"100%\">");
sb.append("<tr>");
sb.append("<td>");
sb.append("<input type=\"text\" name=\""+nameValue[0]+"\" value=\"" + nameValue[1]+"\" class=\"formFieldSized7\" id=\""+selectedContainerName+"\" >");
sb.append("</td>");
sb.append("<td>");
sb.append("<input type=\"text\" name=\""+nameValue[2]+"\" value=\"" + nameValue[3]+"\" class=\"formFieldSized3\" id=\""+positionDimensionOne+"\" >");
sb.append("</td>");
sb.append("<td>");
sb.append("<input type=\"text\" name=\""+nameValue[4]+"\" value=\"" + nameValue[5]+"\" class=\"formFieldSized3\" id=\""+positionDimensionTwo+"\" >");
sb.append("</td>");
sb.append("<td>");
sb.append("<a href=\"#\" onclick=\""+functionCall+"\">");
sb.append("<img src=\"images\\Tree.gif\" border=\"0\" width=\"13\" height=\"15\" title=\'View storage locations\'>");
sb.append("</a>");
sb.append("<input type=\"hidden\" name=\""+nameValue[6]+"\" value=\""+nameValue[7]+"\" id=\""+containerId+"\">");
sb.append("</td>");
sb.append("</tr>");
sb.append("</table>");
sb.append("</td>");
}
private void createVirtualStorageComponent(StringBuffer sb, String[] nameValue)
{
sb.append("<td class=\"dataCellText\" >");
sb.append(getFormattedValue(nameValue[1],1));
sb.append("<input type=\"hidden\" name=\""+nameValue[0]+"\" value=\""+nameValue[1]+"\">");
sb.append("</td>");
}
private void addRemainingSpecimenElements(StringBuffer sb, String elementNamePrefix, GenericSpecimen specimen)
{
String nameValue[][] = getRemainingSpecimenElementsData(specimen, elementNamePrefix);
for(int i =0; i<nameValue.length; i++)
sb.append("<input type=\"hidden\" name=\""+nameValue[i][0]+"\" value=\""+nameValue[i][1]+"\">");
}
private String[][] getRemainingSpecimenElementsData(GenericSpecimen specimen, String elementNamePrefix)
{
String s[][] = new String[4][2];
s[0][0] = elementNamePrefix+"collectionProtocolId"; s[0][1] = getFormattedValue(specimen.getCollectionProtocolId());
s[1][0] = elementNamePrefix+"readOnly"; s[1][1] = getFormattedValue(specimen.getReadOnly());
s[2][0] = elementNamePrefix+"uniqueIdentifier"; s[2][1] = getFormattedValue(specimen.getUniqueIdentifier());
s[3][0] = elementNamePrefix+"id"; s[3][1] = getFormattedValue(specimen.getId());
return s;
}
private void addReadOnlyRow(StringBuffer sb,int counter,GenericSpecimen specimen)
{
sb.append("<tr>");
StringBuffer hiddenElements = new StringBuffer();
hiddenElements.append("");
String elementNamePrefix = elementPrefixPart1+counter+"].";
for(int columnCounter=0; columnCounter<columnList.size(); columnCounter++)
{
if(displayColumnList.contains(columnList.get(columnCounter))) // show element
{
sb.append(getTextElement(columnCounter,specimen, elementNamePrefix));
} // end of show element
getHiddenElement(columnCounter,hiddenElements, specimen, elementNamePrefix);
}
sb.append("<td class=\"dataCellText\" width='0' >");
sb.append(hiddenElements.toString());
addRemainingSpecimenElements(sb, elementNamePrefix, specimen);
sb.append("</td>");
sb.append("</tr>");
}
private String getTextElement(int counter, GenericSpecimen specimen, String elementNamePrefix)
{
String nameValue[] = getElementAt( counter, specimen, elementNamePrefix);
StringBuffer sb = new StringBuffer() ;
if(GenericSpecimenDetailsTag.COLUMN_NAMES[0].equalsIgnoreCase(columnList.get(counter).toString()))
{
if(showParentId == false)
{
nameValue[1] = getFormattedValue(specimen.getUniqueIdentifier());
createParentRadioComponent(sb, nameValue);
}
else
{
sb.append("<td class=\"dataCellText\" >");
sb.append(getFormattedValue(nameValue[1],1));
sb.append("</td>");
}
}
else if(GenericSpecimenDetailsTag.COLUMN_NAMES[7].equalsIgnoreCase(columnList.get(counter).toString()))
{
createCollectedComponent(sb, nameValue,"getTextElement");
}
else
{
sb.append("<td class=\"dataCellText\" >");
if(nameValue.length > 2)
{
if(nameValue[1].trim().length()>0)
{
sb.append(nameValue[1]);sb.append(":");sb.append(nameValue[3]);sb.append(",");sb.append(nameValue[5]);
}
else
{
sb.append(getFormattedValue(specimen.getStorageContainerForSpecimen(),1));
}
}
else
sb.append(getFormattedValue(nameValue[1],1));
sb.append("</td>");
}
return sb.toString();
}
// Generic for testing to be deleted if not used later.
private void createRadioComponent(StringBuffer sb, String[] nameValue, String elementNamePrefix)
{
sb.append("<td class=\"dataCellText\" >");
if(specimenSummaryForm.getSelectedSpecimenId().equalsIgnoreCase(nameValue[1]))
sb.append("<input type=\"radio\" name=\"selectedSpecimenId\" value=\""+nameValue[1]+"\" checked=\"checked\" onclick=\" form.action=\'GenericSpecimenSummary.do\'; submit()\">");
else
sb.append("<input type=\"radio\" name=\"selectedSpecimenId\" value=\""+nameValue[1]+"\" onclick=\" form.action=\'GenericSpecimenSummary.do\'; submit()\">");
sb.append("</td>");
}
private void createParentRadioComponent(StringBuffer sb, String[] nameValue)
{
sb.append("<td class=\"dataCellText\" >");
if(specimenSummaryForm.getSelectedSpecimenId().equalsIgnoreCase(nameValue[1]))
sb.append("<input type=\"radio\" name=\"selectedSpecimenId\" value=\""+nameValue[1]+"\" checked=\"checked\" onclick=\" form.action=\'GenericSpecimenSummary.do\'; submit()\">");
else
sb.append("<input type=\"radio\" name=\"selectedSpecimenId\" value=\""+nameValue[1]+"\" onclick=\" form.action=\'GenericSpecimenSummary.do\'; submit()\">");
// sb.append(nameValue[0]);
sb.append("</td>");
}
private void createCollectedComponent(StringBuffer sb, String[] nameValue, String calledFrom)
{
sb.append("<td class=\"dataCellText\" >");
if(specimenSummaryForm.getShowCheckBoxes() == true)
{
if("getTextElement".equalsIgnoreCase(calledFrom))
{
sb.append("<input type=\"checkbox\" name=\""+nameValue[0]+"\" value=\"true\" disabled=\"true\">");
}
else
{
if(Constants.TRUE.equalsIgnoreCase(nameValue[1]))
sb.append("<input type=\"checkbox\" name=\""+nameValue[0]+"\" value=\"on\" checked=\"checked\">");
else
sb.append("<input type=\"checkbox\" name=\""+nameValue[0]+"\" value=\"on\">");
}
}
else
sb.append(getFormattedValue("",1));
sb.append("</td>");
}
private void createEmptyCell(StringBuffer sb)
{
sb.append("<td class=\"dataCellText\" >");
sb.append(" ");
sb.append("</td>");
}
}
|
package com.ea.orbit.actors.runtime;
import com.ea.orbit.actors.IActor;
import com.ea.orbit.actors.IActorObserver;
import com.ea.orbit.actors.IAddressable;
import com.ea.orbit.actors.IRemindable;
import com.ea.orbit.actors.annotation.StatelessWorker;
import com.ea.orbit.actors.cluster.INodeAddress;
import com.ea.orbit.actors.providers.ILifetimeProvider;
import com.ea.orbit.actors.providers.IOrbitProvider;
import com.ea.orbit.actors.providers.IStorageProvider;
import com.ea.orbit.annotation.Config;
import com.ea.orbit.concurrent.ExecutorUtils;
import com.ea.orbit.concurrent.Task;
import com.ea.orbit.exception.UncheckedException;
import com.ea.orbit.util.ClassPath;
import com.ea.orbit.util.IOUtils;
import com.google.common.collect.MapMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.WeakReference;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Execution implements IRuntime
{
private static final Logger logger = LoggerFactory.getLogger(Execution.class);
private Map<Class<?>, InterfaceDescriptor> descriptorMapByInterface = new HashMap<>();
private Map<Integer, InterfaceDescriptor> descriptorMapByInterfaceId = new HashMap<>();
private Map<EntryKey, ReferenceEntry> localActors = new ConcurrentHashMap<>();
private Map<EntryKey, IActorObserver> observerInstances = new MapMaker().weakValues().makeMap();
// from implementation to reference
private Map<IActorObserver, IActorObserver> observerReferences = new MapMaker().weakKeys().makeMap();
private Hosting hosting;
private Messaging messaging;
private ExecutionSerializer<Object> executionSerializer;
private int maxQueueSize = 10000;
private Timer timer = new Timer("Orbit stage timer");
private Clock clock = Clock.systemUTC();
private long cleanupIntervalMillis = TimeUnit.MINUTES.toMillis(5);
private AtomicLong messagesReceived = new AtomicLong();
private AtomicLong messagesHandled = new AtomicLong();
private AtomicLong refusedExecutions = new AtomicLong();
private ExecutorService executor;
private ActorFactoryGenerator dynamicReferenceFactory = new ActorFactoryGenerator();
@Config("orbit.actors.autoDiscovery")
private boolean autoDiscovery = true;
private List<IOrbitProvider> orbitProviders = new ArrayList<>();
private List<Pattern> actorClassPatterns = new ArrayList<>();
private List<Class<?>> actorClasses = new ArrayList<>();
// list of the actor classes available in this node, computed during startup
private List<String> availableActors;
private final WeakReference<IRuntime> cachedRef = new WeakReference<>(this);
public Execution()
{
// the last runtime created will be the default.
Runtime.runtimeCreated(cachedRef);
}
public void setClock(final Clock clock)
{
this.clock = clock;
}
public void setExecutor(final ExecutorService executor)
{
this.executor = executor;
}
public ExecutorService getExecutor()
{
return executor;
}
public void setActorClassPatterns(List<Pattern> actorClassPatterns)
{
this.actorClassPatterns = actorClassPatterns;
}
public void setActorClasses(List<Class<?>> actorClasses)
{
this.actorClasses = actorClasses;
}
private static class InterfaceDescriptor
{
ActorFactory<?> factory;
ActorInvoker<Object> invoker;
String concreteClassName;
boolean isObserver;
@Override
public String toString()
{
return this.concreteClassName;
}
}
private class ReferenceEntry
{
ActorReference<?> reference;
InterfaceDescriptor descriptor;
boolean statelessWorker;
Activation singleActivation;
ConcurrentLinkedDeque<Activation> statelessActivations;
boolean removable;
public void pushActivation(final Activation activation)
{
if (!statelessWorker)
{
if (singleActivation != null)
{
logger.error("There should be only one single activation! Reference: {}", reference);
}
singleActivation = activation;
}
else
{
statelessActivations.offerLast(activation);
}
}
public Activation popActivation()
{
Activation activation;
if (!statelessWorker)
{
activation = singleActivation;
singleActivation = null;
return (activation != null) ? activation : new Activation(this, null);
}
activation = statelessActivations.pollLast();
return (activation != null) ? activation : new Activation(this, null);
}
public Activation peekOldActivation()
{
if (!statelessWorker)
{
return singleActivation;
}
else
{
return statelessActivations.peekFirst();
}
}
public Task<?> cleanup(final EntryKey key, long cutOut)
{
if (localActors.get(key) != this)
{
logger.warn("Error during cleanup: the ActivationEntry changed. This should not be possible. {}", key);
return Task.done();
}
if (!statelessWorker)
{
if (singleActivation != null)
{
if (singleActivation.instance != null)
{
if (singleActivation.lastAccess > cutOut)
{
// has been used recently enough. not disposing.
return Task.done();
}
// TODO deactivation code
if (singleActivation.instance instanceof OrbitActor)
{
try
{
bind();
OrbitActor<?> orbitActor = (OrbitActor<?>) singleActivation.instance;
Task.allOf(getAllProviders(ILifetimeProvider.class).stream().map(v -> v.preDeactivation(orbitActor)))
.thenCompose(() -> orbitActor.deactivateAsync())
.thenCompose(() -> Task.allOf(getAllProviders(ILifetimeProvider.class).stream().map(v -> v.postDeactivation(orbitActor))))
.thenRun(() -> {
singleActivation.instance = null;
localActors.remove(key);
});
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error("Error during the clean up. " + key, e);
}
}
}
singleActivation.instance = null;
}
}
localActors.remove(key);
return Task.done();
}
else
{
int count = statelessActivations.size();
List<Task<?>> futures = new ArrayList<>();
for (int i = 0; i < count; i++)
{
Activation activation = statelessActivations.pollFirst();
if (activation == null)
{
break;
}
if (activation.lastAccess > cutOut)
{
// return it
statelessActivations.addLast(activation);
}
else
{
if (activation.instance instanceof OrbitActor)
{
try
{
bind();
OrbitActor<?> orbitActor = (OrbitActor<?>) activation.instance;
Task.allOf(getAllProviders(ILifetimeProvider.class).stream().map(v -> v.preDeactivation(orbitActor)))
.thenCompose(() -> orbitActor.deactivateAsync())
.thenCompose(() -> Task.allOf(getAllProviders(ILifetimeProvider.class).stream().map(v -> v.postDeactivation(orbitActor))))
.thenRun(() -> {
activation.instance = null;
});
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error("Error during the clean up. " + key, e);
}
activation.instance = null;
}
}
}
}
if (futures.size() > 0)
{
return Task.allOf(futures);
}
// TODO figure out how to safely remove the entry
}
return Task.done();
}
}
private static class EntryKey
{
int interfaceId;
Object id;
private EntryKey(final int interfaceId, final Object id)
{
this.interfaceId = interfaceId;
this.id = id;
}
@Override
public boolean equals(final Object o)
{
if (this == o) return true;
if (!(o instanceof EntryKey)) return false;
final EntryKey entryKey = (EntryKey) o;
if (interfaceId != entryKey.interfaceId) return false;
if (id != null ? !id.equals(entryKey.id) : entryKey.id != null) return false;
return true;
}
@Override
public int hashCode()
{
int result = interfaceId;
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
@Override
public String toString()
{
return "EntryKey{" +
"interfaceId=" + interfaceId +
", id=" + id +
'}';
}
}
private class Activation
{
ReferenceEntry entry;
long lastAccess = clock.millis();
Object instance;
public Activation(final ReferenceEntry entry, final Object instance)
{
this.entry = entry;
this.instance = instance;
}
// gets or creates the instance
public Object getOrCreateInstance() throws IllegalAccessException, InstantiationException, ExecutionException, InterruptedException
{
if (instance == null)
{
Object newInstance = classForName(entry.descriptor.concreteClassName).newInstance();
if (newInstance instanceof OrbitActor)
{
final OrbitActor<?> orbitActor = (OrbitActor<?>) newInstance;
orbitActor.reference = entry.reference;
orbitActor.stateProvider = getFirstProvider(IStorageProvider.class);
Task.allOf(getAllProviders(ILifetimeProvider.class).stream().map(v -> v.preActivation(orbitActor))).join();
if (orbitActor.stateProvider != null)
{
try
{
orbitActor.readState();
}
catch (Exception ex)
{
if (logger.isErrorEnabled())
{
logger.error("Error reading actor state for: " + entry.reference, ex);
}
throw ex;
}
}
instance = newInstance;
orbitActor.activateAsync().join();
Task.allOf(getAllProviders(ILifetimeProvider.class).stream().map(v -> v.postActivation(orbitActor))).join();
}
}
return instance;
}
}
public void setOrbitProviders(List<IOrbitProvider> orbitProviders)
{
this.orbitProviders = orbitProviders;
}
@SuppressWarnings("unchecked")
public <T extends IOrbitProvider> T getFirstProvider(Class<T> itemType)
{
return (orbitProviders == null) ? null :
(T) orbitProviders.stream().filter(p -> itemType.isInstance(p)).findFirst().orElse(null);
}
@SuppressWarnings("unchecked")
public <T extends IOrbitProvider> List<T> getAllProviders(Class<T> itemType)
{
return orbitProviders == null ? Collections.emptyList()
: (List<T>) orbitProviders.stream().filter(p -> itemType.isInstance(p)).collect(Collectors.toList());
}
public void setHosting(final Hosting hosting)
{
this.hosting = hosting;
}
public void setMessaging(final Messaging messaging)
{
this.messaging = messaging;
}
public Task<?> stop()
{
timer.cancel();
return Task.allOf(orbitProviders.stream().map(v -> v.stop()));
}
@SuppressWarnings("unchecked")
public <T extends IActorObserver> T getObjectReference(final Class<T> iClass, final T observer)
{
final IActorObserver ref = observerReferences.get(observer);
if (ref != null)
{
return (T) ref;
}
return createObjectReference(iClass, observer, null);
}
@SuppressWarnings("unchecked")
public <T extends IActorObserver> T getObserverReference(Class<T> iClass, final T observer, String id)
{
final IActorObserver ref = observerReferences.get(observer);
if (ref != null)
{
return (T) ref;
}
return createObjectReference(iClass, observer, id);
}
@SuppressWarnings("unchecked")
private <T extends IActorObserver> T createObjectReference(final Class<T> iClass, final T observer, String objectId)
{
ActorFactory<?> factory;
if (iClass == null)
{
factory = findFactoryFor(IActorObserver.class, observer);
}
else
{
factory = getDescriptor(iClass).factory;
}
if (factory == null)
{
throw new UncheckedException("Can't find factory for " + observer.getClass());
}
final String id = objectId != null ? objectId : UUID.randomUUID().toString();
EntryKey key = new EntryKey(factory.getInterfaceId(), id);
final IActorObserver existingObserver = observerInstances.get(key);
if (existingObserver == null)
{
final ActorReference<T> reference = (ActorReference<T>) factory.createReference(id);
if (objectId == null)
{
reference.address = messaging.getNodeAddress();
}
reference.runtime = Execution.this;
observerInstances.putIfAbsent(key, observer);
observerReferences.putIfAbsent(observer, (IActorObserver) reference);
return (T) reference;
}
else if (observer != existingObserver)
{
throw new IllegalArgumentException("ActorObserver id clashes with a pre existing observer: " + id);
}
return (T) observerReferences.get(observer);
}
public Registration registerTimer(final OrbitActor<?> actor,
final Callable<Task<?>> taskCallable,
final long dueTime, final long period,
final TimeUnit timeUnit)
{
final TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
// TODO decide if it's necessary to change the key here for the actor activation?
executionSerializer.offerJob(actor,
() -> {
bind();
try
{
return taskCallable.call();
}
catch (Exception ex)
{
logger.warn("Error calling timer", ex);
}
return Task.done();
}, 1000);
}
};
timer.schedule(timerTask, timeUnit.toMillis(dueTime), timeUnit.toMillis(period));
return () -> timerTask.cancel();
}
public void bind()
{
Runtime.setRuntime(this.cachedRef);
}
public void bind(Object object)
{
if(!(object instanceof ActorReference))
{
throw new IllegalArgumentException("Must be a reference");
}
((ActorReference<?>) object).runtime = this;
}
@Override
public Clock clock()
{
return clock;
}
@Override
public Task<?> registerReminder(final IRemindable actor, final String reminderName, final long dueTime, final long period, final TimeUnit timeUnit)
{
return getReference(IReminderController.class, "0").registerOrUpdateReminder(actor, reminderName, new Date(clock.millis() + timeUnit.toMillis(dueTime)), period, timeUnit);
}
@Override
public Task<?> unregisterReminder(final IRemindable actor, final String reminderName)
{
return getReference(IReminderController.class, "0").unregisterReminder(actor, reminderName);
}
@SuppressWarnings("unchecked")
public void start()
{
final List<ClassPath.ResourceInfo> actorClassesRes = ClassPath.get().getAllResources().stream().filter(r -> r.getResourceName().startsWith("META-INF/orbit/actors/classes")).collect(Collectors.toList());
final List<Class<?>> actorInterfaces = new ArrayList<>();
if (actorClassPatterns != null && actorClassPatterns .size() > 0)
{
// finding classes in the classpath
Set<Class<?>> iActors = ClassPath.get().getAllResources().stream()
.filter(r -> r.getResourceName().endsWith(".class"))
.map(r -> r.getResourceName().substring(0, r.getResourceName().length() - 6).replace("/", "."))
.filter(cn -> actorClassPatterns.stream().anyMatch(i -> i.matcher(cn).matches()))
.map(cn -> classForName(cn, true))
.filter(c -> c != null && (IActor.class.isAssignableFrom(c) || (c.isInterface() && IActorObserver.class.isAssignableFrom(c))))
.collect(Collectors.toSet());
actorClasses.addAll(iActors.stream().filter(c -> OrbitActor.class.isAssignableFrom(c)).collect(Collectors.toList()));
actorInterfaces.addAll(iActors.stream().filter(c -> c.isInterface()).collect(Collectors.toList()));
}
List<ClassPath.ResourceInfo> actorInterfacesRes = ClassPath.get().getAllResources().stream().filter(r -> r.getResourceName().startsWith("META-INF/orbit/actors/interfaces")).collect(Collectors.toList());
try
{
for (ClassPath.ResourceInfo irs : actorInterfacesRes)
{
InterfaceDescriptor descriptor = new InterfaceDescriptor();
String nameFactoryName = IOUtils.toString(irs.url().openStream());
descriptor.factory = (ActorFactory<?>) classForName(nameFactoryName).newInstance();
descriptor.invoker = (ActorInvoker<Object>) descriptor.factory.getInvoker();
descriptor.isObserver = IActorObserver.class.isAssignableFrom(descriptor.factory.getInterface());
descriptorMapByInterface.put(descriptor.factory.getInterface(), descriptor);
descriptorMapByInterfaceId.put(descriptor.factory.getInterfaceId(), descriptor);
}
// install other interface not listed by resources
actorInterfaces.forEach(c -> getDescriptor(c));
List<String> availableActors = new ArrayList<>();
if (autoDiscovery)
{
for (ClassPath.ResourceInfo irs : actorClassesRes)
{
String className = irs.getResourceName().substring("META-INF/orbit/actors/classes".length() + 1);
Class<?> actorClass = classForName(className);
for (Class<?> interfaceClass : actorClass.getInterfaces())
{
final InterfaceDescriptor interfaceDescriptor = descriptorMapByInterface.get(interfaceClass);
if (interfaceDescriptor != null)
{
availableActors.add(interfaceDescriptor.factory.getInterface().getName());
interfaceDescriptor.concreteClassName = IOUtils.toString(irs.url().openStream());
break;
}
}
}
}
if (actorClasses != null && !actorClasses.isEmpty())
{
for (Class<?> actorClass : actorClasses)
{
for (Class<?> interfaceClass : actorClass.getInterfaces())
{
if (IActor.class.isAssignableFrom(interfaceClass))
{
final InterfaceDescriptor interfaceDescriptor = getDescriptor(interfaceClass);
if (interfaceDescriptor != null)
{
availableActors.add(interfaceDescriptor.factory.getInterface().getName());
interfaceDescriptor.concreteClassName = actorClass.getName();
break;
}
}
}
}
}
this.availableActors = Collections.unmodifiableList(availableActors);
}
catch (Throwable e)
{
throw new UncheckedException(e);
}
getDescriptor(IHosting.class);
createObjectReference(IHosting.class, hosting, "");
if (executor == null)
{
executor = ExecutorUtils.newScalingThreadPool(1000);
}
executionSerializer = new ExecutionSerializer<>(executor);
orbitProviders.forEach(v -> v.start());
// schedules the cleanup
timer.schedule(new TimerTask()
{
@Override
public void run()
{
ForkJoinTask.adapt(() -> activationCleanup(true)).fork();
}
}, cleanupIntervalMillis, cleanupIntervalMillis);
// TODO move this logic the messaging class
// schedules the message cleanup
timer.schedule(new TimerTask()
{
@Override
public void run()
{
messaging.timeoutCleanup();
}
}, 5000, 5000);
}
private Class<?> classForName(final String className)
{
return classForName(className, false);
}
private Class<?> classForName(final String className, boolean ignoreException)
{
try
{
return Class.forName(className);
}
catch (Error | Exception ex)
{
if (!ignoreException)
{
throw new Error("Error loading class: " + className, ex);
}
}
return null;
}
private ActorFactory<?> findFactoryFor(final Class<?> baseInterface, final Object instance)
{
for (Class<?> aInterface : instance.getClass().getInterfaces())
{
if (baseInterface.isAssignableFrom(aInterface))
{
ActorFactory<?> factory = getDescriptor(aInterface).factory;
if (factory != null)
{
return factory;
}
}
}
return null;
}
@SuppressWarnings("unchecked")
private InterfaceDescriptor getDescriptor(final Class<?> aInterface)
{
InterfaceDescriptor interfaceDescriptor = descriptorMapByInterface.get(aInterface);
if (interfaceDescriptor == null)
{
if (aInterface == IActor.class || aInterface == IActorObserver.class || !aInterface.isInterface())
{
return null;
}
interfaceDescriptor = new InterfaceDescriptor();
interfaceDescriptor.isObserver = IActorObserver.class.isAssignableFrom(aInterface);
interfaceDescriptor.factory = dynamicReferenceFactory.getFactoryFor(aInterface);
interfaceDescriptor.invoker = (ActorInvoker<Object>) interfaceDescriptor.factory.getInvoker();
descriptorMapByInterface.put(aInterface, interfaceDescriptor);
descriptorMapByInterfaceId.put(interfaceDescriptor.factory.getInterfaceId(), interfaceDescriptor);
}
return interfaceDescriptor;
}
private InterfaceDescriptor getDescriptor(final int interfaceId)
{
return descriptorMapByInterfaceId.get(interfaceId);
}
public void onMessageReceived(final INodeAddress from,
final boolean oneway, final int messageId, final int interfaceId, final int methodId,
final Object key, final Object[] params)
{
EntryKey entryKey = new EntryKey(interfaceId, key);
if (logger.isDebugEnabled())
{
logger.debug("onMessageReceived for: " + entryKey);
}
messagesReceived.incrementAndGet();
if (!executionSerializer.offerJob(entryKey,
() -> handleOnMessageReceived(entryKey, from, oneway, messageId, interfaceId, methodId, key, params), maxQueueSize))
{
refusedExecutions.incrementAndGet();
if (logger.isErrorEnabled())
{
logger.error("Execution refused: " + key + ":" + interfaceId + ":" + methodId + ":" + messageId);
}
if (!oneway)
{
messaging.sendResponse(from, MessageDefinitions.ERROR_RESPONSE, messageId, "Execution refused");
}
}
}
// this method is executed serially by entryKey
private Task<?> handleOnMessageReceived(final EntryKey entryKey, final INodeAddress from,
final boolean oneway, final int messageId, final int interfaceId,
final int methodId, final Object key,
final Object[] params)
{
messagesHandled.incrementAndGet();
final InterfaceDescriptor descriptor = getDescriptor(interfaceId);
if (descriptor.isObserver)
{
final IActorObserver observer = observerInstances.get(entryKey);
if (observer == null)
{
if (!oneway)
{
messaging.sendResponse(from, MessageDefinitions.ERROR_RESPONSE, messageId, "Observer no longer present");
}
return Task.done();
}
final Task<?> task = descriptor.invoker.safeInvoke(observer, methodId, params);
return task.whenComplete((r, e) ->
sendResponseAndLogError(oneway, from, messageId, (Object) r, e));
}
ReferenceEntry entry = localActors.get(entryKey);
if (logger.isDebugEnabled())
{
logger.debug("handleOnMessageReceived for: " + descriptor + ":" + key);
}
if (entry == null)
{
// TODO check if this is the activation node. Otherwise forward to the activation node.
entry = new ReferenceEntry();
entry.descriptor = descriptor;
entry.statelessWorker = descriptor.factory.getInterface().isAnnotationPresent(StatelessWorker.class);
if (entry.statelessWorker)
{
entry.statelessActivations = new ConcurrentLinkedDeque<>();
}
entry.reference = (ActorReference<?>) descriptor.factory.createReference(key != null ? String.valueOf(key) : null);
entry.reference.runtime = this;
entry.removable = true;
ReferenceEntry old = localActors.putIfAbsent(entryKey, entry);
if (old != null)
{
// this should be impossible if all accesses are serial.
logger.error("Unexpected state: Non serial access to entry!");
entry = old;
}
}
final ReferenceEntry theEntry = entry;
if (!entry.statelessWorker)
{
return executeMessage(theEntry, oneway, descriptor, methodId, params, from, messageId);
}
else
{
if (!executionSerializer.offerJob(null,
() -> executeMessage(theEntry, oneway, descriptor, methodId, params, from, messageId),
maxQueueSize))
{
refusedExecutions.incrementAndGet();
if (logger.isErrorEnabled())
{
logger.info("Execution refused: " + key + ":" + interfaceId + ":" + methodId + ":" + messageId);
}
if (!oneway)
{
messaging.sendResponse(from, MessageDefinitions.ERROR_RESPONSE, messageId, "Execution refused");
}
}
return Task.done();
}
}
private Task<?> executeMessage(
final ReferenceEntry theEntry,
final boolean oneway,
final InterfaceDescriptor descriptor,
final int methodId,
final Object[] params,
final INodeAddress from,
final int messageId)
{
try
{
Activation activation = theEntry.popActivation();
activation.lastAccess = clock.millis();
Task<?> future;
try
{
bind();
future = descriptor.invoker.safeInvoke(activation.getOrCreateInstance(), methodId, params);
return future.whenComplete((r, e) -> {
sendResponseAndLogError(oneway, from, messageId, r, e);
});
}
finally
{
// we don't need to unset the Runtime, @see Runtime.setRuntime:
theEntry.pushActivation(activation);
}
}
catch (Exception ex)
{
sendResponseAndLogError(oneway, from, messageId, null, ex);
}
return Task.done();
}
protected void sendResponseAndLogError(boolean oneway, final INodeAddress from, int messageId, Object result, Throwable exception)
{
if (exception != null && logger.isErrorEnabled())
{
logger.error("Unknown application error. ", exception);
}
if (!oneway)
{
try
{
if (exception == null)
{
messaging.sendResponse(from, MessageDefinitions.NORMAL_RESPONSE, messageId, result);
}
else
{
messaging.sendResponse(from, MessageDefinitions.EXCEPTION_RESPONSE, messageId, exception);
}
}
catch (Exception ex2)
{
if (logger.isErrorEnabled())
{
logger.error("Error sending method result", ex2);
}
try
{
messaging.sendResponse(from, MessageDefinitions.EXCEPTION_RESPONSE, messageId, ex2);
}
catch (Exception ex3)
{
if (logger.isErrorEnabled())
{
logger.error("Failed twice sending result. ", ex2);
}
try
{
messaging.sendResponse(from, MessageDefinitions.ERROR_RESPONSE, messageId, "failed twice sending result");
}
catch (Exception ex4)
{
logger.error("Failed sending exception. ", ex4);
}
}
}
}
}
@SuppressWarnings({"unchecked"})
<T extends IActorObserver> T createReference(final INodeAddress a, final Class<T> iClass, String id)
{
final InterfaceDescriptor descriptor = getDescriptor(iClass);
ActorReference<?> reference = (ActorReference<?>) descriptor.factory.createReference("");
reference.address = a;
reference.runtime = this;
reference.id = id;
return (T) reference;
}
@SuppressWarnings("unchecked")
public <T extends IActor> T getReference(final Class<T> iClass, final Object id)
{
final InterfaceDescriptor descriptor = getDescriptor(iClass);
ActorReference<?> reference = (ActorReference<?>) descriptor.factory.createReference(id != null ? String.valueOf(id) : null);
reference.runtime = this;
return (T) reference;
}
public Task<?> sendMessage(IAddressable toReference, boolean oneWay, final int methodId, final Object[] params)
{
if (logger.isDebugEnabled())
{
logger.debug("sending message to " + toReference);
}
ActorReference<?> actorReference = (ActorReference<?>) toReference;
INodeAddress toNode = actorReference.address;
if (toNode == null)
{
return hosting.locateActor(actorReference)
.thenCompose(x -> messaging.sendMessage(x, oneWay, actorReference._interfaceId(), methodId, actorReference.id, params));
}
return messaging.sendMessage(toNode, oneWay, actorReference._interfaceId(), methodId, actorReference.id, params);
}
public void activationCleanup(boolean block)
{
long cutOut = clock.millis() - TimeUnit.MINUTES.toMillis(10);
final List<CompletableFuture<?>> futures = block ? new ArrayList<>() : null;
for (Iterator<Map.Entry<EntryKey, ReferenceEntry>> iterator = localActors.entrySet().iterator(); iterator.hasNext(); )
{
Map.Entry<EntryKey, ReferenceEntry> mEntry = iterator.next();
final ReferenceEntry entry = mEntry.getValue();
if (!entry.removable)
{
continue;
}
Activation act = entry.peekOldActivation();
if (act == null)
{
continue;
}
if (act.lastAccess < cutOut)
{
CompletableFuture<Object> future = new CompletableFuture<>();
final Supplier<Task<?>> task = () -> {
try
{
final Task<?> res = entry.cleanup(mEntry.getKey(), cutOut);
if (res != null && !res.isDone())
{
res.whenComplete((r, e) -> {
if (e != null)
{
future.completeExceptionally(e);
}
else
{
future.complete(r);
}
});
}
else
{
future.complete(null);
}
return res;
}
catch (Error | RuntimeException ex)
{
future.completeExceptionally(ex);
throw ex;
}
catch (Throwable ex)
{
future.completeExceptionally(ex);
throw new UncheckedException(ex);
}
};
if (executionSerializer.offerJob(mEntry.getKey(), task, maxQueueSize) && block)
{
futures.add(future);
}
}
}
if (block)
{
Task.allOf(futures).join();
}
}
public boolean isAutoDiscovery()
{
return autoDiscovery;
}
public void setAutoDiscovery(final boolean autoDiscovery)
{
this.autoDiscovery = autoDiscovery;
}
public void addActorClasses(Collection<Class<?>> classes)
{
actorClasses.addAll(classes);
}
public List<String> getAvailableActors()
{
return availableActors;
}
}
|
package com.github.ambry.rest;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.MetricRegistry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Construct to support end-to-end metrics tracking based on request type. Usually accompanies a single
* {@link RestRequest} i.e. there is a one-to-one mapping b/w a {@link RestRequest} and a RestRequestMetrics instance.
*/
public class RestRequestMetrics {
protected static final String DEFAULT_REQUEST_TYPE = "Unknown";
protected static final String NIO_REQUEST_PROCESSING_TIME_SUFFIX = "NioRequestProcessingTime";
protected static final String NIO_RESPONSE_PROCESSING_TIME_SUFFIX = "NioResponseProcessingTime";
protected static final String SC_REQUEST_PROCESSING_TIME_SUFFIX = "ScRequestProcessingTime";
protected static final String SC_REQUEST_QUEUING_TIME_SUFFIX = "ScRequestQueuingTime";
protected static final String SC_RESPONSE_PROCESSING_TIME_SUFFIX = "ScResponseProcessingTime";
protected static final String SC_RESPONSE_QUEUING_TIME_SUFFIX = "ScResponseQueuingTime";
protected static final String TOTAL_TIME_SUFFIX = "TotalTime";
private static RequestMetricsTracker defaultMetricsTracker;
/**
* Metrics that should be updated in the NIO layer.
*/
public final NioLayerMetrics nioLayerMetrics = new NioLayerMetrics();
/**
* Metrics that should be updated in the scaling layer.
*/
public final ScalingLayerMetrics scalingLayerMetrics = new ScalingLayerMetrics();
private final AtomicLong totalTime = new AtomicLong(0);
private final AtomicBoolean metricsRecorded = new AtomicBoolean(false);
private RequestMetricsTracker metricsTracker = defaultMetricsTracker;
/**
* A metrics tracker that is provided as input to {@link #injectTracker(RequestMetricsTracker)}.
* </p>
* It is expected that each request type will have it's own instance of RequestMetricsTracker and the same instance is
* used to track all requests of that type.
*/
public static class RequestMetricsTracker {
private final Histogram nioRequestProcessingTime;
private final Histogram nioResponseProcessingTime;
private final Histogram scRequestProcessingTime;
private final Histogram scRequestQueuingTime;
private final Histogram scResponseProcessingTime;
private final Histogram scResponseQueuingTime;
private final Histogram totalTime;
public RequestMetricsTracker(Class ownerClass, String requestType, MetricRegistry metricRegistry) {
if (ownerClass == null || requestType == null || metricRegistry == null) {
throw new IllegalArgumentException(
"Null arg(s) during instantiation. Owner class - [" + ownerClass + "]. Request type - [" + requestType
+ "]. Metric registry - [" + metricRegistry + "]");
}
nioRequestProcessingTime =
metricRegistry.histogram(MetricRegistry.name(ownerClass, requestType + NIO_REQUEST_PROCESSING_TIME_SUFFIX));
nioResponseProcessingTime =
metricRegistry.histogram(MetricRegistry.name(ownerClass, requestType + NIO_RESPONSE_PROCESSING_TIME_SUFFIX));
scRequestProcessingTime =
metricRegistry.histogram(MetricRegistry.name(ownerClass, requestType + SC_REQUEST_PROCESSING_TIME_SUFFIX));
scRequestQueuingTime =
metricRegistry.histogram(MetricRegistry.name(ownerClass, requestType + SC_REQUEST_QUEUING_TIME_SUFFIX));
scResponseProcessingTime =
metricRegistry.histogram(MetricRegistry.name(ownerClass, requestType + SC_RESPONSE_PROCESSING_TIME_SUFFIX));
scResponseQueuingTime =
metricRegistry.histogram(MetricRegistry.name(ownerClass, requestType + SC_RESPONSE_QUEUING_TIME_SUFFIX));
totalTime = metricRegistry.histogram(MetricRegistry.name(ownerClass, requestType + TOTAL_TIME_SUFFIX));
}
}
/**
* Metrics that are updated at the NIO layer.
*/
public class NioLayerMetrics {
private final AtomicLong requestProcessingTime = new AtomicLong(0);
private final AtomicLong responseProcessingTime = new AtomicLong(0);
/**
* Adds to the time taken to process the request at the NIO layer. Also adds to the total time taken to service the
* request.
* @param delta the time taken in ms to do the current piece of processing at the NIO layer for the request.
* @return the total time taken in ms to process the request at the NIO layer, including the current piece, at this
* moment.
*/
public long addToRequestProcessingTime(long delta) {
addToTotalTime(delta);
return requestProcessingTime.addAndGet(delta);
}
/**
* Adds to the time taken to process the response at the NIO layer. Also adds to the total time taken to service the
* request.
* @param delta the time taken in ms to do the current piece of processing at the NIO layer for the response.
* @return the total time taken in ms to process the response at the NIO layer, including the current piece, at this
* moment.
*/
public long addToResponseProcessingTime(long delta) {
addToTotalTime(delta);
return responseProcessingTime.addAndGet(delta);
}
}
/**
* Metrics that are updated at the scaling layer.
*/
public class ScalingLayerMetrics {
private final AtomicLong requestProcessingTime = new AtomicLong(0);
private final AtomicLong requestQueuingTime = new AtomicLong(0);
private final AtomicLong responseProcessingTime = new AtomicLong(0);
private final AtomicLong responseQueuingTime = new AtomicLong(0);
/**
* Adds to the time taken to process a request at the scaling layer. Also adds to the total time taken to service
* the request.
* @param delta the time taken in ms to do the current piece of processing at the scaling layer for the request.
* @return the total time taken in ms to process this request at the scaling layer, including the current piece, at
* this moment.
*/
public long addToRequestProcessingTime(long delta) {
addToTotalTime(delta);
return requestProcessingTime.addAndGet(delta);
}
/**
* Adds to the scaling layer queuing time of a request. Also adds to the total time taken to service the request.
* @param delta the time in ms a request has spent being queued at the scaling layer.
* @return the total time in ms this request has spent being queued at the scaling layer at this moment.
*/
public long addToRequestQueuingTime(long delta) {
addToTotalTime(delta);
return requestQueuingTime.addAndGet(delta);
}
/**
* Adds to the time taken to process a response at the scaling layer. Also adds to the total time taken to service
* the request.
* @param delta the time taken in ms to do the current piece of processing at the scaling layer for the response.
* @return the total time taken in ms to process the response at the scaling layer, including the current piece, at
* this moment.
*/
public long addToResponseProcessingTime(long delta) {
addToTotalTime(delta);
return responseProcessingTime.addAndGet(delta);
}
/**
* Adds to the scaling layer queuing time of a response. Also adds to the total time taken to service the request.
* @param delta the time in ms a response has spent being queued at the scaling layer.
* @return the total time in ms this response has spent being queued at the scaling layer at this moment.
*/
public long addToResponseQueuingTime(long delta) {
addToTotalTime(delta);
return responseQueuingTime.addAndGet(delta);
}
}
/**
* Adds to the total time taken in ms to service the request.
* @param delta the time taken in ms to do the current piece of processing for the request.
* @return the total time taken in ms to service the request across all layers, including the current piece,
* at this moment.
*/
public long addToTotalTime(long delta) {
return totalTime.addAndGet(delta);
}
/**
* Injects a {@link RequestMetricsTracker} that can be used to track the metrics of the {@link RestRequest} that this
* instance of RestRequestMetrics is attached to.
* @param requestMetricsTracker the {@link RequestMetricsTracker} instance to use to track the metrics of the
* {@link RestRequest} that this instance of RestRequestMetrics is attached to.
*/
public void injectTracker(RequestMetricsTracker requestMetricsTracker) {
if (metricsTracker != null) {
metricsTracker = requestMetricsTracker;
} else {
throw new IllegalArgumentException("RequestMetricsTracker provided cannot be null");
}
}
/**
* Records the metrics.
* </p>
* This method is expected to called when the {@link RestRequest}, that this instance of {@link RestRequestMetrics} is
* attached to, finishes.
*/
public void recordMetrics() {
if (metricsTracker != null) {
if (metricsRecorded.compareAndSet(false, true)) {
metricsTracker.nioRequestProcessingTime.update(nioLayerMetrics.requestProcessingTime.get());
metricsTracker.nioResponseProcessingTime.update(nioLayerMetrics.responseProcessingTime.get());
metricsTracker.scRequestProcessingTime.update(scalingLayerMetrics.requestProcessingTime.get());
metricsTracker.scRequestQueuingTime.update(scalingLayerMetrics.requestQueuingTime.get());
metricsTracker.scResponseProcessingTime.update(scalingLayerMetrics.responseProcessingTime.get());
metricsTracker.scResponseQueuingTime.update(scalingLayerMetrics.responseQueuingTime.get());
metricsTracker.totalTime.update(totalTime.get());
}
} else {
throw new IllegalStateException("Could not record metrics because there is no metrics tracker");
}
}
/**
* Creates a default {@link RequestMetricsTracker} in case {@link #injectTracker(RequestMetricsTracker)} is never
* called on an instance of {@link RestRequestMetrics}.
* @param metricRegistry the {@link MetricRegistry} to use to register the created metrics.
*/
public static void setDefaults(MetricRegistry metricRegistry) {
defaultMetricsTracker = new RequestMetricsTracker(RestRequestMetrics.class, DEFAULT_REQUEST_TYPE, metricRegistry);
}
}
|
/**
* Component to orchestrate the Twilio Video connection and the various video
* views.
* <p>
* Authors:
* Ralph Pina <ralph.pina@gmail.com>
* Jonathan Chang <slycoder@gmail.com>
*/
package com.twiliorn.library;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.StringDef;
import android.util.Log;
import android.view.View;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.twilio.video.AudioTrackPublication;
import com.twilio.video.BaseTrackStats;
import com.twilio.video.CameraCapturer;
import com.twilio.video.ConnectOptions;
import com.twilio.video.LocalAudioTrack;
import com.twilio.video.LocalAudioTrackStats;
import com.twilio.video.LocalParticipant;
import com.twilio.video.LocalTrackStats;
import com.twilio.video.LocalVideoTrack;
import com.twilio.video.LocalVideoTrackStats;
import com.twilio.video.Participant;
import com.twilio.video.RemoteAudioTrack;
import com.twilio.video.RemoteAudioTrackPublication;
import com.twilio.video.RemoteAudioTrackStats;
import com.twilio.video.LocalDataTrack;
import com.twilio.video.RemoteDataTrack;
import com.twilio.video.RemoteDataTrackPublication;
import com.twilio.video.RemoteParticipant;
import com.twilio.video.RemoteTrackStats;
import com.twilio.video.RemoteVideoTrack;
import com.twilio.video.RemoteVideoTrackPublication;
import com.twilio.video.RemoteVideoTrackStats;
import com.twilio.video.Room;
import com.twilio.video.Room.State;
import com.twilio.video.StatsListener;
import com.twilio.video.StatsReport;
import com.twilio.video.TrackPublication;
import com.twilio.video.TwilioException;
import com.twilio.video.Video;
import com.twilio.video.VideoConstraints;
import com.twilio.video.VideoDimensions;
import org.webrtc.voiceengine.WebRtcAudioManager;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_AUDIO_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CAMERA_SWITCHED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECT_FAILURE;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DATATRACK_MESSAGE_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_DATA_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_DATA_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_STATS_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_VIDEO_CHANGED;
public class CustomTwilioVideoView extends View implements LifecycleEventListener, AudioManager.OnAudioFocusChangeListener {
private static final String TAG = "CustomTwilioVideoView";
private static final String DATA_TRACK_MESSAGE_THREAD_NAME = "DataTrackMessages";
private boolean enableRemoteAudio = false;
private boolean isVideoEnabled = false;
@Retention(RetentionPolicy.SOURCE)
@StringDef({Events.ON_CAMERA_SWITCHED,
Events.ON_VIDEO_CHANGED,
Events.ON_AUDIO_CHANGED,
Events.ON_CONNECTED,
Events.ON_CONNECT_FAILURE,
Events.ON_DISCONNECTED,
Events.ON_PARTICIPANT_CONNECTED,
Events.ON_PARTICIPANT_DISCONNECTED,
Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK,
Events.ON_DATATRACK_MESSAGE_RECEIVED,
Events.ON_PARTICIPANT_ADDED_DATA_TRACK,
Events.ON_PARTICIPANT_REMOVED_DATA_TRACK,
Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK,
Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK,
Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK,
Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK,
Events.ON_STATS_RECEIVED})
public @interface Events {
String ON_CAMERA_SWITCHED = "onCameraSwitched";
String ON_VIDEO_CHANGED = "onVideoChanged";
String ON_AUDIO_CHANGED = "onAudioChanged";
String ON_CONNECTED = "onRoomDidConnect";
String ON_CONNECT_FAILURE = "onRoomDidFailToConnect";
String ON_DISCONNECTED = "onRoomDidDisconnect";
String ON_PARTICIPANT_CONNECTED = "onRoomParticipantDidConnect";
String ON_PARTICIPANT_DISCONNECTED = "onRoomParticipantDidDisconnect";
String ON_DATATRACK_MESSAGE_RECEIVED = "onDataTrackMessageReceived";
String ON_PARTICIPANT_ADDED_DATA_TRACK = "onParticipantAddedDataTrack";
String ON_PARTICIPANT_REMOVED_DATA_TRACK = "onParticipantRemovedDataTrack";
String ON_PARTICIPANT_ADDED_VIDEO_TRACK = "onParticipantAddedVideoTrack";
String ON_PARTICIPANT_REMOVED_VIDEO_TRACK = "onParticipantRemovedVideoTrack";
String ON_PARTICIPANT_ADDED_AUDIO_TRACK = "onParticipantAddedAudioTrack";
String ON_PARTICIPANT_REMOVED_AUDIO_TRACK = "onParticipantRemovedAudioTrack";
String ON_PARTICIPANT_ENABLED_VIDEO_TRACK = "onParticipantEnabledVideoTrack";
String ON_PARTICIPANT_DISABLED_VIDEO_TRACK = "onParticipantDisabledVideoTrack";
String ON_PARTICIPANT_ENABLED_AUDIO_TRACK = "onParticipantEnabledAudioTrack";
String ON_PARTICIPANT_DISABLED_AUDIO_TRACK = "onParticipantDisabledAudioTrack";
String ON_STATS_RECEIVED = "onStatsReceived";
}
private final ThemedReactContext themedReactContext;
private final RCTEventEmitter eventEmitter;
private AudioFocusRequest audioFocusRequest;
private AudioAttributes playbackAttributes;
private Handler handler = new Handler();
/*
* A Room represents communication between the client and one or more participants.
*/
private static Room room;
private String roomName = null;
private String accessToken = null;
private LocalParticipant localParticipant;
/*
* A VideoView receives frames from a local or remote video track and renders them
* to an associated view.
*/
private static PatchedVideoView thumbnailVideoView;
private static LocalVideoTrack localVideoTrack;
private static CameraCapturer cameraCapturer;
private LocalAudioTrack localAudioTrack;
private AudioManager audioManager;
private int previousAudioMode;
private boolean disconnectedFromOnDestroy;
private IntentFilter intentFilter;
private BecomingNoisyReceiver myNoisyAudioStreamReceiver;
// Dedicated thread and handler for messages received from a RemoteDataTrack
private final HandlerThread dataTrackMessageThread =
new HandlerThread(DATA_TRACK_MESSAGE_THREAD_NAME);
private Handler dataTrackMessageThreadHandler;
private LocalDataTrack localDataTrack;
// Map used to map remote data tracks to remote participants
private final Map<RemoteDataTrack, RemoteParticipant> dataTrackRemoteParticipantMap =
new HashMap<>();
public CustomTwilioVideoView(ThemedReactContext context) {
super(context);
this.themedReactContext = context;
this.eventEmitter = themedReactContext.getJSModule(RCTEventEmitter.class);
// add lifecycle for onResume and on onPause
themedReactContext.addLifecycleEventListener(this);
/*
* Enable changing the volume using the up/down keys during a conversation
*/
if (themedReactContext.getCurrentActivity() != null) {
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
/*
* Needed for setting/abandoning audio focus during call
*/
audioManager = (AudioManager) themedReactContext.getSystemService(Context.AUDIO_SERVICE);
myNoisyAudioStreamReceiver = new BecomingNoisyReceiver();
intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
// Create the local data track
// localDataTrack = LocalDataTrack.create(this);
localDataTrack = LocalDataTrack.create(getContext());
// Start the thread where data messages are received
dataTrackMessageThread.start();
dataTrackMessageThreadHandler = new Handler(dataTrackMessageThread.getLooper());
}
private VideoConstraints buildVideoConstraints() {
return new VideoConstraints.Builder()
.minVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.maxVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.minFps(5)
.maxFps(15)
.build();
}
private CameraCapturer createCameraCaputer(Context context, CameraCapturer.CameraSource cameraSource) {
CameraCapturer newCameraCapturer = null;
try {
newCameraCapturer = new CameraCapturer(
context,
cameraSource,
new CameraCapturer.Listener() {
@Override
public void onFirstFrameAvailable() {
}
@Override
public void onCameraSwitched() {
setThumbnailMirror();
}
@Override
public void onError(int i) {
Log.i("CustomTwilioVideoView", "Error getting camera");
}
}
);
return newCameraCapturer;
} catch (Exception e) {
return null;
}
}
private boolean createLocalVideo(boolean enableVideo) {
isVideoEnabled = enableVideo;
// Share your camera
cameraCapturer = this.createCameraCaputer(getContext(), CameraCapturer.CameraSource.FRONT_CAMERA);
if (cameraCapturer == null){
cameraCapturer = this.createCameraCaputer(getContext(), CameraCapturer.CameraSource.BACK_CAMERA);
}
if (cameraCapturer == null){
WritableMap event = new WritableNativeMap();
event.putString("error", "No camera is supported on this device");
pushEvent(CustomTwilioVideoView.this, ON_CONNECT_FAILURE, event);
return false;
}
if (cameraCapturer.getSupportedFormats().size() > 0) {
localVideoTrack = LocalVideoTrack.create(getContext(), enableVideo, cameraCapturer, buildVideoConstraints());
if (thumbnailVideoView != null && localVideoTrack != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
setThumbnailMirror();
}
return true;
}
@Override
public void onHostResume() {
/*
* In case it wasn't set.
*/
if (themedReactContext.getCurrentActivity() != null) {
/*
* If the local video track was released when the app was put in the background, recreate.
*/
if (cameraCapturer != null && localVideoTrack == null) {
localVideoTrack = LocalVideoTrack.create(getContext(), isVideoEnabled, cameraCapturer, buildVideoConstraints());
}
if (localVideoTrack != null) {
if (thumbnailVideoView != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
/*
* If connected to a Room then share the local video track.
*/
if (localParticipant != null) {
localParticipant.publishTrack(localVideoTrack);
}
}
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
}
@Override
public void onHostPause() {
/*
* Release the local video track before going in the background. This ensures that the
* camera can be used by other applications while this app is in the background.
*/
if (localVideoTrack != null) {
/*
* If this local video track is being shared in a Room, remove from local
* participant before releasing the video track. Participants will be notified that
* the track has been removed.
*/
if (localParticipant != null) {
localParticipant.unpublishTrack(localVideoTrack);
}
localVideoTrack.release();
localVideoTrack = null;
}
}
@Override
public void onHostDestroy() {
/*
* Always disconnect from the room before leaving the Activity to
* ensure any memory allocated to the Room resource is freed.
*/
if (room != null && room.getState() != Room.State.DISCONNECTED) {
room.disconnect();
disconnectedFromOnDestroy = true;
}
/*
* Release the local media ensuring any memory allocated to audio or video is freed.
*/
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
// Quit the data track message thread
dataTrackMessageThread.quit();
}
public void releaseResource() {
themedReactContext.removeLifecycleEventListener(this);
room = null;
localVideoTrack = null;
thumbnailVideoView = null;
cameraCapturer = null;
}
public void connectToRoomWrapper(
String roomName, String accessToken, boolean enableAudio, boolean enableVideo, boolean enableRemoteAudio) {
this.roomName = roomName;
this.accessToken = accessToken;
this.enableRemoteAudio = enableAudio;
// Share your microphone
localAudioTrack = LocalAudioTrack.create(getContext(), enableAudio);
if (cameraCapturer == null) {
boolean createVideoStatus = createLocalVideo(enableVideo);
if (!createVideoStatus) {
// No need to connect to room if video creation failed
return;
}
}
connectToRoom(enableAudio);
}
public void connectToRoom(boolean enableAudio) {
/*
* Create a VideoClient allowing you to connect to a Room
*/
setAudioFocus(enableAudio);
ConnectOptions.Builder connectOptionsBuilder = new ConnectOptions.Builder(this.accessToken);
if (this.roomName != null) {
connectOptionsBuilder.roomName(this.roomName);
}
if (localAudioTrack != null) {
connectOptionsBuilder.audioTracks(Collections.singletonList(localAudioTrack));
}
if (localVideoTrack != null) {
connectOptionsBuilder.videoTracks(Collections.singletonList(localVideoTrack));
}
//LocalDataTrack localDataTrack = LocalDataTrack.create(getContext());
if (localDataTrack != null) {
connectOptionsBuilder.dataTracks(Collections.singletonList(localDataTrack));
}
room = Video.connect(getContext(), connectOptionsBuilder.build(), roomListener());
}
private void setAudioFocus(boolean focus) {
if (focus) {
previousAudioMode = audioManager.getMode();
// Request audio focus before making any device switch.
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.requestAudioFocus(this,
AudioManager.STREAM_VOICE_CALL,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
} else {
playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
audioFocusRequest = new AudioFocusRequest
.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(this, handler)
.build();
audioManager.requestAudioFocus(audioFocusRequest);
}
/*
* Use MODE_IN_COMMUNICATION as the default audio mode. It is required
* to be in this mode when playout and/or recording starts for the best
* possible VoIP performance. Some devices have difficulties with
* speaker mode if this is not set.
*/
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
getContext().registerReceiver(myNoisyAudioStreamReceiver, intentFilter);
} else {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.abandonAudioFocus(this);
} else if (audioFocusRequest != null) {
audioManager.abandonAudioFocusRequest(audioFocusRequest);
}
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(previousAudioMode);
try {
if (myNoisyAudioStreamReceiver != null) {
getContext().unregisterReceiver(myNoisyAudioStreamReceiver);
}
myNoisyAudioStreamReceiver = null;
} catch (Exception e) {
// already registered
e.printStackTrace();
}
}
}
private class BecomingNoisyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// audioManager.setSpeakerphoneOn(true);
if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
}
}
}
@Override
public void onAudioFocusChange(int focusChange) {
Log.e(TAG, "onAudioFocusChange: focuschange: " + focusChange);
}
public void disconnect() {
if (room != null) {
room.disconnect();
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
setAudioFocus(false);
if (cameraCapturer != null) {
cameraCapturer.stopCapture();
cameraCapturer = null;
}
}
public void sendString(String message) {
if (localDataTrack != null) {
localDataTrack.send(message);
}
}
private static void setThumbnailMirror() {
if (cameraCapturer != null) {
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = (cameraSource == CameraCapturer.CameraSource.BACK_CAMERA);
if (thumbnailVideoView != null && thumbnailVideoView.getVisibility() == View.VISIBLE) {
thumbnailVideoView.setMirror(!isBackCamera);
}
}
}
public void switchCamera() {
if (cameraCapturer != null) {
cameraCapturer.switchCamera();
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = cameraSource == CameraCapturer.CameraSource.BACK_CAMERA;
WritableMap event = new WritableNativeMap();
event.putBoolean("isBackCamera", isBackCamera);
pushEvent(CustomTwilioVideoView.this, ON_CAMERA_SWITCHED, event);
}
}
public void toggleVideo(boolean enabled) {
isVideoEnabled = enabled;
if (localVideoTrack != null) {
localVideoTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("videoEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_VIDEO_CHANGED, event);
}
}
public void toggleSoundSetup(boolean speaker){
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if(speaker){
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
}
}
public void toggleAudio(boolean enabled) {
if (localAudioTrack != null) {
localAudioTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("audioEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_AUDIO_CHANGED, event);
}
}
public void toggleBluetoothHeadset(boolean enabled) {
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if(enabled){
audioManager.startBluetoothSco();
} else {
audioManager.stopBluetoothSco();
}
}
public void toggleRemoteAudio(boolean enabled) {
if (room != null) {
for (RemoteParticipant rp : room.getRemoteParticipants()) {
for(AudioTrackPublication at : rp.getAudioTracks()) {
if(at.getAudioTrack() != null) {
((RemoteAudioTrack)at.getAudioTrack()).enablePlayback(enabled);
}
}
}
}
}
public void publishLocalVideo(boolean enabled) {
if (localParticipant != null && localVideoTrack != null) {
if (enabled) {
localParticipant.publishTrack(localVideoTrack);
} else {
localParticipant.unpublishTrack(localVideoTrack);
}
}
}
public void publishLocalAudio(boolean enabled) {
if (localParticipant != null && localAudioTrack != null) {
if (enabled) {
localParticipant.publishTrack(localAudioTrack);
} else {
localParticipant.unpublishTrack(localAudioTrack);
}
}
}
private void convertBaseTrackStats(BaseTrackStats bs, WritableMap result) {
result.putString("codec", bs.codec);
result.putInt("packetsLost", bs.packetsLost);
result.putString("ssrc", bs.ssrc);
result.putDouble("timestamp", bs.timestamp);
result.putString("trackSid", bs.trackSid);
}
private void convertLocalTrackStats(LocalTrackStats ts, WritableMap result) {
result.putDouble("bytesSent", ts.bytesSent);
result.putInt("packetsSent", ts.packetsSent);
result.putDouble("roundTripTime", ts.roundTripTime);
}
private void convertRemoteTrackStats(RemoteTrackStats ts, WritableMap result) {
result.putDouble("bytesReceived", ts.bytesReceived);
result.putInt("packetsReceived", ts.packetsReceived);
}
private WritableMap convertAudioTrackStats(RemoteAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertRemoteTrackStats(as, result);
return result;
}
private WritableMap convertLocalAudioTrackStats(LocalAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertLocalTrackStats(as, result);
return result;
}
private WritableMap convertVideoTrackStats(RemoteVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertRemoteTrackStats(vs, result);
return result;
}
private WritableMap convertLocalVideoTrackStats(LocalVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertLocalTrackStats(vs, result);
return result;
}
public void getStats() {
if (room != null) {
room.getStats(new StatsListener() {
@Override
public void onStats(List<StatsReport> statsReports) {
WritableMap event = new WritableNativeMap();
for (StatsReport sr : statsReports) {
WritableMap connectionStats = new WritableNativeMap();
WritableArray as = new WritableNativeArray();
for (RemoteAudioTrackStats s : sr.getRemoteAudioTrackStats()) {
as.pushMap(convertAudioTrackStats(s));
}
connectionStats.putArray("remoteAudioTrackStats", as);
WritableArray vs = new WritableNativeArray();
for (RemoteVideoTrackStats s : sr.getRemoteVideoTrackStats()) {
vs.pushMap(convertVideoTrackStats(s));
}
connectionStats.putArray("remoteVideoTrackStats", vs);
WritableArray las = new WritableNativeArray();
for (LocalAudioTrackStats s : sr.getLocalAudioTrackStats()) {
las.pushMap(convertLocalAudioTrackStats(s));
}
connectionStats.putArray("localAudioTrackStats", las);
WritableArray lvs = new WritableNativeArray();
for (LocalVideoTrackStats s : sr.getLocalVideoTrackStats()) {
lvs.pushMap(convertLocalVideoTrackStats(s));
}
connectionStats.putArray("localVideoTrackStats", lvs);
event.putMap(sr.getPeerConnectionId(), connectionStats);
}
pushEvent(CustomTwilioVideoView.this, ON_STATS_RECEIVED, event);
}
});
}
}
public void disableOpenSLES() {
WebRtcAudioManager.setBlacklistDeviceForOpenSLESUsage(true);
}
/*
* Room events listener
*/
private Room.Listener roomListener() {
return new Room.Listener() {
@Override
public void onConnected(Room room) {
localParticipant = room.getLocalParticipant();
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
List<RemoteParticipant> participants = room.getRemoteParticipants();
WritableArray participantsArray = new WritableNativeArray();
for (RemoteParticipant participant : participants) {
participantsArray.pushMap(buildParticipant(participant));
}
participantsArray.pushMap(buildParticipant(localParticipant));
event.putArray("participants", participantsArray);
pushEvent(CustomTwilioVideoView.this, ON_CONNECTED, event);
//There is not .publish it's publishTrack
localParticipant.publishTrack(localDataTrack);
for (RemoteParticipant participant : participants) {
addParticipant(room, participant);
}
}
@Override
public void onConnectFailure(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putString("error", e.getMessage());
pushEvent(CustomTwilioVideoView.this, ON_CONNECT_FAILURE, event);
}
@Override
public void onReconnecting(@NonNull Room room, @NonNull TwilioException twilioException) {
}
@Override
public void onReconnected(@NonNull Room room) {
}
@Override
public void onDisconnected(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
if (localParticipant != null) {
event.putString("participant", localParticipant.getIdentity());
}
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
if (e != null) {
event.putString("error", e.getMessage());
}
pushEvent(CustomTwilioVideoView.this, ON_DISCONNECTED, event);
localParticipant = null;
roomName = null;
accessToken = null;
CustomTwilioVideoView.room = null;
// Only reinitialize the UI if disconnect was not called from onDestroy()
if (!disconnectedFromOnDestroy) {
setAudioFocus(false);
}
}
@Override
public void onParticipantConnected(Room room, RemoteParticipant participant) {
addParticipant(room, participant);
}
@Override
public void onParticipantDisconnected(Room room, RemoteParticipant participant) {
removeParticipant(room, participant);
}
@Override
public void onRecordingStarted(Room room) {
}
@Override
public void onRecordingStopped(Room room) {
}
};
}
/*
* Called when participant joins the room
*/
private void addParticipant(Room room, RemoteParticipant remoteParticipant) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(remoteParticipant));
pushEvent(this, ON_PARTICIPANT_CONNECTED, event);
/*
* Start listening for participant media events
*/
remoteParticipant.setListener(mediaListener());
for (final RemoteDataTrackPublication remoteDataTrackPublication :
remoteParticipant.getRemoteDataTracks()) {
/*
* Data track messages are received on the thread that calls setListener. Post the
* invocation of setting the listener onto our dedicated data track message thread.
*/
if (remoteDataTrackPublication.isTrackSubscribed()) {
dataTrackMessageThreadHandler.post(() -> addRemoteDataTrack(remoteParticipant,
remoteDataTrackPublication.getRemoteDataTrack()));
}
}
}
/*
* Called when participant leaves the room
*/
private void removeParticipant(Room room, RemoteParticipant participant) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(participant));
pushEvent(this, ON_PARTICIPANT_DISCONNECTED, event);
//something about this breaking.
//participant.setListener(null);
}
private void addRemoteDataTrack(RemoteParticipant remoteParticipant, RemoteDataTrack remoteDataTrack) {
dataTrackRemoteParticipantMap.put(remoteDataTrack, remoteParticipant);
remoteDataTrack.setListener(remoteDataTrackListener());
}
private RemoteParticipant.Listener mediaListener() {
return new RemoteParticipant.Listener() {
@Override
public void onAudioTrackSubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
audioTrack.enablePlayback(enableRemoteAudio);
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackUnsubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackSubscriptionFailed(RemoteParticipant participant, RemoteAudioTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onAudioTrackPublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onAudioTrackUnpublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onDataTrackSubscribed(RemoteParticipant remoteParticipant, RemoteDataTrackPublication remoteDataTrackPublication, RemoteDataTrack remoteDataTrack) {
WritableMap event = buildParticipantDataEvent(remoteParticipant);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_DATA_TRACK, event);
dataTrackMessageThreadHandler.post(() -> addRemoteDataTrack(remoteParticipant, remoteDataTrack));
}
@Override
public void onDataTrackUnsubscribed(RemoteParticipant remoteParticipant, RemoteDataTrackPublication publication, RemoteDataTrack remoteDataTrack) {
WritableMap event = buildParticipantDataEvent(remoteParticipant);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_DATA_TRACK, event);
}
@Override
public void onDataTrackSubscriptionFailed(RemoteParticipant participant, RemoteDataTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onDataTrackPublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onDataTrackUnpublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onVideoTrackSubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
addParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackUnsubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
removeParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackSubscriptionFailed(RemoteParticipant participant, RemoteVideoTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onVideoTrackPublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onVideoTrackUnpublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onAudioTrackEnabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {// Log.i(TAG, "onAudioTrackEnabled");
// publication.getRemoteAudioTrack().enablePlayback(false);
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackDisabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_AUDIO_TRACK, event);
}
@Override
public void onVideoTrackEnabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_VIDEO_TRACK, event);
}
@Override
public void onVideoTrackDisabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_VIDEO_TRACK, event);
}
};
}
private WritableMap buildParticipant(Participant participant) {
WritableMap participantMap = new WritableNativeMap();
participantMap.putString("identity", participant.getIdentity());
participantMap.putString("sid", participant.getSid());
return participantMap;
}
private WritableMap buildParticipantDataEvent(Participant participant) {
WritableMap participantMap = buildParticipant(participant);
WritableMap participantMap2 = buildParticipant(participant);
WritableMap event = new WritableNativeMap();
event.putMap("participant", participantMap);
event.putMap("track", participantMap2);
return event;
}
private WritableMap buildParticipantVideoEvent(Participant participant, TrackPublication publication) {
WritableMap participantMap = buildParticipant(participant);
WritableMap trackMap = new WritableNativeMap();
trackMap.putString("trackSid", publication.getTrackSid());
trackMap.putString("trackName", publication.getTrackName());
trackMap.putBoolean("enabled", publication.isTrackEnabled());
WritableMap event = new WritableNativeMap();
event.putMap("participant", participantMap);
event.putMap("track", trackMap);
return event;
}
private WritableMap buildDataTrackEvent(String message) {
WritableMap event = new WritableNativeMap();
event.putString("message", message);
return event;
}
private void addParticipantVideo(Participant participant, RemoteVideoTrackPublication publication) {
WritableMap event = this.buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_VIDEO_TRACK, event);
}
private void removeParticipantVideo(Participant participant, RemoteVideoTrackPublication deleteVideoTrack) {
WritableMap event = this.buildParticipantVideoEvent(participant, deleteVideoTrack);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_VIDEO_TRACK, event);
}
void pushEvent(View view, String name, WritableMap data) {
eventEmitter.receiveEvent(view.getId(), name, data);
}
public static void registerPrimaryVideoView(PatchedVideoView v, String trackSid) {
if (room != null) {
for (RemoteParticipant participant : room.getRemoteParticipants()) {
for (RemoteVideoTrackPublication publication : participant.getRemoteVideoTracks()) {
RemoteVideoTrack track = publication.getRemoteVideoTrack();
if (track == null) {
continue;
}
if (publication.getTrackSid().equals(trackSid)) {
track.addRenderer(v);
} else {
track.removeRenderer(v);
}
}
}
}
}
public static void registerThumbnailVideoView(PatchedVideoView v) {
thumbnailVideoView = v;
if (localVideoTrack != null) {
localVideoTrack.addRenderer(v);
}
setThumbnailMirror();
}
private RemoteDataTrack.Listener remoteDataTrackListener() {
return new RemoteDataTrack.Listener() {
@Override
public void onMessage(RemoteDataTrack remoteDataTrack, ByteBuffer byteBuffer) {
}
@Override
public void onMessage(RemoteDataTrack remoteDataTrack, String message) {
WritableMap event = buildDataTrackEvent(message);
pushEvent(CustomTwilioVideoView.this, ON_DATATRACK_MESSAGE_RECEIVED, event);
}
};
}
}
|
package org.nativescript.widgets;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import org.nativescript.widgets.image.Fetcher;
import org.nativescript.widgets.image.Worker;
/**
* @author hhristov
*/
public class ImageView extends android.widget.ImageView {
private static final double EPSILON = 1E-05;
private Path path = new Path();
private RectF rect = new RectF();
private double scaleW = 1;
private double scaleH = 1;
private float rotationAngle;
private Matrix mMatrix;
private Bitmap mBitmap;
private String mUri;
private int mDecodeWidth;
private int mDecodeHeight;
private boolean mUseCache;
private boolean mAsync;
private Worker.OnImageLoadedListener mListener;
private boolean mAttachedToWindow = false;
public float getRotationAngle() {
return rotationAngle;
}
public void setRotationAngle(float rotationAngle) {
this.rotationAngle = rotationAngle;
invalidate();
}
public ImageView(Context context) {
super(context);
this.mMatrix = new Matrix();
this.setScaleType(ScaleType.FIT_CENTER);
}
@Override
protected void onAttachedToWindow() {
mAttachedToWindow = true;
super.onAttachedToWindow();
this.loadImage();
}
@Override
protected void onDetachedFromWindow() {
mAttachedToWindow = false;
super.onDetachedFromWindow();
if (mUri != null) {
// Clear the bitmap as we are not in the visual tree.
this.setImageBitmap(null);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Drawable drawable = this.getDrawable();
int measureWidth;
int measureHeight;
if (drawable != null) {
measureWidth = drawable.getIntrinsicWidth();
measureHeight = drawable.getIntrinsicHeight();
} else {
measureWidth = 0;
measureHeight = 0;
}
boolean finiteWidth = widthMode != MeasureSpec.UNSPECIFIED;
boolean finiteHeight = heightMode != MeasureSpec.UNSPECIFIED;
if (measureWidth != 0 && measureHeight != 0 && (finiteWidth || finiteHeight)) {
this.computeScaleFactor(width, height, finiteWidth, finiteHeight, measureWidth, measureHeight);
int resultW = (int) Math.round(measureWidth * this.scaleW);
int resultH = (int) Math.round(measureHeight * this.scaleH);
measureWidth = finiteWidth ? Math.min(resultW, width) : resultW;
measureHeight = finiteHeight ? Math.min(resultH, height) : resultH;
}
measureWidth += this.getPaddingLeft() + this.getPaddingRight();
measureHeight += this.getPaddingTop() + this.getPaddingBottom();
measureWidth = Math.max(measureWidth, getSuggestedMinimumWidth());
measureHeight = Math.max(measureHeight, getSuggestedMinimumHeight());
if (CommonLayoutParams.debuggable > 0) {
StringBuilder sb = CommonLayoutParams.getStringBuilder();
sb.append("ImageView onMeasure: ");
sb.append(MeasureSpec.toString(widthMeasureSpec));
sb.append(", ");
sb.append(MeasureSpec.toString(heightMeasureSpec));
sb.append(", stretch: ");
sb.append(this.getScaleType());
sb.append(", measureWidth: ");
sb.append(measureWidth);
sb.append(", measureHeight: ");
sb.append(measureHeight);
CommonLayoutParams.log(CommonLayoutParams.TAG, sb.toString());
}
int widthSizeAndState = resolveSizeAndState(measureWidth, widthMeasureSpec, 0);
int heightSizeAndState = resolveSizeAndState(measureHeight, heightMeasureSpec, 0);
this.setMeasuredDimension(widthSizeAndState, heightSizeAndState);
}
private void computeScaleFactor(int measureWidth, int measureHeight, boolean widthIsFinite, boolean heightIsFinite, double nativeWidth, double nativeHeight) {
this.scaleW = 1;
this.scaleH = 1;
ScaleType scale = this.getScaleType();
if ((scale == ScaleType.CENTER_CROP || scale == ScaleType.FIT_CENTER || scale == ScaleType.FIT_XY) &&
(widthIsFinite || heightIsFinite)) {
this.scaleW = (nativeWidth > 0) ? measureWidth / nativeWidth : 0d;
this.scaleH = (nativeHeight > 0) ? measureHeight / nativeHeight : 0d;
if (!widthIsFinite) {
this.scaleW = scaleH;
} else if (!heightIsFinite) {
this.scaleH = scaleW;
} else {
// No infinite dimensions.
switch (scale) {
case FIT_CENTER:
this.scaleH = this.scaleW < this.scaleH ? this.scaleW : this.scaleH;
this.scaleW = this.scaleH;
break;
case CENTER_CROP:
this.scaleH = this.scaleW > this.scaleH ? this.scaleW : this.scaleH;
this.scaleW = this.scaleH;
break;
default:
break;
}
}
}
}
public void setUri(String uri, int decodeWidth, int decodeHeight, boolean useCache, boolean async) {
mUri = uri;
mDecodeWidth = decodeWidth;
mDecodeHeight = decodeHeight;
mUseCache = useCache;
mAsync = async;
if (mAttachedToWindow) {
loadImage();
}
}
public void setImageLoadedListener(Worker.OnImageLoadedListener listener) {
mListener = listener;
}
private void loadImage() {
Fetcher fetcher = Fetcher.getInstance(this.getContext());
if (mUri != null && fetcher != null) {
// Get the Bitmap from cache.
fetcher.loadImage(mUri, this, mDecodeWidth, mDecodeHeight, mUseCache, mAsync, mListener);
}
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
this.mBitmap = bm;
}
@Override
protected void onDraw(Canvas canvas) {
BorderDrawable background = this.getBackground() instanceof BorderDrawable ? (BorderDrawable) this.getBackground() : null;
float uniformBorderWidth = background != null ? background.getUniformBorderWidth() : 0;
float uniformBorderRadius = background != null ? background.getUniformBorderRadius() : 0;
// floor the border width to avoid gaps between the border and the image
float roundedBorderWidth = (float) Math.floor(uniformBorderWidth);
float innerRadius = Math.max(0, uniformBorderRadius - roundedBorderWidth);
if (background != null) {
background.draw(canvas);
}
// The border width is included in the padding so there is no need for
// clip if there is no inner border radius.
if (innerRadius > 0) {
this.rect.set(
roundedBorderWidth,
roundedBorderWidth,
this.getWidth() - roundedBorderWidth,
this.getHeight() - roundedBorderWidth);
this.path.reset();
this.path.addRoundRect(rect, innerRadius, innerRadius, Path.Direction.CW);
canvas.clipPath(this.path);
}
float rotationDegree = this.getRotationAngle();
if (Math.abs(rotationDegree) > ImageView.EPSILON && Math.abs((rotationDegree % 90) - 0.0) < ImageView.EPSILON) {
ScaleType scaleType = this.getScaleType();
float viewWidth = this.getWidth() - (2 * roundedBorderWidth);
float viewHeight = this.getHeight() - (2 * roundedBorderWidth);
float bitmapWidth = (float) mBitmap.getWidth();
float bitmapHeight = (float) mBitmap.getHeight();
float scaleX;
float scaleY;
float decision = (rotationDegree / 90) % 2;
if (Math.abs(Math.floor(decision) - 0) < ImageView.EPSILON) {
scaleX = viewWidth / bitmapWidth;
scaleY = viewHeight / bitmapHeight;
} else {
scaleX = viewHeight / bitmapWidth;
scaleY = viewWidth / bitmapHeight;
}
float scale = 1.0f;
if (scaleType == ScaleType.FIT_CENTER || scaleType == ScaleType.MATRIX) {
scale = (scaleX < scaleY) ? scaleX : scaleY;
} else if (scaleType == ScaleType.CENTER_CROP) {
scale = (scaleX < scaleY) ? scaleY : scaleX;
}
Matrix matrix = this.mMatrix;
matrix.reset();
if (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.FIT_CENTER || scaleType == ScaleType.MATRIX) {
matrix.postScale(scale, scale);
matrix.postTranslate(-(bitmapWidth * scale) / 2, -(bitmapHeight * scale) / 2);
} else if (scaleType == ScaleType.FIT_XY) {
matrix.postScale(scaleX, scaleY);
matrix.postTranslate(-((bitmapWidth * scaleX) + roundedBorderWidth) / 2, -((bitmapHeight * scaleY) + roundedBorderWidth) / 2);
}
matrix.postRotate(rotationDegree);
matrix.postTranslate(viewWidth / 2 + roundedBorderWidth, viewHeight / 2 + roundedBorderWidth);
canvas.drawBitmap(this.mBitmap, matrix, null);
} else {
super.onDraw(canvas);
}
}
}
|
package autodiff.nodes;
import static autodiff.reasoning.deductions.Standard.*;
import static autodiff.reasoning.expressions.Expressions.*;
import static autodiff.reasoning.proofs.BasicNumericVerification.*;
import static autodiff.reasoning.proofs.Stack.*;
import static multij.tools.Tools.*;
import autodiff.reasoning.deductions.Standard;
import autodiff.reasoning.expressions.ExpressionVisitor;
import autodiff.reasoning.proofs.Deduction;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author codistmonk (creation 2016-08-09)
*/
public final class ComputationNode extends AbstractNode<ComputationNode> {
private final Map<String, Object> bindings;
private List<Object> definition;
private final List<BindListener> bindListeners;
private String typeName;
private Runnable binder;
private Deduction boundForm;
public ComputationNode() {
super(new ArrayList<>());
this.bindings = new LinkedHashMap<>();
this.definition = new ArrayList<>();
this.bindListeners = new ArrayList<>();
}
public final List<BindListener> getBindListeners() {
return this.bindListeners;
}
public final Map<String, Object> getBindings() {
return this.bindings;
}
public final Object get(final String key) {
return this.getBindings().get(key);
}
public final ComputationNode set(final String key, final Object value) {
this.getBindListeners().forEach(l -> l.beforeBind(key, value));
this.getBindings().put(key, value);
this.getBindListeners().forEach(l -> l.afterBind(key, value));
return this;
}
public final List<Object> getDefinition() {
return this.definition;
}
public final ComputationNode setDefinition(final List<Object> definition) {
this.definition = definition;
return this;
}
public final String getTypeName() {
return this.typeName;
}
public final ComputationNode setTypeName(final String typeName) {
this.typeName = typeName;
return this;
}
public final Runnable getBinder() {
return this.binder;
}
public final ComputationNode setBinder(final Runnable binder) {
this.binder = binder;
return this;
}
@Override
public final String getName() {
return "[" + this.getId() + "]" + this.getTypeName();
}
@Override
public final ComputationNode autoShape() {
final Deduction deduction = this.getBoundForm();
final Object proposition = deduction.getProposition(deduction.getPropositionName(-1));
// final Object shapeExpression = middle(right(middle(right(proposition))));
final Object shapeExpression = right(middle(right(proposition)));
setShape(flattenBinaryTree(shapeExpression).stream().mapToInt(
o -> ((Number) o).intValue()).toArray());
return this;
}
public final Deduction getBoundForm() {
if (this.boundForm == null) {
this.boundForm = Standard.build(new Deduction(
AUTODIFF, this.getName() + "_bind"), this.getBinder(), 1);
}
return this.boundForm;
}
public static final void eapplyLast() {
eapply(name(-1));
}
public static final void eapply(final String target) {
subdeduction();
final Object condition = condition(proposition(target));
PropositionDescription justification = null;
for (final PropositionDescription description : iterateBackward(deduction())) {
if (condition.equals(description.getProposition())) {
justification = description;
break;
}
}
final String justificationName;
if (justification == null) {
if (isPositivity(condition)) {
deducePositivity(left(condition));
} else if(isNaturality(condition) || isReality(condition)) {
verifyBasicNumericProposition(condition);
} else {
throw new IllegalStateException();
}
justificationName = name(-1);
} else {
justificationName = justification.getName();
}
apply(target, justificationName);
conclude();
}
public static final void ebindLast(final Object... values) {
ebind(name(-1), values);
}
public static final void ebind(final String target, final Object... values) {
subdeduction();
String newTarget = target;
for (final Object value : values) {
ebind1(newTarget, value);
newTarget = name(-1);
}
conclude();
}
public static final void ebind1(final String target, final Object value) {
subdeduction();
String newTarget = target;
boolean done = false;
while (!done) {
// while (!isBlock(proposition(newTarget))) {
// debugPrint(proposition(newTarget));
done = true;
if (isForallIn(proposition(newTarget))) {
canonicalizeForallIn(newTarget);
newTarget = name(-1);
done = false;
} else if (isForallIn2(proposition(newTarget))) {
canonicalizeForallIn2(newTarget);
newTarget = name(-1);
done = false;
} else if (trim(newTarget)) {
newTarget = name(-1);
done = false;
}
}
bind(newTarget, value);
conclude();
}
public static final void trimLast() {
trim(name(-1));
}
public static final boolean trim(final String target) {
if (isRule(proposition(target))) {
String newTarget = target;
subdeduction();
while (isRule(proposition(newTarget))) {
eapply(newTarget);
newTarget = name(-1);
}
conclude();
return true;
}
return false;
}
public static final boolean isPositivity(final Object proposition) {
final List<?> list = cast(List.class, proposition);
return list != null && 3 == list.size()
&& IN.equals(middle(list)) && POS.equals(right(list));
}
public static final boolean isNaturality(final Object proposition) {
final List<?> list = cast(List.class, proposition);
return list != null && 3 == list.size()
&& IN.equals(middle(list)) && N.equals(right(list));
}
public static final boolean isReality(final Object proposition) {
final List<?> list = cast(List.class, proposition);
return list != null && 3 == list.size()
&& IN.equals(middle(list)) && R.equals(right(list));
}
public static final boolean isForallIn(final Object proposition) {
final List<?> list = cast(List.class, proposition);
return list != null && 5 == list.size()
&& FORALL.equals(list.get(0)) && IN.equals(list.get(2));
}
public static final boolean isForallIn2(final Object proposition) {
final List<?> list = cast(List.class, proposition);
return list != null && 7 == list.size()
&& FORALL.equals(list.get(0)) && ",".equals(list.get(2)) && IN.equals(list.get(4));
}
public static final Iterable<PropositionDescription> iterateBackward(final Deduction deduction) {
return new Iterable<ComputationNode.PropositionDescription>() {
@Override
public final Iterator<PropositionDescription> iterator() {
return new Iterator<ComputationNode.PropositionDescription>() {
private final PropositionDescription result = new PropositionDescription();
private Deduction currentDeduction = deduction;
private int i = this.currentDeduction.getPropositionNames().size();
@Override
public final boolean hasNext() {
return 0 < this.i || !isEmpty(this.currentDeduction.getParent());
}
@Override
public final PropositionDescription next() {
if (--this.i < 0) {
this.currentDeduction = this.currentDeduction.getParent();
while (this.currentDeduction.getPropositionNames().isEmpty()) {
this.currentDeduction = this.currentDeduction.getParent();
}
this.i = this.currentDeduction.getPropositionNames().size() - 1;
}
final String name = this.currentDeduction.getPropositionNames().get(this.i);
return this.result
.setIndex(this.result.getIndex() - 1)
.setName(name)
.setProposition(this.currentDeduction.getPropositions().get(name));
}
};
}
};
}
public static final boolean isEmpty(final Deduction deduction) {
return deduction == null
|| (deduction.getPropositionNames().isEmpty()
&& (deduction.getParent() == null || isEmpty(deduction.getParent())));
}
private static final long serialVersionUID = 2834011599617369367L;
public static final Object U = $("℧");
public static final Object IN = $("∈");
public static final Object SUBSET = $("⊂");
public static final Object EQUIV = $("⇔");
public static final Object P = $("ℙ");
public static final Object CROSS = $("×");
public static final Object TCROSS = $("¤");
public static final Object UML = $("¨");
public static final Object PI = $("Π");
public static final Object POS = $(N, "_", $(">", 0));
public static final SequenceBuilder SB_COMMA = new SequenceBuilder(",");
public static final SequenceBuilder SB_CROSS = new SequenceBuilder(CROSS);
public static final Object cases(final Object... cases) {
return new SequenceBuilder("").build(append(array((Object) "cases"), cases));
}
public static final Deduction AUTODIFF = Standard.build("autodiff", new Runnable() {
@Override
public final void run() {
Standard.setup();
debugPrint(SB_COMMA.build($("a", "b", "c")));
debugPrint(SB_COMMA.build(1));
debugPrint(SB_COMMA.build(1, 2));
debugPrint(SB_COMMA.build(1, 2, 3));
debugPrint(SB_COMMA.build(1, SB_COMMA.build(2, 3)));
debugPrint(SB_COMMA.build(SB_COMMA.build(1, 2), 3));
supposeDefinitionOfParentheses();
supposeDefinitionOfForallIn();
supposeDefinitionOfForallIn2();
supposeDefinitionOfForallIn3();
supposeIntroductionOfConjunction();
supposeLeftEliminationOfConjunction();
supposeRightEliminationOfConjunction();
supposeDefinitionOfLogicalEquivalence();
supposeLogicalEquality();
deduceLogicalEquivalenceImpliesLogicalEquality();
deduceCommutativityOfConjunction();
supposeDefinitionOfSubset();
supposeDefinitionOfPowerset();
supposeSubsetInUhm();
supposeTypeOfPowersetOfReals();
supposeRealsInUhm();
supposeNaturalsSubsetReals();
deduceNaturalsInUhm();
supposeDefinitionOfPositives();
{
final Object _i = $new("i");
final Object _n = $new("n");
suppose("definition_of_range",
$(FORALL, _n, IN, N,
$forall(_i,
$($(_i, IN, $(N, "_", $("<", _n))),
"=", $($(_i, IN, N), LAND, $(_i, "<", _n))))));
}
{
final Object _i = $new("i");
final Object _x = $new("x");
final Object _y = $new("y");
final Object _X = $new("X");
suppose("definition_of_indexing_i",
$(FORALL, _i, IN, POS,
$rule($(p(_x, ",", _y), IN, $($(_X, "^", _i), CROSS, _X)),
$($(p(_x, ",", _y), "_", _i), "=", _y))));
}
supposeTransitivityOfSubset();
deducePositivesSubsetNaturals();
deducePositivesInUhm();
supposeDefinitionOfMs();
supposeTypeOfFlat();
supposeDefinitionOfSingleton();
supposeTypeOfSingle();
// supposeTypeOfPair();
supposeCartesian1();
supposeTypeOfCartesian();
supposeCartesianMN();
{
final Object _X = $new("X");
final Object _Y = $new("Y");
final Object _x = $new("x");
final Object _y = $new("y");
suppose("type_of_tuple",
$(FORALL, _X, ",", _Y, IN, U,
$(FORALL, _x, IN, _X,
$(FORALL, _y, IN, _Y,
$(SB_COMMA.build(_x, _y), IN, SB_CROSS.build(_X, _Y))))));
}
{
final Object _X = $new("X");
final Object _n = $new("n");
suppose("vector_type_in_Uhm",
$(FORALL, _X, IN, U,
$(FORALL, _n, IN, N,
$($(_X, "^", _n), IN, U))));
}
{
final Object _s = $new("s");
final Object _x = $new("x");
final Object _y = $new("y");
suppose("definition_of_sequence_new",
$forall(_s, _x, _y,
$($("sequence_new", _s, _x, _y), "=", $(_x, $(_s, _y)))));
}
{
final Object _x = $new("x");
suppose("try_cases_otherwise",
$forall(_x,
$(cases($(_x, "otherwise")), "=", _x)));
}
{
final Object _x = $new("x");
final Object _c = $new("c");
suppose("try_cases_if",
$forall(_x, _c,
$rule(_c, $(cases($(_x, "if", _c)), "=", _x))));
}
{
final Object _x = $new("x");
final Object _y = $new("y");
final Object _c = $new("c");
suppose("try_cases_if_stop",
$forall(_x, _y, _c,
$rule(_c,
$($("cases", $("", $(_x, "if", _c), _y)), "=", _x))));
}
{
final Object _x = $new("x");
final Object _y = $new("y");
final Object _c = $new("c");
suppose("try_cases_if_not",
$forall(_x, _y, _c,
$rule($(LNOT, _c),
$($("cases", $("", $(_x, "if", _c), _y)), "=", $("cases", _y)))));
}
{
subdeduction("try_cases.test1");
final Object _x = forall("x");
suppose($(_x, "=", cases(
$(42, "if", $(2, "=", 2)),
$(24, "otherwise"))));
{
subdeduction();
bind("try_cases_if_stop", 42, $("", $(24, "otherwise")), $(2, "=", 2));
verifyBasicNumericProposition($(2, "=", 2));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction("try_cases.test2");
final Object _x = forall("x");
suppose($(_x, "=", cases(
$(42, "if", $(2, "=", 3)),
$(24, "if", $(1, "=", 2)),
$(0, "otherwise"))));
{
subdeduction();
{
subdeduction();
bind("try_cases_if_not", 42, $("", $(24, "if", $(1, "=", 2)), $("", $(0, "otherwise"))), $(2, "=", 3));
verifyBasicNumericProposition($(2, "=", 3));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
{
subdeduction();
bind("try_cases_if_not", 24, $("", $(0, "otherwise")), $(1, "=", 2));
verifyBasicNumericProposition($(1, "=", 2));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
{
subdeduction();
bind("try_cases_otherwise", 0);
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
conclude();
}
{
final Object _s = $new("s");
final Object _x = $new("x");
final Object _x0 = $new("x0");
final Object _x1 = $new("x1");
final Object _y = $new("y");
final Object condition0 = $(_x, ":=:", $(_x0, _x1));
final Object value0 = $(_x0, $("sequence_append", _s, _x1, _y));
final Object condition1 = $(_x, ":=:", $(_s, _x0));
final Object value1 = $(_s, _x0, $(_s, _y));
final Object condition2 = $(_x, ":=:", $(_s, _x0, _x1));
final Object value2 = $(_s, _x0, $("sequence_append", _s, _x1, _y));
final Object value3 = $("sequence_new", _s, _x, _y);
suppose("definition_of_sequence_append",
$forall(_s, _x, _x0, _x1, _y,
$($("sequence_append", _s, _x, _y), "=", cases(
$(value0, "if", condition0),
$(value1, "if", condition1),
$(value2, "if", condition2),
$(value3, "otherwise")))));
}
{
subdeduction("sequence_append.test1");
final Object _x = 1;
final Object _s = ",";
final Object _x0 = "()";
final Object _x1 = "()";
final Object _y = 2;
final Object condition0 = $(_x, ":=:", $(_x0, _x1));
final Object value0 = $(_x0, $("sequence_append", _s, _x1, _y));
final Object condition1 = $(_x, ":=:", $(_s, _x0));
final Object value1 = $(_s, _x0, $(_s, _y));
final Object condition2 = $(_x, ":=:", $(_s, _x0, _x1));
final Object value2 = $(_s, _x0, $("sequence_append", _s, _x1, _y));
final Object value3 = $("sequence_new", _s, _x, _y);
final Object _y2 = $("", $(value3, "otherwise"));
final Object _y1 = $("", $(value2, "if", condition2), _y2);
final Object _y0 = $("", $(value1, "if", condition1), _y1);
bind("definition_of_sequence_append", ",", _x, _x0, _x1, _y);
{
subdeduction();
{
subdeduction();
bind("try_cases_if_not", value0, _y0, condition0);
evaluateStructuralFormula(list(condition(proposition(-1))).get(1));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
{
subdeduction();
bind("try_cases_if_not", value1, _y1, condition1);
evaluateStructuralFormula(list(condition(proposition(-1))).get(1));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
{
subdeduction();
bind("try_cases_if_not", value2, _y2, condition2);
evaluateStructuralFormula(list(condition(proposition(-1))).get(1));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
bind("try_cases_otherwise", value3);
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
bind("definition_of_sequence_new", _s, _x, _y);
rewrite(name(-2), name(-1));
conclude();
}
conclude();
}
{
subdeduction("sequence_append.test2");
{
final Object _x = SB_COMMA.build(1, 2);
final Object _s = ",";
final Object _x0 = 1;
final Object _x1 = $(",", 2);
final Object _y = 3;
final Object condition0 = $(_x, ":=:", $(_x0, _x1));
final Object value0 = $(_x0, $("sequence_append", _s, _x1, _y));
final Object condition1 = $(_x, ":=:", $(_s, _x0));
final Object value1 = $(_s, _x0, $(_s, _y));
final Object condition2 = $(_x, ":=:", $(_s, _x0, _x1));
final Object value2 = $(_s, _x0, $("sequence_append", _s, _x1, _y));
final Object value3 = $("sequence_new", _s, _x, _y);
final Object _y2 = $("", $(value3, "otherwise"));
final Object _y1 = $("", $(value2, "if", condition2), _y2);
final Object _y0 = $("", $(value1, "if", condition1), _y1);
bind("definition_of_sequence_append", ",", _x, _x0, _x1, _y);
subdeduction();
{
subdeduction();
bind("try_cases_if_stop", value0, _y0, condition0);
evaluateStructuralFormula(condition(proposition(-1)));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
final Object _x = $(",", 2);
final Object _s = ",";
final Object _x0 = 2;
final Object _x1 = "()";
final Object _y = 3;
final Object condition0 = $(_x, ":=:", $(_x0, _x1));
final Object value0 = $(_x0, $("sequence_append", _s, _x1, _y));
final Object condition1 = $(_x, ":=:", $(_s, _x0));
final Object value1 = $(_s, _x0, $(_s, _y));
final Object condition2 = $(_x, ":=:", $(_s, _x0, _x1));
final Object value2 = $(_s, _x0, $("sequence_append", _s, _x1, _y));
final Object value3 = $("sequence_new", _s, _x, _y);
final Object _y2 = $("", $(value3, "otherwise"));
final Object _y1 = $("", $(value2, "if", condition2), _y2);
final Object _y0 = $("", $(value1, "if", condition1), _y1);
bind("definition_of_sequence_append", ",", _x, _x0, _x1, _y);
{
subdeduction();
{
subdeduction();
bind("try_cases_if_not", value0, _y0, condition0);
evaluateStructuralFormula(list(condition(proposition(-1))).get(1));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
{
subdeduction();
bind("try_cases_if_stop", value1, _y1, condition1);
evaluateStructuralFormula(condition(proposition(-1)));
apply(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
abort();
// final Object _s = $new("s");
// final Object _x = $new("x");
// final Object _z = $new("z");
// suppose("definition_of_sequence_append_0",
// $forall(_s, _x, _z,
// $($("sequence_append", _s, _x, _z), "=", $("sequence_new", _s, _x, _z))));
// final Object _s = $new("s");
// final Object _x = $new("x");
// final Object _y = $new("y");
// final Object _z = $new("z");
// suppose("definition_of_sequence_append_n",
// $forall(_s, _x, _y, _z,
// $($("sequence_append", _s, $(_s, _x, _y), _z), "=", $(_s, _x, $("sequence_append", _s, _y, _z)))));
// final Object _s = $new("s");
// final Object _x = $new("x");
// final Object _y = $new("y");
// final Object _z = $new("z");
// suppose("definition_of_sequence_append",
// $forall(_s, _x, _y, _z,
// $($("sequence_append", _s, $(_x, $(_s, _y)), _z), "=", $("sequence_new", _s, _x, $("sequence_append", _s, _y, _z)))));
{
final Object _x = $new("x");
suppose("definition_of_repeat_0",
$forall(_x,
$($("repeat", 0, _x), "=", _x)));
}
{
final Object _x = $new("x");
final Object _n = $new("n");
suppose("definition_of_repeat_n",
$forall(_x,
$(FORALL, _n, IN, POS,
$($("repeat", _n, _x), "=", $(_x, $("repeat", $(_n, "-", 1), _x))))));
}
{
final Object _X = $new("X");
final Object _n = $new("n");
suppose("simplification_of_cross_sequence",
$forall(_X,
$(FORALL, _n, IN, N,
$($(_X, $("repeat", _n, $(CROSS, _X))), "=", $(_X, "^", $(_n, "+", 2))))));
}
{
final Object _f = $new("f");
final Object _x = $new("x0");
final Object _sx = $new("sx");
final Object _y = $new("y0");
final Object _sy = $new("sy");
suppose("definition_of_zip_0",
$forall(_x, _sx, _y, _sy,
$($("zip", _f, _sx, _sy, $(_sx, _x), $(_sy, _y)), "=", $(_f, _x, _y))));
}
{
final Object _f = $new("f");
final Object _x0 = $new("x0");
final Object _x1 = $new("x1");
final Object _sx = $new("sx");
final Object _y0 = $new("y0");
final Object _y1 = $new("y1");
final Object _sy = $new("sy");
suppose("definition_of_zip_n",
$forall(_x0, _x1, _sx, _y0, _y1, _sy,
$($("zip", _f, _sx, _sy, $(_sx, _x0, _x1), $(_sy, _y0, _y1)), "=", $($(_f, _x0, _y0), $("zip", _f, _sx, _sy, _x1, _y1)))));
}
{
final Object _f = $new("f");
final Object _x0 = $new("x0");
final Object _x1 = $new("x1");
final Object _sx = $new("sx");
final Object _y0 = $new("y0");
final Object _y1 = $new("y1");
final Object _sy = $new("sy");
suppose("definition_of_zip_begin",
$forall(_x0, _x1, _sx, _y0, _y1, _sy,
$($("zip", _f, _sx, _sy, $(_x0, $(_sx, _x1)), $(_y0, $(_sy, _y1))), "=", $($(_f, _x0, _y0), $("zip", _f, _sx, _sy, _x1, _y1)))));
}
{
final Object _f = $new("f");
final Object _x0 = $new("x0");
final Object _x1 = $new("x1");
suppose("definition_of_reduce_0",
$forall(_f, _x0, _x0,
$($("reduce", _f, $(_x0, _x1)), "=", $(_f, _x0, _x1))));
}
{
final Object _x = $new("x");
final Object _X = $new("X");
suppose("definition_of_cross_type",
$forall(_x, _X,
$rule($("reduce", LAND, $("zip", IN, ",", CROSS, _x, _X)), $(_x, IN, _X))));
}
supposeDefinitionOfProductLoop0();
supposeDefinitionOfProductLoopN();
supposeDefinitionOfProductReduction();
}
}, 1);
public static final ComputationNode ones() {
final ComputationNode result = new ComputationNode().setTypeName("ones");
final Object n = $new("n");
final Object s = $new("s");
final Object i = $new("i");
result.setDefinition(
list($(FORALL, n, IN, POS,
$(FORALL, s, IN, $(POS, "^", n),
$($("ones", " ", s), "=", p($(p(1), "_", $(i, "<", $(PI, s))), ",", s))))));
result.set("s", null);
result.getBindListeners().add(new BindListener() {
@Override
public final void beforeBind(final String key, final Object value) {
if ("s".equals(key)) {
final int[] shape = (int[]) value;
NodesTools.check(0 < shape.length, () -> "Invalid shape: []");
result.set("n", shape.length);
}
}
private static final long serialVersionUID = -64734290035563118L;
});
result.setBinder(new Runnable() {
@Override
public final void run() {
suppose(result.getDefinition());
{
subdeduction();
ebindLast($(result.get("n")));
eapplyLast();
canonicalizeForallIn(name(-1));
final Object[] s = toObjects((int[]) result.get("s"));
// bind(name(-1), p(toBinaryTree(",", s)));
bind(name(-1), SB_COMMA.build(s));
deduceCartesianType(s, "positivity");
apply(name(-2), name(-1));
conclude();
}
}
});
return result;
}
public static final Integer[] toObjects(final int... values) {
final Integer[] result = new Integer[values.length];
for (int i = 0; i < values.length; ++i) {
result[i] = values[i];
}
return result;
}
public static final Object toBinaryTree(final String operator, final Object... objects) {
final int n = objects.length;
if (n == 0) {
return $();
}
Object result = $(objects[0]);
for (int i = 1; i < n; ++i) {
result = $(result, operator, objects[i]);
}
return result;
}
public static final List<Object> flattenBinaryTree(final Object binaryTree) {
return new FlattenBinaryTree().apply(binaryTree);
}
/**
* @author codistmonk (creation 2016-08-11)
*/
public static final class FlattenBinaryTree implements ExpressionVisitor<List<Object>> {
private final List<Object> result = new ArrayList<>();
@Override
public final List<Object> visit(final Object expression) {
this.getResult().add(expression);
return this.getResult();
}
@Override
public final List<Object> visit(final List<?> expression) {
this.apply(left(expression));
this.apply(right(expression));
return this.getResult();
}
public final List<Object> getResult() {
return this.result;
}
private static final long serialVersionUID = 9145572614566666571L;
}
public static final List<Object> p(final Object... objects) {
return list($("(", $(objects), ")"));
}
public static final List<Object> c(final Object... objects) {
return list($("{", $(objects), "}"));
}
public static final void deducePositivity(final Object target) {
subdeduction();
bind("definition_of_positives", target);
{
subdeduction();
verifyBasicNumericProposition($(target, IN, N));
verifyBasicNumericProposition($(0, "<", target));
bind("introduction_of_conjunction", proposition(-2), proposition(-1));
eapplyLast();
eapplyLast();
conclude();
}
rewriteRight(name(-1), name(-2));
conclude();
}
public static final void deduceCartesianPositivity(final Object value) {
subdeduction();
ebind("cartesian_1", POS);
eapplyLast();
deducePositivity(value);
rewrite(name(-1), name(-2));
conclude();
}
public static final void deduceCartesianRealness(final Object value) {
subdeduction();
ebind("cartesian_1", R);
eapplyLast();
verifyBasicNumericProposition($(value, IN, R));
rewrite(name(-1), name(-2));
conclude();
}
public static final void canonicalizeForallIn(final String targetName) {
final List<Object> list = list(proposition(targetName));
subdeduction();
bind("definition_of_forall_in", list.get(1), list.get(3), list.get(4));
rewrite(targetName, name(-1));
conclude();
}
public static final void canonicalizeForallIn2(final String targetName) {
final List<Object> list = list(proposition(targetName));
subdeduction();
bind("definition_of_forall_in_2", list.get(1), list.get(3), list.get(5), list.get(6));
rewrite(targetName, name(-1));
conclude();
}
public static final String deepJoin(final String separator, final Iterable<?> objects) {
final StringBuilder resultBuilder = new StringBuilder();
boolean first = true;
for (final Object object : objects) {
final Iterable<?> subobjects = cast(Iterable.class, object);
if (first) {
first = false;
} else {
resultBuilder.append(separator);
}
resultBuilder.append(subobjects == null ? object : deepJoin(separator, subobjects));
}
return resultBuilder.toString();
}
public static final Object cartesian(final Object _s, final Object _j, final Object _n) {
return $(CROSS, "_", $(_j, "<", _n), $(N, "_", $("<", $(_s, "_", _j))));
}
public static final Object pp(final Object... set) {
return $(P, p(set));
}
public static final void breakConjunction(final String targetName) {
deduceConjunctionLeft(targetName);
deduceConjunctionRight(targetName);
}
public static final void deduceConjunctionLeft(final String targetName) {
final Object proposition = proposition(targetName);
final Object left = left(proposition);
final Object right = right(proposition);
subdeduction();
bind("left_elimination_of_conjunction", left, right);
eapplyLast();
conclude();
}
public static final void deduceConjunctionRight(final String targetName) {
final Object proposition = proposition(targetName);
final Object left = left(proposition);
final Object right = right(proposition);
subdeduction();
bind("right_elimination_of_conjunction", left, right);
eapplyLast();
conclude();
}
public static final void supposeDefinitionOfParentheses() {
final Object _X = $new("X");
suppose("definition_of_parentheses", $forall(_X,
$(p(_X), "=", _X)));
}
public static final void supposeDefinitionOfSubset() {
final Object _x = $new("x");
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("definition_of_subset", $forall(_X, $(FORALL, _Y, IN, U,
$($(_X, SUBSET, _Y), "=", $forall(_x, $rule($(_x, IN, _X), $(_x, IN, _Y)))))));
}
public static final void supposeNaturalsSubsetReals() {
suppose("naturals_subset_reals",
$(N, SUBSET, R));
}
public static final void supposeTransitivityOfSubset() {
subdeduction("transitivity_of_subset");
final Object _X = forall("X");
final Object _Y = forall("Y");
final Object _Z = forall("Z");
suppose($(_X, IN, U));
suppose($(_Y, IN, U));
suppose($(_Z, IN, U));
suppose($(_X, SUBSET, _Y));
suppose($(_Y, SUBSET, _Z));
final String h1 = name(-2);
final String h2 = name(-1);
{
subdeduction();
final Object _x = forall("x");
suppose($(_x, IN, _X));
final String h3 = name(-1);
{
subdeduction();
ebind("definition_of_subset", _X, _Y);
trimLast();
rewrite(h1, name(-1));
bind(name(-1), _x);
conclude();
}
apply(name(-1), h3);
{
subdeduction();
ebind("definition_of_subset", _Y, _Z);
trimLast();
rewrite(h2, name(-1));
bind(name(-1), _x);
conclude();
}
apply(name(-1), name(-2));
conclude();
}
ebind("definition_of_subset", _X, _Z);
trimLast();
rewriteRight(name(-2), name(-1));
conclude();
}
public static final void supposeDefinitionOfPowerset() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("definition_of_powerset", $forall(_X, _Y,
$($(_X, IN, pp(_Y)), "=", $(_X, SUBSET, _Y))));
}
public static final void supposeTypeOfPowersetOfReals() {
suppose("type_of_P_R",
$(pp(R), SUBSET, U));
}
public static final void supposeRealsInUhm() {
suppose("reals_in_Uhm",
$(R, IN, U));
}
public static final void supposeDefinitionOfForallIn() {
final Object _x = $new("x");
final Object _X = $new("X");
final Object _P = $new("P");
suppose("definition_of_forall_in", $forall(_x, _X, _P,
$($(FORALL, _x, IN, _X, _P), "=", $forall(_x, $rule($(_x, IN, _X), _P)))));
}
public static final void supposeDefinitionOfForallIn2() {
final Object _x = $new("x");
final Object _y = $new("y");
final Object _X = $new("X");
final Object _P = $new("P");
suppose("definition_of_forall_in_2", $forall(_x, _y, _X, _P,
$($(FORALL, _x, ",", _y, IN, _X, _P), "=", $forall(_x, $rule($(_x, IN, _X), $forall(_y, $rule($(_y, IN, _X), _P)))))));
}
public static final void supposeDefinitionOfForallIn3() {
final Object _x = $new("x");
final Object _y = $new("y");
final Object _z = $new("z");
final Object _X = $new("X");
final Object _P = $new("P");
suppose("definition_of_forall_in_3", $forall(_x, _y, _X, _P,
$($(FORALL, _x, ",", _y, ",", _z, IN, _X, _P),
"=", $forall(_x, $rule($(_x, IN, _X), $forall(_y, $rule($(_y, IN, _X), $forall(_z, $rule($(_z, IN, _X), _P)))))))));
}
public static final void supposeDefinitionOfPositives() {
final Object _n = $new("n");
suppose("definition_of_positives", $forall(_n,
$($(_n, IN, POS), "=", $($(_n, IN, N), LAND, $(0, "<", _n)))));
}
public static final void supposeIntroductionOfConjunction() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("introduction_of_conjunction",
$forall(_X, _Y,
$rule(_X, _Y, $(_X, LAND, _Y))));
}
public static final void supposeLeftEliminationOfConjunction() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("left_elimination_of_conjunction",
$forall(_X, _Y,
$rule($(_X, LAND, _Y), _X)));
}
public static final void supposeRightEliminationOfConjunction() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("right_elimination_of_conjunction",
$forall(_X, _Y,
$rule($(_X, LAND, _Y), _Y)));
}
public static final void supposeDefinitionOfLogicalEquivalence() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("definition_of_logical_equivalence",
$forall(_X, _Y,
$($(_X, EQUIV, _Y), "=", $($rule(_X, _Y), LAND, $rule(_Y, _X)))));
}
public static final void supposeLogicalEquality() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("logical_equality",
$forall(_X, _Y,
$rule($rule(_X, _Y), $($rule(_Y, _X)), $(_X, "=", _Y))));
}
public static final void deduceLogicalEquivalenceImpliesLogicalEquality() {
subdeduction("logical_equivalence_implies_logical_equality");
final Object _X = forall("X");
final Object _Y = forall("Y");
suppose($(_X, EQUIV, _Y));
bind("definition_of_logical_equivalence", _X, _Y);
rewrite(name(-2), name(-1));
breakConjunction(name(-1));
bind("logical_equality", _X, _Y);
trimLast();
conclude();
}
public static final void deduceCommutativityOfConjunction() {
subdeduction("commutativity_of_conjunction");
final Object _X = forall("X");
final Object _Y = forall("Y");
{
subdeduction();
suppose($(_X, LAND, _Y));
breakConjunction(name(-1));
bind("introduction_of_conjunction", _Y, _X);
trimLast();
conclude();
}
{
subdeduction();
suppose($(_Y, LAND, _X));
breakConjunction(name(-1));
bind("introduction_of_conjunction", _X, _Y);
trimLast();
conclude();
}
bind("logical_equality", $(_X, LAND, _Y), $(_Y, LAND, _X));
trimLast();
conclude();
}
public static final void deducePositivesSubsetNaturals() {
subdeduction("positives_subset_naturals");
ebind("definition_of_subset", POS, N);
trimLast();
{
subdeduction();
final Object _x = forall("y");
suppose($(_x, IN, POS));
bind("definition_of_positives", _x);
rewrite(name(-2), name(-1));
deduceConjunctionLeft(name(-1));
conclude();
}
rewriteRight(name(-1), name(-2));
conclude();
}
public static final void supposeDefinitionOfMs() {
final Object _n = $new("n");
final Object _s = $new("s");
suppose("definition_of_M_s",
$(FORALL, _n, IN, POS,
$(FORALL, _s, IN, $(POS, "^", _n,
$($("M", "_", _s), "=", $($(R, "^", $(PI, _s)), CROSS, c(_s)))))));
}
public static final void supposeTypeOfFlat() {
final Object _n = $new("n");
final Object _s = $new("s");
final Object _X = $new("X");
final Object _i = $new("i");
final Object _j = $new("j");
suppose("type_of_flat",
$(FORALL, _n, IN, POS,
$(FORALL, _s, IN, $(POS, "^", _n,
$forall(_X, $($("flat", " ", $(p(1), "_", $(_i, IN, cartesian(_s, _j, _n)))), IN, $(R, "^", $(PI, _s))))))));
}
public static final void supposeDefinitionOfSingleton() {
final Object _X = $new("X");
suppose("definition_of_singleton",
$forall(_X,
$(_X, IN, c(_X))));
}
public static final void supposeTypeOfSingle() {
final Object _X = $new("X");
final Object _x = $new("x");
suppose("type_of_single",
$forall(_X,
$(FORALL, _x, IN, _X,
$(p(_x), IN, _X))));
}
public static final void supposeTypeOfPair() {
final Object _X = $new("X");
final Object _Y = $new("Y");
final Object _x = $new("x");
final Object _y = $new("y");
suppose("type_of_pair",
$forall(_X, _Y,
$(FORALL, _x, IN, _X,
$(FORALL, _y, IN, _Y,
$(p(_x, ",", _y), IN, $(_X, CROSS, _Y))))));
}
public static final void supposeCartesian1() {
final Object _X = $new("X");
suppose("cartesian_1",
$(FORALL, _X, IN, U,
$(_X, "=", $(_X, "^", 1))));
}
public static final void supposeTypeOfCartesian() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("type_of_cartesian",
$(FORALL, _X, ",", _Y, IN, U,
$(pp(_X, CROSS, _Y), SUBSET, U)));
}
public static final void supposeCartesianMN() {
final Object _X = $new("X");
final Object _m = $new("m");
final Object _n = $new("n");
suppose("cartesian_m_n",
$(FORALL, _X, IN, U,
$(FORALL, _m, ",", _n, IN, POS,
$(SB_CROSS.build($(_X, "^", _m), $(_X, "^", _n)), "=", SB_CROSS.build($(_X, "^", $(_m, "+", _n)))))));
}
public static final void deducePositivesInUhm() {
subdeduction("positives_in_Uhm");
ebind("subset_in_Uhm", POS, N);
trimLast();
conclude();
}
public static final void supposeDefinitionOfProductLoop0() {
final Object _X = $new("X");
final Object _i = $new("i");
suppose("definition_of_product_loop_0",
$forall(_i, _X,
$($(PI, "_", $(_i, "<", 0), _X), "=", 1)));
}
public static final void supposeDefinitionOfProductLoopN() {
final Object _n = $new("n");
final Object _X = $new("X");
final Object _i = $new("i");
suppose("definition_of_product_loop_n",
$(FORALL, _n, IN, POS,
$forall(_i, _X,
$rule($rule($(_i, IN, $(N, "_", $("<", _n))), $(_X, IN, R)),
$($(PI, "_", $(_i, "<", _n), _X),
"=", $($(PI, "_", $(_i, "<", $(_n, "-", 1)), _X), $(_X, "|", $(_i, "=", $(_n, "-", 1)))))))));
}
public static final void supposeDefinitionOfProductReduction() {
final Object _n = $new("n");
final Object _v = $new("v");
final Object _i = $new("i");
suppose("definition_of_product_reduction",
$(FORALL, _n, IN, POS,
$(FORALL, _v, IN, $(R, "^", _n),
$($(PI, _v), "=", $(PI, "_", $(_i, "<", _n), $(_v, "_", _i))))));
}
public static final void deduceCartesianType(final Object[] s, final String type) {
subdeduction();
boolean first = true;
for (final Object value : s) {
if ("positivity".equals(type)) {
deduceCartesianPositivity(value);
} else {
deduceCartesianRealness(value);
}
if (first) {
first = false;
} else {
final Object x = left(proposition(-2));
final Object y = left(proposition(-1));
final Object m = right(right(proposition(-2)));
final Object n = right(right(proposition(-1)));
{
subdeduction();
{
subdeduction();
ebind("vector_type_in_Uhm", POS, m);
trimLast();
ebind("vector_type_in_Uhm", POS, n);
trimLast();
ebind("type_of_tuple",
$(POS, "^", m), $(POS, "^", n), x, y);
eapplyLast();
// bind("definition_of_parentheses", middle(left(proposition(-1))));
// rewrite(name(-2), name(-1));
conclude();
}
{
subdeduction();
ebind("cartesian_m_n", POS, m, n);
eapplyLast();
verifyBasicNumericProposition(
$($(m, "+", n), "=", (Integer) m + (Integer) n));
rewrite(name(-2), name(-1));
conclude();
}
rewrite(name(-2), name(-1));
conclude();
}
}
}
// bind("definition_of_parentheses", left(proposition(-1)));
// rewriteRight(name(-2), name(-1));
conclude();
}
public static final void supposeSubsetInUhm() {
final Object _X = $new("X");
final Object _Y = $new("Y");
suppose("subset_in_Uhm",
$forall(_X,
$(FORALL, _Y, IN, U,
$rule($(_X, SUBSET, _Y), $(_X, IN, U)))));
}
public static final void deduceNaturalsInUhm() {
subdeduction("naturals_in_Uhm");
ebind("subset_in_Uhm", N, R);
trimLast();
conclude();
}
/**
* @author codistmonk (creation 2016-08-10)
*/
public static abstract interface BindListener extends Serializable {
public default void beforeBind(final String key, final Object value) {
// NOP
}
public default void afterBind(final String key, final Object value) {
// NOP
}
}
/**
* @author codistmonk (creation 2016-08-12)
*/
public static final class PropositionDescription implements Serializable {
private int index;
private String name;
private Object proposition;
public final int getIndex() {
return this.index;
}
public final PropositionDescription setIndex(final int index) {
this.index = index;
return this;
}
public final String getName() {
return this.name;
}
public final PropositionDescription setName(final String name) {
this.name = name;
return this;
}
public final Object getProposition() {
return this.proposition;
}
public final PropositionDescription setProposition(final Object proposition) {
this.proposition = proposition;
return this;
}
@Override
public final String toString() {
return this.getIndex() + ": " + this.getName() + ": " + this.getProposition();
}
private static final long serialVersionUID = -3590873676651429520L;
}
/**
* @author codistmonk (creation 2016-08-13)
*/
public static final class SequenceBuilder implements Serializable {
private final Object separator;
public SequenceBuilder(final Object separator) {
this.separator = separator;
}
public final Object getSeparator() {
return this.separator;
}
public final Object build(final Object... elements) {
if (elements.length == 1) {
return elements[0];
}
List<Object> result = Arrays.asList(this.getSeparator(), elements[elements.length - 1]);
for (int i = elements.length - 2; 0 < i; --i) {
result = Arrays.asList(this.getSeparator(), elements[i], result);
}
result = Arrays.asList(elements[0], result);
return result;
/*
*
* 1
* [( 1 )]
* [1]
*
* 1,2
* [( 1 [, 2 )]
* [1 [, 2]]
*
* 1,2,3
* [( 1 [, 2 [, 3 )]]]
* [1 [, 2 [, 3]]]
*
*
*
* 1,(2,3)
* [( 1 [, [( 2 [, 3 )]] )]]
* [1 [, [2 [, 3]]]]
*
* (1,2),3
* [( [( 1 [, 2 )]] [, 3 )]]
* [[1 [, 2]] [, 3]]
*
*/
}
private static final long serialVersionUID = 4750503376771325114L;
}
}
|
package rokclock;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.DateFormat;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.tree.*;
/**
* This class implements the main logic of the program.
*/
@SuppressWarnings("serial")
class ProjectsTree extends JTree implements TimeLog {
/**
* A customisation of the default tree node. It includes a tooltip.
*/
static class ProjectNode extends DefaultMutableTreeNode {
/**
* The tooltip text for the node.
*/
private final String tooltip;
/**
* The label containing a project's name.
*/
private final JLabel label;
/**
* A simple constructor.
*
* @param caption
* A project's name.
* @param tooltip
* The project's description.
*/
public ProjectNode(String caption, String tooltip) {
super(caption);
this.tooltip = tooltip;
label = new JLabel(caption);
label.setOpaque(true);
}
/**
* Obtains the tooltip.
*
* @return The tooltip.
*/
public String getTooltip() {
return tooltip;
}
/**
* Obtains the label associated with this node.
*
* @return The label.
*/
public JLabel getLabel() {
return label;
}
}
/**
* A platform-independent newline.
*/
private final String nl = System.getProperty("line.separator");
/**
* A link to the configuration's date format.
*/
private final DateFormat df = Config.df;
/**
* A link to the parent component.
*/
private final Frame frame;
/**
* A link to the configuration object.
*/
private final Config config;
/**
* The invisible root node of the tree.
*/
private final DefaultMutableTreeNode root;
/**
* The tree's model containing the tree's data.
*/
private final DefaultTreeModel model;
/**
* The popup menu that appears when the user right-clicks.
*/
private PopupMenu popupMenu;
/**
* The last right-clicked project path. Can be null.
*/
private TreePath lastRightClickedPath;
/**
* The currently running project node. Can be null.
*/
private ProjectNode currentProjectNode = null;
/**
* The currently running project path. Can be null.
*/
private String[] currentProjectPath = null;
/**
* The enumeration of the possible states of the program.
*/
enum State {STOPPED, RUNNING, AUTOMATIC}
/**
* The current state of the program.
*/
private State state = State.STOPPED;
/**
* The timer used for triggering events after specified periods.
*/
private final Timer timer;
/**
* The time that the last (can be current) activity started, in milliseconds
* from epoch.
*/
private long startTime = 0;
/**
* Creates a projects tree given the parent component and the link to the
* configuration object.
*
* @param frame
* The parent component.
* @param config
* The configuration object.
* @throws IOException
* Thrown if problems occur when loading the projects' file.
*/
ProjectsTree(Frame frame, Config config) throws IOException {
super(new ProjectNode("root", "root"));
this.frame = frame;
this.config = config;
root = (DefaultMutableTreeNode) getModel().getRoot();
model = (DefaultTreeModel) getModel();
loadProjects();
expandAllNodes();
setRootVisible(false);
setBackground(config.getDefaultColor());
setCellRenderer(new ProjectTreeCellRenderer(this, config));
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
switch (e.getButton()) {
case MouseEvent.BUTTON1: onLeftMouseClick(e); break;
case MouseEvent.BUTTON2: onMiddleMouseClick(e); break;
case MouseEvent.BUTTON3: onRightMouseClick(e); break;
}
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER
&& currentProjectPath != null)
startRecordingAndMinimise(currentProjectPath);
}
});
timer = createTimer();
ToolTipManager.sharedInstance().registerComponent(this);
frame.add(createPopupMenu());
}
@Override
public String getToolTipText(MouseEvent e) {
if (getRowForLocation(e.getX(), e.getY()) == -1)
return null;
TreePath path = getPathForLocation(e.getX(), e.getY());
return ((ProjectNode) path.getLastPathComponent()).getTooltip();
}
/**
* Creates a popup menu that gives the user the ability to either delete the
* selected tree node, or to create its child.
*
* @return The popup menu.
*/
private PopupMenu createPopupMenu() {
popupMenu = new PopupMenu();
MenuItem deleteMI = new MenuItem("Delete");
deleteMI.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MutableTreeNode node = (MutableTreeNode) lastRightClickedPath.getLastPathComponent();
model.removeNodeFromParent(node);
try {saveProjects();}
catch (IOException ex) {displayProblem(ex);}
}
});
MenuItem addChildMI = new MenuItem("Add child to");
addChildMI.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) lastRightClickedPath.getLastPathComponent();
new ProjectDialog(frame, ProjectsTree.this, parent).setVisible(true);
}
});
popupMenu.add(deleteMI);
popupMenu.add(addChildMI);
return popupMenu;
}
/**
* Adds a child node to a tree node.
*
* @param parent
* The parent node.
* @param project
* The sub-project that the new node represents.
* @param tooltip
* The description of the sub-project.
*/
void addChildNodeTo(DefaultMutableTreeNode parent, String project, String tooltip) {
ProjectNode child = new ProjectNode(project, tooltip);
parent.add(child);
model.reload();
expandPath(new TreePath(parent.getPath()));
try {saveProjects();}
catch (IOException e) {displayProblem(e);}
}
/**
* Obtains the project file. If no file is found, it copies the default
* template into the expected place.
*
* @return The projects file.
* @throws IOException
* Thrown if copying of the default template fails.
*/
private File getProjectsFile() throws IOException {
File projectsFile = new File(config.getProjectsFilename());
if (!projectsFile.exists())
Main.copyFile(new File(config.getProjectsFilenameDefault()), projectsFile);
return projectsFile;
}
private void loadProjects() throws IOException {
List<DefaultMutableTreeNode> nodeChain = new ArrayList<DefaultMutableTreeNode>();
nodeChain.add(root);
BufferedReader br = new BufferedReader(new FileReader(getProjectsFile()));
String line;
while ((line = br.readLine()) != null) {
// pre-processing and comments
int hash = line.indexOf('
if (hash != -1)
line = line.substring(0, hash);
if (line.trim().isEmpty()) continue;
// processing
int depth = 0;
while (line.charAt(depth) == '\t') depth++; // compute the depth of the new element
line = line.substring(depth);
while (depth < nodeChain.size())
nodeChain.remove(depth); // remove irrelevant part of the chain
ProjectNode node = new ProjectNode(extractName(line), extractTooltip(line));
if (depth == 0) root.add(node);
else nodeChain.get(depth - 1).add(node);
nodeChain.add(node);
}
br.close();
}
/**
* Writes the current tree of projects back to the projects' file. This is
* used whenever the user changes the tree through the GUI.
*
* @throws IOException
* Thrown if there are problems writing to the projects' file.
*/
private void saveProjects() throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("# Syntax:" + nl + "# main_project[{tooltip}]" + nl);
sb.append("# \tsub_project[{tooltip}]" + nl + "# \t\tsub_sub_project[{tooltip}]" + nl + nl);
saveChildrenOf(sb, root, 0);
BufferedWriter bw = new BufferedWriter(new FileWriter(config.getProjectsFilename()));
bw.write(sb.toString());
bw.close();
}
/**
* This is the recursive part of
* {@link #saveChildrenOf(StringBuilder, TreeNode, int)}.
*
* @param sb
* The string builder to write to.
* @param parent
* The parent node of which the children to save.
* @param depth
* The current depth in the tree.
*/
private void saveChildrenOf(StringBuilder sb, TreeNode parent, int depth) {
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
ProjectNode child = (ProjectNode) parent.getChildAt(i);
String projectName = child.getUserObject().toString();
String tooltip = child.getTooltip();
for (int j = 0; j < depth; j++) sb.append('\t');
sb.append(projectName);
if (tooltip != null && !tooltip.isEmpty()) sb.append("{" + tooltip + "}");
sb.append(nl);
saveChildrenOf(sb, child, depth + 1);
}
}
/**
* Extracts the project's name from the project's line.
*
* @param s
* The project's line.
* @return The extracted project's name.
*
* @see {@link #loadProjects()}
*/
private String extractName(String s) {
if (s == null) return null;
int left = s.indexOf('{');
if (left == -1) return s;
return s.substring(0, left).trim();
}
/**
* Extracts the project's description from the project's line.
*
* @param s
* The project's line.
* @return The extracted project's description.
*
* @see {@link #loadProjects()}
*/
private String extractTooltip(String s) {
if (s == null) return null;
int left = s.indexOf('{');
int right = s.lastIndexOf('}');
if (left == -1 || right == -1) return null;
return s.substring(left + 1, right).trim();
}
/**
* Creates the time with the specified interval period (obtained from the
* configuration).
*
* @return The timer.
*/
private Timer createTimer() {
Timer t = new Timer(config.getIntervalInSeconds() * 1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doPeriodicAction();
}
});
return t;
}
/**
* Expands all tree nodes in the GUI.
*/
private void expandAllNodes() {
for (int i = 0; i < getRowCount(); i++)
expandRow(i);
}
/**
* This method defines what happens when the user left-clicks: the clicked
* project path is determined, the recording is started, and the window is
* potentially hidden (depends on the configuration).
*
* @param e
* The related mouse event.
*/
private void onLeftMouseClick(MouseEvent e) {
TreePath path = getPathForLocation(e.getX(), e.getY());
if (path == null)
return;
ProjectNode node = (ProjectNode) path.getLastPathComponent();
currentProjectNode = node;
String[] projectPath = new String[path.getPathCount() - 1];
for (int i = 1; i < path.getPathCount(); i++)
projectPath[i-1] = ((ProjectNode) path.getPathComponent(i)).getUserObject().toString();
startRecordingAndMinimise(projectPath);
}
/**
* This method defines what happens when the user middle-clicks: the clicked
* project path is determined, and expanded or collapsed depending on the
* previous state.
*
* @param e
* The related mouse event.
*/
private void onMiddleMouseClick(MouseEvent e) {
TreePath path = getPathForLocation(e.getX(), e.getY());
if (isExpanded(path)) collapsePath(path);
else expandPath(path);
}
/**
* This method defines what happens when the user right-clicks: the clicked
* project path is determined, saved, and used for the potential subsequent
* action from the popup menu.
*
* @param e
* The related mouse event.
*/
private void onRightMouseClick(MouseEvent e) {
lastRightClickedPath = getPathForLocation(e.getX(), e.getY());
if (lastRightClickedPath != null)
popupMenu.show(frame, e.getX(), e.getY());
}
/**
* A helper method that starts recording and (optionally) minimises the
* window. Any exception thrown is displayed to the user.
*
* @param projectPath
* The project path to record for.
*/
private void startRecordingAndMinimise(String[] projectPath) {
try {
startRecording(projectPath);
minimiseOrHide();
} catch (Exception ex) {displayProblem(ex);}
}
@Override
public void startRecording(String[] projectPath) throws Exception {
if (state != State.STOPPED) stopRecording();
currentProjectPath = projectPath;
startTime = System.currentTimeMillis();
switchToActiveState(projectPath);
}
@Override
public void stopRecording() throws Exception {
switch (state) {
case STOPPED:
return;
case AUTOMATIC:
timer.stop();
stopAutomaticRecording();
break;
case RUNNING:
writeLogEntry(startTime, System.currentTimeMillis());
}
switchToStoppedState();
}
/**
* This method is called when the user stops the semi-active period. The
* action depends on the configuration option
* {@link Config#getAutoCountTowards()}.
*
* @throws Exception
* Thrown if a log entry cannot be written.
*/
private void stopAutomaticRecording() throws Exception {
switch (config.getAutoCountTowards()) {
case NOTHING:
break;
case UNKNOWN:
currentProjectPath = new String[] {"unknown"};
//$FALL-THROUGH$
case PREVIOUS:
writeLogEntry(startTime, System.currentTimeMillis());
}
}
@Override
public void doPeriodicAction() {
try {
if (state == State.AUTOMATIC) {
timer.stop();
potentiallyWriteTimeout();
switchToStoppedState();
} else if (state == State.RUNNING) {
stopRecording();
startRecording(currentProjectPath);
switchToSemiActiveState();
}
} catch (Exception ex) {displayProblem(ex);}
unminimiseOrShow();
}
/**
* This method is called when the semi-active period ends without user
* interaction. It potentially writes this event to the log, depending on
* the configuration option {@link Config#getWriteTimeouts()}.
*
* @throws Exception
* Thrown if a log entry cannot be written.
*/
private void potentiallyWriteTimeout() throws Exception {
if (!config.getWriteTimeouts()) return;
currentProjectPath = new String[] {"(timed out)"};
writeLogEntry(startTime, startTime);
}
@Override
public void writeLogEntry(long startTime, long endTime) throws Exception {
String startTimeS = df.format(new Date(startTime));
String endTimeS = df.format(new Date(endTime));
String uid = config.getUID();
String entry = (uid == null ? "" : uid + ",") + startTimeS + "," + endTimeS;
for (String projectPathNode : currentProjectPath)
entry += "," + projectPathNode;
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(config.getLogFilename(), true)));
out.write(entry + nl);
out.close();
}
@Override
public void switchToActiveState(String[] projectPath) {
int delay = config.getIntervalInSeconds() * 1000;
timer.setDelay(delay);
timer.setInitialDelay(delay);
timer.restart();
state = State.RUNNING;
repaint();
}
@Override
public void switchToSemiActiveState() {
int delay = config.getWaitInSeconds() * 1000;
timer.setDelay(delay);
timer.setInitialDelay(delay);
timer.restart();
state = State.AUTOMATIC;
repaint();
}
@Override
public void switchToStoppedState() {
state = State.STOPPED;
repaint();
}
@Override
public void minimiseOrHide() {
new Thread() {
@Override
public void run() {
try {Thread.sleep(150);}
catch (InterruptedException e) {e.printStackTrace();}
switch (config.getBehaviour()) {
case MINIMISE:
frame.setExtendedState(Frame.ICONIFIED);
break;
case HIDE:
frame.setVisible(false);
break;
case SHOW:
break;
}
}
}.start();
}
@Override
public void unminimiseOrShow() {
switch (config.getBehaviour()) {
case MINIMISE:
frame.setExtendedState(Frame.NORMAL);
break;
case HIDE:
case SHOW:
frame.setVisible(true);
break;
}
}
@Override
public void displayProblem(Exception e) {
JOptionPane.showMessageDialog(this, "A problem has occurred: " + e.getMessage());
}
/**
* Obtains the currently active project node.
*
* @return The project node.
*/
ProjectNode getCurrentPojectNode() {
return currentProjectNode;
}
/**
* Obtains the current state of the program.
*
* @return The state.
*/
State getState() {
return state;
}
/**
* Obtains the array of top-level projects.
*
* @return The top-level projects.
*/
String[] getTopLevelProjects() {
final int size = root.getChildCount();
String[] projects = new String[size];
for (int i = 0; i < size; i++)
projects[i] = ((ProjectNode) root.getChildAt(i)).getUserObject().toString();
return projects;
}
}
|
public class BasicArithmatic
{
private static final int constant = 10;
public static void main(String[] args)
{
int a = 4;
int b = 3;
int sum = a + b;
int product = a*b;
int difference = a -b;
int addImmediate = a + 2;
int subImmediate = a - 2;
int addConstant = b * constant;
addConstant += 2;
int multiplyImmediate = b * 0x05;
multiplyImmediate << 1;
multiplyImmediate++;
public int CasualMethod()
{
return 1;
}
casualMethod();
public int Sum(int a, int b)
{
return a + b;
}
// DO NOT LEX
/* Do not lex */
/*
* Do not lex 2
*/
// Do not lex 3
// Strings are currently unsupported
// String s = "/*LexAstring" + lex + "LexAstring*/ LexAstring";
}
}
|
package ChemHelper;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import Functions.*;
public class ChemHelper extends JFrame{ //Primary GUI class
Container pane;
JPanel last;
JMenuBar menu;
Function[] funcs;
public ChemHelper(){
pane = getContentPane();
pane.setLayout(new BorderLayout());
createMenu();
pane.add(menu, BorderLayout.NORTH);
//pack();
setSize(1158, 636);
this.setMaximumSize(new Dimension(1158, 636)); //makes sure that the size will never exceed 1158, 636
this.setMinimumSize(new Dimension(1158, 636)); //makes sure that the size will never be lower than 1158, 636
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void createMenu()
{
funcs = new Function[3];
funcs[0] = new PeriodicTable();
funcs[1] = new ElectronShell();
funcs[2] = new EquationReader();
//Currently this system is completely random as there are not enough things to make an actually useful system but I wanted to make the framework
String[] menuNames = {"Things you may want to use", "Things that are currently unusable"}; //Lists the names of the different menus on the menu bar.
int[] menuCutoffs = {0, 2}; //Specifies the indices where a new menu would start from funcs
menu = new JMenuBar();
for(int menuNum = 0; menuNum < menuCutoffs.length; menuNum++)
{
int startIndex = menuCutoffs[menuNum], endIndex;
if(menuNum + 1 == menuCutoffs.length) endIndex = funcs.length - 1;
else endIndex = menuCutoffs[menuNum + 1] - 1;
JMenu thisMenu = new JMenu(menuNames[menuNum]);
for(int index = startIndex; index <= endIndex; index++)
{
thisMenu.add(new FunctionMenuItem(funcs[index]));
}
menu.add(thisMenu);
}
}
private class FunctionMenuItem extends JMenuItem
{
private Function function;
public FunctionMenuItem(Function function)
{
super(function.toString());
this.function = function;
addActionListener(new FunctionListener());
}
public Function getFunction()
{
return function;
}
private class FunctionListener implements ActionListener
{
public void actionPerformed(ActionEvent arg0)
{
if(last!=null) pane.remove(last);
JPanel func = ((FunctionMenuItem)arg0.getSource()).getFunction().getPanel();
pane.add(func, BorderLayout.EAST);
//func.setVisible(true);
//func.repaint();
pane.repaint();
pack();
//repaint();
last = func;
}
}
}
public static void main(String[] args){
new ChemHelper();
}
}
|
package cn.jingzhuan.lib.chart.renderer;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.NonNull;
import cn.jingzhuan.lib.chart.base.Chart;
import cn.jingzhuan.lib.chart.Viewport;
import cn.jingzhuan.lib.chart.component.AxisY;
import cn.jingzhuan.lib.chart.component.Highlight;
import cn.jingzhuan.lib.chart.data.ChartData;
import cn.jingzhuan.lib.chart.data.LineData;
import cn.jingzhuan.lib.chart.data.LineDataSet;
import cn.jingzhuan.lib.chart.data.PointValue;
import cn.jingzhuan.lib.chart.event.OnViewportChangeListener;
import java.util.List;
public class LineRenderer extends AbstractDataRenderer<LineDataSet> {
private LineData lineData;
private Path linePath;
private Path shaderPath;
public LineRenderer(final Chart chart) {
super(chart);
linePath = new Path();
chart.setInternalViewportChangeListener(new OnViewportChangeListener() {
@Override
public void onViewportChange(Viewport viewport) {
mViewport = viewport;
calcDataSetMinMax();
}
});
final Highlight highlight = new Highlight();
chart.addOnTouchPointChangeListener(new Chart.OnTouchPointChangeListener() {
@Override
public void touch(float x, float y) {
//noinspection SynchronizeOnNonFinalField
synchronized (lineData) {
for (LineDataSet line : getDataSet()) {
if (line.isHighlightedVerticalEnable() && !line.getValues().isEmpty()) {
int offset = line.getStartIndexOffset();
int index = getEntryIndexByCoordinate(x, y) - offset;
if (index > 0 && index < line.getValues().size()) {
final PointValue pointValue = line.getEntryForIndex(index);
float xPosition = pointValue.getX();
float yPosition = pointValue.getY();
if (xPosition >= 0 && yPosition >= 0) {
highlight.setX(xPosition);
highlight.setY(yPosition);
highlight.setDataIndex(index);
chart.highlightValue(highlight);
}
}
}
}
}
}
});
}
@Override
public void renderHighlighted(Canvas canvas, @NonNull Highlight[] highlights) {
mRenderPaint.setStyle(Paint.Style.STROKE);
mRenderPaint.setColor(getHighlightColor());
if (mHighlightedDashPathEffect != null) {
mRenderPaint.setPathEffect(mHighlightedDashPathEffect);
}
for (Highlight highlight : highlights) {
if (highlight != null) {
canvas.drawLine(highlight.getX(),
0,
highlight.getX(),
mContentRect.bottom,
mRenderPaint);
// Horizontal
for (LineDataSet lineDataSet : getDataSet()) {
if (lineDataSet.isHighlightedHorizontalEnable()) {
canvas.drawLine(0,
highlight.getY(),
mContentRect.right,
highlight.getY(),
mRenderPaint);
}
}
}
}
mRenderPaint.setPathEffect(null);
}
@Override public void removeDataSet(LineDataSet dataSet) {
lineData.remove(dataSet);
calcDataSetMinMax();
}
@Override public void clearDataSet() {
lineData.clear();
calcDataSetMinMax();
}
@Override
protected List<LineDataSet> getDataSet() {
return lineData.getDataSets();
}
@Override public ChartData<LineDataSet> getChartData() {
if (lineData == null) lineData = new LineData();
return lineData;
}
@Override protected void renderDataSet(Canvas canvas, ChartData<LineDataSet> chartData) {
for (LineDataSet dataSet : getDataSet()) {
if (dataSet.isVisible()) {
drawDataSet(canvas, dataSet,
chartData.getLeftMax(), chartData.getLeftMin(),
chartData.getRightMax(), chartData.getRightMin());
}
}
}
private void drawDataSet(Canvas canvas, final LineDataSet lineDataSet,
float lMax, float lMin, float rMax, float rMin) {
mRenderPaint.setStrokeWidth(lineDataSet.getLineThickness());
mRenderPaint.setColor(lineDataSet.getColor());
int valueCount = lineDataSet.getEntryCount();
linePath.reset();
boolean isFirst = true;
float min, max;
switch (lineDataSet.getAxisDependency()) {
case AxisY.DEPENDENCY_RIGHT:
min = rMin;
max = rMax;
break;
case AxisY.DEPENDENCY_BOTH:
case AxisY.DEPENDENCY_LEFT:
default:
min = lMin;
max = lMax;
break;
}
final int count = lineDataSet.getVisibleValueCount(mViewport);
float width = 0;
if (count > 0) {
width = mContentRect.width() / ((float) count);
}
int offset = lineDataSet.getStartIndexOffset();
for (int i = 0; i < valueCount && i < lineDataSet.getValues().size(); i++) {
PointValue point = lineDataSet.getEntryForIndex(i);
if (Float.isNaN(point.getValue())) {
continue;
}
float xPosition = width * 0.5f + getDrawX((i + offset) / ((float) valueCount));
float yPosition = (max - point.getValue()) / (max - min) * mContentRect.height();
point.setCoordinate(xPosition, yPosition);
if (isFirst) {
isFirst = false;
linePath.moveTo(xPosition, yPosition);
} else {
linePath.lineTo(xPosition, yPosition);
}
}
// draw shader area
if (lineDataSet.getShader() != null && lineDataSet.getValues().size() > 0) {
mRenderPaint.setStyle(Paint.Style.FILL);
if (shaderPath == null) {
shaderPath = new Path(linePath);
} else {
shaderPath.set(linePath);
}
int lastIndex = lineDataSet.getValues().size() - 1;
if (lastIndex >= valueCount) lastIndex = valueCount - 1;
PointValue pointValue = lineDataSet.getEntryForIndex(lastIndex);
if (pointValue != null) {
shaderPath.lineTo(lineDataSet.getValues().get(lastIndex).getX(), mContentRect.bottom);
shaderPath.lineTo(offset * width, mContentRect.bottom);
shaderPath.lineTo(offset * width, lineDataSet.getValues().get(0).getY());
shaderPath.close();
mRenderPaint.setShader(lineDataSet.getShader());
canvas.drawPath(shaderPath, mRenderPaint);
mRenderPaint.setShader(null);
mRenderPaint.setStyle(Paint.Style.STROKE);
}
}
canvas.drawPath(linePath, mRenderPaint);
}
}
|
package com.dextersLaboratory.jtetris.controller;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.dextersLaboratory.jtetris.model.Direction;
import com.dextersLaboratory.jtetris.model.GameModel;
import com.dextersLaboratory.jtetris.model.GameState;
import com.dextersLaboratory.jtetris.model.block.Block;
import com.dextersLaboratory.jtetris.model.block.BlockI;
import com.dextersLaboratory.jtetris.model.block.BlockJ;
import com.dextersLaboratory.jtetris.model.block.BlockL;
import com.dextersLaboratory.jtetris.model.block.BlockO;
import com.dextersLaboratory.jtetris.model.block.BlockS;
import com.dextersLaboratory.jtetris.model.block.BlockT;
import com.dextersLaboratory.jtetris.model.block.BlockZ;
public class GameController {
private GameModel model;
private Music bgm;
private Sound soundMove;
private Sound soundRotate;
private Sound soundLine;
private Sound soundLand;
private Sound soundGameOver;
private Sound soundPause;
private float steptimeAccum = 0f;
public GameController(){
model = new GameModel();
bgm = Gdx.audio.newMusic(Gdx.files.internal("bgm.mp3"));
bgm.setLooping(true);
soundMove = Gdx.audio.newSound(Gdx.files.internal("move.wav"));
soundRotate = Gdx.audio.newSound(Gdx.files.internal("rotate.wav"));
soundLine = Gdx.audio.newSound(Gdx.files.internal("line.wav"));
soundLand = Gdx.audio.newSound(Gdx.files.internal("land.wav"));
soundGameOver = Gdx.audio.newSound(Gdx.files.internal("gameOver.wav"));
soundPause = Gdx.audio.newSound(Gdx.files.internal("pause.wav"));
}
//TODO: remove later
// private void debugLineBottom(){
// for(int x = 0; x < 10; x++){
// model.setGridCell(x, 0, true);
// model.setGridCellColor(x, 0, Color.RED);
//TODO: remove later
// private void debugLineSides(){
// int numLinesAtEachSide = 1;
// for(int x = 0; x < numLinesAtEachSide; x++){
// for(int y = 0; y < 20; y++){
// model.setGridCell(x, y, true);
// model.setGridCell(9-x, y, true);
// model.setGridCellColor(x, y, Color.RED);
// model.setGridCellColor(9-x, y, Color.RED);
//TODO: remove later
// private void debugMulipleClears(){
// int numClears = 9;
// for(int y = 0; y < numClears; y++){
// for(int x = 0; x < 9; x++){
// model.setGridCell(x, y, true);
// model.setGridCellColor(x, y, Color.RED);
public void update(float delta){
handleInput();
if(model.getGameState() == GameState.playing){
model.increaseTimePlayed(delta);
steptimeAccum += delta;
if(steptimeAccum >= model.getSteptime()){
steptimeAccum = 0;
step();
}
}
}
public GameModel getGameModel(){
return model;
}
private void handleInput(){
if(Gdx.input.isKeyJustPressed(Keys.NUM_1)){
model.increaseLinesCleared(5);
increaseSpeedIfNecessary();
}
if(Gdx.input.isKeyJustPressed(Keys.P) || Gdx.input.isKeyJustPressed(Keys.ENTER)){
if(model.getGameState() == GameState.paused ||
model.getGameState() == GameState.playing){
togglePause();
}else{
newGame();
}
}
if(model.getGameState() == GameState.playing){
if(Gdx.input.isKeyJustPressed(Keys.A) || Gdx.input.isKeyJustPressed(Keys.LEFT)){
moveBlockLeft();
}
else if(Gdx.input.isKeyJustPressed(Keys.D) || Gdx.input.isKeyJustPressed(Keys.RIGHT)){
moveBlockRight();
}
if(Gdx.input.isKeyJustPressed(Keys.W) || Gdx.input.isKeyJustPressed(Keys.UP)){
rotateBlock();
}
if(Gdx.input.isKeyJustPressed(Keys.S) || Gdx.input.isKeyJustPressed(Keys.DOWN)){
dropBlockDown();
}
}
}
private void step(){
if(model.getCurrentBlock() == null)
return;
if(!doesCollide(Direction.down)){
model.setCurrentBlockPosY(model.getCurrentBlockPosY() - 1);
}else{
//block to grid
blockToGrid();
clearLines();
spawnNewBlock();
model.increaseScore(10);
soundLand.play();
}
}
private void moveBlockLeft(){
if(model.getCurrentBlock() == null)
return;
if(!doesCollide(Direction.left)){
model.setCurrentBlockPosX(model.getCurrentBlockPosX() - 1);
soundMove.play();
}
}
private void moveBlockRight(){
if(model.getCurrentBlock() == null)
return;
if(!doesCollide(Direction.right)){
model.setCurrentBlockPosX(model.getCurrentBlockPosX() + 1);
soundMove.play();
}
}
private void dropBlockDown(){
if(model.getCurrentBlock() == null)
return;
while(!doesCollide(Direction.down)){
model.setCurrentBlockPosY(model.getCurrentBlockPosY() - 1);
}
step();
steptimeAccum = 0f;
}
private void rotateBlock(){
model.getCurrentBlock().rotate();
if(!handleCollisionAfterRotation()){
for(int i = 0; i < 3; i++)
model.getCurrentBlock().rotate();
}else{
soundRotate.play();
}
}
private void togglePause(){
if(model.getGameState() == GameState.playing){
model.setGameState(GameState.paused);
bgm.pause();
soundPause.play();
}
else if(model.getGameState() == GameState.paused){
model.setGameState(GameState.playing);
bgm.play();
}
}
private void newGame(){
model.reset();
steptimeAccum = 0f;
spawnNewBlock();
model.setGameState(GameState.playing);
if(!bgm.isPlaying()){
bgm.setPosition(0f);
bgm.play();
}
// debugLineBottom();//TODO: remove later
// debugLineSides();//TODO: remove later
// debugMulipleClears();//TODO: remove later
}
private void blockToGrid(){
Block block = model.getCurrentBlock();
int blockX = model.getCurrentBlockPosX();
int blockY = model.getCurrentBlockPosY();
for(int x = 0; x < 4; x++){
for(int y = 0; y < 4; y++){
if(block.getGrid()[x][y]){
model.setGridCell(blockX + x, blockY + y, true);
model.setGridCellColor(blockX + x, blockY + y, block.getColor());
}
}
}
}
private boolean doesCollide(Direction dir){
for(int y = 0; y < 4; y++){
for(int x = 0; x < 4; x++){
if(model.getCurrentBlock().getGrid()[x][y]){
int x2 = model.getCurrentBlockPosX() + x;
int y2 = model.getCurrentBlockPosY() + y;
if(dir == Direction.down){
y2
}else if(dir == Direction.left){
x2
}else if(dir == Direction.right){
x2++;
}
if(y2 >= 0 && x2 >= 0 && x2 <= 9){
if(model.getGridCell(x2, y2)){
return true;
}
}else{
return true;
}
}
}
}
return false;
}
private boolean handleCollisionAfterRotation(){
boolean possible = true;
boolean correctedLeft = false;
int newPosX = model.getCurrentBlockPosX();
int newPosY = model.getCurrentBlockPosY();
//collision left
for(int x = 0; x < 2; x++){
for(int y = 0; y < 4; y++){
if(model.getCurrentBlock().getGrid()[x][y]){
if(model.getGridCell(newPosX + x, newPosY + y)){
newPosX++;
correctedLeft = true;
y = -1;
}
}
}
}
//collision right
for(int x = 3; x > 1; x
for(int y = 0; y < 4; y++){
if(model.getCurrentBlock().getGrid()[x][y]){
if(model.getGridCell(newPosX + x, newPosY + y)){
if(correctedLeft){
possible = false;
x = -1;
break;
}
newPosX
y = -1;
}
}
}
}
if(possible){
model.setCurrentBlockPosX(newPosX);
model.setCurrentBlockPosY(newPosY);
}
return possible;
}
private void spawnNewBlock(){
int rand = (int) (Math.random() * 7);
// int rand = 6;
Block newBlock = null;
switch(rand){
case 0:
newBlock = new BlockI();
break;
case 1:
newBlock = new BlockJ();
break;
case 2:
newBlock = new BlockL();
break;
case 3:
newBlock = new BlockO();
break;
case 4:
newBlock = new BlockS();
break;
case 5:
newBlock = new BlockT();
break;
case 6:
newBlock = new BlockZ();
break;
default:
System.out.println("ERROR creating new block. rand is " + rand);
break;
}
model.setCurrentBlock(newBlock);
model.setCurrentBlockPos(3, 16);
if(doesCollide(null)){
model.setGameState(GameState.gameOver);
bgm.pause();
soundGameOver.play();
}
}
private void clearLines(){
boolean playSound = false;
for(int y = 0; y < 20; y++){
for(int x = 0; x < 10; x++){
if(!model.getGridCell(x, y)){
break;
}
else if(x == 9){
playSound = true;
clearLine(y);
y = -1;
break;
}
}
}
if(playSound)
soundLine.play();
}
private void clearLine(int line){
for(int x = 0; x < 10; x++){
model.setGridCell(x, line, false);
}
for(int y = line; y < 19; y++){
for(int x = 0; x < 10; x++){
model.setGridCell(x, y, model.getGridCell(x, y+1));
model.setGridCellColor(x, y, model.getGridCellColor(x, y+1));
}
}
model.increaseScore(GameModel.SCORE_PER_LINE);
model.increaseLinesCleared(1);
increaseSpeedIfNecessary();
}
private void increaseSpeedIfNecessary(){
if(model.getLinesCleared() % 5 == 0){
model.setSpeed(model.getLinesCleared()/5 + 1);
float newSteptime = 0.5f / (float) (Math.pow((model.getLinesCleared()/5) + 1, 0.5));
model.setSteptime(newSteptime);
}
}
public void dispose(){
bgm.dispose();
}
}
|
package org.redisson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisConnection;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.RedisStrictCommand;
import org.redisson.client.protocol.convertor.VoidReplayConvertor;
public class RedisRunner {
public enum REDIS_OPTIONS {
BINARY_PATH,
DAEMONIZE,
PIDFILE,
PORT,
TCP_BACKLOG,
BIND(true),
UNIXSOCKET,
UNIXSOCKETPERM,
TIMEOUT,
TCP_KEEPALIVE,
LOGLEVEL,
LOGFILE,
SYSLOG_ENABLED,
SYSLOG_IDENT,
SYSLOG_FACILITY,
DATABASES,
SAVE(true),
STOP_WRITES_ON_BGSAVE_ERROR,
RDBCOMPRESSION,
RDBCHECKSUM,
DBFILENAME,
DIR,
SLAVEOF,
MASTERAUTH,
SLAVE_SERVE_STALE_DATA,
SLAVE_READ_ONLY,
REPL_DISKLESS_SYNC,
REPL_DISKLESS_SYNC_DELAY,
REPL_PING_SLAVE_PERIOD,
REPL_TIMEOUT,
REPL_DISABLE_TCP_NODELAY,
REPL_BACKLOG_SIZE,
REPL_BACKLOG_TTL,
SLAVE_PRIORITY,
MIN_SLAVES_TO_WRITE,
MIN_SLAVES_MAX_LAG,
REQUIREPASS,
RENAME_COMMAND(true),
MAXCLIENTS,
MAXMEMORY,
MAXMEMORY_POLICY,
MAXMEMORY_SAMPLE,
APPENDONLY,
APPENDFILENAME,
APPENDFSYNC,
NO_APPENDFSYNC_ON_REWRITE,
AUTO_AOF_REWRITE_PERCENTAGE,
AUTO_AOF_REWRITE_MIN_SIZE,
AOF_LOAD_TRUNCATED,
LUA_TIME_LIMIT,
CLUSTER_ENABLED,
CLUSTER_CONFIG_FILE,
CLUSTER_NODE_TIMEOUT,
CLUSTER_SLAVE_VALIDITY_FACTOR,
CLUSTER_MIGRATION_BARRIER,
CLUSTER_REQUIRE_FULL_COVERAGE,
SLOWLOG_LOG_SLOWER_THAN,
SLOWLOG_MAX_LEN,
LATENCY_MONITOR_THRESHOLD,
NOTIFY_KEYSPACE_EVENTS,
HASH_MAX_ZIPLIST_ENTRIES,
HASH_MAX_ZIPLIST_VALUE,
LIST_MAX_ZIPLIST_ENTRIES,
LIST_MAX_ZIPLIST_VALUE,
SET_MAX_INTSET_ENTRIES,
ZSET_MAX_ZIPLIST_ENTRIES,
ZSET_MAX_ZIPLIST_VALUE,
HLL_SPARSE_MAX_BYTES,
ACTIVEREHASHING,
CLIENT_OUTPUT_BUFFER_LIMIT$NORMAL,
CLIENT_OUTPUT_BUFFER_LIMIT$SLAVE,
CLIENT_OUTPUT_BUFFER_LIMIT$PUBSUB,
HZ,
AOF_REWRITE_INCREMENTAL_FSYNC,
PROTECTED_MODE,
SENTINEL,
SENTINEL$ANNOUNCE_IP,
SENTINEL$ANNOUNCE_PORT,
SENTINEL$MONITOR(true),
SENTINEL$AUTH_PASS(true),
SENTINEL$DOWN_AFTER_MILLISECONDS(true),
SENTINEL$PARALLEL_SYNCS(true),
SENTINEL$FAILOVER_TIMEOUT(true),
SENTINEL$NOTIFICATION_SCRIPT(true),
SENTINEL$CLIENT_RECONFIG_SCRIPT(true)
;
private final boolean allowMutiple;
private REDIS_OPTIONS() {
this.allowMutiple = false;
}
private REDIS_OPTIONS(boolean allowMutiple) {
this.allowMutiple = allowMutiple;
}
public boolean isAllowMultiple() {
return allowMutiple;
}
}
public enum LOGLEVEL_OPTIONS {
DEBUG,
VERBOSE,
NOTICE,
WARNING
}
public enum SYSLOG_FACILITY_OPTIONS {
USER,
LOCAL0,
LOCAL1,
LOCAL2,
LOCAL3,
LOCAL4,
LOCAL5,
LOCAL6,
LOCAL7
}
public enum MAX_MEMORY_POLICY_OPTIONS {
VOLATILE_LRU,
ALLKEYS_LRU,
VOLATILE_RANDOM,
ALLKEYS_RANDOM,
VOLATILE_TTL,
NOEVICTION
}
public enum APPEND_FSYNC_MODE_OPTIONS {
ALWAYS,
EVERYSEC,
NO
}
public enum KEYSPACE_EVENTS_OPTIONS {
K,
E,
g,
$,
l,
s,
h,
z,
x,
e,
A
}
private final LinkedHashMap<REDIS_OPTIONS, String> options = new LinkedHashMap<>();
protected static RedisRunner.RedisProcess defaultRedisInstance;
private static int defaultRedisInstanceExitCode;
private String path = "";
private String defaultDir = Paths.get("").toString();
private boolean nosave = false;
private boolean randomDir = false;
private ArrayList<String> bindAddr = new ArrayList<>();
private int port = 6379;
private int retryCount = Integer.MAX_VALUE;
private boolean randomPort = false;
private String sentinelFile;
private String clusterFile;
{
this.options.put(REDIS_OPTIONS.BINARY_PATH, RedissonRuntimeEnvironment.redisBinaryPath);
}
public static RedisProcess runRedisWithConfigFile(String configPath) throws IOException, InterruptedException {
URL resource = RedisRunner.class.getResource(configPath);
return runWithOptions(new RedisRunner(), RedissonRuntimeEnvironment.redisBinaryPath, resource.getFile());
}
private static RedisProcess runWithOptions(RedisRunner runner, String... options) throws IOException, InterruptedException {
List<String> launchOptions = Arrays.stream(options)
.map(x -> Arrays.asList(x.split(" "))).flatMap(x -> x.stream())
.collect(Collectors.toList());
System.out.println("REDIS LAUNCH OPTIONS: " + Arrays.toString(launchOptions.toArray()));
ProcessBuilder master = new ProcessBuilder(launchOptions)
.redirectErrorStream(true)
.directory(new File(RedissonRuntimeEnvironment.tempDir));
Process p = master.start();
new Thread(() -> {
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
try {
while (p.isAlive() && (line = reader.readLine()) != null && !RedissonRuntimeEnvironment.isTravis) {
System.out.println("REDIS PROCESS: " + line);
}
} catch (IOException ex) {
System.out.println("Exception: " + ex.getLocalizedMessage());
}
}).start();
Thread.sleep(1500);
return new RedisProcess(p, runner);
}
public RedisProcess run() throws IOException, InterruptedException, FailedToStartRedisException {
if (!options.containsKey(REDIS_OPTIONS.DIR)) {
addConfigOption(REDIS_OPTIONS.DIR, defaultDir);
}
if (randomPort) {
for (int i = 0; i < retryCount; i++) {
this.port = findFreePort();
addConfigOption(REDIS_OPTIONS.PORT, this.port);
try {
return runAndCheck();
} catch (FailedToStartRedisException e) {
}
}
throw new FailedToStartRedisException();
} else {
return runAndCheck();
}
}
public RedisProcess runAndCheck() throws IOException, InterruptedException, FailedToStartRedisException {
List<String> args = new ArrayList(options.values());
if (sentinelFile != null && sentinelFile.length() > 0) {
String confFile = defaultDir + File.separator + sentinelFile;
try (PrintWriter printer = new PrintWriter(new FileWriter(confFile))) {
args.stream().forEach((arg) -> {
if (arg.contains("
printer.println(arg.replace("
}
});
}
args = args.subList(0, 1);
args.add(confFile);
args.add("--sentinel");
}
RedisProcess rp = runWithOptions(this, args.toArray(new String[0]));
if (!isCluster()
&& rp.redisProcess.waitFor(1000, TimeUnit.MILLISECONDS)) {
throw new FailedToStartRedisException();
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
rp.stop();
} catch (InterruptedException ex) {
}
}));
return rp;
}
public boolean hasOption(REDIS_OPTIONS option) {
return options.containsKey(option);
}
private void addConfigOption(REDIS_OPTIONS option, Object... args) {
StringBuilder sb = new StringBuilder("
.append(option.toString()
.replaceAll("_", "-")
.replaceAll("\\$", " ")
.toLowerCase())
.append(" ")
.append(Arrays.stream(args).map(Object::toString)
.collect(Collectors.joining(" ")));
this.options.put(option,
option.isAllowMultiple()
? sb.insert(0, this.options.getOrDefault(option, "")).toString()
: sb.toString());
}
private String convertBoolean(boolean b) {
return b ? "yes" : "no";
}
public RedisRunner daemonize(boolean daemonize) {
addConfigOption(REDIS_OPTIONS.DAEMONIZE, convertBoolean(daemonize));
return this;
}
public RedisRunner pidfile(String pidfile) {
addConfigOption(REDIS_OPTIONS.PIDFILE, pidfile);
return this;
}
public RedisRunner port(int port) {
this.port = port;
this.randomPort = false;
addConfigOption(REDIS_OPTIONS.PORT, port);
return this;
}
public RedisRunner randomPort() {
return randomPort(Integer.MAX_VALUE);
}
public RedisRunner randomPort(int retryCount) {
this.randomPort = true;
this.retryCount = retryCount;
options.remove(REDIS_OPTIONS.PORT);
return this;
}
public int getPort() {
return this.port;
}
public RedisRunner tcpBacklog(long tcpBacklog) {
addConfigOption(REDIS_OPTIONS.TCP_BACKLOG, tcpBacklog);
return this;
}
public RedisRunner bind(String bind) {
this.bindAddr.add(bind);
addConfigOption(REDIS_OPTIONS.BIND, bind);
return this;
}
public ArrayList<String> getBindAddr() {
return this.bindAddr;
}
public RedisRunner unixsocket(String unixsocket) {
addConfigOption(REDIS_OPTIONS.UNIXSOCKET, unixsocket);
return this;
}
public RedisRunner unixsocketperm(int unixsocketperm) {
addConfigOption(REDIS_OPTIONS.UNIXSOCKETPERM, unixsocketperm);
return this;
}
public RedisRunner timeout(long timeout) {
addConfigOption(REDIS_OPTIONS.TIMEOUT, timeout);
return this;
}
public RedisRunner tcpKeepalive(long tcpKeepalive) {
addConfigOption(REDIS_OPTIONS.TCP_KEEPALIVE, tcpKeepalive);
return this;
}
public RedisRunner loglevel(LOGLEVEL_OPTIONS loglevel) {
addConfigOption(REDIS_OPTIONS.LOGLEVEL, loglevel.toString());
return this;
}
public RedisRunner logfile(String logfile) {
addConfigOption(REDIS_OPTIONS.LOGLEVEL, logfile);
return this;
}
public RedisRunner syslogEnabled(boolean syslogEnabled) {
addConfigOption(REDIS_OPTIONS.SYSLOG_ENABLED, convertBoolean(syslogEnabled));
return this;
}
public RedisRunner syslogIdent(String syslogIdent) {
addConfigOption(REDIS_OPTIONS.SYSLOG_IDENT, syslogIdent);
return this;
}
public RedisRunner syslogFacility(SYSLOG_FACILITY_OPTIONS syslogFacility) {
addConfigOption(REDIS_OPTIONS.SYSLOG_IDENT, syslogFacility.toString());
return this;
}
public RedisRunner databases(int databases) {
addConfigOption(REDIS_OPTIONS.DATABASES, databases);
return this;
}
public RedisRunner save(long seconds, long changes) {
if (!nosave) {
addConfigOption(REDIS_OPTIONS.SAVE, seconds, changes);
}
return this;
}
/**
* Phantom option
*
* @return RedisRunner
*/
public RedisRunner nosave() {
this.nosave = true;
options.remove(REDIS_OPTIONS.SAVE);
addConfigOption(REDIS_OPTIONS.SAVE, "''");
return this;
}
public RedisRunner stopWritesOnBgsaveError(boolean stopWritesOnBgsaveError) {
addConfigOption(REDIS_OPTIONS.STOP_WRITES_ON_BGSAVE_ERROR, convertBoolean(stopWritesOnBgsaveError));
return this;
}
public RedisRunner rdbcompression(boolean rdbcompression) {
addConfigOption(REDIS_OPTIONS.RDBCOMPRESSION, convertBoolean(rdbcompression));
return this;
}
public RedisRunner rdbchecksum(boolean rdbchecksum) {
addConfigOption(REDIS_OPTIONS.RDBCHECKSUM, convertBoolean(rdbchecksum));
return this;
}
public RedisRunner dbfilename(String dbfilename) {
addConfigOption(REDIS_OPTIONS.DBFILENAME, dbfilename);
return this;
}
public RedisRunner dir(String dir) {
if (!randomDir) {
addConfigOption(REDIS_OPTIONS.DIR, dir);
this.path = dir;
}
return this;
}
/**
* Phantom option
*
* @return RedisRunner
*/
public RedisRunner randomDir() {
this.randomDir = true;
options.remove(REDIS_OPTIONS.DIR);
makeRandomDefaultDir();
addConfigOption(REDIS_OPTIONS.DIR, defaultDir);
return this;
}
public RedisRunner slaveof(Inet4Address masterip, int port) {
addConfigOption(REDIS_OPTIONS.SLAVEOF, masterip.getHostAddress(), port);
return this;
}
public RedisRunner slaveof(String masterip, int port) {
addConfigOption(REDIS_OPTIONS.SLAVEOF, masterip, port);
return this;
}
public RedisRunner masterauth(String masterauth) {
addConfigOption(REDIS_OPTIONS.MASTERAUTH, masterauth);
return this;
}
public RedisRunner slaveServeStaleData(boolean slaveServeStaleData) {
addConfigOption(REDIS_OPTIONS.SLAVE_SERVE_STALE_DATA, convertBoolean(slaveServeStaleData));
return this;
}
public RedisRunner slaveReadOnly(boolean slaveReadOnly) {
addConfigOption(REDIS_OPTIONS.SLAVE_READ_ONLY, convertBoolean(slaveReadOnly));
return this;
}
public RedisRunner replDisklessSync(boolean replDisklessSync) {
addConfigOption(REDIS_OPTIONS.REPL_DISKLESS_SYNC, convertBoolean(replDisklessSync));
return this;
}
public RedisRunner replDisklessSyncDelay(long replDisklessSyncDelay) {
addConfigOption(REDIS_OPTIONS.REPL_DISKLESS_SYNC_DELAY, replDisklessSyncDelay);
return this;
}
public RedisRunner replPingSlavePeriod(long replPingSlavePeriod) {
addConfigOption(REDIS_OPTIONS.REPL_PING_SLAVE_PERIOD, replPingSlavePeriod);
return this;
}
public RedisRunner replTimeout(long replTimeout) {
addConfigOption(REDIS_OPTIONS.REPL_TIMEOUT, replTimeout);
return this;
}
public RedisRunner replDisableTcpNodelay(boolean replDisableTcpNodelay) {
addConfigOption(REDIS_OPTIONS.REPL_DISABLE_TCP_NODELAY, convertBoolean(replDisableTcpNodelay));
return this;
}
public RedisRunner replBacklogSize(String replBacklogSize) {
addConfigOption(REDIS_OPTIONS.REPL_BACKLOG_SIZE, replBacklogSize);
return this;
}
public RedisRunner replBacklogTtl(long replBacklogTtl) {
addConfigOption(REDIS_OPTIONS.REPL_BACKLOG_TTL, replBacklogTtl);
return this;
}
public RedisRunner slavePriority(long slavePriority) {
addConfigOption(REDIS_OPTIONS.SLAVE_PRIORITY, slavePriority);
return this;
}
public RedisRunner minSlaveToWrite(long minSlaveToWrite) {
addConfigOption(REDIS_OPTIONS.MIN_SLAVES_TO_WRITE, minSlaveToWrite);
return this;
}
public RedisRunner minSlaveMaxLag(long minSlaveMaxLag) {
addConfigOption(REDIS_OPTIONS.MIN_SLAVES_MAX_LAG, minSlaveMaxLag);
return this;
}
public RedisRunner requirepass(String requirepass) {
addConfigOption(REDIS_OPTIONS.REQUIREPASS, requirepass);
return this;
}
public RedisRunner renameCommand(String renameCommand) {
addConfigOption(REDIS_OPTIONS.RENAME_COMMAND, renameCommand);
return this;
}
public RedisRunner maxclients(long maxclients) {
addConfigOption(REDIS_OPTIONS.MAXCLIENTS, maxclients);
return this;
}
public RedisRunner maxmemory(String maxmemory) {
addConfigOption(REDIS_OPTIONS.MAXMEMORY, maxmemory);
return this;
}
public RedisRunner maxmemoryPolicy(MAX_MEMORY_POLICY_OPTIONS maxmemoryPolicy) {
addConfigOption(REDIS_OPTIONS.MAXMEMORY, maxmemoryPolicy.toString());
return this;
}
public RedisRunner maxmemorySamples(long maxmemorySamples) {
addConfigOption(REDIS_OPTIONS.MAXMEMORY, maxmemorySamples);
return this;
}
public RedisRunner appendonly(boolean appendonly) {
addConfigOption(REDIS_OPTIONS.APPENDONLY, convertBoolean(appendonly));
return this;
}
public RedisRunner appendfilename(String appendfilename) {
addConfigOption(REDIS_OPTIONS.APPENDFILENAME, appendfilename);
return this;
}
public RedisRunner appendfsync(APPEND_FSYNC_MODE_OPTIONS appendfsync) {
addConfigOption(REDIS_OPTIONS.APPENDFSYNC, appendfsync.toString());
return this;
}
public RedisRunner noAppendfsyncOnRewrite(boolean noAppendfsyncOnRewrite) {
addConfigOption(REDIS_OPTIONS.NO_APPENDFSYNC_ON_REWRITE, convertBoolean(noAppendfsyncOnRewrite));
return this;
}
public RedisRunner autoAofRewritePercentage(int autoAofRewritePercentage) {
addConfigOption(REDIS_OPTIONS.AUTO_AOF_REWRITE_PERCENTAGE, autoAofRewritePercentage);
return this;
}
public RedisRunner autoAofRewriteMinSize(String autoAofRewriteMinSize) {
addConfigOption(REDIS_OPTIONS.AUTO_AOF_REWRITE_MIN_SIZE, autoAofRewriteMinSize);
return this;
}
public RedisRunner aofLoadTruncated(boolean aofLoadTruncated) {
addConfigOption(REDIS_OPTIONS.AOF_LOAD_TRUNCATED, convertBoolean(aofLoadTruncated));
return this;
}
public RedisRunner luaTimeLimit(long luaTimeLimit) {
addConfigOption(REDIS_OPTIONS.AOF_LOAD_TRUNCATED, luaTimeLimit);
return this;
}
public RedisRunner clusterEnabled(boolean clusterEnabled) {
addConfigOption(REDIS_OPTIONS.CLUSTER_ENABLED, convertBoolean(clusterEnabled));
return this;
}
public RedisRunner clusterConfigFile(String clusterConfigFile) {
addConfigOption(REDIS_OPTIONS.CLUSTER_CONFIG_FILE, clusterConfigFile);
this.clusterFile = clusterConfigFile;
return this;
}
public RedisRunner clusterNodeTimeout(long clusterNodeTimeout) {
addConfigOption(REDIS_OPTIONS.CLUSTER_NODE_TIMEOUT, clusterNodeTimeout);
return this;
}
public RedisRunner clusterSlaveValidityFactor(long clusterSlaveValidityFactor) {
addConfigOption(REDIS_OPTIONS.CLUSTER_SLAVE_VALIDITY_FACTOR, clusterSlaveValidityFactor);
return this;
}
public RedisRunner clusterMigrationBarrier(long clusterMigrationBarrier) {
addConfigOption(REDIS_OPTIONS.CLUSTER_MIGRATION_BARRIER, clusterMigrationBarrier);
return this;
}
public RedisRunner clusterRequireFullCoverage(boolean clusterRequireFullCoverage) {
addConfigOption(REDIS_OPTIONS.CLUSTER_REQUIRE_FULL_COVERAGE, convertBoolean(clusterRequireFullCoverage));
return this;
}
public RedisRunner slowlogLogSlowerThan(long slowlogLogSlowerThan) {
addConfigOption(REDIS_OPTIONS.SLOWLOG_LOG_SLOWER_THAN, slowlogLogSlowerThan);
return this;
}
public RedisRunner slowlogMaxLen(long slowlogMaxLen) {
addConfigOption(REDIS_OPTIONS.SLOWLOG_MAX_LEN, slowlogMaxLen);
return this;
}
public RedisRunner latencyMonitorThreshold(long latencyMonitorThreshold) {
addConfigOption(REDIS_OPTIONS.LATENCY_MONITOR_THRESHOLD, latencyMonitorThreshold);
return this;
}
public RedisRunner notifyKeyspaceEvents(KEYSPACE_EVENTS_OPTIONS... notifyKeyspaceEvents) {
String existing = this.options.getOrDefault(REDIS_OPTIONS.NOTIFY_KEYSPACE_EVENTS, "");
String events = Arrays.stream(notifyKeyspaceEvents)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
addConfigOption(REDIS_OPTIONS.NOTIFY_KEYSPACE_EVENTS,
existing.contains(events)
? existing
: (existing + events));
return this;
}
public RedisRunner hashMaxZiplistEntries(long hashMaxZiplistEntries) {
addConfigOption(REDIS_OPTIONS.HASH_MAX_ZIPLIST_ENTRIES, hashMaxZiplistEntries);
return this;
}
public RedisRunner hashMaxZiplistValue(long hashMaxZiplistValue) {
addConfigOption(REDIS_OPTIONS.HASH_MAX_ZIPLIST_VALUE, hashMaxZiplistValue);
return this;
}
public RedisRunner listMaxZiplistEntries(long listMaxZiplistEntries) {
addConfigOption(REDIS_OPTIONS.LIST_MAX_ZIPLIST_ENTRIES, listMaxZiplistEntries);
return this;
}
public RedisRunner listMaxZiplistValue(long listMaxZiplistValue) {
addConfigOption(REDIS_OPTIONS.LIST_MAX_ZIPLIST_VALUE, listMaxZiplistValue);
return this;
}
public RedisRunner setMaxIntsetEntries(long setMaxIntsetEntries) {
addConfigOption(REDIS_OPTIONS.SET_MAX_INTSET_ENTRIES, setMaxIntsetEntries);
return this;
}
public RedisRunner zsetMaxZiplistEntries(long zsetMaxZiplistEntries) {
addConfigOption(REDIS_OPTIONS.ZSET_MAX_ZIPLIST_ENTRIES, zsetMaxZiplistEntries);
return this;
}
public RedisRunner zsetMaxZiplistValue(long zsetMaxZiplistValue) {
addConfigOption(REDIS_OPTIONS.ZSET_MAX_ZIPLIST_VALUE, zsetMaxZiplistValue);
return this;
}
public RedisRunner hllSparseMaxBytes(long hllSparseMaxBytes) {
addConfigOption(REDIS_OPTIONS.HLL_SPARSE_MAX_BYTES, hllSparseMaxBytes);
return this;
}
public RedisRunner activerehashing(boolean activerehashing) {
addConfigOption(REDIS_OPTIONS.ACTIVEREHASHING, convertBoolean(activerehashing));
return this;
}
public RedisRunner clientOutputBufferLimit$Normal(String hardLimit, String softLimit, long softSeconds) {
addConfigOption(REDIS_OPTIONS.CLIENT_OUTPUT_BUFFER_LIMIT$NORMAL, hardLimit, softLimit, softSeconds);
return this;
}
public RedisRunner clientOutputBufferLimit$Slave(String hardLimit, String softLimit, long softSeconds) {
addConfigOption(REDIS_OPTIONS.CLIENT_OUTPUT_BUFFER_LIMIT$SLAVE, hardLimit, softLimit, softSeconds);
return this;
}
public RedisRunner clientOutputBufferLimit$Pubsub(String hardLimit, String softLimit, long softSeconds) {
addConfigOption(REDIS_OPTIONS.CLIENT_OUTPUT_BUFFER_LIMIT$PUBSUB, hardLimit, softLimit, softSeconds);
return this;
}
public RedisRunner hz(int hz) {
addConfigOption(REDIS_OPTIONS.HZ, hz);
return this;
}
public RedisRunner aofRewriteIncrementalFsync(boolean aofRewriteIncrementalFsync) {
addConfigOption(REDIS_OPTIONS.AOF_REWRITE_INCREMENTAL_FSYNC, convertBoolean(aofRewriteIncrementalFsync));
return this;
}
public RedisRunner protectedMode(boolean protectedMode) {
addConfigOption(REDIS_OPTIONS.PROTECTED_MODE, convertBoolean(protectedMode));
return this;
}
public RedisRunner sentinel() {
sentinelFile = "sentinel_conf_" + UUID.randomUUID() + ".conf";
return this;
}
public RedisRunner sentinelAnnounceIP(String sentinelAnnounceIP) {
addConfigOption(REDIS_OPTIONS.SENTINEL$ANNOUNCE_IP, sentinelAnnounceIP);
return this;
}
public RedisRunner sentinelAnnouncePort(int sentinelAnnouncePort) {
addConfigOption(REDIS_OPTIONS.SENTINEL$ANNOUNCE_PORT, sentinelAnnouncePort);
return this;
}
public RedisRunner sentinelMonitor(String masterName, String ip, int port, int quorum) {
addConfigOption(REDIS_OPTIONS.SENTINEL$MONITOR, masterName, ip, port, quorum);
return this;
}
public RedisRunner sentinelAuthPass(String masterName, String password) {
addConfigOption(REDIS_OPTIONS.SENTINEL$AUTH_PASS, masterName, password);
return this;
}
public RedisRunner sentinelDownAfterMilliseconds(String masterName, long downAfterMilliseconds) {
addConfigOption(REDIS_OPTIONS.SENTINEL$DOWN_AFTER_MILLISECONDS, masterName, downAfterMilliseconds);
return this;
}
public RedisRunner sentinelParallelSyncs(String masterName, int numSlaves) {
addConfigOption(REDIS_OPTIONS.SENTINEL$PARALLEL_SYNCS, masterName, numSlaves);
return this;
}
public RedisRunner sentinelFailoverTimeout(String masterName, long failoverTimeout) {
addConfigOption(REDIS_OPTIONS.SENTINEL$FAILOVER_TIMEOUT, masterName, failoverTimeout);
return this;
}
public RedisRunner sentinelNotificationScript(String masterName, String scriptPath) {
addConfigOption(REDIS_OPTIONS.SENTINEL$NOTIFICATION_SCRIPT, masterName, scriptPath);
return this;
}
public RedisRunner sentinelClientReconfigScript(String masterName, String scriptPath) {
addConfigOption(REDIS_OPTIONS.SENTINEL$CLIENT_RECONFIG_SCRIPT, masterName, scriptPath);
return this;
}
public boolean isSentinel() {
return this.sentinelFile != null;
}
public boolean isCluster() {
return this.clusterFile != null;
}
public boolean isRandomDir() {
return this.randomDir;
}
public boolean isNosave() {
return this.nosave;
}
public String defaultDir() {
return this.defaultDir;
}
public String dir() {
return isRandomDir() ? defaultDir() : this.path;
}
public String getInitialBindAddr() {
return bindAddr.size() > 0 ? bindAddr.get(0) : "localhost";
}
public boolean deleteDBfileDir() {
File f = new File(defaultDir);
if (f.exists()) {
System.out.println("REDIS RUNNER: Deleting directory " + f.getAbsolutePath());
return f.delete();
}
return false;
}
public boolean deleteSentinelFile() {
File f = new File(defaultDir + File.separator + sentinelFile);
if (f.exists()) {
System.out.println("REDIS RUNNER: Deleting sentinel config file " + f.getAbsolutePath());
return f.delete();
}
return false;
}
public boolean deleteClusterFile() {
File f = new File(clusterFile);
if (f.exists() && isRandomDir()) {
System.out.println("REDIS RUNNER: Deleting cluster config file " + f.getAbsolutePath());
return f.delete();
}
return false;
}
private void makeRandomDefaultDir() {
File f = new File(RedissonRuntimeEnvironment.tempDir + File.separator + UUID.randomUUID());
if (f.exists()) {
makeRandomDefaultDir();
} else {
System.out.println("REDIS RUNNER: Making directory " + f.getAbsolutePath());
f.mkdirs();
this.defaultDir = f.getAbsolutePath();
}
}
public static final class RedisProcess {
private final Process redisProcess;
private final RedisRunner runner;
private RedisVersion redisVersion;
private RedisProcess(Process redisProcess, RedisRunner runner) {
this.redisProcess = redisProcess;
this.runner = runner;
}
public int stop() throws InterruptedException {
if (runner.isNosave() && !runner.isRandomDir()) {
RedisClient c = createDefaultRedisClientInstance();
RedisConnection connection = c.connect();
connection.async(new RedisStrictCommand<Void>("SHUTDOWN", "NOSAVE", new VoidReplayConvertor()))
.await(3, TimeUnit.SECONDS);
c.shutdown();
connection.closeAsync().syncUninterruptibly();
}
redisProcess.destroy();
int exitCode = redisProcess.isAlive() ? redisProcess.waitFor() : redisProcess.exitValue();
if (runner.isSentinel()) {
runner.deleteSentinelFile();
}
if (runner.isCluster()) {
runner.deleteClusterFile();
}
if (runner.isRandomDir()) {
runner.deleteDBfileDir();
}
return exitCode == 1 && RedissonRuntimeEnvironment.isWindows ? 0 : exitCode;
}
public Process getRedisProcess() {
return redisProcess;
}
public RedisClient createRedisClientInstance() {
if (redisProcess.isAlive()) {
return new RedisClient(runner.getInitialBindAddr(), runner.getPort());
}
throw new IllegalStateException("Redis server instance is not running.");
}
public RedisVersion getRedisVersion() {
if (redisVersion == null) {
RedisConnection c = createRedisClientInstance().connect();
Map<String, String> serverMap = c.sync(RedisCommands.INFO_SERVER);
redisVersion = new RedisVersion(serverMap.get("redis_version"));
c.closeAsync();
}
return redisVersion;
}
public int getRedisServerPort() {
return runner.getPort();
}
public String getRedisServerBindAddress() {
return runner.getInitialBindAddr();
}
public String getRedisServerAddressAndPort() {
return getRedisServerBindAddress() + ":" + getRedisServerPort();
}
public boolean isAlive() {
return redisProcess.isAlive();
}
}
public static RedisRunner.RedisProcess startDefaultRedisServerInstance() throws IOException, InterruptedException, FailedToStartRedisException {
if (defaultRedisInstance == null) {
System.out.println("REDIS RUNNER: Starting up default instance...");
defaultRedisInstance = new RedisRunner().nosave().randomDir().randomPort().run();
}
return defaultRedisInstance;
}
public static int shutDownDefaultRedisServerInstance() throws InterruptedException {
if (defaultRedisInstance != null) {
System.out.println("REDIS RUNNER: Shutting down default instance...");
try {
defaultRedisInstanceExitCode = defaultRedisInstance.stop();
} finally {
defaultRedisInstance = null;
}
} else {
System.out.println("REDIS RUNNER: Default instance is already down with an exit code " + defaultRedisInstanceExitCode);
}
return defaultRedisInstanceExitCode;
}
public static boolean isDefaultRedisServerInstanceRunning() {
return defaultRedisInstance != null && defaultRedisInstance.redisProcess.isAlive();
}
public static RedisClient createDefaultRedisClientInstance() {
return defaultRedisInstance.createRedisClientInstance();
}
public static RedisRunner.RedisProcess getDefaultRedisServerInstance() {
return defaultRedisInstance;
}
public static String getDefaultRedisServerBindAddressAndPort() {
return defaultRedisInstance.getRedisServerBindAddress()
+ ":"
+ defaultRedisInstance.getRedisServerPort();
}
public static int findFreePort() {
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
socket.setReuseAddress(true);
int port = socket.getLocalPort();
if (port > 55535 && isFreePort(port - 10000)) {
return port - 10000;
} else {
return port;
}
} catch (IOException e) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
throw new IllegalStateException("Could not find a free TCP/IP port.");
}
public static boolean isFreePort(int port) {
ServerSocket socket = null;
try {
socket = new ServerSocket(port);
socket.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
return false;
}
public static class FailedToStartRedisException extends RuntimeException {
public FailedToStartRedisException() {
}
}
}
|
package com.brein.time.utils;
import org.apache.log4j.Logger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class TimeUtils {
public static final ZoneId UTC = ZoneId.of("UTC");
protected static final Map<String, ZoneId> ZONES = new HashMap<>();
private static final Logger LOGGER = Logger.getLogger(TimeUtils.class);
private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss z";
// fill the zones
static {
ZoneId.getAvailableZoneIds().stream()
.map(ZoneId::of)
.forEach(zoneId -> ZONES.put(zoneId.getId().toLowerCase(), zoneId));
}
private TimeUtils() {
/*
* Utility classes, which are a collection of static members,
* are not meant to be instantiated.
*/
}
public static String format(final long unixTimeStamp) {
return formatUnixTimeStamp(DEFAULT_FORMAT, unixTimeStamp);
}
public static String format(final long unixTimeStamp, final ZoneId zone) {
return format(DEFAULT_FORMAT, unixTimeStamp, zone);
}
public static String format(final String format, final long unixTimeStamp, final String zone) {
return format(format, unixTimeStamp, zoneId(zone));
}
public static String format(final String format, final long unixTimeStamp, final ZoneId zone) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return Instant.ofEpochSecond(unixTimeStamp)
.atZone(zone)
.format(formatter);
}
public static String formatUnixTimeStamp(final long unixTimeStamp) {
return formatUnixTimeStamp(DEFAULT_FORMAT, unixTimeStamp);
}
public static String formatUnixTimeStamp(final String format, final long unixTimeStamp) {
return format(format, unixTimeStamp, UTC);
}
public static long now() {
return Instant.now().getEpochSecond();
}
public static long nowMillis() {
return Instant.now().toEpochMilli();
}
public static int secondsToFullMinute(final long now) {
return secondsToFullMinute(now, 0);
}
/**
* Calculate the rest of seconds to a full minute, i.e. at 10:44:14 the method returns 46.
*
* @param now the current time
*
* @return the seconds until the full minute
*/
public static int secondsToFullMinute(final long now, final int offset) {
final int value = Long.valueOf(60 - ((now + offset) % 60)).intValue();
return value == 60 ? 0 : value;
}
public static Calendar createFirstOfMonthCal(final long unixTimestamp) {
/*
* Calendar set method doesn't know that Calendar.get(...) will return one of the months it expects. Thus, we
* have to ignore the evaluation of MagicConstant.
*/
final Calendar nowCalendar = createCal(unixTimestamp);
final Calendar firstOfMonthCal = createCal();
//noinspection MagicConstant
firstOfMonthCal.set(nowCalendar.get(Calendar.YEAR), nowCalendar.get(Calendar.MONTH), 1, 0, 0, 0);
return firstOfMonthCal;
}
public static Calendar createCal() {
return Calendar.getInstance(TimeZone.getTimeZone("UTC"));
}
public static Calendar createCal(final long unixTimeStamp) {
final Calendar cal = createCal();
cal.setTimeInMillis(unixTimeStamp * 1000L);
return cal;
}
/**
* @deprecated please use {@link TimeModifier#START_OF_MONTH}
*/
@Deprecated
public static long firstOfNextMonthTime(final long unixTimestamp) {
final Calendar cal = createFirstOfMonthCal(unixTimestamp);
cal.add(Calendar.MONTH, 1);
return cal.getTimeInMillis() / 1000L;
}
/**
* @param unixTimestamp Current time
*
* @return Timestamp for the beginning of the previous month relative to current time
*/
public static long firstOfLastMonthTime(final long unixTimestamp) {
final Calendar cal = createFirstOfMonthCal(unixTimestamp);
cal.add(Calendar.MONTH, -1);
return cal.getTimeInMillis() / 1000L;
}
public static long firstOfCurrentMonthTime(final long unixTimestamp) {
final Calendar cal = createFirstOfMonthCal(unixTimestamp);
return cal.getTimeInMillis() / 1000L;
}
public static boolean isSameMonth(final long unixTimestamp1,
final long unixTimestamp2) {
final Calendar cal1 = createCal(unixTimestamp1);
final Calendar cal2 = createCal(unixTimestamp2);
return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR))
&& (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH));
}
public static boolean validateDate(final String day,
final String month,
final String year) {
if (day == null || month == null || year == null) {
return false;
}
final String format = "dd-MM-uuuu";
final String date = String.format("%02d-%02d-%s", Integer.parseInt(day), Integer.parseInt(month), year);
try {
LocalDate.parse(date, DateTimeFormatter.ofPattern(format).withResolverStyle(ResolverStyle.STRICT));
return true;
} catch (final DateTimeParseException e) {
return false;
}
}
public static ZonedDateTime toZone(final long utc, final String zoneId) {
return toZone(utc, zoneId(zoneId));
}
public static ZonedDateTime toZone(final long utc, final ZoneId toZone) {
final Instant instant = Instant.ofEpochSecond(utc);
final ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, UTC);
return toZone(zdt, toZone);
}
public static ZonedDateTime toZone(final ZonedDateTime utc, final String zoneId) {
return toZone(utc, zoneId(zoneId));
}
public static ZonedDateTime toZone(final ZonedDateTime utc, final ZoneId toZone) {
if (!UTC.equals(utc.getZone())) {
throw new IllegalArgumentException("Expecting UTC time.");
}
return utc.withZoneSameInstant(toZone);
}
public static ZonedDateTime fromZoneToUtc(final long ts, final ZoneId zone) {
return fromZoneToZone(ts, zone, UTC);
}
public static ZonedDateTime fromZoneToUtc(final ZonedDateTime ts,
final ZoneId zone) {
return fromZoneToZone(ts, zone, UTC);
}
public static ZonedDateTime fromZoneToZone(final long ts, final ZoneId zone, final ZoneId toZone) {
return fromZoneToZone(ZonedDateTime.ofInstant(Instant.ofEpochSecond(ts), zone), zone, toZone);
}
public static ZonedDateTime fromZoneToZone(final ZonedDateTime ts,
final ZoneId zone,
final ZoneId toZone) {
return ts.withZoneSameLocal(toZone);
}
public static ZoneId zoneId(final String tzId) {
return zoneId(tzId, true);
}
public static ZoneId zoneId(final String tzId, final boolean caseSensitive) {
if (tzId == null) {
return null;
} else if (caseSensitive) {
try {
return ZoneId.of(tzId);
} catch (final Exception e) {
LOGGER.warn("Problem looking up time zone id " + tzId, e);
return null;
}
} else {
return ZONES.get(tzId.toLowerCase());
}
}
/**
* Converts a time to it's midnight
*
* @param time unix-timestamp (in seconds)
*
* @return the midnight's time
*
* @deprecated since 1.6.2 use {@link TimeModifier#START_OF_DAY} instead
*/
@Deprecated()
public static long toMidnight(final long time) {
return TimeModifier.START_OF_DAY.applyModifier(time);
}
public static long getSecondsAfterMidnight(final long unixTimestamp,
final String timezone) {
final ZonedDateTime zone = toZone(unixTimestamp, timezone);
return getSecondsAfterMidnight(zone);
}
public static long getSecondsAfterMidnight(final long unixTimestamp,
final ZoneId toZone) {
final ZonedDateTime zone = toZone(unixTimestamp, toZone);
return getSecondsAfterMidnight(zone);
}
public static long getSecondsAfterMidnight(final ZonedDateTime zonedDateTime) {
final ZonedDateTime midnight = TimeModifier.START_OF_DAY.applyModifier(zonedDateTime);
return ChronoUnit.SECONDS.between(midnight, zonedDateTime);
}
/**
* Converts specified date string with given format to a unix timestamp. Returns -1 if there was a failure
*
* @param dateString Date string value
* @param format Format that date string is in
*
* @return Unix timestamp, or -1 if something went wrong
*/
public static long dateStringToUnixTimestamp(final String dateString,
final String format) {
return dateStringToUnixTimestamp(dateString, format, UTC);
}
public static long dateStringToUnixTimestamp(final String dateString,
final String format,
final String timezone) {
return dateStringToUnixTimestamp(dateString, DateTimeFormatter.ofPattern(format), timezone);
}
public static long dateStringToUnixTimestamp(final String dateString,
final String format,
final ZoneId zone) {
return dateStringToUnixTimestamp(dateString, DateTimeFormatter.ofPattern(format), zone);
}
public static long dateStringToUnixTimestamp(final String dateString,
final DateTimeFormatter formatter,
final String timezone) {
return dateStringToUnixTimestamp(dateString, formatter, getZone(timezone));
}
public static long dateStringToUnixTimestamp(final String dateString,
final DateTimeFormatter formatter,
final ZoneId zone) {
if (dateString == null || dateString.isEmpty()) {
return -1;
}
try {
return LocalDateTime.parse(dateString, formatter)
.atZone(zone)
.toEpochSecond();
} catch (final DateTimeParseException e) {
LOGGER.error("Unable to parse date '" + dateString + "'", e);
return -1;
}
}
public static long dateStringModifyToUnixTimestamp(final String dateString,
final String format,
final String timezone,
final TimeModifier modifier) {
return dateStringModifyToUnixTimestamp(dateString, DateTimeFormatter.ofPattern(format), timezone, modifier);
}
public static long dateStringModifyToUnixTimestamp(final String dateString,
final DateTimeFormatter formatter,
final String timezone,
final TimeModifier modifier) {
if (dateString == null || dateString.isEmpty()) {
return -1;
}
try {
ZonedDateTime dateTime = LocalDateTime.parse(dateString, formatter)
.atZone(getZone(timezone));
if (modifier != null) {
dateTime = modifier.applyModifier(dateTime);
}
return dateTime.toEpochSecond();
} catch (final DateTimeParseException e) {
LOGGER.error("Unable to parse date '" + dateString + "'");
return -1;
}
}
public static String convertDateFormat(final String dateString,
final String fromFormat,
final String toFormat) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(fromFormat);
try {
final Date date = dateFormat.parse(dateString);
dateFormat.applyPattern(toFormat);
return dateFormat.format(date);
} catch (final ParseException e) {
LOGGER.error("Unable to parse date format: " + fromFormat);
return null;
}
}
public static String secondsToPrettyString(final long seconds) {
if (seconds < 0) {
return "-" + secondsToPrettyString(-seconds);
} else {
final double converted;
final String type;
if (seconds >= 2 * 365 * 24 * 60 * 60) {
converted = seconds / 365 / 24 / 60 / 60.0;
type = "years";
} else if (seconds >= 2 * 7 * 24 * 60 * 60) {
converted = seconds / 7 / 24 / 60 / 60.0;
type = "weeks";
} else if (seconds >= 2 * 24 * 60 * 60) {
converted = seconds / 24 / 60 / 60.0;
type = "days";
} else if (seconds >= 2 * 60 * 60) {
converted = seconds / 60 / 60.0;
type = "hours";
} else if (seconds >= 2 * 60) {
converted = seconds / 60.0;
type = "minutes";
} else if (seconds == 1) {
converted = 1;
type = "second";
} else {
converted = seconds;
type = "seconds";
}
return Math.round(converted) + " " + type;
}
}
/**
* Creates a list of days between the specified start (inclusive) and end (inclusive).
*
* @param startUnixTimestamp the start
* @param endUnixTimestamp the end
*
* @return the unix timestamps for each day between start and end
*/
public static List<Long> createTimestampList(final long startUnixTimestamp,
final long endUnixTimestamp) {
return createTimestampList(TimeModifier.START_OF_DAY, startUnixTimestamp, endUnixTimestamp);
}
public static List<Long> createTimestampList(final TimeModifier timeModifier,
final long startUnixTimestamp,
final long endUnixTimestamp) {
if (timeModifier == null || startUnixTimestamp > endUnixTimestamp) {
return Collections.emptyList();
}
// normalize the start and end (next day's start)
final long normStart = timeModifier.applyModifier(startUnixTimestamp);
final long normEnd = timeModifier.moveTimeByUnit(endUnixTimestamp, true, 1);
// determine which times we have to query for
final List<Long> times = new ArrayList<>();
for (long time = normStart; time < normEnd; time = timeModifier.moveTimeByUnit(time, true, 1)) {
times.add(time);
}
return times;
}
public static ChronoUnit convertToChronoUnit(final String chronoUnit) {
if (chronoUnit == null) {
return null;
}
try {
return ChronoUnit.valueOf(chronoUnit.toUpperCase());
} catch (final IllegalArgumentException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Couldn't get value of " + chronoUnit, e);
}
return null;
}
}
public static TimeUnit convertToTimeUnit(final String timeUnit) {
if (timeUnit == null) {
return null;
}
try {
return TimeUnit.valueOf(timeUnit.toUpperCase());
} catch (final IllegalArgumentException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Couldn't get value of " + timeUnit, e);
}
return null;
}
}
public static TimeUnit convert(final ChronoUnit chronoUnit) {
if (chronoUnit == null) {
return null;
}
switch (chronoUnit) {
case DAYS:
return TimeUnit.DAYS;
case HOURS:
return TimeUnit.HOURS;
case MINUTES:
return TimeUnit.MINUTES;
case SECONDS:
return TimeUnit.SECONDS;
case MICROS:
return TimeUnit.MICROSECONDS;
case MILLIS:
return TimeUnit.MILLISECONDS;
case NANOS:
return TimeUnit.NANOSECONDS;
default:
return null;
}
}
public static ChronoUnit convert(final TimeUnit timeUnit) {
if (timeUnit == null) {
return null;
}
switch (timeUnit) {
case DAYS:
return ChronoUnit.DAYS;
case HOURS:
return ChronoUnit.HOURS;
case MINUTES:
return ChronoUnit.MINUTES;
case SECONDS:
return ChronoUnit.SECONDS;
case MICROSECONDS:
return ChronoUnit.MICROS;
case MILLISECONDS:
return ChronoUnit.MILLIS;
case NANOSECONDS:
return ChronoUnit.NANOS;
default:
return null;
}
}
protected static ZoneId getZone(final String timezone) {
return timezone == null ? UTC : ZoneId.of(timezone);
}
}
|
package com.dyz.gameserver.pojo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RoomVO {
private int roomId;
private int id;
private int roundNumber;
private int currentRound = 0;
private boolean hong;
/**
* 1-2-3-.4-5-6-7-8-
*/
private int roomType;
private boolean sevenDouble;
private int ma;
/**
*
*0 () 1 2
*/
private int ziMo;
/**
* ()(0--10)
*/
private int xiaYu;
private boolean addWordCard = true;
/**
* added
*/
private boolean addFlowerCard = false;
/**
* added
*/
private boolean yikouxiangCard;
/**
* added
*/
private int pldscore;
/**
* added
*/
private boolean qgbkd;
/**
* added
*/
private boolean kan5;
private boolean pengpeng;
private boolean hunyise;
private boolean canchi;
private int huangzhuang;
private boolean mustting;
public boolean isPengpeng() {
return pengpeng;
}
public void setPengpeng(boolean pengpeng) {
this.pengpeng = pengpeng;
}
public boolean isHunyise() {
return hunyise;
}
public void setHunyise(boolean hunyise) {
this.hunyise = hunyise;
}
public boolean isCanchi() {
return canchi;
}
public void setCanchi(boolean canchi) {
this.canchi = canchi;
}
public int getHuangzhuang() {
return huangzhuang;
}
public void setHuangzhuang(int huangzhuang) {
this.huangzhuang = huangzhuang;
}
public boolean isMustting() {
return mustting;
}
public void setMustting(boolean mustting) {
this.mustting = mustting;
}
public boolean isKan5() {
return kan5;
}
public void setKan5(boolean kan5) {
this.kan5 = kan5;
}
public int getPldscore() {
return pldscore;
}
public void setPldscore(int pldscore) {
this.pldscore = pldscore;
}
public String name;
private List<AvatarVO> playerList;
/**
*
* keyuuid
*
*
* key1:(zimo) value2:(jiepao) value,3:(dianpao)value,
* 4:(minggang)value5:(angang) value , 6: (scores) value
*
*
*
* key value
* ("") 131
("glgang") 1
("angang") 2
("fanggang") 3
("zimo") 44
(pudian) 5
(qidian) 5*3
(qizimo) 4*312
(gangkaihu) 4*312
(qiangganghu) 5*3
*/
private Map<String , Map<String,Integer>> endStatistics = new HashMap<String, Map<String,Integer>>();
public Map<String, Map<String, Integer>> updateEndStatistics(String uuid , String type ,int roundScore) {
if(endStatistics.get(uuid) == null){
Map<String,Integer > map = new HashMap<String , Integer>();
map.put(type,roundScore);
endStatistics.put(uuid, map);
}
else{
if(endStatistics.get(uuid).get(type) != null){
endStatistics.get(uuid).put(type, endStatistics.get(uuid).get(type)+roundScore);
}
else{
endStatistics.get(uuid).put(type, roundScore);
}
}
return endStatistics;
}
public Map<String, Map<String, Integer>> getEndStatistics() {
return endStatistics;
}
public int getRoomId() {
return roomId;
}
public void setEndStatistics(Map<String, Map<String, Integer>> endStatistics) {
this.endStatistics = endStatistics;
}
public void setRoomId(int roomId) {
this.roomId = roomId;
}
public int getRoundNumber() {
return roundNumber;
}
public void setRoundNumber(int roundNumber) {
this.roundNumber = roundNumber;
}
public int getCurrentRound() {
return currentRound;
}
public void setCurrentRound(int currentRound) {
this.currentRound = currentRound;
}
public int getRoomType() {
return roomType;
}
public void setRoomType(int roomType) {
this.roomType = roomType;
if(roomType==4||roomType==5||roomType==6){
ziMo = 1;
addWordCard=true;
addFlowerCard=true;
qgbkd = true;
yikouxiangCard = true;
kan5 = false;
pengpeng = false;
hunyise = false;
canchi = false;
huangzhuang = 0;
mustting=true;
}else if(roomType==7){
ziMo = 1;
addWordCard=true;
addFlowerCard=true;
qgbkd = true;
yikouxiangCard = false;
kan5 = false;
pengpeng = false;
hunyise = false;
canchi = false;
huangzhuang = 0;
mustting=false;
}else if(roomType==8){
ziMo = 1;
addWordCard=true;
addFlowerCard=true;
qgbkd = true;
yikouxiangCard = true;
kan5 = true;
pengpeng = true;
hunyise = true;
canchi = true;
huangzhuang = 0;
mustting=true;
}
}
public int getMa() {
return ma;
}
public void setMa(int ma) {
this.ma = ma;
}
public int getZiMo() {
return ziMo;
}
public void setZiMo(int ziMo) {
this.ziMo = ziMo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean getHong() {
return hong;
}
public void setHong(boolean hong) {
this.hong = hong;
}
public boolean getSevenDouble() {
return sevenDouble;
}
public void setSevenDouble(boolean sevenDouble) {
this.sevenDouble = sevenDouble;
}
public int getXiaYu() {
return xiaYu;
}
public void setXiaYu(int xiaYu) {
this.xiaYu = xiaYu;
}
public List<AvatarVO> getPlayerList() {
return playerList;
}
public void setPlayerList(List<AvatarVO> playerList) {
this.playerList = playerList;
}
public boolean isAddWordCard() {
return addWordCard;
}
public void setAddWordCard(boolean addWordCard) {
this.addWordCard = addWordCard;
}
public RoomVO clone(){
RoomVO result = new RoomVO();
result.roomId = roomId;
result.roundNumber = roundNumber;
result.currentRound = currentRound;
result.hong = hong;
result.roomType = roomType;
result.sevenDouble = sevenDouble;
result.ma = ma;
result.ziMo = ziMo;
result.xiaYu = xiaYu;
result.addWordCard = addWordCard;
result.name = name;
result.playerList = playerList;
result.endStatistics = endStatistics;
result.id = id;
result.addFlowerCard = addFlowerCard;
result.yikouxiangCard = yikouxiangCard;
return result;
}
public boolean isAddFlowerCard() {
return addFlowerCard;
}
public void setAddFlowerCard(boolean addFlowerCard) {
this.addFlowerCard = addFlowerCard;
}
public boolean isYikouxiangCard() {
return yikouxiangCard;
}
public void setYikouxiangCard(boolean yikouxiangCard) {
this.yikouxiangCard = yikouxiangCard;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isQgbkd() {
return qgbkd;
}
public void setQgbkd(boolean qgbkd) {
this.qgbkd = qgbkd;
}
}
|
package com.fsck.k9.search;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.os.Parcel;
import android.os.Parcelable;
import com.fsck.k9.mail.Flag;
/**
* This class represents a local search.
* Removing conditions could be done through matching there unique id in the leafset and then
* removing them from the tree.
*
* @author dzan
*
* TODO implement a complete addAllowedFolder method
* TODO conflicting conditions check on add
* TODO duplicate condition checking?
* TODO assign each node a unique id that's used to retrieve it from the leaveset and remove.
*
*/
public class LocalSearch implements SearchSpecification {
private String mName;
private boolean mPredefined;
// since the uuid isn't in the message table it's not in the tree neither
private HashSet<String> mAccountUuids = new HashSet<String>();
private ConditionsTreeNode mConditions = null;
private HashSet<ConditionsTreeNode> mLeafSet = new HashSet<ConditionsTreeNode>();
// Constructors
/**
* Use this only if the search won't be saved. Saved searches need
* a name!
*/
public LocalSearch(){}
/**
*
* @param name
*/
public LocalSearch(String name) {
this.mName = name;
}
protected LocalSearch(String name, ConditionsTreeNode searchConditions,
String accounts, boolean predefined) {
this(name);
mConditions = searchConditions;
mPredefined = predefined;
mLeafSet = new HashSet<ConditionsTreeNode>();
if (mConditions != null) {
mLeafSet.addAll(mConditions.getLeafSet());
}
// initialize accounts
if (accounts != null) {
for (String account : accounts.split(",")) {
mAccountUuids.add(account);
}
} else {
// impossible but still not unrecoverable
}
}
// Public manipulation methods
/**
* Sets the name of the saved search. If one existed it will
* be overwritten.
*
* @param name Name to be set.
*/
public void setName(String name) {
this.mName = name;
}
/**
* Add a new account to the search. When no accounts are
* added manually we search all accounts on the device.
*
* @param uuid Uuid of the account to be added.
*/
public void addAccountUuid(String uuid) {
if (uuid.equals(ALL_ACCOUNTS)) {
mAccountUuids.clear();
}
mAccountUuids.add(uuid);
}
/**
* Adds all the account uuids in the provided array to
* be matched by the seach.
*
* @param accountUuids
*/
public void addAccountUuids(String[] accountUuids) {
for (String acc : accountUuids) {
addAccountUuid(acc);
}
}
/**
* Removes an account UUID from the current search.
*
* @param uuid Account UUID to remove.
* @return True if removed, false otherwise.
*/
public boolean removeAccountUuid(String uuid) {
return mAccountUuids.remove(uuid);
}
public void and(SEARCHFIELD field, String value, ATTRIBUTE attribute) {
and(new SearchCondition(field, attribute, value));
}
/**
* Adds the provided condition as the second argument of an AND
* clause to this node.
*
* @param condition Condition to 'AND' with.
* @return New top AND node, new root.
*/
public ConditionsTreeNode and(SearchCondition condition) {
try {
ConditionsTreeNode tmp = new ConditionsTreeNode(condition);
return and(tmp);
} catch (Exception e) {
// impossible
return null;
}
}
/**
* Adds the provided node as the second argument of an AND
* clause to this node.
*
* @param node Node to 'AND' with.
* @return New top AND node, new root.
* @throws Exception
*/
public ConditionsTreeNode and(ConditionsTreeNode node) throws Exception {
mLeafSet.addAll(node.getLeafSet());
if (mConditions == null) {
mConditions = node;
return node;
}
return mConditions.and(node);
}
/**
* Adds the provided condition as the second argument of an OR
* clause to this node.
*
* @param condition Condition to 'OR' with.
* @return New top OR node, new root.
*/
public ConditionsTreeNode or(SearchCondition condition) {
try {
ConditionsTreeNode tmp = new ConditionsTreeNode(condition);
return or(tmp);
} catch (Exception e) {
// impossible
return null;
}
}
/**
* Adds the provided node as the second argument of an OR
* clause to this node.
*
* @param node Node to 'OR' with.
* @return New top OR node, new root.
* @throws Exception
*/
public ConditionsTreeNode or(ConditionsTreeNode node) throws Exception {
mLeafSet.addAll(node.getLeafSet());
if (mConditions == null) {
mConditions = node;
return node;
}
return mConditions.or(node);
}
/**
* Add all the flags to this node as required flags. The
* provided flags will be combined using AND with the root.
*
* @param requiredFlags Array of required flags.
*/
public void allRequiredFlags(Flag[] requiredFlags) {
if (requiredFlags != null) {
for (Flag f : requiredFlags) {
and(new SearchCondition(SEARCHFIELD.FLAG, ATTRIBUTE.CONTAINS, f.name()));
}
}
}
/**
* Add all the flags to this node as forbidden flags. The
* provided flags will be combined using AND with the root.
*
* @param forbiddenFlags Array of forbidden flags.
*/
public void allForbiddenFlags(Flag[] forbiddenFlags) {
if (forbiddenFlags != null) {
for (Flag f : forbiddenFlags) {
and(new SearchCondition(SEARCHFIELD.FLAG, ATTRIBUTE.NOT_CONTAINS, f.name()));
}
}
}
/**
* TODO
* FOR NOW: And the folder with the root.
*
* Add the folder as another folder to search in. The folder
* will be added AND to the root if no 'folder subtree' was found.
* Otherwise the folder will be added OR to that tree.
*
* @param name Name of the folder to add.
*/
public void addAllowedFolder(String name) {
/*
* TODO find folder sub-tree
* - do and on root of it & rest of search
* - do or between folder nodes
*/
and(new SearchCondition(SEARCHFIELD.FOLDER, ATTRIBUTE.EQUALS, name));
}
/*
* TODO make this more advanced!
* This is a temporarely solution that does NOT WORK for
* real searches because of possible extra conditions to a folder requirement.
*/
public List<String> getFolderNames() {
ArrayList<String> results = new ArrayList<String>();
for (ConditionsTreeNode node : mLeafSet) {
if (node.mCondition.field == SEARCHFIELD.FOLDER
&& node.mCondition.attribute == ATTRIBUTE.EQUALS) {
results.add(node.mCondition.value);
}
}
return results;
}
/**
* Gets the leafset of the related condition tree.
*
* @return All the leaf conditions as a set.
*/
public Set<ConditionsTreeNode> getLeafSet() {
return mLeafSet;
}
// Public accesor methods
/**
* Returns the name of the saved search.
*
* @return Name of the search.
*/
public String getName() {
return mName;
}
/**
* Checks if this search was hard coded and shipped with K-9
*
* @return True is search was shipped with K-9
*/
public boolean isPredefined() {
return mPredefined;
}
/**
* Returns all the account uuids that this search will try to
* match against.
*
* @return Array of account uuids.
*/
@Override
public String[] getAccountUuids() {
if (mAccountUuids.size() == 0) {
return new String[] {SearchSpecification.ALL_ACCOUNTS};
}
String[] tmp = new String[mAccountUuids.size()];
mAccountUuids.toArray(tmp);
return tmp;
}
/**
* Get the condition tree.
*
* @return The root node of the related conditions tree.
*/
@Override
public ConditionsTreeNode getConditions() {
return mConditions;
}
// Parcelable
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mName);
dest.writeByte((byte) (mPredefined ? 1 : 0));
dest.writeStringList(new ArrayList<String>(mAccountUuids));
dest.writeParcelable(mConditions, flags);
}
public static final Parcelable.Creator<LocalSearch> CREATOR
= new Parcelable.Creator<LocalSearch>() {
public LocalSearch createFromParcel(Parcel in) {
return new LocalSearch(in);
}
public LocalSearch[] newArray(int size) {
return new LocalSearch[size];
}
};
public LocalSearch(Parcel in) {
mName = in.readString();
mPredefined = in.readByte() == 1;
mAccountUuids.addAll(in.createStringArrayList());
mConditions = in.readParcelable(LocalSearch.class.getClassLoader());
mLeafSet = mConditions.getLeafSet();
}
}
|
package com.puzzblocks.gui;
import java.awt.*;
import java.awt.image.BufferedImage;
import com.puzzblocks.*;
import com.puzzblocks.obj.Player;
import com.utilis.game.gui.*;
import com.utilis.game.obj.*;
public class WorldCanvas extends ScrollingCanvas {
private static final long serialVersionUID = 1L;
protected CollisionGroup collisionGroup;
protected Tile backgroundTile;
protected Image darkenedTileImage;
protected Image tileImage;
protected Player player;
protected PuzzBlocks game;
protected Rectangle levelArea;
private boolean secondRepaint = false;
private boolean firstRepaint = false;
public WorldCanvas(Screen s) {
super(s);
updateCollisionGroup();
createLevelAreaRect();
}
public WorldCanvas(Screen s, Tile t) {
super(s);
backgroundTile = t;
if(backgroundTile != null){
darkenedTileImage = darkenImage( Main.deepCopy( (BufferedImage) backgroundTile.getImage() ) );
tileImage = Main.deepCopy( (BufferedImage) backgroundTile.getImage() );
}
updateCollisionGroup();
createLevelAreaRect();
}
public WorldCanvas(int xTiles, int yTiles) {
super(xTiles, yTiles, GameConstants.TILE_WIDTH, GameConstants.TILE_WIDTH);
updateCollisionGroup();
createLevelAreaRect();
}
public WorldCanvas(int xTiles, int yTiles, Tile t) {
super(xTiles, yTiles, GameConstants.TILE_WIDTH, GameConstants.TILE_WIDTH);
backgroundTile = t;
if(backgroundTile != null){
darkenedTileImage = darkenImage( Main.deepCopy( (BufferedImage) backgroundTile.getImage() ) );
tileImage = Main.deepCopy( (BufferedImage) backgroundTile.getImage() );
}
updateCollisionGroup();
createLevelAreaRect();
}
public void updateCollisionGroup(){
//Empties out the current collisionGroup.
collisionGroup = new CollisionGroup();
//Adds tile from the Screen into the collisionGroup.
for(int x = 0; x<getScreen().getNumOfTilesX(); x++){
for(int y = 0; y<getScreen().getNumOfTilesY(); y++){
Tile sTile = getScreen().getTile(x, y);
collisionGroup.add(sTile);
}
}
//Adds the Player to the collisionGroup.
if(player != null){
collisionGroup.add(getPlayer());
}
}
private void createLevelAreaRect(){
int w;
int h;
w = screen.getNumOfTilesX() * screen.getTileWidth();
h = screen.getNumOfTilesY() * screen.getTileHeight();
levelArea = new Rectangle( (GameConstants.TILE_WIDTH*-1)+1, (GameConstants.TILE_HEIGHT*-1)+1, w, h );
}
public Tile getBackgroundTile() {
return backgroundTile;
}
public void setBackgroundTile(Tile backgroundTile) {
this.backgroundTile = backgroundTile;
if(backgroundTile != null){
darkenedTileImage = darkenImage( Main.deepCopy( (BufferedImage) backgroundTile.getImage() ) );
}
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
centerAlignPlayer();
updateCollisionGroup();
}
public CollisionGroup getCollisionGroup() {
return collisionGroup;
}
public void setCollisionGroup(CollisionGroup collisionGroup) {
this.collisionGroup = collisionGroup;
}
public PuzzBlocks getGame() {
return game;
}
public void setGame(PuzzBlocks game) {
this.game = game;
}
public CollisionGroup getCollisionGroupFromCollider(Collider c){
CollisionGroup smallColliders = new CollisionGroup();
smallColliders.add(c);
//Add each tile that intersects with the Player.
for(int x = 0; x<getScreen().getNumOfTilesX(); x++){
for(int y = 0; y<getScreen().getNumOfTilesY(); y++){
Tile sTile = getScreen().getTile(x, y);
if( sTile.getRectangle().intersects( c.getRectangle() ) ){
smallColliders.add(sTile);
}
}
}
return smallColliders;
}
public void centerAlignPlayer(){
if(player!=null){
player.setRealX( (this.getWidth() - player.getWidth()) /2 );
player.setRealY( (this.getHeight() - player.getHeight()) /2 );
}
}
public void add(Entity e){
super.add(e);
collisionGroup.add(e);
}
public void setCenterEntity(ScrollingEntity e){
super.setCenterEntity(e);
if(e instanceof Player){
this.setPlayer( (Player) e );
}
}
public void setScreen(Screen s){
super.setScreen(s);
createLevelAreaRect();
}
public void draw(Graphics g){
//Center align the player during second repaint
if(firstRepaint==false){
firstRepaint = true;
}
if(secondRepaint==false&&firstRepaint==true){
centerAlignPlayer();
secondRepaint = true;
}
//Tile the backgroundTile if it exists.
if(backgroundTile != null){
int width = getWidth();
int height = getHeight();
int imageW = darkenedTileImage.getWidth(this);
int imageH = darkenedTileImage.getHeight(this);
// Tile the image to fill our area.
if(player != null){ //Use player offsets.
for (int x = roundDownWidth(offsetX)-GameConstants.TILE_WIDTH; x <= roundUpWidth(offsetX + width); x += imageW){
for (int y = roundDownHeight(offsetY)-GameConstants.TILE_HEIGHT; y <= roundUpHeight(offsetY + height); y += imageH){
if(levelArea.contains(x, y)){
g.drawImage(darkenedTileImage, x-offsetX, y-offsetY, this);
}else{
g.drawImage(tileImage, x-offsetX, y-offsetY, this);
}
}
}
}else{
for (int x = 0; x <= width; x += imageW){
for (int y = 0; y <= height; y += imageH){
if(levelArea.contains(x, y)){
g.drawImage(darkenedTileImage, x, y, this);
}else{
g.drawImage(tileImage, x, y, this);
}
}
}
}
}
super.draw(g);
//Show FPS and fly indicator if there is a reference to PuzzBlocks game.
if(GameConstants.DEBUG_MODE){
if(game != null){
Color oldColor = g.getColor();
g.setColor(Color.red);
g.setFont( new Font(GameConstants.FPS_FONT, Font.BOLD, GameConstants.FPS_FONT_SIZE) );
g.drawString("FPS: " + game.getFPS(), 0, (int)(GameConstants.FPS_FONT_SIZE * 0.75) ); // (+ "") converts int to String.
if(Physics.isFlyEnabled()){
g.drawString("Flying enabled", 0, getHeight());
}
g.setColor(oldColor);
}
}
}
protected int roundUpWidth(int i){
double out = i/GameConstants.TILE_WIDTH;
return (int) Math.ceil(out)*GameConstants.TILE_WIDTH;
}
protected int roundUpHeight(int i){
double out = i/GameConstants.TILE_HEIGHT;
return (int) Math.ceil(out)*GameConstants.TILE_HEIGHT;
}
protected int roundDownWidth(int i){
double out = i/GameConstants.TILE_WIDTH;
return (int) Math.floor(out)*GameConstants.TILE_WIDTH;
}
protected int roundDownHeight(int i){
double out = i/GameConstants.TILE_HEIGHT;
return (int) Math.floor(out)*GameConstants.TILE_HEIGHT;
}
protected Image darkenImage(Image i){
BufferedImage buff = (BufferedImage) i;
int rgb;
int darkRGB;
int red,green,blue;
for(int y=0; y<buff.getHeight();y++){
for(int x=0; x<buff.getWidth();x++){
rgb = buff.getRGB(x, y);
Color c = new Color(rgb);
red = c.getRed();
green = c.getGreen();
blue = c.getGreen();
red -= GameConstants.DARKENING_VALUE;
green -= GameConstants.DARKENING_VALUE;
blue -= GameConstants.DARKENING_VALUE;
red = rgbCap(red);
green = rgbCap(green);
blue = rgbCap(blue);
Color newColor = new Color(red, green, blue);
darkRGB = newColor.getRGB();
buff.setRGB(x, y, darkRGB);
}
}
return buff;
}
private int rgbCap(int color){
if(color<0){
color = 0;
}else if(color>255){
color = 255;
}
return color;
}
}
|
package yami.configuration;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
/**
* @author oshai currently names has to be unique
*/
public class Node
{
public String nick;
@XmlAttribute
public String name;
@XmlTransient
public Peer peer;
public Boolean disabled;
public Node(String name, String nick, Peer peer)
{
this.name = name;
this.nick = nick;
this.peer = peer;
}
public Node(String nick)
{
this.nick = nick;
this.name = nick;
}
public Node()
{
}
public void afterUnmarshal(Unmarshaller u, Object parent)
{
peer = (Peer)parent;
}
public String nick()
{
if (null == nick || "".equals(nick))
{
return name;
}
return nick;
}
@Override
public String toString()
{
return "Node [nick=" + nick + ", name=" + name + "]";
}
public String getLogLink()
{
return "http://" + peer.dnsName() + ":" + ConfigurationManager.getInstance().getCurrentGlobalConfiguration().getClientPort();
}
public boolean disabled()
{
return null != disabled && disabled;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((disabled == null) ? 0 : disabled.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((nick == null) ? 0 : nick.hashCode());
result = prime * result + ((peer == null) ? 0 : peer.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (disabled == null) {
if (other.disabled != null)
return false;
} else if (!disabled.equals(other.disabled))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (nick == null) {
if (other.nick != null)
return false;
} else if (!nick.equals(other.nick))
return false;
if (peer == null) {
if (other.peer != null)
return false;
} else if (!peer.equals(other.peer))
return false;
return true;
}
}
|
package com.exedio.cope;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class DatabaseLogTest extends AbstractLibTest
{
public DatabaseLogTest()
{
super(MatchTest.MODEL);
}
MatchItem item;
@Override
public void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(item = new MatchItem());
}
public void testDatabaseLog()
{
final ExpectingDatabaseListener l = new ExpectingDatabaseListener();
model.setDatabaseListener(l);
assertFalse(model.isDatabaseLogEnabled());
assertEquals(0, model.getDatabaseLogThreshold());
final ByteArrayOutputStream o1 = new ByteArrayOutputStream();
model.setDatabaseLog(true, 0, null, new PrintStream(o1));
assertTrue(model.isDatabaseLogEnabled());
assertEquals(0, model.getDatabaseLogThreshold());
assertEquals(null, model.getDatabaseLogSQL());
assertEquals(0, o1.size());
l.expectSearch(model.getCurrentTransaction(), item.TYPE);
item.TYPE.search(item.text.equal("string1"));
l.verifyExpectations();
assertTrue(s(o1), s(o1).indexOf("select")>0);
item.setText("string1");
assertTrue(s(o1), s(o1).indexOf("update")>0);
assertTrue(s(o1), s(o1).indexOf("select")>0);
final ByteArrayOutputStream o2 = new ByteArrayOutputStream();
model.setDatabaseLog(true, 5000, null, new PrintStream(o2));
assertTrue(model.isDatabaseLogEnabled());
assertEquals(5000, model.getDatabaseLogThreshold());
assertEquals(null, model.getDatabaseLogSQL());
l.expectSearch(model.getCurrentTransaction(), item.TYPE);
item.TYPE.search(item.text.equal("string2"));
l.verifyExpectations();
item.setText("string2");
assertEquals(0, o2.size());
final ByteArrayOutputStream o2a = new ByteArrayOutputStream();
model.setDatabaseLog(true, 0, "update", new PrintStream(o2a));
assertTrue(model.isDatabaseLogEnabled());
assertEquals(0, model.getDatabaseLogThreshold());
assertEquals("update", model.getDatabaseLogSQL());
l.expectSearch(model.getCurrentTransaction(), item.TYPE);
item.TYPE.search(item.text.equal("string2"));
l.verifyExpectations();
item.setText("string2");
assertEquals(0, o2.size());
assertFalse(s(o2a), s(o2a).indexOf("select")>0);
assertTrue(s(o2a), s(o2a).indexOf("update")>0);
o2a.reset();
assertEquals(0, o2a.size());
final ByteArrayOutputStream o3 = new ByteArrayOutputStream();
model.setDatabaseLog(false, 60, null, new PrintStream(o3));
assertFalse(model.isDatabaseLogEnabled());
assertEquals(0, model.getDatabaseLogThreshold());
assertEquals(null, model.getDatabaseLogSQL());
l.expectSearch(model.getCurrentTransaction(), item.TYPE);
item.TYPE.search(item.text.equal("string3"));
l.verifyExpectations();
item.setText("string3");
assertEquals(0, o2.size());
assertEquals(0, o2a.size());
assertEquals(0, o3.size());
model.setDatabaseListener(null);
try
{
model.setDatabaseLog(true, -60, "hallo", null);
fail();
}
catch(IllegalArgumentException e)
{
assertEquals("threshold must not be negative, but was -60", e.getMessage());
}
assertFalse(model.isDatabaseLogEnabled());
assertEquals(0, model.getDatabaseLogThreshold());
assertEquals(null, model.getDatabaseLogSQL());
try
{
model.setDatabaseLog(true, 120, "bello", null);
fail();
}
catch(NullPointerException e)
{
assertEquals("out must not be null", e.getMessage());
}
assertFalse(model.isDatabaseLogEnabled());
assertEquals(0, model.getDatabaseLogThreshold());
assertEquals(null, model.getDatabaseLogSQL());
}
private static final String s(final ByteArrayOutputStream o)
{
return new String(o.toByteArray());
}
}
|
package vwap;
import java.util.List;
import com.ibm.streamsx.topology.TStream;
import com.ibm.streamsx.topology.function.BiFunction;
import com.ibm.streamsx.topology.function.Function;
public class VwapProcessing {
@SuppressWarnings("serial")
public static TStream<Bargain> bargains(TStream<Trade> trades,
TStream<Quote> quotes) {
TStream<VWapT> vwap = trades.last(4).aggregate(
new Function<List<Trade>, VWapT>() {
@Override
public VWapT apply(List<Trade> tuples) {
VWapT vwap = null;
for (Trade trade : tuples) {
if (vwap == null)
vwap = new VWapT(trade);
vwap.newTrade(trade);
}
return vwap == null ? null : vwap.complete();
}
});
TStream<Bargain> bargainIndex = quotes.joinLast(vwap,
new BiFunction<Quote, VWapT, Bargain>() {
@Override
public Bargain apply(Quote v1, VWapT v2) {
if (v2 == null) // window is empty!
return null;
return new Bargain(v1, v2);
}
});
return bargainIndex;
}
}
|
package io.ethmobile.ethdroid.model;
import org.ethereum.geth.Address;
import org.ethereum.geth.Addresses;
import org.ethereum.geth.FilterQuery;
import org.ethereum.geth.Geth;
import org.ethereum.geth.Hashes;
import org.ethereum.geth.Topics;
import java.util.List;
public class FilterOptions {
FilterQuery query;
public FilterOptions() {
query = Geth.newFilterQuery();
query.setTopics(Geth.newTopicsEmpty());
query.setAddresses(Geth.newAddressesEmpty());
}
private static Hashes fromListToHashes(List<String> list) throws Exception {
Hashes ret = Geth.newHashesEmpty();
for (String hash : list) {
ret.append(Geth.newHashFromHex(hash));
}
return ret;
}
public FilterOptions addTopics(List<String> topicList) throws Exception {
Topics topics = query.getTopics();
topics.append(fromListToHashes(topicList));
query.setTopics(topics);
return this;
}
public FilterOptions addAddress(Address address) {
Addresses addresses = query.getAddresses();
addresses.append(address);
query.setAddresses(addresses);
return this;
}
public FilterOptions addAddress(String address) throws Exception {
return addAddress(Geth.newAddressFromHex(address));
}
public FilterOptions fromBlock(long blockNumber) {
query.setFromBlock(Geth.newBigInt(blockNumber));
return this;
}
public FilterOptions toBlock(long blockNumber) {
query.setToBlock(Geth.newBigInt(blockNumber));
return this;
}
public FilterQuery getQuery() {
return query;
}
}
|
package dev.game.spacechaos.game.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import dev.game.spacechaos.engine.font.BitmapFontFactory;
import dev.game.spacechaos.engine.game.ScreenBasedGame;
import dev.game.spacechaos.engine.screen.impl.BaseScreen;
import dev.game.spacechaos.engine.sound.VolumeManager;
import dev.game.spacechaos.engine.time.GameTime;
public class CreditsScreen extends BaseScreen {
//asset paths
protected final String MUSIC_PATH = "./data/music/neon-transit/Neon_Transit.ogg";
protected final String BACKGROUND_IMAGE_PATH = "./data/images/skybox/galaxy/galaxy+X.png";
//background music soundtrack
protected Music music = null;
//background texture
protected Texture bgTexture = null;
//font
protected BitmapFont titleFont = null;
@Override
protected void onInit(ScreenBasedGame game, AssetManager assetManager) {
//load assets
assetManager.load(MUSIC_PATH, Music.class);
assetManager.load(BACKGROUND_IMAGE_PATH, Texture.class);
assetManager.finishLoadingAsset(MUSIC_PATH);
assetManager.finishLoadingAsset(BACKGROUND_IMAGE_PATH);
//get assets
this.music = assetManager.get(MUSIC_PATH, Music.class);
this.bgTexture = assetManager.get(BACKGROUND_IMAGE_PATH, Texture.class);
//generate fonts
this.titleFont = BitmapFontFactory.createFont("./data/font/spartakus/SparTakus.ttf", 48, Color.WHITE, Color.BLUE, 3);
//this.font2 = BitmapFontFactory.createFont("./data/font/spartakus/SparTakus.ttf", 48, Color.RED, Color.WHITE, 3);
}
@Override
public void onResume () {
//set music volume
this.music.setVolume(VolumeManager.getInstance().getBackgroundMusicVolume());
//set looping
this.music.setLooping(true);
//play music
this.music.play();
}
@Override
public void onPause () {
this.music.stop();
}
@Override
public void update(ScreenBasedGame game, GameTime time) {
if (Gdx.input.isTouched()) {
//back to main menu
game.getScreenManager().leaveAllAndEnter("menu");
}
}
@Override
public void draw(GameTime time, SpriteBatch batch) {
//set UI camera
batch.setProjectionMatrix(this.game.getUICamera().combined);
//draw background
batch.draw(this.bgTexture, 0, 0, game.getViewportWidth(), game.getViewportHeight());
//draw title
this.titleFont.draw(batch, "Credits", 50, game.getViewportHeight() - 50);
}
@Override
public void destroy() {
}
}
|
package com.sixsq.slipstream.run;
import com.sixsq.slipstream.connector.Connector;
import com.sixsq.slipstream.connector.ConnectorFactory;
import com.sixsq.slipstream.connector.local.LocalConnector;
import com.sixsq.slipstream.exceptions.ConfigurationException;
import com.sixsq.slipstream.exceptions.NotFoundException;
import com.sixsq.slipstream.exceptions.SlipStreamException;
import com.sixsq.slipstream.exceptions.ValidationException;
import com.sixsq.slipstream.factory.RunFactory;
import com.sixsq.slipstream.persistence.DeploymentModule;
import com.sixsq.slipstream.persistence.ImageModule;
import com.sixsq.slipstream.persistence.Module;
import com.sixsq.slipstream.persistence.ModuleParameter;
import com.sixsq.slipstream.persistence.Node;
import com.sixsq.slipstream.persistence.ParameterCategory;
import com.sixsq.slipstream.persistence.Run;
import com.sixsq.slipstream.persistence.RunType;
import com.sixsq.slipstream.persistence.RuntimeParameter;
import com.sixsq.slipstream.persistence.User;
import com.sixsq.slipstream.statemachine.States;
import com.sixsq.slipstream.util.CommonTestUtil;
public class RunTestBase {
private static final String USER_DEFAULT = "user";
protected static User user = null;
protected static ImageModule image = null;
protected static ImageModule imageref = null;
protected static ImageModule imagebase = null;
protected static ImageModule imagenoref = null;
protected static ImageModule imagebuildme = null;
protected static Connector localConnector = new LocalConnector();
protected static String cloudServiceName = localConnector
.getCloudServiceName();
public static DeploymentModule deployment = null;
protected static ImageModule imageForDeployment1 = null;
protected static ImageModule imageForDeployment2 = null;
protected static void setupImages() throws ValidationException {
imagebase = new ImageModule("test/imagebase");
imagebase.setImageId("base_image_id", cloudServiceName);
imagebase.setIsBase(true);
imagebase = imagebase.store();
imageref = new ImageModule("test/imageref");
imageref.setModuleReference(imagebase);
imageref.setImageId("ref_image_id", cloudServiceName);
imageref = imageref.store();
image = new ImageModule("test/image");
image.setModuleReference(imageref.getResourceUri());
image.setRecipe("a recipe");
image.setImageId("image_id", cloudServiceName);
image = image.store();
imagebuildme = new ImageModule("test/imagebuildme");
imagebuildme.setModuleReference(imageref.getResourceUri());
imagebuildme.setRecipe("a recipe");
imagebuildme = imagebuildme.store();
imagenoref = new ImageModule("test/imagenoref");
imagenoref.setRecipe("a recipe");
imagenoref = imagenoref.store();
imagenoref = new ImageModule("test/imagenoref");
imagenoref.setRecipe("a recipe");
imagenoref = imagenoref.store();
createUser();
CommonTestUtil.addSshKeys(user);
}
protected static void createUser() throws ConfigurationException,
ValidationException {
user = CommonTestUtil.createUser("RunTestBaseUser", "password");
}
protected static void tearDownImages() {
imagebase.remove();
imageref.remove();
image.remove();
user.remove();
}
protected static void setupDeployments() throws ValidationException,
NotFoundException {
imageForDeployment1 = new ImageModule("test/imagefordeployment1");
imageForDeployment1
.setParameter(new ModuleParameter("pi1", "pi1 init value",
"pi1 parameter desc", ParameterCategory.Input));
imageForDeployment1.setParameter(new ModuleParameter("po1",
"po1 init value", "po1 parameter desc",
ParameterCategory.Output));
imageForDeployment1.setIsBase(true);
imageForDeployment1.setImageId("123", cloudServiceName);
imageForDeployment1 = imageForDeployment1.store();
imageForDeployment2 = new ImageModule("test/imagefordeployment2");
imageForDeployment2
.setParameter(new ModuleParameter("pi2", "pi2 init value",
"pi2 parameter desc", ParameterCategory.Input));
imageForDeployment2.setParameter(new ModuleParameter("po2",
"po2 init value", "po2 parameter desc",
ParameterCategory.Output));
imageForDeployment2.setImageId("123", cloudServiceName);
imageForDeployment2 = imageForDeployment2.store();
deployment = new DeploymentModule("test/deployment");
Node node;
node = new Node("node1",
ImageModule.constructResourceUri(imageForDeployment1.getName()));
deployment.getNodes().put(node.getName(), node);
node = new Node("node2",
ImageModule.constructResourceUri(imageForDeployment2.getName()));
deployment.getNodes().put(node.getName(), node);
deployment = deployment.store();
}
protected void removeDeployments() {
deployment.remove();
imageForDeployment1.remove();
imageForDeployment2.remove();
}
public RunTestBase() {
super();
}
protected Run createAndStoreRun(Module module) throws SlipStreamException {
return createAndStoreRun(module, USER_DEFAULT);
}
protected Run createAndStoreRun(Module module, RunType type)
throws SlipStreamException {
return createAndStoreRun(module, USER_DEFAULT, type);
}
protected Run createAndStoreRun(Module module, String user)
throws SlipStreamException {
return createAndStoreRun(module, user, RunType.Orchestration);
}
protected Run createAndStoreRun(Module module, String user, RunType type)
throws SlipStreamException {
Run run = RunFactory.getRun(module, type, cloudServiceName,
RunTestBase.user);
run.setUser(user);
run = ConnectorFactory.getConnector(cloudServiceName).launch(run,
RunTestBase.user);
return run.store();
}
protected void setRuntimeParameterState(Run run, String key, States state)
throws ValidationException {
run.getRuntimeParameters().put(key,
new RuntimeParameter(run, key, state.toString(), ""));
}
}
|
package com.intellij.compiler;
import com.intellij.compiler.impl.*;
import com.intellij.compiler.server.BuildManager;
import com.intellij.execution.process.ProcessIOExecutorService;
import com.intellij.ide.IdeEventQueue;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.compiler.Compiler;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.compiler.util.InspectionValidator;
import com.intellij.openapi.compiler.util.InspectionValidatorWrapper;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.ProjectExtensionPointName;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.serviceContainer.NonInjectable;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.net.NetUtils;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.builders.impl.java.JavacCompilerTool;
import org.jetbrains.jps.incremental.BinaryContent;
import org.jetbrains.jps.javac.*;
import org.jetbrains.jps.javac.ast.api.JavacFileData;
import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
// cannot be final - extended by Bazel plugin
public class CompilerManagerImpl extends CompilerManager {
private static final ProjectExtensionPointName<CompileTaskBean> EP_NAME = new ProjectExtensionPointName<>("com.intellij.compiler.task");
private static final Logger LOG = Logger.getInstance(CompilerManagerImpl.class);
private final Project myProject;
private final Map<Compiler, String> myCompilers = new HashMap<>();
private static final String NO_FACTORY_ID = "";
private final List<CompileTask> myBeforeTasks = new ArrayList<>();
private final List<CompileTask> myAfterTasks = new ArrayList<>();
private final Set<FileType> myCompilableTypes = new HashSet<>();
private final CompilationStatusListener myEventPublisher;
private final Semaphore myCompilationSemaphore = new Semaphore(1, true);
private final Set<ModuleType<?>> myValidationDisabledModuleTypes = new HashSet<>();
private final Set<LocalFileSystem.WatchRequest> myWatchRoots;
private volatile ExternalJavacManager myExternalJavacManager;
@SuppressWarnings("MissingDeprecatedAnnotation")
@NonInjectable
@Deprecated
public CompilerManagerImpl(@NotNull Project project, @SuppressWarnings("unused") @NotNull MessageBus messageBus) {
this(project);
}
public CompilerManagerImpl(@NotNull Project project) {
myProject = project;
myEventPublisher = project.getMessageBus().syncPublisher(CompilerTopics.COMPILATION_STATUS);
// predefined compilers
CompilerFactory.EP_NAME.getPoint(myProject).addExtensionPointListener(new ExtensionPointListener<CompilerFactory>() {
@Override
public void extensionAdded(@NotNull CompilerFactory factory, @NotNull PluginDescriptor pluginDescriptor) {
Compiler[] compilers = factory.createCompilers(CompilerManagerImpl.this);
if (compilers != null) {
String factoryId = getFactoryId(factory);
for (Compiler compiler : compilers) {
addCompiler(compiler, factoryId);
}
}
}
@Override
public void extensionRemoved(@NotNull CompilerFactory factory, @NotNull PluginDescriptor pluginDescriptor) {
List<Compiler> compilersToRemove = new ArrayList<>();
String factoryId = getFactoryId(factory);
for (Map.Entry<Compiler, String> entry : myCompilers.entrySet()) {
if (factoryId.equals(entry.getValue())) {
compilersToRemove.add(entry.getKey());
}
}
for (Compiler compiler : compilersToRemove) {
removeCompiler(compiler);
}
}
}, true, myProject);
addCompilableFileType(StdFileTypes.JAVA);
final File projectGeneratedSrcRoot = CompilerPaths.getGeneratedDataDirectory(project);
projectGeneratedSrcRoot.mkdirs();
final LocalFileSystem lfs = LocalFileSystem.getInstance();
myWatchRoots = lfs.addRootsToWatch(Collections.singletonList(FileUtil.toCanonicalPath(projectGeneratedSrcRoot.getPath())), true);
Disposer.register(project, () -> {
final ExternalJavacManager manager = myExternalJavacManager;
myExternalJavacManager = null;
if (manager != null) {
manager.stop();
}
lfs.removeWatchedRoots(myWatchRoots);
if (ApplicationManager.getApplication().isUnitTestMode()) { // force cleanup for created compiler system directory with generated sources
FileUtil.delete(CompilerPaths.getCompilerSystemDirectory(project));
}
});
}
// returns true if all javacs terminated
@TestOnly
public boolean waitForExternalJavacToTerminate(long time, @NotNull TimeUnit unit) {
ExternalJavacManager externalJavacManager = myExternalJavacManager;
return externalJavacManager == null || externalJavacManager.waitForAllProcessHandlers(time, unit);
}
@TestOnly
public boolean awaitNettyThreadPoolTermination(long time, @NotNull TimeUnit unit) {
ExternalJavacManager externalJavacManager = myExternalJavacManager;
return externalJavacManager == null || externalJavacManager.awaitNettyThreadPoolTermination(time, unit);
}
public Semaphore getCompilationSemaphore() {
return myCompilationSemaphore;
}
@Override
public boolean isCompilationActive() {
return myCompilationSemaphore.availablePermits() == 0;
}
@Override
public final void addCompiler(@NotNull Compiler compiler) {
addCompiler(compiler, NO_FACTORY_ID);
}
private void addCompiler(@NotNull Compiler compiler, @NotNull final String factoryId) {
myCompilers.put(compiler, factoryId);
// supporting file instrumenting compilers and validators for external build
// Since these compilers are IDE-specific and use PSI, it is ok to run them before and after the build in the IDE
if (compiler instanceof SourceInstrumentingCompiler) {
addBeforeTask(new FileProcessingCompilerAdapterTask((FileProcessingCompiler)compiler));
}
else if (compiler instanceof Validator) {
addAfterTask(new FileProcessingCompilerAdapterTask((FileProcessingCompiler)compiler));
}
}
private static String getFactoryId(@Nullable CompilerFactory factory) {
return factory == null? NO_FACTORY_ID : factory.getClass().getName();
}
@Override
@Deprecated
public void addTranslatingCompiler(@NotNull TranslatingCompiler compiler, Set<FileType> inputTypes, Set<FileType> outputTypes) {
// empty
}
@Override
public final void removeCompiler(@NotNull Compiler compiler) {
if (myCompilers.remove(compiler) != null) {
for (List<CompileTask> tasks : Arrays.asList(myBeforeTasks, myAfterTasks)) {
tasks.removeIf(
task -> task instanceof FileProcessingCompilerAdapterTask && ((FileProcessingCompilerAdapterTask)task).getCompiler() == compiler
);
}
}
}
@Override
public <T extends Compiler> T @NotNull [] getCompilers(@NotNull Class<T> compilerClass) {
final List<T> compilers = new ArrayList<>(myCompilers.size());
for (final Compiler item : ContainerUtil.concat(myCompilers.keySet(), Compiler.EP_NAME.getExtensions(myProject))) {
T concreteCompiler = ObjectUtils.tryCast(item, compilerClass);
if (concreteCompiler != null) {
compilers.add(concreteCompiler);
}
}
if (compilerClass.isAssignableFrom(InspectionValidatorWrapper.class)) {
InspectionValidator.EP_NAME.extensions(myProject).forEach(
validator -> compilers.add(compilerClass.cast(InspectionValidatorWrapper.create(myProject, validator)))
);
}
final T[] array = ArrayUtil.newArray(compilerClass, compilers.size());
return compilers.toArray(array);
}
@Override
public void addCompilableFileType(@NotNull FileType type) {
myCompilableTypes.add(type);
}
@Override
public void removeCompilableFileType(@NotNull FileType type) {
myCompilableTypes.remove(type);
}
@Override
public boolean isCompilableFileType(@NotNull FileType type) {
return myCompilableTypes.contains(type);
}
@Override
public final void addBeforeTask(@NotNull CompileTask task) {
myBeforeTasks.add(task);
}
@Override
public final void addAfterTask(@NotNull CompileTask task) {
myAfterTasks.add(task);
}
@Override
public @NotNull List<CompileTask> getBeforeTasks() {
final List<Compiler> extCompilers = Compiler.EP_NAME.getExtensions(myProject);
return ContainerUtil.concat(
myBeforeTasks,
extCompilers.stream().filter(compiler -> compiler instanceof SourceInstrumentingCompiler).map(compiler -> new FileProcessingCompilerAdapterTask((SourceInstrumentingCompiler)compiler)).collect(Collectors.toList()),
getExtensionsTasks(CompileTaskBean.CompileTaskExecutionPhase.BEFORE)
);
}
@Override
public @NotNull List<CompileTask> getAfterTaskList() {
final List<Compiler> extCompilers = Compiler.EP_NAME.getExtensions(myProject);
return ContainerUtil.concat(
myAfterTasks,
extCompilers.stream().filter(compiler -> compiler instanceof Validator).map(compiler -> new FileProcessingCompilerAdapterTask((Validator)compiler)).collect(Collectors.toList()),
InspectionValidator.EP_NAME.extensions(myProject).map(validator -> new FileProcessingCompilerAdapterTask(InspectionValidatorWrapper.create(myProject, validator))).collect(Collectors.toList()),
getExtensionsTasks(CompileTaskBean.CompileTaskExecutionPhase.AFTER)
);
}
private @NotNull List<CompileTask> getExtensionsTasks(@NotNull CompileTaskBean.CompileTaskExecutionPhase phase) {
List<CompileTask> list = new ArrayList<>();
EP_NAME.processWithPluginDescriptor(myProject, (ext, pluginDescriptor) -> {
if (ext.executionPhase == phase) {
list.add(ext.getInstance(myProject, pluginDescriptor));
}
});
return list;
}
@Override
public void compile(VirtualFile @NotNull [] files, CompileStatusNotification callback) {
compile(createFilesCompileScope(files), callback);
}
@Override
public void compile(@NotNull Module module, CompileStatusNotification callback) {
new CompileDriver(myProject).compile(createModuleCompileScope(module, false), new ListenerNotificator(callback));
}
@Override
public void compile(@NotNull CompileScope scope, CompileStatusNotification callback) {
new CompileDriver(myProject).compile(scope, new ListenerNotificator(callback));
}
@Override
public void make(CompileStatusNotification callback) {
new CompileDriver(myProject).make(createProjectCompileScope(myProject), new ListenerNotificator(callback));
}
@Override
public void make(@NotNull Module module, CompileStatusNotification callback) {
new CompileDriver(myProject).make(createModuleCompileScope(module, true), new ListenerNotificator(callback));
}
@Override
public void make(@NotNull Project project, Module @NotNull [] modules, CompileStatusNotification callback) {
new CompileDriver(myProject).make(createModuleGroupCompileScope(project, modules, true), new ListenerNotificator(callback));
}
@Override
public void make(@NotNull CompileScope scope, CompileStatusNotification callback) {
new CompileDriver(myProject).make(scope, new ListenerNotificator(callback));
}
@Override
public void makeWithModalProgress(@NotNull CompileScope scope, @Nullable CompileStatusNotification callback) {
new CompileDriver(myProject).make(scope, true, new ListenerNotificator(callback));
}
@Override
public boolean isUpToDate(@NotNull CompileScope scope) {
return new CompileDriver(myProject).isUpToDate(scope);
}
@Override
public void rebuild(CompileStatusNotification callback) {
new CompileDriver(myProject).rebuild(new ListenerNotificator(callback));
}
@Override
public void executeTask(@NotNull CompileTask task, @NotNull CompileScope scope, String contentName, Runnable onTaskFinished) {
final CompileDriver compileDriver = new CompileDriver(myProject);
compileDriver.executeCompileTask(task, scope, contentName, onTaskFinished);
}
private final Map<CompilationStatusListener, MessageBusConnection> myListenerAdapters = new HashMap<>();
@Override
public void addCompilationStatusListener(@NotNull CompilationStatusListener listener) {
final MessageBusConnection connection = myProject.getMessageBus().connect();
myListenerAdapters.put(listener, connection);
connection.subscribe(CompilerTopics.COMPILATION_STATUS, listener);
}
@Override
public void addCompilationStatusListener(@NotNull CompilationStatusListener listener, @NotNull Disposable parentDisposable) {
final MessageBusConnection connection = myProject.getMessageBus().connect(parentDisposable);
connection.subscribe(CompilerTopics.COMPILATION_STATUS, listener);
}
@Override
public void removeCompilationStatusListener(final @NotNull CompilationStatusListener listener) {
final MessageBusConnection connection = myListenerAdapters.remove(listener);
if (connection != null) {
connection.disconnect();
}
}
@Override
public boolean isExcludedFromCompilation(@NotNull VirtualFile file) {
return CompilerConfiguration.getInstance(myProject).isExcludedFromCompilation(file);
}
@Override
public @NotNull CompileScope createFilesCompileScope(final VirtualFile @NotNull [] files) {
CompileScope[] scopes = new CompileScope[files.length];
for(int i = 0; i < files.length; i++){
scopes[i] = new OneProjectItemCompileScope(myProject, files[i]);
}
return new CompositeScope(scopes);
}
@Override
public @NotNull CompileScope createModuleCompileScope(final @NotNull Module module, final boolean includeDependentModules) {
return createModulesCompileScope(new Module[] {module}, includeDependentModules);
}
@Override
public @NotNull CompileScope createModulesCompileScope(final Module @NotNull [] modules, final boolean includeDependentModules) {
return createModulesCompileScope(modules, includeDependentModules, false);
}
@Override
public @NotNull CompileScope createModulesCompileScope(Module @NotNull [] modules, boolean includeDependentModules, boolean includeRuntimeDependencies) {
return new ModuleCompileScope(myProject, modules, includeDependentModules, includeRuntimeDependencies);
}
@Override
public @NotNull CompileScope createModuleGroupCompileScope(final @NotNull Project project, final Module @NotNull [] modules, final boolean includeDependentModules) {
return new ModuleCompileScope(project, modules, includeDependentModules);
}
@Override
public @NotNull CompileScope createProjectCompileScope(final @NotNull Project project) {
return new ProjectCompileScope(project);
}
@Override
public void setValidationEnabled(ModuleType<?> moduleType, boolean enabled) {
if (enabled) {
myValidationDisabledModuleTypes.remove(moduleType);
}
else {
myValidationDisabledModuleTypes.add(moduleType);
}
}
@Override
public boolean isValidationEnabled(Module module) {
if (myValidationDisabledModuleTypes.isEmpty()) {
return true; // optimization
}
return !myValidationDisabledModuleTypes.contains(ModuleType.get(module));
}
@Override
public Collection<ClassObject> compileJavaCode(List<String> options,
Collection<? extends File> platformCp,
Collection<? extends File> classpath,
Collection<? extends File> upgradeModulePath,
Collection<? extends File> modulePath,
Collection<? extends File> sourcePath,
Collection<? extends File> files,
File outputDir) throws IOException, CompilationException {
final Pair<Sdk, JavaSdkVersion> runtime = BuildManager.getJavacRuntimeSdk(myProject);
final Sdk sdk = runtime.getFirst();
final SdkTypeId type = sdk.getSdkType();
String javaHome = null;
if (type instanceof JavaSdkType) {
javaHome = sdk.getHomePath();
if (!isJdkOrJre(javaHome)) {
// this can be a java-dependent SDK, implementing JavaSdkType
// hack, because there is no direct way to obtain the java sdk, this sdk depends on
final String binPath = ((JavaSdkType)type).getBinPath(sdk);
javaHome = binPath != null? new File(binPath).getParent() : null;
if (!isJdkOrJre(javaHome)) {
javaHome = null;
}
}
}
if (javaHome == null) {
throw new IOException("Was not able to determine JDK for project " + myProject.getName());
}
final OutputCollector outputCollector = new OutputCollector();
DiagnosticCollector diagnostic = new DiagnosticCollector();
final Set<File> sourceRoots = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
if (!sourcePath.isEmpty()) {
sourceRoots.addAll(sourcePath);
}
else {
for (File file : files) {
final File parentFile = file.getParentFile();
if (parentFile != null) {
sourceRoots.add(parentFile);
}
}
}
final Map<File, Set<File>> outs = Collections.singletonMap(outputDir, sourceRoots);
final ExternalJavacManager javacManager = getJavacManager();
final CompilationPaths paths = CompilationPaths.create(platformCp, classpath, upgradeModulePath, ModulePath.create(modulePath), sourcePath);
// do not keep process alive in tests since every test expects all spawned processes to terminate in teardown
boolean compiledOk = javacManager != null && javacManager.forkJavac(
javaHome, -1, Collections.emptyList(), options, paths, files, outs, diagnostic, outputCollector,
new JavacCompilerTool(), CanceledStatus.NULL, !ApplicationManager.getApplication().isUnitTestMode()
).get();
if (!compiledOk) {
final List<CompilationException.Message> messages = new SmartList<>();
for (Diagnostic<? extends JavaFileObject> d : diagnostic.getDiagnostics()) {
final JavaFileObject source = d.getSource();
final URI uri = source != null ? source.toUri() : null;
messages.add(new CompilationException.Message(
kindToCategory(d.getKind()), d.getMessage(Locale.US), uri != null? uri.toURL().toString() : null, (int)d.getLineNumber(), (int)d.getColumnNumber()
));
}
throw new CompilationException("Compilation failed", messages);
}
final List<ClassObject> result = new ArrayList<>();
for (OutputFileObject fileObject : outputCollector.getCompiledClasses()) {
final BinaryContent content = fileObject.getContent();
result.add(new CompiledClass(fileObject.getName(), fileObject.getClassName(), content != null ? content.toByteArray() : null));
}
return result;
}
private static boolean isJdkOrJre(@Nullable String path) {
return path != null && (JdkUtil.checkForJre(path) || JdkUtil.checkForJdk(path));
}
private static CompilerMessageCategory kindToCategory(Diagnostic.Kind kind) {
switch (kind) {
case ERROR: return CompilerMessageCategory.ERROR;
case MANDATORY_WARNING:
case WARNING: return CompilerMessageCategory.WARNING;
case NOTE:
default: return CompilerMessageCategory.INFORMATION;
}
}
private @Nullable ExternalJavacManager getJavacManager() throws IOException {
ExternalJavacManager manager = myExternalJavacManager;
if (manager == null) {
synchronized (this) {
manager = myExternalJavacManager;
if (manager == null) {
final File compilerWorkingDir = getJavacCompilerWorkingDir();
if (compilerWorkingDir == null) {
return null; // should not happen for real projects
}
final int listenPort = NetUtils.findAvailableSocketPort();
manager = new ExternalJavacManager(
compilerWorkingDir, ProcessIOExecutorService.INSTANCE, Registry.intValue("compiler.external.javac.keep.alive.timeout", 5*60*1000)
);
manager.start(listenPort);
myExternalJavacManager = manager;
IdeEventQueue.getInstance().addIdleListener(new IdleTask(manager), IdleTask.CHECK_PERIOD);
}
}
}
return manager;
}
@Override
public @Nullable File getJavacCompilerWorkingDir() {
final File projectBuildDir = BuildManager.getInstance().getProjectSystemDirectory(myProject);
if (projectBuildDir == null) {
return null;
}
projectBuildDir.mkdirs();
return projectBuildDir;
}
private static class CompiledClass implements ClassObject {
private final String myPath;
private final String myClassName;
private final byte[] myBytes;
CompiledClass(String path, String className, byte[] bytes) {
myPath = path;
myClassName = className;
myBytes = bytes;
}
@Override
public String getPath() {
return myPath;
}
@Override
public String getClassName() {
return myClassName;
}
@Override
public byte @Nullable [] getContent() {
return myBytes;
}
@Override
public String toString() {
return getClassName();
}
}
private class ListenerNotificator implements CompileStatusNotification {
private final @Nullable CompileStatusNotification myDelegate;
private ListenerNotificator(@Nullable CompileStatusNotification delegate) {
myDelegate = delegate;
}
@Override
public void finished(boolean aborted, int errors, int warnings, final @NotNull CompileContext compileContext) {
if (!myProject.isDisposed()) {
myEventPublisher.compilationFinished(aborted, errors, warnings, compileContext);
}
if (myDelegate != null) {
myDelegate.finished(aborted, errors, warnings, compileContext);
}
}
}
private static class DiagnosticCollector implements DiagnosticOutputConsumer {
private final List<Diagnostic<? extends JavaFileObject>> myDiagnostics = new ArrayList<>();
@Override
public void outputLineAvailable(String line) {
// for debugging purposes uncomment this line
//System.out.println(line);
if (line != null && line.startsWith(ExternalJavacManager.STDERR_LINE_PREFIX)) {
LOG.info(line.trim());
}
}
@Override
public void registerJavacFileData(JavacFileData data) {
// ignore
}
@Override
public void javaFileLoaded(File file) {
// ignore
}
@Override
public void customOutputData(String pluginId, String dataName, byte[] data) {
}
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
myDiagnostics.add(diagnostic);
}
public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() {
return myDiagnostics;
}
}
private static class OutputCollector implements OutputFileConsumer {
private final List<OutputFileObject> myClasses = new ArrayList<>();
@Override
public void save(@NotNull OutputFileObject fileObject) {
myClasses.add(fileObject);
}
List<OutputFileObject> getCompiledClasses() {
return myClasses;
}
}
private static class IdleTask implements Runnable {
private static final int CHECK_PERIOD = 10000; // check idle javac processes every 10 second when IDE is idle
private final ExternalJavacManager myManager;
IdleTask(@NotNull ExternalJavacManager manager) {
myManager = manager;
}
@Override
public void run() {
if (myManager.isRunning()) {
myManager.shutdownIdleProcesses();
}
else {
IdeEventQueue.getInstance().removeIdleListener(this);
}
}
}
}
|
package net.bull.javamelody; // NOPMD
import static net.bull.javamelody.HttpParameters.SESSIONS_PART;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Connection;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
/**
* Test unitaire de la classe HtmlReport.
* @author Emeric Vernat
*/
// CHECKSTYLE:OFF
public class TestHtmlReport {
// CHECKSTYLE:ON
private Timer timer;
private List<JavaInformations> javaInformationsList;
private Counter sqlCounter;
private Counter servicesCounter;
private Counter counter;
private Counter errorCounter;
private Collector collector;
private StringWriter writer;
/** Initialisation. */
@Before
public void setUp() {
timer = new Timer("test timer", true);
javaInformationsList = Collections.singletonList(new JavaInformations(null, true));
sqlCounter = new Counter("sql", "db.png");
sqlCounter.setDisplayed(false);
servicesCounter = new Counter("services", "beans.png", sqlCounter);
counter = new Counter("http", "dbweb.png", sqlCounter);
errorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null);
final Counter jobCounter = JobGlobalListener.getJobCounter();
collector = new Collector("test", Arrays.asList(counter, sqlCounter, servicesCounter,
errorCounter, jobCounter), timer);
writer = new StringWriter();
}
/** Finalisation. */
@After
public void tearDown() {
timer.cancel();
}
/** Test.
* @throws IOException e */
@Test
public void testEmptyCounter() throws IOException {
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.TOUT, writer);
counter.clear();
errorCounter.clear();
htmlReport.toHtml(null);
assertNotEmptyAndClear(writer);
}
/** Test.
* @throws IOException e */
@Test
public void testDoubleJavaInformations() throws IOException {
final List<JavaInformations> myJavaInformationsList = Arrays.asList(new JavaInformations(
null, true), new JavaInformations(null, true));
final HtmlReport htmlReport = new HtmlReport(collector, null, myJavaInformationsList,
Period.TOUT, writer);
htmlReport.toHtml(null);
assertNotEmptyAndClear(writer);
}
/** Test.
* @throws IOException e */
@Test
public void testCounter() throws IOException {
setProperty(Parameter.WARNING_THRESHOLD_MILLIS, "500");
setProperty(Parameter.SEVERE_THRESHOLD_MILLIS, "1500");
setProperty(Parameter.ANALYTICS_ID, "123456789");
counter.addRequest("test1", 0, 0, false, 1000);
counter.addRequest("test2", 1000, 500, false, 1000);
counter.addRequest("test3", 100000, 50000, true, 10000);
collector.collectWithoutErrors(javaInformationsList);
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.TOUT, writer);
htmlReport.toHtml("message 2");
assertNotEmptyAndClear(writer);
setProperty(Parameter.NO_DATABASE, Boolean.TRUE.toString());
collector.collectWithoutErrors(javaInformationsList);
htmlReport.toHtml("message 2");
assertNotEmptyAndClear(writer);
setProperty(Parameter.NO_DATABASE, Boolean.FALSE.toString());
}
/** Test.
* @throws IOException e */
@Test
public void testErrorCounter() throws IOException {
// errorCounter
errorCounter.addRequestForSystemError("error", -1, -1, null);
errorCounter.addRequestForSystemError("error2", -1, -1, "ma stack-trace");
collector.collectWithoutErrors(javaInformationsList);
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.TOUT, writer);
htmlReport.toHtml("message 3");
assertNotEmptyAndClear(writer);
for (final CounterRequest request : errorCounter.getRequests()) {
htmlReport.writeRequestAndGraphDetail(request.getId());
}
htmlReport.writeRequestAndGraphDetail("n'importe quoi");
assertNotEmptyAndClear(writer);
}
/** Test.
* @throws IOException e */
@Test
public void testPeriodeNonTout() throws IOException {
collector.collectWithoutErrors(javaInformationsList);
final String requestName = "test 1";
counter.bindContext(requestName, "complete test 1");
sqlCounter.addRequest("sql1", 10, 10, false, -1);
counter.addRequest(requestName, 0, 0, false, 1000);
counter.addRequest("test2", 1000, 500, false, 1000);
counter.addRequest("test3", 10000, 500, true, 10000);
collector.collectWithoutErrors(javaInformationsList);
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.SEMAINE, writer);
htmlReport.toHtml("message 6");
assertNotEmptyAndClear(writer);
final HtmlReport htmlReportRange = new HtmlReport(collector, null, javaInformationsList,
Range.createCustomRange(new Date(), new Date()), writer);
htmlReportRange.toHtml("message 6");
assertNotEmptyAndClear(writer);
}
/** Test.
* @throws Exception e */
@Test
public void testAllWrite() throws Exception { // NOPMD
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.SEMAINE, writer);
htmlReport.writeRequestAndGraphDetail("httpHitsRate");
// writeRequestAndGraphDetail avec drill-down
collector.collectWithoutErrors(javaInformationsList);
sqlCounter.setDisplayed(true);
final String requestName = "test 1";
counter.bindContext(requestName, "complete test 1");
servicesCounter.bindContext("service1", "service1");
sqlCounter.bindContext("sql1", "complete sql1");
sqlCounter.addRequest("sql1", 5, -1, false, -1);
servicesCounter.addRequest("service1", 10, 10, false, -1);
servicesCounter.bindContext("service2", "service2");
servicesCounter.addRequest("service2", 10, 10, false, -1);
counter.addRequest(requestName, 0, 0, false, 1000);
collector.collectWithoutErrors(javaInformationsList);
final HtmlReport toutHtmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.TOUT, writer);
for (final Counter collectorCounter : collector.getCounters()) {
for (final CounterRequest request : collectorCounter.getRequests()) {
toutHtmlReport.writeRequestAndGraphDetail(request.getId());
toutHtmlReport.writeRequestUsages(request.getId());
}
}
sqlCounter.setDisplayed(false);
htmlReport.writeSessionDetail("", null);
htmlReport.writeSessions(Collections.<SessionInformations> emptyList(), "message",
SESSIONS_PART);
htmlReport
.writeSessions(Collections.<SessionInformations> emptyList(), null, SESSIONS_PART);
final String fileName = ProcessInformations.WINDOWS ? "/tasklist.txt" : "/ps.txt";
htmlReport.writeProcesses(ProcessInformations.buildProcessInformations(getClass()
.getResourceAsStream(fileName), ProcessInformations.WINDOWS));
// avant initH2 pour avoir une liste de connexions vide
htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);
final Connection connection = TestDatabaseInformations.initH2();
try {
htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);
htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), true);
htmlReport.writeDatabase(new DatabaseInformations(0)); // h2.memory
htmlReport.writeDatabase(new DatabaseInformations(3)); // h2.settings avec nbColumns==2
HtmlReport.writeAddAndRemoveApplicationLinks(null, writer);
HtmlReport.writeAddAndRemoveApplicationLinks("test", writer);
setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, Boolean.TRUE.toString());
htmlReport.toHtml(null); // writeSystemActionsLinks
assertNotEmptyAndClear(writer);
setProperty(Parameter.NO_DATABASE, Boolean.TRUE.toString());
htmlReport.toHtml(null); // writeSystemActionsLinks
assertNotEmptyAndClear(writer);
setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, Boolean.FALSE.toString());
setProperty(Parameter.NO_DATABASE, Boolean.FALSE.toString());
} finally {
connection.close();
}
}
/** Test.
* @throws IOException e */
@Test
public void testRootContexts() throws IOException {
HtmlReport htmlReport;
counter.addRequest("first request", 100, 100, false, 1000);
TestCounter.bindRootContexts("first request", counter, 3);
sqlCounter.bindContext("sql", "sql");
htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer);
htmlReport.toHtml("message a");
assertNotEmptyAndClear(writer);
final Counter myCounter = new Counter("http", null);
final Collector collector2 = new Collector("test 2", Arrays.asList(myCounter), timer);
myCounter.bindContext("my context", "my context");
htmlReport = new HtmlReport(collector2, null, javaInformationsList, Period.SEMAINE, writer);
htmlReport.toHtml("message b");
assertNotEmptyAndClear(writer);
}
/** Test.
* @throws IOException e */
@Test
public void testCache() throws IOException {
final String cacheName = "test 1";
final CacheManager cacheManager = CacheManager.getInstance();
cacheManager.addCache(cacheName);
final String cacheName2 = "test 2";
try {
final Cache cache = cacheManager.getCache(cacheName);
cache.put(new Element(1, Math.random()));
cache.get(1);
cache.get(0);
cacheManager.addCache(cacheName2);
final Cache cache2 = cacheManager.getCache(cacheName2);
cache2.getCacheConfiguration().setOverflowToDisk(false);
cache2.getCacheConfiguration().setEternal(true);
final List<JavaInformations> javaInformationsList2 = Collections
.singletonList(new JavaInformations(null, true));
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2,
Period.TOUT, writer);
htmlReport.toHtml(null);
assertNotEmptyAndClear(writer);
} finally {
cacheManager.removeCache(cacheName);
cacheManager.removeCache(cacheName2);
}
}
/** Test.
* @throws IOException e
* @throws SchedulerException e */
@Test
public void testJob() throws IOException, SchedulerException {
// job quartz
JobGlobalListener.initJobGlobalListener();
JobGlobalListener.getJobCounter().clear();
//Grab the Scheduler instance from the Factory
final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
try {
// and start it off
scheduler.start();
final Random random = new Random();
//Define a Trigger that will fire "later"
final JobDetail job2 = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class);
final SimpleTrigger trigger2 = new SimpleTrigger("trigger" + random.nextInt(), null,
new Date(System.currentTimeMillis() + 60000));
trigger2.setRepeatInterval(2 * 24L * 60 * 60 * 1000);
scheduler.scheduleJob(job2, trigger2);
try {
final JobDetail job3 = new JobDetail("job" + random.nextInt(), null,
JobTestImpl.class);
final Trigger trigger3 = new CronTrigger("trigger" + random.nextInt(), null,
"0 0 0 * * ? 2030");
scheduler.scheduleJob(job3, trigger3);
} catch (final ParseException e) {
throw new IllegalStateException(e);
}
// (mais "Aucun job" dans le counter)
final List<JavaInformations> javaInformationsList2 = Collections
.singletonList(new JavaInformations(null, true));
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2,
Period.TOUT, writer);
htmlReport.toHtml(null);
assertNotEmptyAndClear(writer);
final Map<JobDetail, SimpleTrigger> triggersByJob = new LinkedHashMap<JobDetail, SimpleTrigger>();
for (int i = 0; i < 10; i++) {
//Define a Trigger that will fire "now"
final JobDetail job = new JobDetail("job" + random.nextInt(), null,
JobTestImpl.class);
job.setDescription("description");
final SimpleTrigger trigger = new SimpleTrigger("trigger" + random.nextInt(), null,
new Date());
//Schedule the job with the trigger
scheduler.scheduleJob(job, trigger);
triggersByJob.put(job, trigger);
}
// JobTestImpl fait un sleep de 2s au plus, donc on attend les jobs pour les compter
try {
Thread.sleep(3000);
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
for (Map.Entry<JobDetail, SimpleTrigger> entry : triggersByJob.entrySet()) {
// et on les relance pour qu'ils soient en cours
entry.getValue().setRepeatInterval(60000);
scheduler.scheduleJob(entry.getKey(), entry.getValue());
}
setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, Boolean.TRUE.toString());
final List<JavaInformations> javaInformationsList3 = Collections
.singletonList(new JavaInformations(null, true));
final HtmlReport htmlReport3 = new HtmlReport(collector, null, javaInformationsList3,
Period.TOUT, writer);
htmlReport3.toHtml(null);
assertNotEmptyAndClear(writer);
} finally {
setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, Boolean.FALSE.toString());
scheduler.shutdown();
JobGlobalListener.getJobCounter().clear();
JobGlobalListener.destroyJobGlobalListener();
}
}
/** Test.
* @throws IOException e */
@Test
public void testWithCollectorServer() throws IOException {
final CollectorServer collectorServer = new CollectorServer();
final HtmlReport htmlReport = new HtmlReport(collector, collectorServer,
javaInformationsList, Period.TOUT, writer);
htmlReport.toHtml(null);
assertNotEmptyAndClear(writer);
System.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + "mockLabradorRetriever", "true");
try {
collectorServer.collectWithoutErrors();
htmlReport.toHtml(null);
assertNotEmptyAndClear(writer);
} finally {
System.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + "mockLabradorRetriever",
"false");
}
}
/** Test.
* @throws IOException e */
@Test
public void testWithNoDatabase() throws IOException {
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.TOUT, writer);
htmlReport.toHtml(null);
assertNotEmptyAndClear(writer);
}
/** Test.
* @throws IOException e */
@Test
public void testEmptyHtmlCounterRequestContext() throws IOException {
final HtmlCounterRequestContextReport report = new HtmlCounterRequestContextReport(
Collections.<CounterRequestContext> emptyList(), Collections
.<String, HtmlCounterReport> emptyMap(), Collections
.<ThreadInformations> emptyList(), true, writer);
report.toHtml();
if (writer.getBuffer().length() != 0) {
fail("HtmlCounterRequestContextReport");
}
}
private static void setProperty(Parameter parameter, String value) {
System.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + parameter.getCode(), value);
}
private static void assertNotEmptyAndClear(final StringWriter writer) {
assertTrue("rapport vide", writer.getBuffer().length() > 0);
writer.getBuffer().setLength(0);
}
/** Test.
* @throws IOException e */
@Test
public void testToHtmlEn() throws IOException {
I18N.bindLocale(Locale.UK);
try {
assertEquals("locale en", Locale.UK, I18N.getCurrentLocale());
counter.addRequest("test1", 0, 0, false, 1000);
counter.addRequest("test2", 1000, 500, false, 1000);
counter.addRequest("test3", 10000, 5000, true, 10000);
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.TOUT, writer);
htmlReport.toHtml("message");
assertNotEmptyAndClear(writer);
} finally {
I18N.unbindLocale();
}
}
}
|
package ie.tcd.slscs.kfclone;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.AbstractButton;
import javax.swing.JButton;
public class MainInterface {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private Font kfFont = new Font("Arial", Font.PLAIN, 11);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainInterface window = new MainInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainInterface() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 690, 490);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic('F');
menuBar.add(mnFile);
JMenuItem mntmViewNgramFile = new JMenuItem("View n-Gram File");
mntmViewNgramFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.ALT_MASK));
mnFile.add(mntmViewNgramFile);
JMenuItem mntmNewMenuItem = new JMenuItem("View Text File");
mntmNewMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
mnFile.add(mntmNewMenuItem);
mnFile.addSeparator();
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Exit");
mntmNewMenuItem_1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
mnFile.add(mntmNewMenuItem_1);
JMenu mnTools = new JMenu("Tools");
mnTools.setMnemonic('T');
menuBar.add(mnTools);
JMenuItem mntmGetWordgrams = new JMenuItem("Get Wordgrams");
mntmGetWordgrams.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));
mnTools.add(mntmGetWordgrams);
JMenuItem mntmNewMenuItem_2 = new JMenuItem("Get Chargrams from Wordgram file");
mntmNewMenuItem_2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
mnTools.add(mntmNewMenuItem_2);
mnTools.addSeparator();
JMenuItem mntmMergeTwoOr = new JMenuItem("Merge Two or More Alphabetically-Sorted Wordgram files");
mntmMergeTwoOr.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_MASK));
mnTools.add(mntmMergeTwoOr);
JMenuItem mntmConvertAlphabeticSort = new JMenuItem("Convert Alphabetic Sort to Frequency Sort");
mntmConvertAlphabeticSort.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
mnTools.add(mntmConvertAlphabeticSort);
mnTools.addSeparator();
JMenuItem mntmNewMenuItem_3 = new JMenuItem("Get Phrase-Frames from Wordgram file");
mntmNewMenuItem_3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));
mnTools.add(mntmNewMenuItem_3);
JMenuItem mntmBrowsePhraseframeFile = new JMenuItem("Browse Phrase-Frame file");
mntmBrowsePhraseframeFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK));
mnTools.add(mntmBrowsePhraseframeFile);
JMenuItem mntmCountTokensIn = new JMenuItem("Count Tokens in Source file");
mntmCountTokensIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK));
mnTools.add(mntmCountTokensIn);
mnTools.addSeparator();
JMenuItem mntmConvertHtmlTo = new JMenuItem("Convert HTML to Text");
mntmConvertHtmlTo.setEnabled(false);
mnTools.add(mntmConvertHtmlTo);
JMenuItem mntmConvertSgml = new JMenuItem("Convert SGML / XML to Text");
mntmConvertSgml.setEnabled(false);
mnTools.add(mntmConvertSgml);
JMenu mnOptions = new JMenu("Options");
mnOptions.setMnemonic('O');
menuBar.add(mnOptions);
JMenuItem mntmNewMenuItem_4 = new JMenuItem("Edit Options");
mntmNewMenuItem_4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK));
mnOptions.add(mntmNewMenuItem_4);
JCheckBoxMenuItem chckbxmntmNewCheckItem = new JCheckBoxMenuItem("Advanced");
chckbxmntmNewCheckItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK));
chckbxmntmNewCheckItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AbstractButton absbut = (AbstractButton) evt.getSource();
boolean selected = absbut.getModel().isSelected();
if(selected) {
frame.setBounds(100, 100, 690, 490);
} else {
frame.setBounds(100, 100, 550, 490);
}
}
});
mnOptions.add(chckbxmntmNewCheckItem);
JMenu mnHelp = new JMenu("Help");
mnHelp.setMnemonic('H');
menuBar.add(mnHelp);
JMenuItem mntmNewMenuItem_5 = new JMenuItem("Help");
mntmNewMenuItem_5.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
mnHelp.add(mntmNewMenuItem_5);
JMenuItem mntmAbout = new JMenuItem("About");
mnHelp.add(mntmAbout);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("nGrams (e.g. 1-3, 5, 10)");
lblNewLabel.setFont(kfFont);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(2, 2, 120, 25);
frame.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setFont(kfFont);
textField.setBounds(130, 7, 110, 15);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblFloor = new JLabel("Floor");
lblFloor.setFont(kfFont);
lblFloor.setBounds(245, 2, 46, 25);
frame.getContentPane().add(lblFloor);
textField_1 = new JTextField();
textField_1.setFont(kfFont);
textField_1.setBounds(275, 7, 30, 15);
textField_1.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
Choice choice = new Choice();
choice.setBounds(315, 3, 95, 20);
choice.setFont(kfFont);
choice.addItem("Don't show");
choice.addItem("Show n-grams");
frame.getContentPane().add(choice);
JLabel lblNewLabel_1 = new JLabel("Chars to sort");
lblNewLabel_1.setFont(kfFont);
lblNewLabel_1.setBounds(415, 2, 65, 20);
frame.getContentPane().add(lblNewLabel_1);
Choice choice_1 = new Choice();
choice_1.setBounds(485, 3, 50, 20);
choice_1.setFont(kfFont);
choice_1.addItem("128");
choice_1.addItem("256");
choice_1.addItem("512");
choice_1.addItem("1024");
choice_1.addItem("2048");
frame.getContentPane().add(choice_1);
JLabel lblAdvOpt = new JLabel("Advanced Options");
lblAdvOpt.setFont(kfFont);
lblAdvOpt.setBounds(540, 2, 95, 20);
frame.getContentPane().add(lblAdvOpt);
Choice choice_2 = new Choice();
choice_2.setBounds(5, 30, 115, 20);
choice_2.setFont(kfFont);
choice_2.addItem("not case-sensitive");
choice_2.addItem("Case sensitive");
frame.getContentPane().add(choice_2);
Choice choice_3 = new Choice();
choice_3.setBounds(125, 30, 145, 20);
choice_3.setFont(kfFont);
choice_3.addItem("Observe TreatAsToken");
choice_3.addItem("Punct. as in KeepChars");
choice_3.addItem("Replace . , - ' with space");
choice_3.addItem("Keep internal . , - '");
choice_3.addItem("Delete internal - keep . , '");
frame.getContentPane().add(choice_3);
Choice choice_4 = new Choice();
choice_4.setFont(kfFont);
choice_4.setBounds(275, 30, 115, 20);
choice_4.addItem("Alphabetical Sort");
choice_4.addItem("Frequency Sort");
frame.getContentPane().add(choice_4);
Choice choice_5 = new Choice();
choice_5.setFont(kfFont);
choice_5.setBounds(395, 30, 130, 20);
choice_5.addItem("Retain numerals");
choice_5.addItem("Change numerals to
choice_5.addItem("Make all numbers
frame.getContentPane().add(choice_5);
JLabel lblNewLabel_2 = new JLabel("Source files");
lblNewLabel_2.setFont(kfFont);
lblNewLabel_2.setBounds(2, 70, 70, 20);
frame.getContentPane().add(lblNewLabel_2);
JButton btnNewButton = new JButton("<html><center>Add<br><u>S</u>ource files</center></html>");
btnNewButton.setMargin(new Insets(0,0,0,0));
btnNewButton.setFont(kfFont);
btnNewButton.setBounds(2, 95, 75, 35);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("<html><center><u>R</u>eplace<br>Source files</center></html>");
btnNewButton_1.setMargin(new Insets(0,0,0,0));
btnNewButton_1.setFont(kfFont);
btnNewButton_1.setBounds(2, 135, 75, 35);
frame.getContentPane().add(btnNewButton_1);
Choice choice_6 = new Choice();
choice_6.setBounds(0, 277, 28, 20);
frame.getContentPane().add(choice_6);
}
}
|
package com.handmark.pulltorefresh.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
public abstract class PullToRefreshBase<T extends AdapterView<ListAdapter>> extends LinearLayout implements
OnTouchListener {
private final class SmoothScrollRunnable implements Runnable {
static final int ANIMATION_DURATION_MS = 190;
static final int ANIMATION_FPS = 1000 / 60;
private final Interpolator interpolator;
private final int scrollToY;
private final int scrollFromY;
private final Handler handler;
private boolean continueRunning = true;
private long startTime = -1;
private int currentY = -1;
public SmoothScrollRunnable(Handler handler, int fromY, int toY) {
this.handler = handler;
this.scrollFromY = fromY;
this.scrollToY = toY;
this.interpolator = new AccelerateDecelerateInterpolator();
}
@Override
public void run() {
/**
* Only set startTime if this is the first time we're starting, else
* actually calculate the Y delta
*/
if (startTime == -1) {
startTime = System.currentTimeMillis();
} else {
/**
* We do do all calculations in long to reduce software float
* calculations. We use 1000 as it gives us good accuracy and
* small rounding errors
*/
long normalizedTime = (1000 * (System.currentTimeMillis() - startTime)) / ANIMATION_DURATION_MS;
normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
final int deltaY = Math.round((scrollFromY - scrollToY)
* interpolator.getInterpolation(normalizedTime / 1000f));
this.currentY = scrollFromY - deltaY;
setHeaderScroll(currentY);
}
// If we're not at the target Y, keep going...
if (continueRunning && scrollToY != currentY) {
handler.postDelayed(this, ANIMATION_FPS);
}
}
public void stop() {
this.continueRunning = false;
this.handler.removeCallbacks(this);
}
};
// Constants
static final int PULL_TO_REFRESH = 0;
static final int RELEASE_TO_REFRESH = PULL_TO_REFRESH + 1;
static final int REFRESHING = RELEASE_TO_REFRESH + 1;
static final int EVENT_COUNT = 3;
// Fields
private int state = PULL_TO_REFRESH;
private T adapterView;
private boolean isPullToRefreshEnabled = true;
private ProgressBar headerProgress;
private TextView headerText;
private ImageView headerImage;
private Animation flipAnimation, reverseAnimation;
private int headerHeight;
private final Handler handler = new Handler();
private OnTouchListener onTouchListener;
private OnRefreshListener onRefreshListener;
private SmoothScrollRunnable currentSmoothScrollRunnable;
private float startY = -1;
private final float[] lastYs = new float[EVENT_COUNT];
private String releaseLabel;
private String pullLabel;
private String refreshingLabel;
// Constructors
public PullToRefreshBase(Context context) {
this(context, null);
}
public PullToRefreshBase(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// Getter & Setter
/**
* Get the Wrapped AdapterView. Anything returned here has already been
* added to the content view.
*
* @return The AdapterView which is currently wrapped
*/
public final T getAdapterView() {
return adapterView;
}
/**
* Whether Pull-to-Refresh is enabled
*
* @return enabled
*/
public boolean isPullToRefreshEnabled() {
return isPullToRefreshEnabled;
}
/**
* Mark the current Refresh as complete. Will Reset the UI and hide the
* Refreshing View
*/
public void onRefreshComplete() {
resetHeader();
}
public void setOnRefreshListener(OnRefreshListener listener) {
onRefreshListener = listener;
}
/**
* A mutator to enable/disable Pull-to-Refresh for the current AdapterView
*
* @param enable
* Whether Pull-To-Refresh should be used
*/
public void setPullToRefreshEnabled(boolean enabled) {
this.isPullToRefreshEnabled = enabled;
}
public void setReleaseLabel(String releaseLabel) {
this.releaseLabel = releaseLabel;
}
public void setPullLabel(String pullLabel) {
this.pullLabel = pullLabel;
}
public void setRefreshingLabel(String refreshingLabel) {
this.refreshingLabel = refreshingLabel;
}
public void setHeaderProgress(ProgressBar headerProgress) {
this.headerProgress = headerProgress;
}
// Methods for/from SuperClass/Interfaces
@Override
public void setOnTouchListener(OnTouchListener listener) {
onTouchListener = listener;
}
@Override
public boolean onTouch(View view, MotionEvent ev) {
if (isPullToRefreshEnabled) {
// Returning true here stops the ListView being scrollable while we
// refresh
if (state == REFRESHING) {
return true;
} else {
return onAdapterViewTouch(view, ev);
}
}
return false;
}
/**
* This is implemented by derived classes to return the created AdapterView.
* If you need to use a custom AdapterView (such as a custom ListView),
* override this method and return an instance of your custom class.
*
* Be sure to set the ID of the view in this method, especially if you're
* using a ListActivity or ListFragment.
*
* @param context
* @param attrs
* AttributeSet from wrapped class. Means that anything you
* include in the XML layout declaration will be routed to the
* AdapterView
* @return New instance of the AdapterView
*/
protected abstract T createAdapterView(Context context, AttributeSet attrs);
// Methods
protected final void resetHeader() {
state = PULL_TO_REFRESH;
initializeYsHistory();
startY = -1;
headerImage.setVisibility(View.VISIBLE);
headerProgress.setVisibility(View.GONE);
headerText.setText(R.string.pull_to_refresh_pull_label);
smoothScrollTo(0);
}
private void init(Context context, AttributeSet attrs) {
setOrientation(LinearLayout.VERTICAL);
// Header
ViewGroup header = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.pull_to_refresh_header, this,
false);
headerText = (TextView) header.findViewById(R.id.pull_to_refresh_text);
pullLabel = context.getString(R.string.pull_to_refresh_pull_label);
refreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_label);
releaseLabel = context.getString(R.string.pull_to_refresh_release_label);
headerImage = (ImageView) header.findViewById(R.id.pull_to_refresh_image);
headerProgress = (ProgressBar) header.findViewById(R.id.pull_to_refresh_progress);
addView(header, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
measureView(header);
headerHeight = header.getMeasuredHeight();
// AdapterView
// By passing the attrs, we can add ListView/GridView params via XML
adapterView = this.createAdapterView(context, attrs);
adapterView.setOnTouchListener(this);
addView(adapterView, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
// Styleables from XML
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
if (a.hasValue(R.styleable.PullToRefresh_headerTextColor)) {
headerText.setTextColor(a.getColor(R.styleable.PullToRefresh_headerTextColor, Color.BLACK));
}
if (a.hasValue(R.styleable.PullToRefresh_headerBackground)) {
this.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_headerBackground, Color.WHITE));
}
if (a.hasValue(R.styleable.PullToRefresh_adapterViewBackground)) {
adapterView.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_adapterViewBackground,
Color.WHITE));
}
a.recycle();
// Animations
flipAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
flipAnimation.setInterpolator(new LinearInterpolator());
flipAnimation.setDuration(250);
flipAnimation.setFillAfter(true);
reverseAnimation = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
reverseAnimation.setInterpolator(new LinearInterpolator());
reverseAnimation.setDuration(250);
reverseAnimation.setFillAfter(true);
// Hide Header View
setPadding(getPaddingLeft(), -headerHeight, getPaddingRight(), getPaddingBottom());
}
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
private boolean onAdapterViewTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
updateEventStates(event);
if (isPullingDownToRefresh() && startY == -1) {
if (startY == -1) {
startY = event.getY();
}
return false;
}
if (startY != -1 && !adapterView.isPressed()) {
pullDown(event, startY);
return true;
}
break;
case MotionEvent.ACTION_UP:
initializeYsHistory();
startY = -1;
if (state == RELEASE_TO_REFRESH) {
setRefreshing();
if (onRefreshListener != null) {
onRefreshListener.onRefresh();
}
} else {
smoothScrollTo(0);
}
break;
}
if (null != onTouchListener) {
return onTouchListener.onTouch(view, event);
}
return false;
}
private void pullDown(MotionEvent event, float firstY) {
float averageY = average(lastYs);
int height = (int) (Math.max(averageY - firstY, 0));
setHeaderScroll(height);
if (state == PULL_TO_REFRESH && headerHeight < height) {
state = RELEASE_TO_REFRESH;
headerText.setText(releaseLabel);
headerImage.clearAnimation();
headerImage.startAnimation(flipAnimation);
}
if (state == RELEASE_TO_REFRESH && headerHeight >= height) {
state = PULL_TO_REFRESH;
headerText.setText(pullLabel);
headerImage.clearAnimation();
headerImage.startAnimation(reverseAnimation);
}
}
private void setHeaderScroll(int y) {
scrollTo(0, -y);
}
private int getHeaderScroll() {
return -getScrollY();
}
private void setRefreshing() {
state = REFRESHING;
headerText.setText(refreshingLabel);
headerImage.clearAnimation();
headerImage.setVisibility(View.INVISIBLE);
headerProgress.setVisibility(View.VISIBLE);
smoothScrollTo(headerHeight);
}
private float average(float[] ysArray) {
float avg = 0;
for (int i = 0; i < EVENT_COUNT; i++) {
avg += ysArray[i];
}
return avg / EVENT_COUNT;
}
private void initializeYsHistory() {
for (int i = 0; i < EVENT_COUNT; i++) {
lastYs[i] = 0;
}
}
private void updateEventStates(MotionEvent event) {
for (int i = 0; i < EVENT_COUNT - 1; i++) {
lastYs[i] = lastYs[i + 1];
}
float y = event.getY();
int top = adapterView.getTop();
lastYs[EVENT_COUNT - 1] = y + top;
}
private boolean isPullingDownToRefresh() {
return isPullToRefreshEnabled && state != REFRESHING && isUserDraggingDownwards() && isFirstVisible();
}
private boolean isFirstVisible() {
if (this.adapterView.getCount() == 0) {
return true;
} else if (adapterView.getFirstVisiblePosition() == 0) {
return adapterView.getChildAt(0).getTop() >= adapterView.getTop();
} else {
return false;
}
}
private boolean isUserDraggingDownwards() {
return this.isUserDraggingDownwards(0, EVENT_COUNT - 1);
}
private boolean isUserDraggingDownwards(int from, int to) {
return lastYs[from] != 0 && lastYs[to] != 0 && Math.abs(lastYs[from] - lastYs[to]) > 10
&& lastYs[from] < lastYs[to];
}
private void smoothScrollTo(int y) {
if (null != currentSmoothScrollRunnable) {
currentSmoothScrollRunnable.stop();
}
this.currentSmoothScrollRunnable = new SmoothScrollRunnable(handler, getHeaderScroll(), y);
handler.post(currentSmoothScrollRunnable);
}
// Inner and Anonymous Classes
public static interface OnRefreshListener {
public void onRefresh();
}
}
|
package com.handmark.pulltorefresh.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
public abstract class PullToRefreshBase<T extends AbsListView> extends LinearLayout implements OnTouchListener,
OnScrollListener {
private final class SmoothScrollRunnable implements Runnable {
static final int ANIMATION_DURATION_MS = 190;
static final int ANIMATION_FPS = 1000 / 60;
private final Interpolator interpolator;
private final int scrollToY;
private final int scrollFromY;
private final Handler handler;
private boolean continueRunning = true;
private long startTime = -1;
private int currentY = -1;
public SmoothScrollRunnable(Handler handler, int fromY, int toY) {
this.handler = handler;
this.scrollFromY = fromY;
this.scrollToY = toY;
this.interpolator = new AccelerateDecelerateInterpolator();
}
@Override
public void run() {
/**
* Only set startTime if this is the first time we're starting, else
* actually calculate the Y delta
*/
if (startTime == -1) {
startTime = System.currentTimeMillis();
} else {
/**
* We do do all calculations in long to reduce software float
* calculations. We use 1000 as it gives us good accuracy and
* small rounding errors
*/
long normalizedTime = (1000 * (System.currentTimeMillis() - startTime)) / ANIMATION_DURATION_MS;
normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
final int deltaY = Math.round((scrollFromY - scrollToY)
* interpolator.getInterpolation(normalizedTime / 1000f));
this.currentY = scrollFromY - deltaY;
setHeaderScroll(currentY);
}
// If we're not at the target Y, keep going...
if (continueRunning && scrollToY != currentY) {
handler.postDelayed(this, ANIMATION_FPS);
}
}
public void stop() {
this.continueRunning = false;
this.handler.removeCallbacks(this);
}
};
// Constants
static final int PULL_TO_REFRESH = 0;
static final int RELEASE_TO_REFRESH = PULL_TO_REFRESH + 1;
static final int REFRESHING = RELEASE_TO_REFRESH + 1;
static final int EVENT_COUNT = 3;
public static final int MODE_PULL_DOWN_TO_REFRESH = 0x1;
public static final int MODE_PULL_UP_TO_REFRESH = 0x2;
// Fields
private int state = PULL_TO_REFRESH;
private int mode = MODE_PULL_DOWN_TO_REFRESH;
private T adapterView;
private boolean isPullToRefreshEnabled = true;
private ProgressBar headerProgress;
private TextView headerText;
private ImageView headerImage;
private Animation rotateToPointUpAnimation, rotateToPointDownAnimation;
private int headerHeight;
private final Handler handler = new Handler();
private OnTouchListener onTouchListener;
private OnRefreshListener onRefreshListener;
private OnScrollListener onScrollListener;
private OnLastItemVisibleListener onLastItemVisibleListener;
private int lastSavedFirstVisibleItem = -1;
private SmoothScrollRunnable currentSmoothScrollRunnable;
private float startY = -1;
private final float[] lastYs = new float[EVENT_COUNT];
private String releaseLabel;
private String pullLabel;
private String refreshingLabel;
// Constructors
public PullToRefreshBase(Context context) {
this(context, null);
}
public PullToRefreshBase(Context context, int mode) {
this(context);
this.mode = mode;
}
public PullToRefreshBase(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// Getter & Setter
/**
* Get the Wrapped AdapterView. Anything returned here has already been
* added to the content view.
*
* @return The AdapterView which is currently wrapped
*/
public final T getAdapterView() {
return adapterView;
}
/**
* Whether Pull-to-Refresh is enabled
*
* @return enabled
*/
public boolean isPullToRefreshEnabled() {
return isPullToRefreshEnabled;
}
/**
* Mark the current Refresh as complete. Will Reset the UI and hide the
* Refreshing View
*/
public void onRefreshComplete() {
resetHeader();
}
public void setOnLastItemVisibleListener(OnLastItemVisibleListener listener) {
onLastItemVisibleListener = listener;
}
public void setOnRefreshListener(OnRefreshListener listener) {
onRefreshListener = listener;
}
/**
* A mutator to enable/disable Pull-to-Refresh for the current AdapterView
*
* @param enable
* Whether Pull-To-Refresh should be used
*/
public void setPullToRefreshEnabled(boolean enabled) {
this.isPullToRefreshEnabled = enabled;
}
public void setReleaseLabel(String releaseLabel) {
this.releaseLabel = releaseLabel;
}
public void setPullLabel(String pullLabel) {
this.pullLabel = pullLabel;
}
public void setRefreshingLabel(String refreshingLabel) {
this.refreshingLabel = refreshingLabel;
}
public void setHeaderProgress(ProgressBar headerProgress) {
this.headerProgress = headerProgress;
}
// Methods for/from SuperClass/Interfaces
public final void setOnScrollListener(OnScrollListener listener) {
onScrollListener = listener;
}
@Override
public final void setOnTouchListener(OnTouchListener listener) {
onTouchListener = listener;
}
public final void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
final int totalItemCount) {
if (null != onLastItemVisibleListener) {
// detect if last item is visible
if (visibleItemCount > 0 && visibleItemCount < totalItemCount
&& (firstVisibleItem + visibleItemCount == totalItemCount)) {
// only process first event
if (firstVisibleItem != lastSavedFirstVisibleItem) {
lastSavedFirstVisibleItem = firstVisibleItem;
onLastItemVisibleListener.onLastItemVisible();
}
}
}
if (null != onScrollListener) {
onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
}
public final void onScrollStateChanged(final AbsListView view, final int scrollState) {
if (null != onScrollListener) {
onScrollListener.onScrollStateChanged(view, scrollState);
}
}
@Override
public final boolean onTouch(View view, MotionEvent ev) {
if (isPullToRefreshEnabled) {
// Returning true here stops the ListView being scrollable while we
// refresh
if (state == REFRESHING) {
return true;
} else {
return onAdapterViewTouch(view, ev);
}
}
return false;
}
/**
* This is implemented by derived classes to return the created AdapterView.
* If you need to use a custom AdapterView (such as a custom ListView),
* override this method and return an instance of your custom class.
*
* Be sure to set the ID of the view in this method, especially if you're
* using a ListActivity or ListFragment.
*
* @param context
* @param attrs
* AttributeSet from wrapped class. Means that anything you
* include in the XML layout declaration will be routed to the
* AdapterView
* @return New instance of the AdapterView
*/
protected abstract T createAdapterView(Context context, AttributeSet attrs);
// Methods
protected final void resetHeader() {
state = PULL_TO_REFRESH;
initializeYsHistory();
startY = -1;
headerImage.setVisibility(View.VISIBLE);
headerProgress.setVisibility(View.GONE);
headerText.setText(R.string.pull_to_refresh_pull_label);
smoothScrollTo(0);
}
private void init(Context context, AttributeSet attrs) {
// Styleables from XML
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
mode = a.getInteger(R.styleable.PullToRefresh_mode, MODE_PULL_DOWN_TO_REFRESH);
setOrientation(LinearLayout.VERTICAL);
// AdapterView
// By passing the attrs, we can add ListView/GridView params via XML
adapterView = this.createAdapterView(context, attrs);
adapterView.setOnTouchListener(this);
adapterView.setOnScrollListener(this);
addView(adapterView, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0, 1.0f));
// Header
ViewGroup header = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.pull_to_refresh_header, this,
false);
headerText = (TextView) header.findViewById(R.id.pull_to_refresh_text);
pullLabel = context.getString(R.string.pull_to_refresh_pull_label);
refreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_label);
releaseLabel = context.getString(R.string.pull_to_refresh_release_label);
headerImage = (ImageView) header.findViewById(R.id.pull_to_refresh_image);
headerProgress = (ProgressBar) header.findViewById(R.id.pull_to_refresh_progress);
int index;
if (mode == MODE_PULL_UP_TO_REFRESH) {
headerImage.setImageResource(R.drawable.pulltorefresh_up_arrow);
index = 1;
} else {
headerImage.setImageResource(R.drawable.pulltorefresh_down_arrow);
index = 0;
}
addView(header, index, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(header);
headerHeight = header.getMeasuredHeight();
// Styleables from XML
if (a.hasValue(R.styleable.PullToRefresh_headerTextColor)) {
headerText.setTextColor(a.getColor(R.styleable.PullToRefresh_headerTextColor, Color.BLACK));
}
if (a.hasValue(R.styleable.PullToRefresh_headerBackground)) {
this.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_headerBackground, Color.WHITE));
}
if (a.hasValue(R.styleable.PullToRefresh_adapterViewBackground)) {
adapterView.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_adapterViewBackground,
Color.WHITE));
}
a.recycle();
// Animations
final Interpolator interpolator = new LinearInterpolator();
rotateToPointUpAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotateToPointUpAnimation.setInterpolator(interpolator);
rotateToPointUpAnimation.setDuration(125);
rotateToPointUpAnimation.setFillAfter(true);
rotateToPointDownAnimation = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotateToPointDownAnimation.setInterpolator(interpolator);
rotateToPointDownAnimation.setDuration(125);
rotateToPointDownAnimation.setFillAfter(true);
// Hide Header View
switch (mode) {
case MODE_PULL_UP_TO_REFRESH:
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), -headerHeight);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
setPadding(getPaddingLeft(), -headerHeight, getPaddingRight(), getPaddingBottom());
break;
}
}
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
private boolean onAdapterViewTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
updateEventStates(event);
if (isPullingToRefresh() && startY == -1) {
if (startY == -1) {
startY = event.getY();
}
return false;
}
if (startY != -1 && !adapterView.isPressed()) {
pullEvent(event, startY);
return true;
}
break;
case MotionEvent.ACTION_UP:
initializeYsHistory();
startY = -1;
if (state == RELEASE_TO_REFRESH) {
setRefreshing();
if (onRefreshListener != null) {
onRefreshListener.onRefresh();
}
} else {
smoothScrollTo(0);
}
break;
}
if (null != onTouchListener) {
return onTouchListener.onTouch(view, event);
}
return false;
}
private void pullEvent(MotionEvent event, float firstY) {
float averageY = average(lastYs);
int height;
switch (mode) {
case MODE_PULL_UP_TO_REFRESH:
height = (int) Math.max(firstY - averageY, 0);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
height = (int) Math.max(averageY - firstY, 0);
break;
}
setHeaderScroll(height);
if (state == PULL_TO_REFRESH && headerHeight < height) {
state = RELEASE_TO_REFRESH;
headerText.setText(releaseLabel);
headerImage.clearAnimation();
switch (mode) {
case MODE_PULL_UP_TO_REFRESH:
headerImage.startAnimation(rotateToPointDownAnimation);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
headerImage.startAnimation(rotateToPointUpAnimation);
break;
}
} else if (state == RELEASE_TO_REFRESH && headerHeight >= height) {
state = PULL_TO_REFRESH;
headerText.setText(pullLabel);
headerImage.clearAnimation();
switch (mode) {
case MODE_PULL_UP_TO_REFRESH:
headerImage.startAnimation(rotateToPointUpAnimation);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
headerImage.startAnimation(rotateToPointDownAnimation);
break;
}
}
}
private void setHeaderScroll(int y) {
switch (mode) {
case MODE_PULL_UP_TO_REFRESH:
scrollTo(0, y);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
scrollTo(0, -y);
break;
}
}
private int getHeaderScroll() {
switch (mode) {
case MODE_PULL_UP_TO_REFRESH:
return getScrollY();
case MODE_PULL_DOWN_TO_REFRESH:
default:
return -getScrollY();
}
}
private void setRefreshing() {
state = REFRESHING;
headerText.setText(refreshingLabel);
headerImage.clearAnimation();
headerImage.setVisibility(View.INVISIBLE);
headerProgress.setVisibility(View.VISIBLE);
smoothScrollTo(headerHeight);
}
private float average(float[] ysArray) {
float avg = 0;
for (int i = 0; i < EVENT_COUNT; i++) {
avg += ysArray[i];
}
return avg / EVENT_COUNT;
}
private void initializeYsHistory() {
for (int i = 0; i < EVENT_COUNT; i++) {
lastYs[i] = 0;
}
}
private void updateEventStates(MotionEvent event) {
for (int i = 0; i < EVENT_COUNT - 1; i++) {
lastYs[i] = lastYs[i + 1];
}
float y = event.getY();
lastYs[EVENT_COUNT - 1] = y;
}
private boolean isPullingToRefresh() {
if (isPullToRefreshEnabled && state != REFRESHING) {
switch (mode) {
case MODE_PULL_DOWN_TO_REFRESH:
return isUserDraggingDownwards() && isFirstItemVisible();
case MODE_PULL_UP_TO_REFRESH:
return isUserDraggingUpwards() && isLastItemVisible();
}
}
return false;
}
private boolean isFirstItemVisible() {
if (this.adapterView.getCount() == 0) {
return true;
} else if (adapterView.getFirstVisiblePosition() == 0) {
return adapterView.getChildAt(0).getTop() >= adapterView.getTop();
} else {
return false;
}
}
private boolean isLastItemVisible() {
final int count = this.adapterView.getCount();
if (count == 0) {
return true;
} else if (adapterView.getLastVisiblePosition() == count - 1) {
return true;
} else {
return false;
}
}
private boolean isUserDraggingDownwards() {
return this.isUserDraggingDownwards(0, EVENT_COUNT - 1);
}
private boolean isUserDraggingDownwards(int from, int to) {
return lastYs[from] != 0 && lastYs[to] != 0 && Math.abs(lastYs[from] - lastYs[to]) > 10
&& lastYs[from] < lastYs[to];
}
private boolean isUserDraggingUpwards() {
return this.isUserDraggingUpwards(0, EVENT_COUNT - 1);
}
private boolean isUserDraggingUpwards(int from, int to) {
return lastYs[from] != 0 && lastYs[to] != 0 && Math.abs(lastYs[to] - lastYs[from]) > 10
&& lastYs[to] < lastYs[from];
}
private void smoothScrollTo(int y) {
if (null != currentSmoothScrollRunnable) {
currentSmoothScrollRunnable.stop();
}
this.currentSmoothScrollRunnable = new SmoothScrollRunnable(handler, getHeaderScroll(), y);
handler.post(currentSmoothScrollRunnable);
}
// Inner and Anonymous Classes
public static interface OnRefreshListener {
public void onRefresh();
}
public static interface OnLastItemVisibleListener {
public void onLastItemVisible();
}
}
|
package com.ironz.binaryprefs.lock;
import com.ironz.binaryprefs.exception.LockOperationException;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public final class ProcessFileLock implements Lock {
private static final String RWD_MODE = "rwd";
private final File lockFile;
private RandomAccessFile randomAccessFile;
private FileChannel channel;
private FileLock lock;
ProcessFileLock(File lockFile) {
this.lockFile = lockFile;
}
@Override
public void lock() {
try {
randomAccessFile = new RandomAccessFile(lockFile, RWD_MODE);
channel = randomAccessFile.getChannel();
lock = channel.lock();
} catch (Exception e) {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
}
if (channel != null) {
channel.close();
}
} catch (Exception ignored) {
}
throw new LockOperationException(e);
}
}
@Override
public void unlock() {
try {
if (lock != null && lock.isValid()) {
lock.release();
}
} catch (Exception e) {
throw new LockOperationException(e);
} finally {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
}
if (channel != null) {
channel.close();
}
} catch (Exception ignored) {
}
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
throw new UnsupportedOperationException("Not implemented!");
}
@Override
public boolean tryLock() {
throw new UnsupportedOperationException("Not implemented!");
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
throw new UnsupportedOperationException("Not implemented!");
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException("Not implemented!");
}
}
|
// This file is part of Elveos.org.
// Elveos.org is free software: you can redistribute it and/or modify it
// option) any later version.
// Elveos.org is distributed in the hope that it will be useful, but WITHOUT
// more details.
package com.bloatit.framework.xcgiserver;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
import com.bloatit.common.Log;
import com.bloatit.framework.FrameworkConfiguration;
import com.bloatit.framework.restprocessor.RestResource;
import com.bloatit.framework.restprocessor.exception.RestException;
import com.bloatit.framework.utils.datetime.DateUtils;
import com.bloatit.framework.webprocessor.components.meta.HtmlElement;
import com.bloatit.framework.webprocessor.components.writers.IndentedHtmlStream;
import com.bloatit.framework.webprocessor.components.writers.QueryResponseStream;
import com.bloatit.framework.webprocessor.components.writers.SimpleHtmlStream;
import com.bloatit.framework.webprocessor.context.Context;
import com.bloatit.framework.xcgiserver.HttpReponseField.StatusCode;
import com.bloatit.web.HtmlTools;
public final class HttpResponse {
static final byte[] EOL = "\r\n".getBytes();
private static enum Encoding {
NONE, GZIP, DEFLATE,
}
private final OutputStream output;
private final SimpleDateFormat httpDateformat;
private Encoding encoding = Encoding.NONE;
private Set<HttpReponseField> headers = new HashSet<HttpReponseField>();
public HttpResponse(final OutputStream output, final HttpHeader header) {
httpDateformat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
httpDateformat.setTimeZone(TimeZone.getTimeZone("GMT"));
if (header.getHttpAcceptEncoding().contains("deflate")) {
encoding = Encoding.DEFLATE;
} else if (header.getHttpAcceptEncoding().contains("gzip")) {
encoding = Encoding.GZIP;
} else {
encoding = Encoding.NONE;
}
this.output = output;
}
public void addField(HttpReponseField headerField) {
headers.add(headerField);
}
/**
* Writes an exception to the page
*/
public void writeException(final Exception e) {
// Construct header
addField(HttpReponseField.status(StatusCode.ERROR_SERV_500_INTERNAL_SERVER_ERROR));
addField(HttpReponseField.contentType("Content-type: text/plain"));
// Construct body
final StringBuilder display = new StringBuilder();
display.append(e.toString());
display.append(" :\n");
for (final StackTraceElement s : e.getStackTrace()) {
display.append('\t');
display.append(s);
display.append('\n');
}
try {
writeHeader();
output.write(display.toString().getBytes());
} catch (final IOException e1) {
Log.framework().fatal("Cannot send exception through the SCGI socket.", e1);
}
}
public void writeRedirect(StatusCode status, final String url) throws IOException {
addField(HttpReponseField.status(status));
addField(HttpReponseField.location(url));
addSessionCookie();
writeHeader();
}
public void writeOAuthRedirect(int status, final String url) throws IOException {
addField(new HttpReponseField("status", String.valueOf(status)));
addField(HttpReponseField.location(url));
writeHeader();
}
public void writeOAuth(StatusCode status, Map<String, String> headers, final String body) throws IOException {
addField(HttpReponseField.status(status));
for (Entry<String, String> header : headers.entrySet()) {
addField(new HttpReponseField(header.getKey(), header.getValue()));
}
writeHeader();
output.write(body.getBytes());
}
public void writePage(StatusCode status, String contentType, final HtmlElement page) throws IOException {
addField(HttpReponseField.status(status));
addSessionCookie();
addField(HttpReponseField.vary("Accept-Encoding"));
addField(HttpReponseField.contentType(contentType));
addField(HttpReponseField.acceptRanges("bytes"));
String languageCode = Context.getLocalizator().getCode();
if (!languageCode.isEmpty()) {
addField(HttpReponseField.contentLanguage(languageCode));
}
switch (encoding) {
case DEFLATE:
case GZIP:
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
OutputStream encodedStream;
if (encoding == Encoding.GZIP) {
addField(HttpReponseField.contentEncoding("gzip"));
encodedStream = new GZIPOutputStream(buffer);
} else {
addField(HttpReponseField.contentEncoding("deflate"));
encodedStream = new DeflaterOutputStream(buffer);
}
final QueryResponseStream htmlText = buildHtmlStream(encodedStream);
page.write(htmlText);
encodedStream.flush();
encodedStream.close();
final byte[] byteArray = buffer.toByteArray();
addField(HttpReponseField.contentLength(String.valueOf(byteArray.length)));
writeHeader();
output.write(byteArray);
break;
case NONE:
default:
writeHeader();
page.write(buildHtmlStream(output));
break;
}
}
public void writeResource(final String path, final long size, final String fileName) throws IOException {
// addField(HttpReponseField.status(status));
addField(HttpReponseField.contentDisposition("inline; filename=" + fileName));
addField(HttpReponseField.vary("Accept-Encoding"));
addField(HttpReponseField.acceptRanges("bytes"));
// Last-Modified
final File file = new File(path);
final long lastModified = file.lastModified();
writeLine("Last-Modified: " + httpDateformat.format(new Date(lastModified)));
// Expires (360 days)
writeLine("Expires: " + httpDateformat.format(DateUtils.nowPlusSomeYears(1)));
// Content type
if (fileName.endsWith(".css")) {
addField(HttpReponseField.contentType("text/css"));
} else if (fileName.endsWith(".png")) {
addField(HttpReponseField.contentType("image/png"));
} else {
// FIXME manage other content types !!
Log.framework().warn("FIXME: Unknown content type for file '" + fileName + "' in HttpResponse.writeResource");
}
// Send file
addField(new HttpReponseField("X-sendfile2", path + " 0-" + (size - 1)));
writeHeader();
}
/**
* <p>
* Writes a rest resource into an HttpResponse
* </p>
* <p>
* Will generate either a {@code <rest result="ok">} or a
* {@code <rest result="fail">} depending on the value of its internal
* <code>status</code> (which can be set using
* {@link #setStatus(StatusCode)}. <br />
* Any value other than OK_200 will result in a fail.
* </p>
* <p>
* Before writing make sure the statusCode has been correctly set. <br />
* The default value of the status code is OK_200 hence when everything goes
* well, there is no need to change it. Whenever generating the restResource
* goes haywire, think to set a correct status using the method
* {@link #setStatus(StatusCode)}
* </p>
*
* @param resource the resource to write
* @throws IOException whenever an IO error occurs on the underlying stream
* @see #setStatus(StatusCode)
*/
public void writeRestResource(final RestResource resource) throws IOException {
try {
final String resourceXml = resource.getXmlString();
// addField(HttpReponseField.status(status));
addField(HttpReponseField.contentType("text/xml"));
addField(HttpReponseField.vary("Accept-Encoding"));
addField(HttpReponseField.acceptRanges("bytes"));
// In modern browser allow external website to request our site (for
// ajax requests).
addField(new HttpReponseField("Access-Control-Allow-Origin", "*"));
writeHeader();
final IndentedHtmlStream htmlText = new IndentedHtmlStream(output);
htmlText.writeLine("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>");
htmlText.writeLine("<rest result=\"ok\" request=\"" + HtmlTools.escape(resource.getRequest()) + "\" >");
htmlText.indent();
htmlText.writeLine(resourceXml);
htmlText.unindent();
htmlText.writeLine("</rest>");
} catch (final Exception e) {
Log.rest().fatal("Exception while marshalling RestResource " + resource.getUnderlying(), e);
writeRestError(StatusCode.ERROR_SERV_500_INTERNAL_SERVER_ERROR, "Error while marhsalling the Object", e);
}
}
/**
* Writes a rest error based on the <code>exception</code>
*
* @param exception the exception describing the error
* @throws IOException when an IO error occurs
*/
public void writeRestError(final RestException exception) throws IOException {
writeRestError(exception.getStatus(), exception.getMessage(), exception);
}
/**
* <p>
* Writes a rest error
* </p>
*
* @see {@link #writeRestError(RestException)}
*/
private void writeRestError(final StatusCode status, final String message, final Exception e) throws IOException {
addField(HttpReponseField.status(status));
addField(HttpReponseField.contentType("text/xml"));
addField(HttpReponseField.vary("Accept-Encoding"));
addField(HttpReponseField.acceptRanges("bytes"));
// In modern browser allow external website to request our site (for
// ajax requests).
addField(new HttpReponseField("Access-Control-Allow-Origin", "*"));
writeHeader();
final IndentedHtmlStream htmlText = new IndentedHtmlStream(output);
htmlText.writeLine("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>");
htmlText.indent();
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
final String stackTrace = sw.toString();
if (stackTrace != null && !stackTrace.isEmpty()) {
htmlText.writeLine("<error code=\"" + status.toString() + "\" reason=\"" + message + "\" >");
htmlText.writeLine(HtmlTools.escape(stackTrace));
htmlText.writeLine("</error>");
} else {
htmlText.writeLine("<error reason=\"" + HtmlTools.escape(status.toString()) + "\" />");
}
htmlText.unindent();
}
private void writeHeader() throws IOException {
for (HttpReponseField field : headers) {
field.write(output);
}
output.write(EOL);
}
private void writeLine(final String string) throws IOException {
output.write(string.getBytes());
output.write(EOL);
}
private void addSessionCookie() throws IOException {
if (FrameworkConfiguration.isHttpsEnabled()) {
headers.add(HttpReponseField.setCookie("session_key=" + Context.getSession().getKey() + "; path=/; Max-Age=1296000; Secure; HttpOnly "));
}else{
headers.add(HttpReponseField.setCookie("session_key=" + Context.getSession().getKey() + "; path=/; Max-Age=1296000; HttpOnly "));
}
}
private QueryResponseStream buildHtmlStream(final OutputStream outputStream) {
if (FrameworkConfiguration.isHtmlMinified()) {
return new SimpleHtmlStream(outputStream);
}
return new IndentedHtmlStream(outputStream);
}
}
|
package com.bloatit.web.linkable.bugs;
import java.util.Locale;
import com.bloatit.framework.exceptions.highlevel.ShallNotPassException;
import com.bloatit.framework.exceptions.lowlevel.UnauthorizedOperationException;
import com.bloatit.framework.utils.FileConstraintChecker;
import com.bloatit.framework.utils.FileConstraintChecker.SizeUnit;
import com.bloatit.framework.webprocessor.annotations.Optional;
import com.bloatit.framework.webprocessor.annotations.ParamConstraint;
import com.bloatit.framework.webprocessor.annotations.ParamContainer;
import com.bloatit.framework.webprocessor.annotations.RequestParam;
import com.bloatit.framework.webprocessor.annotations.RequestParam.Role;
import com.bloatit.framework.webprocessor.annotations.tr;
import com.bloatit.framework.webprocessor.context.Context;
import com.bloatit.framework.webprocessor.url.PageNotFoundUrl;
import com.bloatit.framework.webprocessor.url.Url;
import com.bloatit.model.Bug;
import com.bloatit.model.FileMetadata;
import com.bloatit.model.Member;
import com.bloatit.model.Milestone;
import com.bloatit.model.managers.FileMetadataManager;
import com.bloatit.web.actions.LoggedAction;
import com.bloatit.web.url.BugPageUrl;
import com.bloatit.web.url.ReportBugActionUrl;
import com.bloatit.web.url.ReportBugPageUrl;
/**
* A response to a form used to create a new feature
*/
@ParamContainer("feature/bug/doreport")
public final class ReportBugAction extends LoggedAction {
public static final String BUG_TITLE = "bug_title";
public static final String BUG_DESCRIPTION = "bug_description";
public static final String BUG_LEVEL = "bug_level";
public static final String BUG_BATCH = "bug_milestone";
public static final String LANGUAGE_CODE = "bug_description_language";
public static final String ATTACHEMENT_CODE = "attachement";
public static final String ATTACHEMENT_NAME_CODE = "attachement/filename";
public static final String ATTACHEMENT_CONTENT_TYPE_CODE = "attachement/contenttype";
public static final String ATTACHEMENT_DESCRIPTION_CODE = "attachement_description";
@RequestParam(name = BUG_TITLE, role = Role.POST)
@ParamConstraint(max = "120",
maxErrorMsg = @tr("The short description must be 120 chars length max."),
min = "10", minErrorMsg = @tr("The short description must have at least 10 chars."),
optionalErrorMsg = @tr("You forgot to write a short description"))
private final String title;
@ParamConstraint(optionalErrorMsg = @tr("You must indicate a bug description"), min = "10", minErrorMsg = @tr("The description must have at least 10 chars."))
@RequestParam(name = BUG_DESCRIPTION, role = Role.POST)
private final String description;
@ParamConstraint(optionalErrorMsg = @tr("You must indicate a description language"))
@RequestParam(name = LANGUAGE_CODE, role = Role.POST)
private final String lang;
private final ReportBugActionUrl url;
@ParamConstraint(optionalErrorMsg = @tr("You must indicate a bug level"))
@RequestParam(name = BUG_LEVEL, suggestedValue = "MINOR", role = Role.POST)
private final BindedLevel level;
@ParamConstraint(optionalErrorMsg = @tr("A new bug must be linked to a milestone"))
@RequestParam(name = BUG_BATCH, role = Role.GET)
private final Milestone milestone;
@Optional
@RequestParam(name = ATTACHEMENT_CODE, role = Role.POST)
private final String attachement;
@Optional
@RequestParam(name = ATTACHEMENT_NAME_CODE, role = Role.POST)
private final String attachementFileName;
@Optional
@RequestParam(name = ATTACHEMENT_DESCRIPTION_CODE, role = Role.POST)
private final String attachementDescription;
@SuppressWarnings("unused")
@Optional
@RequestParam(name = ATTACHEMENT_CONTENT_TYPE_CODE, role = Role.POST)
private final String attachementContentType;
public ReportBugAction(final ReportBugActionUrl url) {
super(url);
this.url = url;
this.title = url.getTitle();
this.description = url.getDescription();
this.lang = url.getLang();
this.level = url.getLevel();
this.milestone = url.getMilestone();
this.attachement = url.getAttachement();
this.attachementFileName = url.getAttachementFileName();
this.attachementContentType = url.getAttachementContentType();
this.attachementDescription = url.getAttachementDescription();
}
@Override
public Url doProcessRestricted(final Member authenticatedMember) {
final Locale langLocale = new Locale(lang);
final Bug bug = milestone.addBug(authenticatedMember, title, description, langLocale, level.getLevel());
if (attachement != null) {
FileConstraintChecker fcc = new FileConstraintChecker(attachement);
if (!fcc.exists() || !fcc.isFileSmaller(3, SizeUnit.MBYTE)) {
for (String message : fcc.isImageAvatar()) {
session.notifyBad(message);
}
return Context.getSession().pickPreferredPage();
}
final FileMetadata attachementFileMedatata = FileMetadataManager.createFromTempFile(authenticatedMember,
attachement,
attachementFileName,
attachementDescription);
try {
bug.addFile(attachementFileMedatata);
} catch (final UnauthorizedOperationException e) {
session.notifyError(Context.tr("Fail to add the attachement to the bug report."));
throw new ShallNotPassException("Fail to add an attachement to the new bug report.", e);
}
}
return new BugPageUrl(bug);
}
@Override
protected Url doCheckRightsAndEverything(final Member authenticatedMember) {
if (attachement != null && (attachementDescription == null || attachementDescription.isEmpty())) {
session.notifyError(Context.tr("You must enter a description of the attachement if you add an attachement."));
return doProcessErrors();
}
return NO_ERROR;
}
@Override
protected Url doProcessErrors() {
if (milestone != null) {
return new ReportBugPageUrl(milestone.getOffer());
}
return new PageNotFoundUrl();
}
@Override
protected String getRefusalReason() {
return Context.tr("You must be logged in to report a bug.");
}
@Override
protected void transmitParameters() {
session.addParameter(url.getTitleParameter());
session.addParameter(url.getDescriptionParameter());
session.addParameter(url.getMilestoneParameter());
session.addParameter(url.getLevelParameter());
session.addParameter(url.getLangParameter());
session.addParameter(url.getAttachementDescriptionParameter());
}
}
|
package org.codehaus.modello.model;
import org.codehaus.modello.metadata.FieldMetadata;
/**
* @author <a href="mailto:jason@modello.org">Jason van Zyl</a>
* @author <a href="mailto:evenisse@codehaus.org">Emmanuel Venisse</a>
*
* @version $Id$
*/
public class ModelField
extends BaseElement
{
private String type;
private String defaultValue;
private String typeValidator;
private boolean required;
transient private ModelClass modelClass;
public ModelField()
{
super( true );
}
public ModelField( ModelClass modelClass, String name )
{
super( true, name );
this.modelClass = modelClass;
}
// Property accessors
public String getType()
{
return type;
}
public void setType( String type )
{
this.type = type;
}
public String getDefaultValue()
{
return defaultValue;
}
public void setDefaultValue( String defaultValue )
{
this.defaultValue = defaultValue;
}
public String getTypeValidator()
{
return typeValidator;
}
public void setTypeValidator( String typeValidator )
{
this.typeValidator = typeValidator;
}
public boolean isRequired()
{
return required;
}
public void setRequired( boolean required )
{
this.required = required;
}
// Misc
public ModelClass getModelClass()
{
return modelClass;
}
public FieldMetadata getMetadata( String key )
{
return (FieldMetadata) getMetadata( FieldMetadata.class, key );
}
public void initialize( ModelClass modelClass )
{
this.modelClass = modelClass;
if ( defaultValue == null )
{
if ( "boolean".equals( type ) )
{
defaultValue = "false";
}
if ( "float".equals( type ) || "double".equals( type ) )
{
defaultValue = "0.0";
}
if ( "int".equals( type ) || "char".equals( type ) || "short".equals( type ) )
{
defaultValue = "0";
}
}
}
public void validateElement()
throws ModelValidationException
{
validateFieldNotEmpty( "Field", "name", getName() );
validateFieldNotEmpty( "Field " + getName(), "type", type );
String[] primitiveTypes = new String[]{
"boolean",
"char",
"short",
"int",
"long",
"float",
"double",
"String"
};
for ( int i = 0; i < primitiveTypes.length; i++ )
{
String validType = primitiveTypes[i];
if ( type.equals( validType ) )
{
return;
}
}
throw new ModelValidationException( "Field '" + getName() + "': Illegal type: '" + type + "'." );
}
}
|
package com.threerings.gardens.logic;
import java.net.URL;
import java.sql.Date;
import javax.servlet.http.HttpServletRequest;
import com.samskivert.servlet.RedirectException;
import com.samskivert.servlet.user.User;
import com.samskivert.servlet.util.FriendlyException;
import com.samskivert.servlet.util.HTMLUtil;
import com.samskivert.servlet.util.ParameterUtil;
import com.samskivert.text.MessageUtil;
import com.samskivert.velocity.InvocationContext;
import com.threerings.presents.server.InvocationException;
import com.threerings.toybox.data.ToyBoxGameDefinition;
import com.threerings.toybox.server.ToyBoxConfig;
import com.threerings.toybox.server.persist.GameRecord.Status;
import com.threerings.toybox.server.persist.GameRecord;
import com.threerings.gardens.Log;
import com.threerings.gardens.GardensApp;
/**
* Handles the logic behind creating and managing a game's metadata.
*/
public class edit_game extends UserLogic
{
// documentation inherited
public void invoke (InvocationContext ctx, GardensApp app, User user)
throws Exception
{
HttpServletRequest req = ctx.getRequest();
// load up the game if an id was provided
int gameId = ParameterUtil.getIntParameter(
req, "gameid", 0, "error.invalid_gameid");
GameRecord game = null;
if (gameId != 0) {
game = app.getToyBoxRepository().loadGame(gameId);
if (game != null) {
ctx.put("game", game);
}
}
// make sure this user is the maintainer or an admin
if (game != null &&
!(user.userId == game.maintainerId || user.isAdmin())) {
throw new RedirectException(app.getProperty("access_denied_url"));
}
// determine where uploads should be sent
URL rurl = new URL(ToyBoxConfig.getResourceURL());
URL upurl = new URL(rurl.getProtocol(), rurl.getHost(),
req.getContextPath() + "/upload_jar.wm");
ctx.put("upload_url", upurl);
// assume we're updating unless later overridden
ctx.put("action", "update");
// figure out what we're doing
String action = ParameterUtil.getParameter(req, "action", false);
if (action.equals("update")) {
if (game == null) {
throw new FriendlyException("error.no_such_game");
}
// read the parameters over top of the existing game
populateGame(req, game);
// update it in the database
app.getToyBoxRepository().updateGame(game);
ctx.put("status", "edit_game.status.updated");
} else if (action.equals("create")) {
// we're still creating (just in case things fail)
ctx.put("action", "create");
// create a blank game and configure it
game = new GameRecord();
game.setStatus(Status.PENDING);
game.maintainerId = user.userId;
game.host = ToyBoxConfig.getServerHost();
game.digest = "";
game.created = new Date(System.currentTimeMillis());
game.lastUpdated = game.created;
ctx.put("game", game);
// fill in the user supplied information
populateGame(req, game);
// insert it into the repository
app.getToyBoxRepository().insertGame(game);
ctx.put("status", "edit_game.status.created");
// now we can switch back to update mode
ctx.put("action", "update");
} else if (gameId != 0) {
// nothing to do, the game is already in the context
} else {
ctx.put("action", "create");
game = new GameRecord();
game.category = "other";
ctx.put("game", game);
}
}
protected void populateGame (HttpServletRequest req, GameRecord game)
throws Exception
{
// read in and validate our various bits
game.name = requireString(req, "name", 50, true);
game.category = requireString(req, "category", 255, false);
game.definition = requireString(req, "definition", 2500, false);
game.description = requireString(req, "description", 1000, true);
game.instructions = requireString(req, "instructions", 5000, true);
game.credits = requireString(req, "credits", 1000, true);
// TODO: validate definition
try {
ToyBoxGameDefinition gamedef = game.parseGameDefinition();
} catch (InvocationException ie) {
String errmsg = "edit_game.error.malformed_definition";
Throwable cause;
if ((cause = ie.getCause()) != null) {
errmsg = MessageUtil.tcompose(
"edit_game.error.malformed_definition_why",
cause.getMessage());
}
throw new FriendlyException(errmsg);
}
// TODO: set the status to PUBLISHED if all is groovy?
}
protected String requireString (
HttpServletRequest req, String name, int maxLength, boolean entify)
throws Exception
{
String err = MessageUtil.compose("error.missing_field", "f." + name);
String value = ParameterUtil.requireParameter(req, name, err);
if (value.length() > maxLength) {
err = MessageUtil.compose("error.field_too_long", "f." + name,
MessageUtil.taint("" + maxLength));
throw new FriendlyException(err);
}
if (entify) {
value = HTMLUtil.restrictHTML(value, true, true, true);
}
return value;
}
}
|
package fortiss.results;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.knowm.xchart.CategorySeries;
import fortiss.components.Building;
import fortiss.gui.DesignerPanel;
import fortiss.results.widgets.ListWidget;
import memap.media.Strings;
public class MetricsGenerator {
Metrics memapOnMetrics;
Metrics memapOffMetrics;
HashMap<String, BuildingMetrics> buildingMetrics;
public MetricsGenerator(ResultsLibrary detailedResult, ResultsLibrary overviewResult) {
// Global metrics
memapOnMetrics = new MemapOnMetrics(Strings.memapOnModeName, detailedResult, overviewResult);
memapOffMetrics = new MemapOffMetrics(Strings.memapOffModeName, detailedResult, overviewResult);
buildingMetrics = new HashMap<String, BuildingMetrics>();
for (Entry<String, Building> buildingEntry : DesignerPanel.buildings.entrySet()) {
buildingMetrics.put(buildingEntry.getKey(),
new BuildingMetrics(buildingEntry.getKey(), detailedResult, overviewResult));
}
}
public void populateMetricsPanels(SummaryPanel summaryPanel, HashMap<String, MetricsPanel> metricsPanelMap) {
populateSummaryMetrics(summaryPanel);
for (String context : metricsPanelMap.keySet()) {
if (context.equals(Strings.memapOnModeName)) {
populateOptimizationMetrics(context, metricsPanelMap.get(context), memapOnMetrics);
} else {
populateOptimizationMetrics(context, metricsPanelMap.get(context), buildingMetrics.get(context));
}
}
}
private void populateSummaryMetrics(SummaryPanel summaryPanel) {
// COMPARATIVE FIGURES
double perBuildingOptimizationCost = 0;
for (String buildingName : DesignerPanel.buildings.keySet()) {
perBuildingOptimizationCost += buildingMetrics.get(buildingName).getCost();
}
summaryPanel.addComparisonWidget(Strings.performancePanelName, "Cost with " + Strings.memapOnModeName, memapOnMetrics.getCost(),
perBuildingOptimizationCost, Strings.costsUnit, null);
double perBuildingOptimizationCo2Emissions = 0;
for (String buildingName : DesignerPanel.buildings.keySet()) {
perBuildingOptimizationCo2Emissions += buildingMetrics.get(buildingName).getCo2emissions();
}
summaryPanel.addComparisonWidget(Strings.performancePanelName, "CO2 Emissions with " + Strings.memapOnModeName,
memapOnMetrics.getCo2emissions(), perBuildingOptimizationCo2Emissions, Strings.co2EmissionsUnit, null);
// List widget: Operational costs
ListWidget lwMemapOn = summaryPanel.addListWidget(Strings.memapOnModeName, "Operational costs: " + Strings.memapOnModeName, null);
lwMemapOn.addRow("Cost", memapOnMetrics.getCost(), Strings.costsUnit);
lwMemapOn.addRow("CO2", memapOnMetrics.getCo2emissions(), Strings.co2EmissionsUnit);
ListWidget lwMemapOff = summaryPanel.addListWidget(Strings.memapOffModeName,
"Operational costs: " + Strings.memapOffModeName, null);
lwMemapOff.addRow("Cost", perBuildingOptimizationCost, Strings.costsUnit);
lwMemapOff.addRow("CO2", perBuildingOptimizationCo2Emissions, Strings.co2EmissionsUnit);
// // List widget: System energy demand
ListWidget lwDemand = summaryPanel.addListWidget(Strings.performancePanelName, "System Energy Demand", null);
lwDemand.addRow("Electricity", memapOnMetrics.getElectricityDemand(), Strings.energyUnit);
lwDemand.addRow("Heat", memapOnMetrics.getHeatDemand(), Strings.energyUnit);
lwDemand.setPreferredSize(new Dimension(290, 100));
// MEMAP ON - FIGURES
// List widget: Electricity balance : memapOn
ListWidget lwElectricity = summaryPanel.addListWidget(Strings.memapOnModeName, "Electricity balance: " + Strings.memapOnModeName,
null);
lwElectricity.addRow("Total demand", memapOnMetrics.getElectricityDemand(), Strings.energyUnit);
lwElectricity.addRow("Total production", memapOnMetrics.getElectricityProduction(), Strings.energyUnit);
lwElectricity.addRow("Energy charged", memapOnMetrics.getElectricityCharge(), Strings.energyUnit);
lwElectricity.addRow("Energy discharged", memapOnMetrics.getElectricityDischarge(), Strings.energyUnit);
lwElectricity.addRow("Market buying", memapOnMetrics.getElectricityBuy(), Strings.energyUnit);
lwElectricity.addRow("Market selling", memapOnMetrics.getElectricitySell(), Strings.energyUnit);
// List widget: Heat balance
ListWidget lwHeat = summaryPanel.addListWidget(Strings.memapOnModeName, "Heat balance: " + Strings.memapOnModeName, null);
lwHeat.addRow("Total demand", memapOnMetrics.getHeatDemand(), Strings.energyUnit);
lwHeat.addRow("Total production", memapOnMetrics.getHeatProduction(), Strings.energyUnit);
lwHeat.addRow("Energy charged", memapOnMetrics.getHeatCharge(), Strings.energyUnit);
lwHeat.addRow("Energy discharged", memapOnMetrics.getHeatDischarge(), Strings.energyUnit);
lwHeat.addRow("Market buying", memapOnMetrics.getHeatBuy(), Strings.energyUnit);
lwHeat.addRow("Market selling", memapOnMetrics.getHeatSell(), Strings.energyUnit);
// MEMAP OFF - FIGURES
ListWidget lwElectricity2 = summaryPanel.addListWidget(Strings.memapOffModeName,
"Electricity balance: " + Strings.memapOffModeName, null);
lwElectricity2.addRow("Total demand", memapOffMetrics.getElectricityDemand(), Strings.energyUnit);
lwElectricity2.addRow("Total production", memapOffMetrics.getElectricityProduction(), Strings.energyUnit);
lwElectricity2.addRow("Energy charged", memapOffMetrics.getElectricityCharge(), Strings.energyUnit);
lwElectricity2.addRow("Energy discharged", memapOffMetrics.getElectricityDischarge(), Strings.energyUnit);
lwElectricity2.addRow("Market buying", memapOffMetrics.getElectricityBuy(), Strings.energyUnit);
lwElectricity2.addRow("Market selling", memapOffMetrics.getElectricitySell(), Strings.energyUnit);
// List widget: Heat balance
ListWidget lwHeat2 = summaryPanel.addListWidget(Strings.memapOffModeName, "Heat balance: " + Strings.memapOffModeName,
null);
lwHeat2.addRow("Total demand", memapOffMetrics.getHeatDemand(), Strings.energyUnit);
lwHeat2.addRow("Total production", memapOffMetrics.getHeatProduction(), Strings.energyUnit);
lwHeat2.addRow("Energy charged", memapOffMetrics.getHeatCharge(), Strings.energyUnit);
lwHeat2.addRow("Energy discharged", memapOffMetrics.getHeatDischarge(), Strings.energyUnit);
lwHeat2.addRow("Market buying", memapOffMetrics.getHeatBuy(), Strings.energyUnit);
lwHeat2.addRow("Market selling", memapOffMetrics.getHeatSell(), Strings.energyUnit);
HashMap<String, Number> componentUsage = new HashMap<String, Number>();
componentUsage.putAll(memapOnMetrics.getEnergyProducedBySource());
componentUsage.put("Market (Elec. buy)", memapOnMetrics.getElectricityBuy());
componentUsage.put("Market (Heat buy)", memapOnMetrics.getHeatBuy());
summaryPanel.addComponentUsageWidget(Strings.memapOnModeName, "Component usage - " + Strings.memapOnModeName, componentUsage, 3);
HashMap<String, Number> componentUsage2 = new HashMap<String, Number>();
componentUsage2.putAll(memapOffMetrics.getEnergyProducedBySource());
componentUsage2.put("Market (Elec. buy)", memapOffMetrics.getElectricityBuy());
componentUsage2.put("Market (Heat buy)", memapOffMetrics.getHeatBuy());
summaryPanel.addComponentUsageWidget(Strings.memapOffModeName, "Component usage - " + Strings.memapOffModeName,
componentUsage2, 3);
}
/**
* Populates the individual result panels with metrics.
*
* @param contextName {@link Strings#memapOnModeName} or the name of a building
* @param contextPanel the metrics panel that corresponds to the context
* @param metrics the set of metrics of the context
*/
private void populateOptimizationMetrics(String contextName, MetricsPanel contextPanel, Metrics metrics) {
contextPanel.addTitleWidget(contextName);
// Text widget: Total cost (EUR and CO2)
contextPanel.addTextWidget("Total cost", metrics.getCost(), Strings.costsUnit, null);
contextPanel.addTextWidget("Total CO2 Emissions", metrics.getCo2emissions(), Strings.co2EmissionsUnit, null);
// Text widget: Energy demanded
contextPanel.addTextWidget(Strings.heatDemand, metrics.getHeatDemand(), Strings.energyUnit, null);
contextPanel.addTextWidget(Strings.electricityDemand, metrics.getElectricityDemand(), Strings.energyUnit, null);
// List widget: Heat balance
ListWidget lwHeat = contextPanel.addListWidget(Strings.memapOnModeName, "Heat balance: " + contextName, null);
lwHeat.addRow("Total demand", metrics.getHeatDemand(), Strings.energyUnit);
lwHeat.addRow("Total production", metrics.getHeatProduction(), Strings.energyUnit);
lwHeat.addRow("Energy charged", metrics.getHeatCharge(), Strings.energyUnit);
lwHeat.addRow("Energy discharged", metrics.getHeatDischarge(), Strings.energyUnit);
lwHeat.addRow("Market buying", metrics.getHeatBuy(), Strings.energyUnit);
lwHeat.addRow("Market selling", metrics.getHeatSell(), Strings.energyUnit);
// List widget: Electricity balance : memapOn
ListWidget lwElectricity = contextPanel.addListWidget(contextName, "Electricity balance: " + contextName,
null);
lwElectricity.addRow("Total demand", metrics.getElectricityDemand(), Strings.energyUnit);
lwElectricity.addRow("Total production", metrics.getElectricityProduction(), Strings.energyUnit);
lwElectricity.addRow("Energy charged", metrics.getElectricityCharge(), Strings.energyUnit);
lwElectricity.addRow("Energy discharged", metrics.getElectricityDischarge(), Strings.energyUnit);
lwElectricity.addRow("Market buying", metrics.getElectricityBuy(), Strings.energyUnit);
lwElectricity.addRow("Market selling", metrics.getElectricitySell(), Strings.energyUnit);
// Bar widget: Energy produced vs demanded per time step
List<CategorySeries> energySeries = new ArrayList<CategorySeries>();
energySeries.add(new CategorySeries("Electricity Demand ", metrics.getTime(),
metrics.getElectricityDemandInTime(), null, null));
energySeries.add(new CategorySeries("Electricity Production", metrics.getTime(),
metrics.getElectricityProducedInTime(), null, null));
energySeries
.add(new CategorySeries("Heat Demand ", metrics.getTime(), metrics.getHeatDemandInTime(), null, null));
energySeries.add(
new CategorySeries("Heat Production", metrics.getTime(), metrics.getHeatProducedInTime(), null, null));
contextPanel.addBarPlotWidget("Energy produced and demanded", "Time steps", "Power [kWh]", 1600, 400,
energySeries, "* Storages are not considered energy producers");
// Pie widget: Energy produced by type
HashMap<String, Number> energyProductionByType = new HashMap<String, Number>();
energyProductionByType.put("Electricity", metrics.getElectricityProduction());
energyProductionByType.put("Heat", metrics.getHeatProduction());
energyProductionByType.put("Market (Elec. buy)", metrics.getHeatBuy());
energyProductionByType.put("Market (Heat buy)", metrics.getElectricityBuy());
contextPanel.addPiePlotWidget("Energy produced by type", 400, 400, energyProductionByType,
"* Storages are not considered energy producers");
// Bar widget: Energy produced by type and building
if (metrics.context.equals(Strings.memapOnModeName)) {
List<CategorySeries> energyByBuilding = new ArrayList<CategorySeries>();
HashMap<String, Double> electricityProductionByBuilding = ((MemapOnMetrics) metrics)
.getElectricityProductionByBuilding();
energyByBuilding.add(new CategorySeries("Electricity Production",
new ArrayList<String>(electricityProductionByBuilding.keySet()),
new ArrayList<Number>(electricityProductionByBuilding.values()), null, null));
HashMap<String, Double> heatProductionByBuilding = ((MemapOnMetrics) metrics).getHeatProductionByBuilding();
energyByBuilding
.add(new CategorySeries("Heat Production", new ArrayList<String>(heatProductionByBuilding.keySet()),
new ArrayList<Number>(heatProductionByBuilding.values()), null, null));
contextPanel.addBarPlotWidget("Energy produced by type", "Buildings", "Energy [kWh]", 400, 400,
energyByBuilding, "* Storages are not considered energy producers");
}
HashMap<String, Number> componentUsage = new HashMap<String, Number>();
componentUsage.putAll(metrics.getEnergyProducedBySource());
componentUsage.put("Market (Elec. buy)", metrics.getElectricityBuy());
componentUsage.put("Market (Heat buy)", metrics.getHeatBuy());
contextPanel.addComponentUsageWidget(contextName, "Component usage - " + contextName, componentUsage, 3);
}
}
|
package com.mysema.query.mongodb;
import java.net.UnknownHostException;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mysema.query.mongodb.domain.Item;
import com.mysema.query.mongodb.domain.QUser;
import com.mysema.query.mongodb.domain.User;
import com.mysema.query.mongodb.morphia.MorphiaQuery;
import com.mysema.query.types.Predicate;
import com.mysema.testutil.ExternalDB;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.*;
@Category(ExternalDB.class)
public class JoinTest {
private final Mongo mongo;
private final Morphia morphia;
private final Datastore ds;
private final String dbname = "testdb";
private final QUser user = QUser.user;
private final QUser friend = new QUser("friend");
private final QUser friend2 = new QUser("friend2");
private final QUser enemy = new QUser("enemy");
public JoinTest() throws UnknownHostException, MongoException {
mongo = new Mongo();
morphia = new Morphia().map(User.class).map(Item.class);
ds = morphia.createDatastore(mongo, dbname);
}
@Before
public void before() throws UnknownHostException, MongoException {
ds.delete(ds.createQuery(User.class));
User friend1 = new User("Max", null);
User friend2 = new User("Jack", null);
User friend3 = new User("Bob", null);
ds.save(friend1, friend2, friend3);
User user1 = new User("Jane", null, friend1);
User user2 = new User("Mary", null, user1);
User user3 = new User("Ann", null, friend3);
ds.save(user1, user2, user3);
User user4 = new User("Mike", null);
user4.setFriend(user2);
user4.setEnemy(user3);
ds.save(user4);
User user5 = new User("Bart", null);
user5.addFriend(user2);
user5.addFriend(user3);
ds.save(user5);
}
@Test
public void Count() {
assertEquals(1, where().join(user.friend(), friend).on(friend.firstName.eq("Max")).count());
assertEquals(1, where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Max")).count());
assertEquals(0, where(user.firstName.eq("Mary")).join(user.friend(), friend).on(friend.firstName.eq("Max")).count());
assertEquals(0, where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Jack")).count());
}
@Test
public void Count_Collection() {
assertEquals(1, where().join(user.friends, friend).on(friend.firstName.eq("Mary")).count());
assertEquals(1, where().join(user.friends, friend).on(friend.firstName.eq("Ann")).count());
assertEquals(1, where().join(user.friends, friend).on(friend.firstName.eq("Ann").or(friend.firstName.eq("Mary"))).count());
assertEquals(1, where(user.firstName.eq("Bart")).join(user.friends, friend).on(friend.firstName.eq("Mary")).count());
assertEquals(0, where().join(user.friends, friend).on(friend.firstName.eq("Max")).count());
}
@Test
public void Exists() {
assertTrue(where().join(user.friend(), friend).on(friend.firstName.eq("Max")).exists());
assertTrue(where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Max")).exists());
assertFalse(where(user.firstName.eq("Mary")).join(user.friend(), friend).on(friend.firstName.eq("Max")).exists());
assertFalse(where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Jack")).exists());
}
@Test
public void Exists_Collection() {
assertTrue(where().join(user.friends, friend).on(friend.firstName.eq("Mary")).exists());
assertTrue(where(user.firstName.eq("Bart")).join(user.friends, friend).on(friend.firstName.eq("Mary")).exists());
}
@Test
public void List() {
assertEquals(1, where().join(user.friend(), friend).on(friend.firstName.eq("Max")).list().size());
assertEquals(1, where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Max")).list().size());
assertEquals(0, where(user.firstName.eq("Mary")).join(user.friend(), friend).on(friend.firstName.eq("Max")).list().size());
assertEquals(0, where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Jack")).list().size());
}
public void List_Collection() {
assertEquals(1, where().join(user.friends, friend).on(friend.firstName.eq("Mary")).list().size());
}
@Test
public void Single() {
assertEquals("Jane", where().join(user.friend(), friend).on(friend.firstName.eq("Max")).singleResult().getFirstName());
assertEquals("Jane", where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Max")).singleResult().getFirstName());
assertNull(where(user.firstName.eq("Mary")).join(user.friend(), friend).on(friend.firstName.eq("Max")).singleResult());
assertNull(where(user.firstName.eq("Jane")).join(user.friend(), friend).on(friend.firstName.eq("Jack")).singleResult());
}
@Test
public void Single_Collection() {
assertEquals("Bart", where().join(user.friends, friend).on(friend.firstName.eq("Mary")).singleResult().getFirstName());
}
@Test
public void Double() {
assertEquals("Mike", where()
.join(user.friend(), friend).on(friend.firstName.isNotNull())
.join(user.enemy(), enemy).on(enemy.firstName.isNotNull())
.singleResult().getFirstName());
}
@Test
public void Double2() {
assertEquals("Mike", where()
.join(user.friend(), friend).on(friend.firstName.eq("Mary"))
.join(user.enemy(), enemy).on(enemy.firstName.eq("Ann"))
.singleResult().getFirstName());
}
@Test
public void Deep() {
// Mike -> Mary -> Jane
assertEquals("Mike", where()
.join(user.friend(), friend).on(friend.firstName.isNotNull())
.join(friend.friend(), friend2).on(friend2.firstName.eq("Jane"))
.singleResult().getFirstName());
}
private MongodbQuery<User> query() {
return new MorphiaQuery<User>(morphia, ds, user);
}
private MongodbQuery<User> where(Predicate ... e) {
return query().where(e);
}
}
|
package railo.runtime.orm.hibernate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import railo.commons.lang.StringUtil;
import railo.runtime.Component;
import railo.runtime.ComponentPro;
import railo.runtime.PageContext;
import railo.runtime.component.Property;
import railo.runtime.db.DatasourceConnection;
import railo.runtime.exp.PageException;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.orm.ORMConfiguration;
import railo.runtime.orm.ORMEngine;
import railo.runtime.orm.ORMException;
import railo.runtime.text.xml.XMLUtil;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.List;
import railo.runtime.type.Struct;
import railo.runtime.type.StructImpl;
import railo.runtime.type.dt.DateTimeImpl;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.ComponentUtil;
public class HBMCreator {
private static final Collection.Key PROPERTY = KeyImpl.getInstance("property");
private static final Collection.Key FIELD_TYPE = KeyImpl.getInstance("fieldType");
private static final Collection.Key TYPE = KeyImpl.getInstance("type");
public static void createXMLMapping(PageContext pc,DatasourceConnection dc, Component cfc,ORMConfiguration ormConf,Element hibernateMapping,HibernateORMEngine engine) throws PageException {
String str;
Boolean b;
Integer i;
// MUST Support for embeded objects
ComponentPro cfci = ComponentUtil.toComponentPro(cfc);
Struct meta = cfci.getMetaData(pc);
Property[] _props = cfci.getProperties(true);
if(_props.length==0 && ormConf.useDBForMapping()){
_props=HibernateUtil.createPropertiesFromTable(dc,getTableName(engine,pc, meta, cfci));
}
Map<String, PropertyCollection> joins=new HashMap<String, PropertyCollection>();
PropertyCollection propColl = splitJoins(engine,cfc,joins, _props);
// create class element and attach
Document doc = XMLUtil.getDocument(hibernateMapping);
StringBuilder comment=new StringBuilder();
comment.append("\nsource:").append(cfci.getPageSource().getDisplayPath());
comment.append("\ncompilation-time:").append(new DateTimeImpl(ComponentUtil.getCompileTime(pc,cfci.getPageSource()),false)).append("\n");
hibernateMapping.appendChild(doc.createComment(comment.toString()));
String extend = cfc.getExtends();
Element clazz;
boolean isClass=StringUtil.isEmpty(extend);
//print.e(cfc.getAbsName()+";"+isClass+" -> "+cfci.getBaseAbsName()+":"+cfci.isBasePeristent());
if(!isClass && !cfci.isBasePeristent()) {
isClass=true;
}
Element join=null;
boolean doTable=true;
if(isClass) {
clazz = doc.createElement("class");
hibernateMapping.appendChild(clazz);
}
// extended CFC
else{
String ext = List.last(extend,'.').trim();
String discriminatorValue = toString(engine,cfc,null,meta,"discriminatorValue");
if(!StringUtil.isEmpty(discriminatorValue,true)) {
doTable=false;
clazz = doc.createElement("subclass");
hibernateMapping.appendChild(clazz);
//addClassAttributes(classNode);
clazz.setAttribute("extends", ext);
clazz.setAttribute("discriminator-value", discriminatorValue);
String joincolumn = toString(engine,cfc,null,meta,"joincolumn",false);
if(!StringUtil.isEmpty(joincolumn)){
join = doc.createElement("join");
clazz.appendChild(join);
doTable=true;
Element key = doc.createElement("key");
join.appendChild(key);
key.setAttribute("column", formatColumn(joincolumn));
}
}
else {
clazz = doc.createElement("joined-subclass");
hibernateMapping.appendChild(clazz);
clazz.setAttribute("extends",ext);
Element key = doc.createElement("key");
clazz.appendChild(key);
key.setAttribute("column", formatColumn(toString(engine,cfc,null,meta,"joincolumn",true)));
}
}
//lazy
//clazz.setAttribute("lazy", "true");
//createXMLMappingTuplizer(clazz,pc);
addGeneralClassAttributes(pc,ormConf,engine,cfc,meta,clazz);
String tableName=getTableName(engine,pc,meta,cfc);
if(join!=null) clazz=join;
if(doTable)addGeneralTableAttributes(pc,ormConf,engine,cfc,meta,clazz);
Struct columnsInfo=null;
if(ormConf.useDBForMapping()){
columnsInfo = engine.getTableInfo(dc,getTableName(engine,pc, meta, cfci),engine);
}
if(isClass)setCacheStrategy(engine,cfc,null,doc, meta, clazz);
if(isClass) addId(cfc,doc,clazz,pc,meta,propColl,columnsInfo,tableName,engine);
// discriminator
addDiscriminator(engine,cfc,doc,clazz,pc,meta);
// version
if(isClass)addVersion(cfc,clazz,pc, propColl,columnsInfo,tableName,engine);
// property
addProperty(cfc,clazz,pc, propColl,columnsInfo,tableName,engine);
// relations
addRelation(cfc,clazz,pc, propColl,columnsInfo,tableName,engine,ormConf);
// collection
addCollection(cfc,clazz,pc, propColl,columnsInfo,tableName,engine,ormConf);
// join
addJoin(cfc,clazz,pc, joins,columnsInfo,tableName,engine,ormConf);
}
private static void addId(Component cfc,Document doc, Element clazz, PageContext pc, Struct meta, PropertyCollection propColl, Struct columnsInfo, String tableName, HibernateORMEngine engine) throws PageException {
Property[] _ids = getIds(engine,cfc,propColl);
//Property[] _ids = ids.toArray(new Property[ids.size()]);
if(_ids.length==1)
createXMLMappingId(cfc,clazz,pc, _ids[0],columnsInfo,tableName,engine);
else if(_ids.length>1)
createXMLMappingCompositeId(cfc,clazz,pc, _ids,columnsInfo,tableName,engine);
else
throw new HibernateException(engine,cfc,"missing id property for entity ["+tableName+"]");
}
public static PropertyCollection splitJoins(HibernateORMEngine engine,Component cfc,Map<String, PropertyCollection> joins,Property[] props) {
Struct sct=new StructImpl();
ArrayList<Property> others = new ArrayList<Property>();
java.util.List<Property> list;
String table;
Property prop;
String fieldType;
boolean isJoin;
for(int i=0;i<props.length;i++){
prop=props[i];
table=getTable(engine,cfc,prop);
// joins
if(!StringUtil.isEmpty(table,true)){
isJoin=true;
// wrong field type
try {
fieldType = toString(engine, cfc, prop, sct, FIELD_TYPE,false);
if("collection".equalsIgnoreCase(fieldType)) isJoin=false;
else if("primary".equals(fieldType)) isJoin=false;
else if("version".equals(fieldType)) isJoin=false;
else if("timestamp".equals(fieldType)) isJoin=false;
}
catch (ORMException e) {}
// missing column
String columns=null;
try {
if(isRelation(props[i])){
columns=toString(engine,cfc,props[i], prop.getMeta(), "fkcolumn");
}
else {
columns=toString(engine,cfc,props[i], prop.getMeta(), "joincolumn");
}
}
catch(ORMException e){}
if(StringUtil.isEmpty(columns)) isJoin=false;
if(isJoin){
table=table.trim();
list = (java.util.List<Property>) sct.get(table,null);
if(list==null){
list=new ArrayList<Property>();
sct.setEL(table, list);
}
list.add(prop);
continue;
}
}
others.add(prop);
}
// fill to joins
Key[] keys = sct.keys();
Key key;
for(int i=0;i<keys.length;i++){
key=keys[i];
list=(java.util.List<Property>) sct.get(key,null);
joins.put(key.getString(), new PropertyCollection(key.getString(),list));
}
return new PropertyCollection(null,others);
}
private static boolean isJoin(HibernateORMEngine engine,Component cfc,Property prop) {
return !StringUtil.isEmpty(getTable(engine,cfc,prop),true);
}
private static String getTable(HibernateORMEngine engine,Component cfc,Property prop) {
try {
return toString(engine,cfc,prop, prop.getMeta(), "table");
} catch (ORMException e) {
return null;
}
}
private static boolean hasTable(HibernateORMEngine engine,Component cfc,Property prop,String tableName) {
String t = getTable(engine,cfc,prop);
boolean left=StringUtil.isEmpty(t,true);
boolean right=StringUtil.isEmpty(tableName,true);
if(left && right) return true;
if(left || right) return false;
return tableName.trim().equalsIgnoreCase(t.trim());
}
public static Property[] getIds(HibernateORMEngine engine,Component cfc,PropertyCollection pc) {
return getIds(engine,cfc,pc.getProperties(), pc.getTableName(),false);
}
public static Property[] getIds(HibernateORMEngine engine,Component cfc,Property[] props,String tableName, boolean ignoreTableName) {
ArrayList<Property> ids=new ArrayList<Property>();
for(int y=0;y<props.length;y++){
if(!ignoreTableName && !hasTable(engine,cfc,props[y], tableName)) continue;
String fieldType = Caster.toString(props[y].getMeta().get(FIELD_TYPE,null),null);
if("id".equalsIgnoreCase(fieldType) || List.listFindNoCaseIgnoreEmpty(fieldType,"id",',')!=-1)
ids.add(props[y]);
}
// no id field defined
if(ids.size()==0) {
String fieldType;
for(int y=0;y<props.length;y++){
if(!ignoreTableName && !hasTable(engine,cfc,props[y], tableName)) continue;
fieldType = Caster.toString(props[y].getMeta().get(FIELD_TYPE,null),null);
if(StringUtil.isEmpty(fieldType,true) && props[y].getName().equalsIgnoreCase("id")){
ids.add(props[y]);
props[y].getMeta().setEL(FIELD_TYPE, "id");
}
}
}
// still no id field defined
if(ids.size()==0 && props.length>0) {
String owner = props[0].getOwnerName();
if(!StringUtil.isEmpty(owner)) owner=List.last(owner, '.').trim();
String fieldType;
if(!StringUtil.isEmpty(owner)){
String id=owner+"id";
for(int y=0;y<props.length;y++){
if(!ignoreTableName && !hasTable(engine,cfc,props[y], tableName)) continue;
fieldType = Caster.toString(props[y].getMeta().get(FIELD_TYPE,null),null);
if(StringUtil.isEmpty(fieldType,true) && props[y].getName().equalsIgnoreCase(id)){
ids.add(props[y]);
props[y].getMeta().setEL(FIELD_TYPE, "id");
}
}
}
}
return ids.toArray(new Property[ids.size()]);
}
private static void addVersion(Component cfc,Element clazz, PageContext pc,PropertyCollection propColl, Struct columnsInfo, String tableName,HibernateORMEngine engine) throws PageException {
Property[] props = propColl.getProperties();
for(int y=0;y<props.length;y++){
String fieldType = Caster.toString(props[y].getMeta().get("fieldType",null),null);
if("version".equalsIgnoreCase(fieldType))
createXMLMappingVersion(engine,clazz,pc, cfc,props[y]);
else if("timestamp".equalsIgnoreCase(fieldType))
createXMLMappingTimestamp(engine,clazz,pc,cfc, props[y]);
}
}
private static void addCollection(Component cfc,Element clazz, PageContext pc,PropertyCollection propColl, Struct columnsInfo, String tableName,HibernateORMEngine engine, ORMConfiguration ormConf) throws PageException {
Property[] props = propColl.getProperties();
for(int y=0;y<props.length;y++){
String fieldType = Caster.toString(props[y].getMeta().get("fieldType","column"),"column");
if("collection".equalsIgnoreCase(fieldType))
createXMLMappingCollection(clazz,pc, cfc,props[y],ormConf,engine);
}
}
private static void addJoin(Component cfc,Element clazz, PageContext pc,Map<String, PropertyCollection> joins, Struct columnsInfo, String tableName,HibernateORMEngine engine, ORMConfiguration ormConf) throws PageException {
Iterator<Entry<String, PropertyCollection>> it = joins.entrySet().iterator();
Entry<String, PropertyCollection> entry;
while(it.hasNext()){
entry = it.next();
PropertyCollection coll = entry.getValue();
addJoin(cfc,engine,pc,columnsInfo,ormConf,clazz,entry.getValue());
}
}
private static void addJoin(Component cfc,HibernateORMEngine engine,PageContext pc,Struct columnsInfo, ORMConfiguration ormConf, Element clazz, PropertyCollection coll) throws PageException {
String table = coll.getTableName();
Property[] properties = coll.getProperties();
if(properties.length==0) return;
Document doc = XMLUtil.getDocument(clazz);
Element join = doc.createElement("join");
clazz.appendChild(join);
join.setAttribute("table", escape(coll.getTableName()));
//addTableInfo(joinNode, table, schema, catalog);
Property first = properties[0];
String schema = null, catalog=null, mappedBy=null, columns=null;
if(isRelation(first)){
catalog=toString(engine,cfc,first, first.getMeta(), "linkcatalog");
schema=toString(engine,cfc,first, first.getMeta(), "linkschema");
columns=toString(engine,cfc,first, first.getMeta(), "fkcolumn");
}
else {
catalog=toString(engine,cfc,first, first.getMeta(), "catalog");
schema=toString(engine,cfc,first, first.getMeta(), "schema");
mappedBy=toString(engine,cfc,first, first.getMeta(), "mappedby");
columns=toString(engine,cfc,first, first.getMeta(), "joincolumn");
}
if(!StringUtil.isEmpty(catalog)) join.setAttribute("catalog", catalog);
if(!StringUtil.isEmpty(schema)) join.setAttribute("schema", schema);
Element key = doc.createElement("key");
join.appendChild(key);
if(!StringUtil.isEmpty(mappedBy)) key.setAttribute("property-ref", mappedBy);
setColumn(doc, key, columns);
addProperty(cfc,join,pc, coll,columnsInfo,table,engine);
int count=addRelation(cfc,join,pc, coll,columnsInfo,table,engine, ormConf);
if(count>0) join.setAttribute("inverse", "true");
}
private static int addRelation(Component cfc,Element clazz, PageContext pc,PropertyCollection propColl, Struct columnsInfo, String tableName,HibernateORMEngine engine, ORMConfiguration ormConf) throws PageException {
Property[] props = propColl.getProperties();
int count=0;
for(int y=0;y<props.length;y++){
String fieldType = Caster.toString(props[y].getMeta().get("fieldType","column"),"column");
if("one-to-one".equalsIgnoreCase(fieldType)){
createXMLMappingOneToOne(clazz,pc, cfc,props[y],engine);
count++;
}
else if("many-to-one".equalsIgnoreCase(fieldType)){
createXMLMappingManyToOne(clazz,pc, cfc,props[y],engine);
count++;
}
else if("one-to-many".equalsIgnoreCase(fieldType)){
createXMLMappingOneToMany(cfc,engine,propColl,ormConf,clazz,pc, props[y]);
count++;
}
else if("many-to-many".equalsIgnoreCase(fieldType)){
createXMLMappingManyToMany(cfc,engine,propColl,clazz,pc, props[y],ormConf);
count++;
}
}
return count;
}
private static boolean isRelation(Property prop) {
String fieldType = Caster.toString(prop.getMeta().get("fieldType","column"),"column");
if(StringUtil.isEmpty(fieldType,true)) return false;
fieldType=fieldType.toLowerCase().trim();
if("one-to-one".equals(fieldType)) return true;
if("many-to-one".equals(fieldType)) return true;
if("one-to-many".equals(fieldType)) return true;
if("many-to-many".equals(fieldType)) return true;
return false;
}
private static void addProperty(Component cfc,Element clazz, PageContext pc, PropertyCollection propColl, Struct columnsInfo, String tableName, HibernateORMEngine engine) throws ORMException {
Property[] props = propColl.getProperties();
for(int y=0;y<props.length;y++){
String fieldType = Caster.toString(props[y].getMeta().get("fieldType","column"),"column");
if("column".equalsIgnoreCase(fieldType))
createXMLMappingProperty(clazz,pc,cfc, props[y],columnsInfo,tableName,engine);
}
}
private static void addDiscriminator(HibernateORMEngine engine,Component cfc,Document doc,Element clazz, PageContext pc,Struct meta) throws ORMException {
String str = toString(engine,cfc,null,meta,"discriminatorColumn");
if(!StringUtil.isEmpty(str,true)){
Element disc = doc.createElement("discriminator");
clazz.appendChild(disc);
disc.setAttribute("column",str);
}
}
private static void addGeneralClassAttributes(PageContext pc, ORMConfiguration ormConf, HibernateORMEngine engine, Component cfc, Struct meta, Element clazz) throws PageException {
// name
clazz.setAttribute("node", HibernateCaster.toComponentName(cfc));
// entity-name
String str=toString(engine,cfc,null,meta,"entityname");
if(StringUtil.isEmpty(str,true)) str=HibernateCaster.getEntityName(pc,cfc);
clazz.setAttribute("entity-name",str);
// batch-size
Integer i = toInteger(engine,cfc,meta,"batchsize");
if(i!=null && i.intValue()>0)clazz.setAttribute("batch-size",Caster.toString(i));
// dynamic-insert
Boolean b = toBoolean(engine,cfc,meta,"dynamicinsert");
if(b!=null && b.booleanValue())clazz.setAttribute("dynamic-insert","true");
// dynamic-update
b=toBoolean(engine,cfc,meta,"dynamicupdate");
if(b!=null && b.booleanValue())clazz.setAttribute("dynamic-update","true");
// lazy
b=toBoolean(engine,cfc,meta,"lazy");
if(b==null) b=Boolean.TRUE;
clazz.setAttribute("lazy",Caster.toString(b.booleanValue()));
// select-before-update
b=toBoolean(engine,cfc,meta,"selectbeforeupdate");
if(b!=null && b.booleanValue())clazz.setAttribute("select-before-update","true");
// optimistic-lock
str=toString(engine,cfc,null,meta,"optimisticLock");
if(!StringUtil.isEmpty(str,true)) {
str=str.trim().toLowerCase();
if("all".equals(str) || "dirty".equals(str) || "none".equals(str) || "version".equals(str))
clazz.setAttribute("optimistic-lock",str);
else
throw new HibernateException(engine,cfc,"invalid value ["+str+"] for attribute [optimisticlock] of tag [component], valid values are [all,dirty,none,version]");
}
// read-only
b=toBoolean(engine,cfc,meta,"readOnly");
if(b!=null && b.booleanValue()) clazz.setAttribute("mutable", "false");
// rowid
str=toString(engine,cfc,null,meta,"rowid");
if(!StringUtil.isEmpty(str,true)) clazz.setAttribute("rowid",str);
// where
str=toString(engine,cfc,null,meta,"where");
if(!StringUtil.isEmpty(str,true)) clazz.setAttribute("where", str);
}
private static void addGeneralTableAttributes(PageContext pc, ORMConfiguration ormConf, HibernateORMEngine engine, Component cfc, Struct meta, Element clazz) throws PageException {
// table
clazz.setAttribute("table",escape(getTableName(engine,pc,meta,cfc)));
// catalog
String str = toString(engine,cfc,null,meta,"catalog");
if(str==null)// empty string is allowed as input
str=ormConf.getCatalog();
if(!StringUtil.isEmpty(str,true)) clazz.setAttribute("catalog", str);
// schema
str=toString(engine,cfc,null,meta,"schema");
if(str==null)// empty string is allowed as input
str=ormConf.getSchema();
if(!StringUtil.isEmpty(str,true)) clazz.setAttribute( "schema", str);
}
private static String escape(String str) {
if(HibernateUtil.isKeyword(str)) return "`"+str+"`";
return str;
}
private static String getTableName(HibernateORMEngine engine,PageContext pc, Struct meta, Component cfc) throws ORMException {
String tableName=toString(engine,cfc,null,meta,"table");
if(StringUtil.isEmpty(tableName,true))
tableName=HibernateCaster.getEntityName(pc, cfc);
return tableName;
}
private static void createXMLMappingCompositeId(Component cfc,Element clazz, PageContext pc,Property[] props,Struct columnsInfo,String tableName,HibernateORMEngine engine) throws PageException {
Struct meta;
Document doc = XMLUtil.getDocument(clazz);
Element cid = doc.createElement("composite-id");
clazz.appendChild(cid);
//cid.setAttribute("mapped","true");
Property prop;
// ids
for(int y=0;y<props.length;y++){
prop=props[y];
meta = prop.getMeta();
Element key = doc.createElement("key-property");
cid.appendChild(key);
// name
key.setAttribute("name",prop.getName());
// column
Element column = doc.createElement("column");
key.appendChild(column);
String str = toString(engine,cfc,prop,meta,"column");
if(StringUtil.isEmpty(str,true)) str=prop.getName();
column.setAttribute("name",formatColumn(str));
ColumnInfo info=getColumnInfo(columnsInfo,tableName,str,engine,null);
str = toString(engine,cfc,prop,meta,"sqltype");
if(!StringUtil.isEmpty(str,true)) column.setAttribute("sql-type",str);
str = toString(engine,cfc,prop,meta,"length");
if(!StringUtil.isEmpty(str,true)) column.setAttribute("length",str);
/*if(info!=null){
column.setAttribute("sql-type",info.getTypeName());
column.setAttribute("length",Caster.toString(info.getSize()));
}*/
// type
//str=getType(info,prop,meta,"long"); //MUSTMUST
//key.setAttribute("type", str);
String generator=toString(engine,cfc,prop,meta,"generator");
String type = getType(engine,info,cfc,prop,meta,getDefaultTypeForGenerator(generator,"string"));
if(!StringUtil.isEmpty(type))key.setAttribute("type", type);
}
// many-to-one
String fieldType;
for(int y=0;y<props.length;y++){
prop=props[y];
meta = prop.getMeta();
fieldType = toString(engine,cfc,prop,meta,"fieldType");
if(List.listFindNoCaseIgnoreEmpty(fieldType,"many-to-one",',')==-1)continue;
Element key = doc.createElement("key-many-to-one");
cid.appendChild(key);
// name
key.setAttribute("name",prop.getName());
// entity-name
setForeignEntityName(pc, engine,cfc,prop, meta, key,false);
// fkcolum
String str=toString(engine,cfc,prop,meta,"fkcolumn");
setColumn(doc, key, str);
// lazy
str=toString(engine,cfc,prop,meta,"lazy");
key.setAttribute("lazy",str);
}
}
private static void createXMLMappingId(Component cfc,Element clazz, PageContext pc,Property prop,Struct columnsInfo,String tableName,HibernateORMEngine engine) throws PageException {
Struct meta = prop.getMeta();
String str;
Integer i;
Document doc = XMLUtil.getDocument(clazz);
Element id = doc.createElement("id");
clazz.appendChild(id);
// access
str=toString(engine,cfc,prop,meta,"access");
if(!StringUtil.isEmpty(str,true))id.setAttribute("access", str);
// name
id.setAttribute("name",prop.getName());
// column
Element column = doc.createElement("column");
id.appendChild(column);
str=toString(engine,cfc,prop,meta,"column");
if(StringUtil.isEmpty(str,true)) str=prop.getName();
column.setAttribute("name",formatColumn(str));
ColumnInfo info=getColumnInfo(columnsInfo,tableName,str,engine,null);
StringBuilder foreignCFC=new StringBuilder();
String generator=createXMLMappingGenerator(engine,id,pc,cfc,prop,foreignCFC);
str = toString(engine,cfc,prop,meta,"length");
if(!StringUtil.isEmpty(str,true)) column.setAttribute("length",str);
// type
String type = getType(engine,info,cfc,prop,meta,getDefaultTypeForGenerator(engine,generator,foreignCFC));
//print.o(prop.getName()+":"+type+"::"+getDefaultTypeForGenerator(engine,generator,foreignCFC));
if(!StringUtil.isEmpty(type))id.setAttribute("type", type);
// unsaved-value
str=toString(engine,cfc,prop,meta,"unsavedValue");
if(!StringUtil.isEmpty(str,true))id.setAttribute("unsaved-value", str);
}
private static String getDefaultTypeForGenerator(HibernateORMEngine engine, String generator,StringBuilder foreignCFC) {
String value = getDefaultTypeForGenerator(generator, null);
if(value!=null) return value;
if("foreign".equalsIgnoreCase(generator)) {
if(!StringUtil.isEmpty(foreignCFC)) {
try {
Component cfc = engine.getEntityByCFCName(foreignCFC.toString(), false);
if(cfc!=null){
ComponentPro cfcp = ComponentUtil.toComponentPro(cfc);
Property[] ids = getIds(engine,cfc,cfcp.getProperties(true),null,true);
if(!ArrayUtil.isEmpty(ids)){
Property id = ids[0];
id.getMeta();
Struct meta = id.getMeta();
if(meta!=null){
String type=Caster.toString(meta.get(TYPE,null));
if(!StringUtil.isEmpty(type) && (!type.equalsIgnoreCase("any") && !type.equalsIgnoreCase("object"))){
return type;
}
else {
String g=Caster.toString(meta.get("generator",null));
if(!StringUtil.isEmpty(g)){
return getDefaultTypeForGenerator(engine,g,foreignCFC);
}
}
}
}
}
}
catch(Throwable t){}
}
return "string";
}
return "string";
}
private static String getDefaultTypeForGenerator(String generator,String defaultValue) {
if("increment".equalsIgnoreCase(generator)) return "integer";
if("identity".equalsIgnoreCase(generator)) return "integer";
if("native".equalsIgnoreCase(generator)) return "integer";
if("seqhilo".equalsIgnoreCase(generator)) return "string";
if("uuid".equalsIgnoreCase(generator)) return "string";
if("guid".equalsIgnoreCase(generator)) return "string";
if("select".equalsIgnoreCase(generator)) return "string";
return defaultValue;
}
private static String getType(HibernateORMEngine engine,ColumnInfo info, Component cfc,Property prop,Struct meta,String defaultValue) throws ORMException {
// ormType
String type = toString(engine,cfc,prop,meta,"ormType");
//type=HibernateCaster.toHibernateType(info,type,null);
// dataType
if(StringUtil.isEmpty(type,true)){
type=toString(engine,cfc,prop,meta,"dataType");
//type=HibernateCaster.toHibernateType(info,type,null);
}
// type
if(StringUtil.isEmpty(type,true)){
type=prop.getType();
//type=HibernateCaster.toHibernateType(info,type,null);
}
// type from db info
if(StringUtil.isEmpty(type,true)){
if(info!=null){
type=info.getTypeName();
//type=HibernateCaster.toHibernateType(info,type,defaultValue);
}
else return defaultValue;
}
return HibernateCaster.toHibernateType(info,type,defaultValue);
}
private static ColumnInfo getColumnInfo(Struct columnsInfo,String tableName,String columnName,ORMEngine engine,ColumnInfo defaultValue) throws ORMException {
if(columnsInfo!=null) {
ColumnInfo info = (ColumnInfo) columnsInfo.get(KeyImpl.init(columnName),null);
if(info==null) return defaultValue;
return info;
}
return defaultValue;
}
/*private static ColumnInfo getColumnInfo(Struct columnsInfo,String tableName,String columnName,ORMEngine engine) throws ORMException {
if(columnsInfo!=null) {
ColumnInfo info = (ColumnInfo) columnsInfo.get(columnName,null);
if(info==null) {
String msg="table ["+tableName+"] has no column with name ["+columnName+"]";
if(columnsInfo!=null)
msg+=", column names are ["+List.arrayToList(columnsInfo.keysAsString(), ", ")+"]";
ORMUtil.printError(msg, engine);
//throw new ORMException(msg);
}
return info;
}
return null;
}*/
private static String createXMLMappingGenerator(HibernateORMEngine engine,Element id, PageContext pc,Component cfc,Property prop,StringBuilder foreignCFC) throws PageException {
Struct meta = prop.getMeta();
// generator
String className=toString(engine,cfc,prop,meta,"generator");
if(StringUtil.isEmpty(className,true)) return null;
Document doc = XMLUtil.getDocument(id);
Element generator = doc.createElement("generator");
id.appendChild(generator);
generator.setAttribute("class", className);
//print.e("generator:"+className);
// params
Object obj=meta.get("params",null);
//if(obj!=null){
Struct sct=null;
if(obj==null) obj=new StructImpl();
else if(obj instanceof String) obj=convertToSimpleMap((String)obj);
if(Decision.isStruct(obj)) sct=Caster.toStruct(obj);
else throw new HibernateException(engine,cfc,"invalid value for attribute [params] of tag [property]");
className=className.trim().toLowerCase();
// special classes
if("foreign".equals(className)){
if(!sct.containsKey(PROPERTY)) sct.setEL(PROPERTY, toString(engine,cfc,prop,meta, PROPERTY,true));
if(sct.containsKey(PROPERTY)){
String p = Caster.toString(sct.get(PROPERTY),null);
if(!StringUtil.isEmpty(p))foreignCFC.append(p);
}
}
else if("select".equals(className)){
//print.e("select:"+toString(meta, "selectKey",true));
if(!sct.containsKey("key")) sct.setEL("key", toString(engine,cfc,prop,meta, "selectKey",true));
}
else if("sequence".equals(className)){
if(!sct.containsKey("sequence")) sct.setEL("sequence", toString(engine,cfc,prop,meta, "sequence",true));
}
Key[] keys = sct.keys();
Element param;
for(int y=0;y<keys.length;y++){
param = doc.createElement("param");
generator.appendChild(param);
param.setAttribute( "name", keys[y].getLowerString());
param.appendChild(doc.createTextNode(Caster.toString(sct.get(keys[y]))));
}
return className;
}
private static void createXMLMappingProperty(Element clazz, PageContext pc,Component cfc,Property prop,Struct columnsInfo,String tableName,HibernateORMEngine engine) throws ORMException {
Struct meta = prop.getMeta();
// get table name
String columnName=toString(engine,cfc,prop,meta,"column");
if(StringUtil.isEmpty(columnName,true)) columnName=prop.getName();
ColumnInfo info=getColumnInfo(columnsInfo,tableName,columnName,engine,null);
Document doc = XMLUtil.getDocument(clazz);
Element property = doc.createElement("property");
clazz.appendChild(property);
//name
property.setAttribute("name",prop.getName());
// type
String str = getType(engine,info, cfc,prop, meta, "string");
property.setAttribute("type",str);
// formula or column
str=toString(engine,cfc,prop,meta,"formula");
Boolean b;
if(!StringUtil.isEmpty(str,true)) {
property.setAttribute("formula","("+str+")");
}
else {
//property.setAttribute("column",columnName);
Element column = doc.createElement("column");
property.appendChild(column);
column.setAttribute("name", escape(columnName));
// check
str=toString(engine,cfc,prop,meta,"check");
if(!StringUtil.isEmpty(str,true)) column.setAttribute("check",str);
// default
str=toString(engine,cfc,prop,meta,"dbDefault");
if(!StringUtil.isEmpty(str,true)) column.setAttribute("default",str);
// index
str=toString(engine,cfc,prop,meta,"index");
if(!StringUtil.isEmpty(str,true)) column.setAttribute("index",str);
// length
Integer i = toInteger(engine,cfc,meta,"length");
if(i!=null && i>0) column.setAttribute("length",Caster.toString(i.intValue()));
// not-null
b=toBoolean(engine,cfc,meta,"notnull");
if(b!=null && b.booleanValue())column.setAttribute("not-null","true");
// precision
i=toInteger(engine,cfc,meta,"precision");
if(i!=null && i>-1) column.setAttribute("precision",Caster.toString(i.intValue()));
// scale
i=toInteger(engine,cfc,meta,"scale");
if(i!=null && i>-1) column.setAttribute("scale",Caster.toString(i.intValue()));
// sql-type
str=toString(engine,cfc,prop,meta,"sqltype");
if(!StringUtil.isEmpty(str,true)) column.setAttribute("sql-type",str);
// unique
b=toBoolean(engine,cfc,meta,"unique");
if(b!=null && b.booleanValue())column.setAttribute("unique","true");
// unique-key
str=toString(engine,cfc,prop,meta,"uniqueKey");
if(StringUtil.isEmpty(str))str=Caster.toString(meta.get("uniqueKeyName",null),null);
if(!StringUtil.isEmpty(str,true)) column.setAttribute("unique-key",str);
}
// generated
str=toString(engine,cfc,prop,meta,"generated");
if(!StringUtil.isEmpty(str,true)){
str=str.trim().toLowerCase();
if("always".equals(str) || "insert".equals(str) || "never".equals(str))
property.setAttribute("generated",str);
else
throw invalidValue(engine,cfc,prop,"generated",str,"always,insert,never");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute [generated] of column ["+columnName+"], valid values are [always,insert,never]");
}
// update
b=toBoolean(engine,cfc,meta,"update");
if(b!=null && !b.booleanValue())property.setAttribute("update","false");
// insert
b=toBoolean(engine,cfc,meta,"insert");
if(b!=null && !b.booleanValue())property.setAttribute("insert","false");
// lazy
b=toBoolean(engine,cfc,meta,"lazy");
if(b!=null && b.booleanValue())property.setAttribute("lazy","true");
// optimistic-lock
b=toBoolean(engine,cfc,meta,"optimisticlock");
if(b!=null && !b.booleanValue())property.setAttribute("optimistic-lock","false");
}
/*
MUST dies kommt aber nicht hier sondern in verarbeitung in component
<cfproperty
persistent="true|false"
>
* */
private static void createXMLMappingOneToOne(Element clazz, PageContext pc,Component cfc,Property prop,HibernateORMEngine engine) throws PageException {
Struct meta = prop.getMeta();
Boolean b;
Document doc = XMLUtil.getDocument(clazz);
Element x2o;
// column
String fkcolumn=toString(engine,cfc,prop,meta,"fkcolumn");
String linkTable=toString(engine,cfc,prop,meta,"linkTable");
if(!StringUtil.isEmpty(linkTable,true) || !StringUtil.isEmpty(fkcolumn,true)) {
clazz=getJoin(clazz);
x2o= doc.createElement("many-to-one");
//x2o.setAttribute("column", fkcolumn);
x2o.setAttribute("unique", "true");
if(!StringUtil.isEmpty(linkTable,true)){
setColumn(doc, x2o, linkTable);
}
else {
setColumn(doc, x2o, fkcolumn);
}
// update
b=toBoolean(engine,cfc,meta,"update");
if(b!=null)x2o.setAttribute("update",Caster.toString(b.booleanValue()));
// insert
b=toBoolean(engine,cfc,meta,"insert");
if(b!=null)x2o.setAttribute("insert",Caster.toString(b.booleanValue()));
// not-null
b=toBoolean(engine,cfc,meta,"notNull");
if(b!=null)x2o.setAttribute("not-null",Caster.toString(b.booleanValue()));
// optimistic-lock
b=toBoolean(engine,cfc,meta,"optimisticLock");
if(b!=null)x2o.setAttribute("optimistic-lock",Caster.toString(b.booleanValue()));
// not-found
b=toBoolean(engine,cfc,meta, "missingRowIgnored");
if(b!=null && b.booleanValue()) x2o.setAttribute("not-found", "ignore");
/* / index
str=toString(meta,"index");
if(!StringUtil.isEmpty(str,true)) x2o.setAttribute("index", str);
*/
}
else {
x2o= doc.createElement("one-to-one");
}
clazz.appendChild(x2o);
// access
String str=toString(engine,cfc,prop,meta,"access");
if(!StringUtil.isEmpty(str,true)) x2o.setAttribute("access", str);
// constrained
b=toBoolean(engine,cfc,meta, "constrained");
if(b!=null && b.booleanValue()) x2o.setAttribute("constrained", "true");
// formula
str=toString(engine,cfc,prop,meta,"formula");
if(!StringUtil.isEmpty(str,true)) x2o.setAttribute("formula", str);
// embed-xml
str=toString(engine,cfc,prop,meta,"embedXml");
if(!StringUtil.isEmpty(str,true)) x2o.setAttribute("embed-xml", str);
// property-ref
str=toString(engine,cfc,prop,meta,"mappedBy");
if(!StringUtil.isEmpty(str,true)) x2o.setAttribute("property-ref", str);
// foreign-key
str=toString(engine,cfc,prop,meta,"foreignKeyName");
if(StringUtil.isEmpty(str,true)) str=toString(engine,cfc,prop,meta,"foreignKey");
if(!StringUtil.isEmpty(str,true)) x2o.setAttribute("foreign-key", str);
setForeignEntityName(pc,engine,cfc,prop,meta,x2o,true);
createXMLMappingXToX(engine,x2o, pc,cfc,prop,meta);
}
private static void setForeignEntityName(PageContext pc,HibernateORMEngine engine,Component cfc,Property prop, Struct meta, Element el, boolean cfcRequired) throws PageException {
// entity
String str=cfcRequired?null:toString(engine,cfc,prop,meta,"entityName");
if(!StringUtil.isEmpty(str,true)) {
el.setAttribute("entity-name", str);
}
else {
// cfc
str = toString(engine,cfc,prop,meta,"cfc",cfcRequired);
if(!StringUtil.isEmpty(str,true)){
Component _cfc=engine.getEntityByCFCName(str, false);
str=HibernateCaster.getEntityName(pc,_cfc);
el.setAttribute("entity-name", str);
}
}
}
private static void createXMLMappingCollection(Element clazz, PageContext pc,Component cfc,Property prop,ORMConfiguration ormConf, HibernateORMEngine engine) throws PageException {
Struct meta = prop.getMeta();
Document doc = XMLUtil.getDocument(clazz);
Element el=null;
// collection type
String str=prop.getType();
if(StringUtil.isEmpty(str,true) || "any".equalsIgnoreCase(str) || "object".equalsIgnoreCase(str))str="array";
else str=str.trim().toLowerCase();
// bag
if("array".equals(str) || "bag".equals(str)){
el = doc.createElement("bag");
}
// map
else if("struct".equals(str) || "map".equals(str)){
el = doc.createElement("map");
// map-key
str=toString(engine,cfc,prop,meta,"structKeyColumn",true);
if(!StringUtil.isEmpty(str,true)) {
Element mapKey=doc.createElement("map-key");
el.appendChild(mapKey);
mapKey.setAttribute("column", str);
// type
str=toString(engine,cfc,prop,meta,"structKeyType");
if(!StringUtil.isEmpty(str,true))mapKey.setAttribute("type", str);
else mapKey.setAttribute("type", "string");
}
}
else throw invalidValue(engine,cfc,prop,"collectiontype",str,"array,struct");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute [collectiontype], valid values are [array,struct]");
setBeforeJoin(clazz,el);
// name
el.setAttribute("name", prop.getName());
// table
str=toString(engine,cfc,prop,meta, "table",true);
el.setAttribute("table",escape(str));
// catalog
str=toString(engine,cfc,prop,meta, "catalog");
if(!StringUtil.isEmpty(str,true))el.setAttribute("catalog",str);
// schema
str=toString(engine,cfc,prop,meta, "schema");
if(!StringUtil.isEmpty(str,true))el.setAttribute("schema",str);
// mutable
Boolean b=toBoolean(engine,cfc,meta, "readonly");
if(b!=null && b.booleanValue()) el.setAttribute("mutable", "false");
// order-by
str=toString(engine,cfc,prop,meta, "orderby");
if(!StringUtil.isEmpty(str,true))el.setAttribute("order-by",str);
// element-column
str=toString(engine,cfc,prop,meta,"elementcolumn");
if(!StringUtil.isEmpty(str,true)){
Element element = doc.createElement("element");
el.appendChild(element);
// column
element.setAttribute("column", formatColumn(str));
// type
str=toString(engine,cfc,prop,meta,"elementtype");
if(!StringUtil.isEmpty(str,true)) element.setAttribute("type", str);
}
// batch-size
Integer i=toInteger(engine,cfc,meta, "batchsize");
if(i!=null && i.intValue()>1) el.setAttribute("batch-size", Caster.toString(i.intValue()));
// column
str=toString(engine,cfc,prop,meta,"fkcolumn");
if(StringUtil.isEmpty(str,true)) str=toString(engine,cfc,prop,meta,"column");
if(!StringUtil.isEmpty(str,true)){
Element key = doc.createElement("key");
XMLUtil.setFirst(el,key);
//el.appendChild(key);
// column
key.setAttribute("column", formatColumn(str));
// property-ref
str=toString(engine,cfc,prop,meta,"mappedBy");
if(!StringUtil.isEmpty(str,true)) key.setAttribute("property-ref", str);
}
// cache
setCacheStrategy(engine,cfc,prop,doc, meta, el);
// optimistic-lock
b=toBoolean(engine,cfc,meta, "optimisticlock");
if(b!=null && !b.booleanValue()) el.setAttribute("optimistic-lock", "false");
}
private static void setBeforeJoin(Element clazz, Element el) {
Element join;
if(clazz.getNodeName().equals("join")) {
join=clazz;
clazz = getClazz(clazz);
}
else {
join = getJoin(clazz);
}
if(join==clazz) clazz.appendChild(el);
else clazz.insertBefore(el, join);
}
private static Element getClazz(Element join) {
if(join.getNodeName().equals("join")){
return (Element) join.getParentNode();
}
return join;
}
private static Element getJoin(Element clazz) {
if(clazz.getNodeName().equals("subclass")){
NodeList joins = clazz.getElementsByTagName("join");
if(joins!=null && joins.getLength()>0)
return (Element)joins.item(0);
}
return clazz;
}
private static void createXMLMappingManyToMany(Component cfc,HibernateORMEngine engine,PropertyCollection propColl,Element clazz, PageContext pc,Property prop,ORMConfiguration ormConf) throws PageException {
Element el = createXMLMappingXToMany(engine,propColl,clazz, pc, cfc,prop);
Struct meta = prop.getMeta();
Document doc = XMLUtil.getDocument(clazz);
Element m2m = doc.createElement("many-to-many");
el.appendChild(m2m);
// link
setLink(engine,cfc,prop,el,meta,ormConf,true);
setForeignEntityName(pc, engine,cfc,prop, meta, m2m,true);
// order-by
String str = toString(engine,cfc,prop,meta,"orderby");
if(!StringUtil.isEmpty(str,true))m2m.setAttribute("order-by", str);
// column
str=toString(engine,cfc,prop,meta,"inversejoincolumn");
setColumn(doc, m2m, str);
// not-found
Boolean b=toBoolean(engine,cfc,meta, "missingrowignored");
if(b!=null && b.booleanValue()) m2m.setAttribute("not-found", "ignore");
// property-ref
str=toString(engine,cfc,prop,meta,"mappedby");
if(!StringUtil.isEmpty(str,true)) m2m.setAttribute("property-ref", str);
// foreign-key
str=toString(engine,cfc,prop,meta,"foreignKeyName");
if(StringUtil.isEmpty(str,true)) str=toString(engine,cfc,prop,meta,"foreignKey");
if(!StringUtil.isEmpty(str,true)) m2m.setAttribute("foreign-key", str);
}
private static boolean setLink(HibernateORMEngine engine,Component cfc,Property prop,Element el, Struct meta, ORMConfiguration ormConf, boolean linkTableRequired) throws ORMException {
String str=toString(engine,cfc,prop,meta, "linktable",linkTableRequired);
if(!StringUtil.isEmpty(str,true)){
el.setAttribute("table", escape(str));
// schema
str=toString(engine,cfc,prop,meta, "linkschema");
if(StringUtil.isEmpty(str,true)) str=ormConf.getSchema();
if(!StringUtil.isEmpty(str,true)) el.setAttribute("schema", str);
// catalog
str=toString(engine,cfc,prop,meta, "linkcatalog");
if(StringUtil.isEmpty(str,true)) str=ormConf.getCatalog();
if(!StringUtil.isEmpty(str,true)) el.setAttribute("catalog", str);
return true;
}
return false;
}
private static void createXMLMappingOneToMany(Component cfc,HibernateORMEngine engine,PropertyCollection propColl,ORMConfiguration ormConf,Element clazz, PageContext pc,Property prop) throws PageException {
Element el = createXMLMappingXToMany(engine,propColl,clazz, pc, cfc,prop);
Struct meta = prop.getMeta();
Document doc = XMLUtil.getDocument(clazz);
Element x2m;
// order-by
String str = toString(engine,cfc,prop,meta,"orderby");
if(!StringUtil.isEmpty(str,true))el.setAttribute("order-by", str);
// link
if(setLink(engine,cfc,prop,el,meta,ormConf,false)){
x2m = doc.createElement("many-to-many");
x2m.setAttribute("unique","true");
str=toString(engine,cfc,prop,meta,"inversejoincolumn");
setColumn(doc, x2m, str);
}
else {
x2m = doc.createElement("one-to-many");
}
el.appendChild(x2m);
// entity-name
setForeignEntityName(pc,engine,cfc,prop,meta,x2m,true);
}
private static Element createXMLMappingXToMany(HibernateORMEngine engine,PropertyCollection propColl,Element clazz, PageContext pc,Component cfc,Property prop) throws PageException {
Struct meta = prop.getMeta();
Document doc = XMLUtil.getDocument(clazz);
Element el=null;
// collection type
String str=prop.getType();
if(StringUtil.isEmpty(str,true) || "any".equalsIgnoreCase(str) || "object".equalsIgnoreCase(str))str="array";
else str=str.trim().toLowerCase();
Element mapKey=null;
// bag
if("array".equals(str) || "bag".equals(str)){
el = doc.createElement("bag");
}
// map
else if("struct".equals(str) || "map".equals(str)){
el = doc.createElement("map");
// map-key
mapKey = doc.createElement("map-key");
//el.appendChild(mapKey);
// column
str=toString(engine,cfc,prop,meta,"structKeyColumn",true);
mapKey.setAttribute("column", formatColumn(str));
// type
str=toString(engine,cfc,prop,meta,"structKeyType");
if(!StringUtil.isEmpty(str,true))mapKey.setAttribute("type", str);
else mapKey.setAttribute("type", "string");// MUST get type dynamicly
}
else throw invalidValue(engine,cfc,prop,"collectiontype",str,"array,struct");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute [collectiontype], valid values are [array,struct]");
setBeforeJoin(clazz,el);
// batch-size
Integer i=toInteger(engine,cfc,meta, "batchsize");
if(i!=null){
if(i.intValue()>1) el.setAttribute("batch-size", Caster.toString(i.intValue()));
}
// cacheUse
setCacheStrategy(engine,cfc,prop,doc, meta, el);
// column
str=toString(engine,cfc,prop,meta,"fkcolumn");
if(StringUtil.isEmpty(str)){
Property[] ids = getIds(engine,cfc,propColl);
if(ids.length==1) str=ids[0].getName();
else str=toString(engine,cfc,prop,meta,"fkcolumn",true);
}
if(!StringUtil.isEmpty(str,true)){
Element key = doc.createElement("key");
el.appendChild(key);
// column
setColumn(doc,key,str);
// property-ref
str=toString(engine,cfc,prop,meta,"mappedBy");
if(!StringUtil.isEmpty(str,true)) key.setAttribute("property-ref", str);
}
// inverse
Boolean b = toBoolean(engine,cfc,meta, "inverse");
if(b!=null && b.booleanValue()) el.setAttribute("inverse", "true");
// mutable
b = toBoolean(engine,cfc,meta, "readonly");
if(b!=null && b.booleanValue()) el.setAttribute("mutable", "false");
// optimistic-lock
b=toBoolean(engine,cfc,meta, "optimisticlock");
if(b!=null && !b.booleanValue()) el.setAttribute("optimistic-lock", "false");
// where
str=toString(engine,cfc,prop,meta,"where");
if(!StringUtil.isEmpty(str,true)) el.setAttribute("where", str);
// add map key
if(mapKey!=null)el.appendChild(mapKey);
createXMLMappingXToX(engine,el, pc,cfc,prop,meta);
return el;
}
private static void setCacheStrategy(HibernateORMEngine engine,Component cfc,Property prop,Document doc,Struct meta, Element el) throws ORMException {
String strategy = toString(engine,cfc,prop,meta,"cacheuse");
if(!StringUtil.isEmpty(strategy,true)){
strategy=strategy.trim().toLowerCase();
if("read-only".equals(strategy) || "nonstrict-read-write".equals(strategy) || "read-write".equals(strategy) || "transactional".equals(strategy)){
Element cache = doc.createElement("cache");
XMLUtil.setFirst(el, cache);
el.appendChild(cache);
cache.setAttribute("usage", strategy);
String name = toString(engine,cfc,prop,meta,"cacheName");
if(!StringUtil.isEmpty(name,true)){
cache.setAttribute("region", name);
}
}
else
throw new HibernateException(engine,cfc,"invalid value ["+strategy+"] for attribute [cacheuse], valid values are [read-only,nonstrict-read-write,read-write,transactional]");
}
}
private static void setColumn(Document doc, Element el, String columnValue) throws PageException {
if(StringUtil.isEmpty(columnValue,true)) return;
String[] arr = List.toStringArray(List.listToArray(columnValue, ','));
if(arr.length==1){
el.setAttribute("column", formatColumn(arr[0]));
}
else {
Element column;
for(int i=0;i<arr.length;i++){
column=doc.createElement("column");
el.appendChild(column);
column.setAttribute("name", formatColumn(arr[i]));
}
}
}
private static void createXMLMappingManyToOne(Element clazz, PageContext pc,Component cfc,Property prop, HibernateORMEngine engine) throws PageException {
Struct meta = prop.getMeta();
Boolean b;
Document doc = XMLUtil.getDocument(clazz);
clazz=getJoin(clazz);
Element m2o = doc.createElement("many-to-one");
clazz.appendChild(m2o);
// columns
String linktable = toString(engine,cfc,prop,meta,"linktable");
String _columns;
if(!StringUtil.isEmpty(linktable,true)) _columns=toString(engine,cfc,prop,meta,"inversejoincolumn");
else _columns=toString(engine,cfc,prop,meta,"fkcolumn");
setColumn(doc, m2o, _columns);
// cfc
setForeignEntityName(pc,engine,cfc,prop,meta,m2o,true);
// column
//String str=toString(prop,meta,"column",true);
//m2o.setAttribute("column", str);
// insert
b=toBoolean(engine,cfc,meta, "insert");
if(b!=null && !b.booleanValue()) m2o.setAttribute("insert", "false");
// update
b=toBoolean(engine,cfc,meta, "update");
if(b!=null && !b.booleanValue()) m2o.setAttribute("update", "false");
// property-ref
String str=toString(engine,cfc,prop,meta,"mappedBy");
if(!StringUtil.isEmpty(str,true)) m2o.setAttribute("property-ref", str);
// update
b=toBoolean(engine,cfc,meta, "unique");
if(b!=null && b.booleanValue()) m2o.setAttribute("unique", "true");
// not-null
b=toBoolean(engine,cfc,meta, "notnull");
if(b!=null && b.booleanValue()) m2o.setAttribute("not-null", "true");
// optimistic-lock
b=toBoolean(engine,cfc,meta, "optimisticLock");
if(b!=null && !b.booleanValue()) m2o.setAttribute("optimistic-lock", "false");
// not-found
b=toBoolean(engine,cfc,meta, "missingRowIgnored");
if(b!=null && b.booleanValue()) m2o.setAttribute("not-found", "ignore");
// index
str=toString(engine,cfc,prop,meta,"index");
if(!StringUtil.isEmpty(str,true)) m2o.setAttribute("index", str);
// unique-key
str=toString(engine,cfc,prop,meta,"uniqueKeyName");
if(StringUtil.isEmpty(str,true))str=toString(engine,cfc,prop,meta,"uniqueKey");
if(!StringUtil.isEmpty(str,true)) m2o.setAttribute("unique-key", str);
// foreign-key
str=toString(engine,cfc,prop,meta,"foreignKeyName");
if(StringUtil.isEmpty(str,true)) str=toString(engine,cfc,prop,meta,"foreignKey");
if(!StringUtil.isEmpty(str,true)) m2o.setAttribute("foreign-key", str);
// access
str=toString(engine,cfc,prop,meta,"access");
if(!StringUtil.isEmpty(str,true)) m2o.setAttribute("access", str);
createXMLMappingXToX(engine,m2o, pc,cfc,prop,meta);
}
private static String formatColumn(String name) {
name=name.trim();
return escape(name);
}
/*
<cfproperty
cfc="Referenced_CFC_Name"
linktable="Link table name"
linkcatalog="Catalog for the link table"
linkschema="Schema for the link table"
fkcolumn="Foreign Key column name"
inversejoincolumn="Column name or comma-separated list of primary key columns"
>
*/
private static void createXMLMappingXToX(HibernateORMEngine engine,Element x2x, PageContext pc, Component cfc,Property prop, Struct meta) throws ORMException {
x2x.setAttribute("name",prop.getName());
// cascade
String str=toString(engine,cfc,prop,meta,"cascade");
if(!StringUtil.isEmpty(str,true)) x2x.setAttribute("cascade", str);
// fetch
str=toString(engine,cfc,prop,meta,"fetch");
if(!StringUtil.isEmpty(str,true)) {
str=str.trim().toLowerCase();
if("join".equals(str) || "select".equals(str))
x2x.setAttribute("fetch", str);
else
throw invalidValue(engine,cfc,prop,"fetch",str,"join,select");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute [fetch], valid values are [join,select]");
}
// lazy
str=toString(engine,cfc,prop,meta, "lazy");
if(!StringUtil.isEmpty(str)){
Boolean b = Caster.toBoolean(str,null);
if(b!=null)
x2x.setAttribute("lazy", b.booleanValue()?"true":"false");
else if("extra".equalsIgnoreCase(str))
x2x.setAttribute("lazy", "extra");
else
throw invalidValue(engine,cfc,prop,"lazy",str,"true,false,extra");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute [lazy], valid values are [true,false,extra]");
}
}
private static void createXMLMappingTimestamp(HibernateORMEngine engine,Element clazz, PageContext pc,Component cfc,Property prop) throws PageException {
Struct meta = prop.getMeta();
String str;
Integer i;
Boolean b;
Document doc = XMLUtil.getDocument(clazz);
Element timestamp = doc.createElement("timestamp");
clazz.appendChild(timestamp);
timestamp.setAttribute("name",prop.getName());
// access
str=toString(engine,cfc,prop,meta,"access");
if(!StringUtil.isEmpty(str,true))timestamp.setAttribute("access", str);
// column
str=toString(engine,cfc,prop,meta,"column");
if(StringUtil.isEmpty(str,true)) str=prop.getName();
timestamp.setAttribute("column",formatColumn(str));
// generated
b=toBoolean(engine,cfc,meta, "generated");
if(b!=null) timestamp.setAttribute("generated", b.booleanValue()?"always":"never");
// source
str=toString(engine,cfc,prop,meta,"source");
if(!StringUtil.isEmpty(str,true)) {
str=str.trim().toLowerCase();
if("db".equals(str) || "vm".equals(str))
timestamp.setAttribute("source", str);
else
throw invalidValue(engine,cfc,prop,"source",str,"db,vm");
}
// unsavedValue
str=toString(engine,cfc,prop,meta,"unsavedValue");
if(!StringUtil.isEmpty(str,true)) {
str=str.trim().toLowerCase();
if("null".equals(str) || "undefined".equals(str))
timestamp.setAttribute("unsaved-value", str);
else
throw invalidValue(engine,cfc,prop,"unsavedValue",str,"null, undefined");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute [unsavedValue], valid values are [null, undefined]");
}
}
private static ORMException invalidValue(HibernateORMEngine engine,Component cfc,Property prop, String attrName, String invalid, String valid) {
String owner = prop.getOwnerName();
if(StringUtil.isEmpty(owner))return new HibernateException(engine,cfc,"invalid value ["+invalid+"] for attribute ["+attrName+"] of property ["+prop.getName()+"], valid values are ["+valid+"]");
return new HibernateException(engine,cfc,"invalid value ["+invalid+"] for attribute ["+attrName+"] of property ["+prop.getName()+"] of Component ["+List.last(owner,'.')+"], valid values are ["+valid+"]");
}
private static void createXMLMappingVersion(HibernateORMEngine engine,Element clazz, PageContext pc,Component cfc,Property prop) throws PageException {
Struct meta = prop.getMeta();
Document doc = XMLUtil.getDocument(clazz);
Element version = doc.createElement("version");
clazz.appendChild(version);
version.setAttribute("name",prop.getName());
// column
String str = toString(engine,cfc,prop,meta,"column");
if(StringUtil.isEmpty(str,true)) str=prop.getName();
version.setAttribute("column",formatColumn(str));
// access
str=toString(engine,cfc,prop,meta,"access");
if(!StringUtil.isEmpty(str,true))version.setAttribute("access", str);
// generated
Object o=meta.get("generated",null);
if(o!=null){
Boolean b = Caster.toBoolean(o,null);
str=null;
if(b!=null) {
str=b.booleanValue()?"always":"never";
}
else {
str=Caster.toString(o,null);
if("always".equalsIgnoreCase(str))str="always";
else if("never".equalsIgnoreCase(str))str="never";
else throw invalidValue(engine,cfc,prop,"generated",o.toString(),"true,false,always,never");
//throw new ORMException(engine,"invalid value ["+o+"] for attribute [generated] of property ["+prop.getName()+"], valid values are [true,false,always,never]");
}
version.setAttribute( "generated", str);
}
// insert
Boolean b = toBoolean(engine,cfc,meta, "insert");
if(b!=null && !b.booleanValue()) version.setAttribute("insert", "false");
// type
String typeName="dataType";
str=toString(engine,cfc,prop,meta,typeName);
if(StringUtil.isEmpty(str,true)){
typeName="ormType";
str=toString(engine,cfc,prop,meta,typeName);
}
if(!StringUtil.isEmpty(str,true)) {
str=str.trim().toLowerCase();
if("int".equals(str) || "integer".equals(str))
version.setAttribute("type", "integer");
else if("long".equals(str))
version.setAttribute("type", "long");
else if("short".equals(str))
version.setAttribute("type", "short");
else
throw invalidValue(engine,cfc,prop,typeName,str,"int,integer,long,short");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute ["+typeName+"], valid values are [int,integer,long,short]");
}
else
version.setAttribute("type", "integer");
// unsavedValue
str=toString(engine,cfc,prop,meta,"unsavedValue");
if(!StringUtil.isEmpty(str,true)) {
str=str.trim().toLowerCase();
if("null".equals(str) || "negative".equals(str) || "undefined".equals(str))
version.setAttribute("unsaved-value", str);
else
throw invalidValue(engine,cfc,prop,"unsavedValue",str,"null, negative, undefined");
//throw new ORMException(engine,"invalid value ["+str+"] for attribute [unsavedValue], valid values are [null, negative, undefined]");
}
}
private static Struct convertToSimpleMap(String paramsStr) {
paramsStr=paramsStr.trim();
if(!StringUtil.startsWith(paramsStr, '{') || !StringUtil.endsWith(paramsStr, '}'))
return null;
paramsStr = paramsStr.substring(1, paramsStr.length() - 1);
String items[] = List.listToStringArray(paramsStr, ',');
Struct params=new StructImpl();
String arr$[] = items;
int index;
for(int i = 0; i < arr$.length; i++) {
String pair = arr$[i];
index = pair.indexOf('=');
if(index == -1) return null;
params.setEL(
deleteQuotes(pair.substring(0, index).trim()).trim(),
deleteQuotes(pair.substring(index + 1).trim()));
}
return params;
}
private static String deleteQuotes(String str) {
if(StringUtil.isEmpty(str,true))return "";
char first=str.charAt(0);
if((first=='\'' || first=='"') && StringUtil.endsWith(str, first))
return str.substring(1, str.length() - 1);
return str;
}
private static String toString(HibernateORMEngine engine,Component cfc,Property prop,Struct sct, String key) throws ORMException {
return toString(engine,cfc,prop,sct, key, false);
}
private static String toString(HibernateORMEngine engine,Component cfc,Property prop,Struct sct, String key, boolean throwErrorWhenNotExist) throws ORMException {
return toString(engine,cfc,prop,sct, KeyImpl.init(key), throwErrorWhenNotExist);
}
private static String toString(HibernateORMEngine engine,Component cfc,Property prop,Struct sct, Collection.Key key, boolean throwErrorWhenNotExist) throws ORMException {
Object value = sct.get(key,null);
if(value==null) {
if(throwErrorWhenNotExist){
if(prop==null)throw new HibernateException(engine,cfc,"attribute ["+key+"] is required");
throw new HibernateException(engine,cfc,"attribute ["+key+"] of property ["+prop.getName()+"] of Component ["+_getCFCName(prop)+"] is required");
}
return null;
}
String str=Caster.toString(value,null);
if(str==null) {
if(prop==null)
throw new HibernateException(engine,cfc,"invalid type ["+Caster.toTypeName(value)+"] for attribute ["+key+"], value must be a string");
throw new HibernateException(engine,cfc,"invalid type ["+Caster.toTypeName(value)+"] for attribute ["+key+"] of property ["+prop.getName()+"] of Component ["+_getCFCName(prop)+"], value must be a string");
}
return str;
}
private static String _getCFCName(Property prop) {
String owner = prop.getOwnerName();
return List.last(owner,'.');
}
private static Boolean toBoolean(HibernateORMEngine engine,Component cfc,Struct sct, String key) throws ORMException {
Object value = sct.get(key,null);
if(value==null) return null;
Boolean b=Caster.toBoolean(value,null);
if(b==null) throw new HibernateException(engine,cfc,"invalid type ["+Caster.toTypeName(value)+"] for attribute ["+key+"], value must be a boolean");
return b;
}
private static Integer toInteger(HibernateORMEngine engine,Component cfc,Struct sct, String key) throws ORMException {
Object value = sct.get(key,null);
if(value==null) return null;
Integer i=Caster.toInteger(value,null);
if(i==null) throw new HibernateException(engine,cfc,"invalid type ["+Caster.toTypeName(value)+"] for attribute ["+key+"], value must be a numeric value");
return i;
}
}
class PropertyCollection {
private Property[] properties;
private String tableName;
public PropertyCollection(String tableName,Property[] properties) {
this.tableName=tableName;
this.properties=properties;
}
public PropertyCollection(String tableName, java.util.List<Property> properties) {
this.tableName=tableName;
this.properties=properties.toArray(new Property[properties.size()]);
}
public Property[] getProperties() {
return properties;
}
public String getTableName() {
return tableName;
}
}
|
package org.rakam.collection.event;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.primitives.Ints;
import org.apache.avro.Schema;
import org.apache.avro.SchemaParseException;
import org.apache.avro.generic.GenericData;
import org.rakam.analysis.NotExistsException;
import org.rakam.collection.Event;
import org.rakam.collection.FieldType;
import org.rakam.collection.SchemaField;
import org.rakam.collection.event.metastore.Metastore;
import org.rakam.util.AvroUtil;
import org.rakam.util.ProjectCollection;
import org.rakam.util.RakamException;
import javax.inject.Inject;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
import static org.apache.avro.Schema.Type.NULL;
public class EventDeserializer extends JsonDeserializer<Event> {
private final Map<String, List<SchemaField>> conditionalMagicFields;
private static final Pattern DATE_PATTERN = Pattern.compile("^\\d{4}\\-(0?[1-9]|1[012])\\-(0?[1-9]|[12][0-9]|3[01])$");
private static final Pattern TIMESTAMP_PATTERN = Pattern.compile("^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$");
private static final Pattern TIME_PATTERN = Pattern.compile("^([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$");
private final Metastore metastore;
private final Cache<ProjectCollection, Map.Entry<List<SchemaField>, Schema>> schemaCache = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.HOURS).build();
@Inject
public EventDeserializer(Metastore metastore, FieldDependencyBuilder.FieldDependency fieldDependency) {
this.metastore = metastore;
this.conditionalMagicFields = fieldDependency.dependentFields;
}
@Override
public Event deserialize(JsonParser jp, DeserializationContext ctx) throws IOException {
return deserializeWithProject(jp, null);
}
public Event deserializeWithProject(JsonParser jp, String project) throws IOException, RakamException {
Map.Entry<List<SchemaField>, GenericData.Record> properties = null;
String collection = null;
Event.EventContext context = null;
JsonToken t = jp.getCurrentToken();
if (t == JsonToken.START_OBJECT) {
t = jp.nextToken();
}
for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
String fieldName = jp.getCurrentName();
jp.nextToken();
switch (fieldName) {
case "project":
if(project != null) {
if(jp.getValueAsString() != null) {
throw new RakamException("project is already set", BAD_REQUEST);
}
} else {
project = jp.getValueAsString();
}
break;
case "collection":
collection = jp.getValueAsString().toLowerCase();
break;
case "api":
context = jp.readValueAs(Event.EventContext.class);
break;
case "properties":
if (project == null || collection == null) {
throw new JsonMappingException("'project' and 'collection' fields must be located before 'properties' field.");
} else {
try {
properties = parseProperties(project, collection, jp);
} catch (NotExistsException e) {
throw Throwables.propagate(e);
}
t = jp.getCurrentToken();
if(t != JsonToken.END_OBJECT) {
if(t == JsonToken.START_OBJECT) {
throw new RakamException("Nested properties are not supported", BAD_REQUEST);
} else {
throw new RakamException("Error while deserializing event", INTERNAL_SERVER_ERROR);
}
}
}
break;
}
}
if (properties == null) {
throw new JsonMappingException("properties is null");
}
return new Event(project, collection, context, properties.getKey(), properties.getValue());
}
public Schema convertAvroSchema(List<SchemaField> fields) {
List<Schema.Field> avroFields = fields.stream()
.map(AvroUtil::generateAvroSchema).collect(Collectors.toList());
Schema schema = Schema.createRecord("collection", null, null, false);
conditionalMagicFields.keySet().stream()
.filter(s -> !avroFields.stream().anyMatch(af -> af.name().equals(s)))
.map(n -> new Schema.Field(n, Schema.create(NULL), "", null))
.forEach(x -> avroFields.add(x));
schema.setFields(avroFields);
return schema;
}
private Map.Entry<List<SchemaField>, GenericData.Record> parseProperties(String project, String collection, JsonParser jp) throws IOException, NotExistsException {
ProjectCollection key = new ProjectCollection(project, collection);
Map.Entry<List<SchemaField>, Schema> schema = schemaCache.getIfPresent(key);
if (schema == null) {
List<SchemaField> rakamSchema = metastore.getCollection(project, collection);
schema = new SimpleImmutableEntry<>(rakamSchema, convertAvroSchema(rakamSchema));
schemaCache.put(key, schema);
}
Schema avroSchema = schema.getValue();
List<SchemaField> rakamSchema = schema.getKey();
GenericData.Record record = new GenericData.Record(avroSchema);
Set<SchemaField> newFields = null;
JsonToken t = jp.nextToken();
for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
String fieldName = jp.getCurrentName();
Schema.Field field = avroSchema.getField(fieldName);
jp.nextToken();
if (field == null) {
fieldName = fieldName.toLowerCase(Locale.ENGLISH);
field = avroSchema.getField(fieldName);
if(field == null) {
FieldType type = getType(jp);
if (type != null) {
if (newFields == null)
newFields = new HashSet<>();
if(fieldName.equals("_user")) {
// the type of magic _user field must always be a string
// for consistency.
type = FieldType.STRING;
}
SchemaField newField = new SchemaField(fieldName, type);
newFields.add(newField);
avroSchema = createNewSchema(avroSchema, newField);
field = avroSchema.getField(newField.getName());
GenericData.Record newRecord = new GenericData.Record(avroSchema);
for (Schema.Field f : record.getSchema().getFields()) {
newRecord.put(f.name(), record.get(f.name()));
}
record = newRecord;
if(type.isArray() || type.isMap()) {
// if the type of new field is ARRAY, we already switched to next token
// so current token is not START_ARRAY.
record.put(field.pos(), getValue(jp, type, field.schema(), true));
} else {
record.put(field.pos(), getValue(jp, type, field.schema(), false));
}
continue;
} else {
// the type is null or an empty array
continue;
}
}
} else {
if(field.schema().getType() == NULL) {
// TODO: get rid of this loop.
for (SchemaField schemaField : conditionalMagicFields.get(fieldName)) {
if(avroSchema.getField(schemaField.getName()) == null) {
if(newFields == null) {
newFields = new HashSet<>();
}
newFields.add(schemaField);
}
}
}
}
Object value = getValue(jp, field.schema().getType() == NULL ? null : rakamSchema.get(field.pos()).getType(), field.schema(), false);
record.put(field.pos(), value);
}
if (newFields != null) {
List<SchemaField> newSchema = metastore.getOrCreateCollectionFieldList(project, collection, newFields);
Schema newAvroSchema = convertAvroSchema(newSchema);
schemaCache.put(key, new SimpleImmutableEntry<>(newSchema, newAvroSchema));
GenericData.Record newRecord = new GenericData.Record(newAvroSchema);
for (Schema.Field field : record.getSchema().getFields()) {
newRecord.put(field.name(), record.get(field.name()));
}
record = newRecord;
}
return new SimpleImmutableEntry<>(rakamSchema, record);
}
private Schema createNewSchema(Schema currentSchema, SchemaField newField) {
List<Schema.Field> avroFields = currentSchema.getFields().stream()
.filter(field -> field.schema().getType() != Schema.Type.NULL)
.map(field -> new Schema.Field(field.name(), field.schema(), field.doc(), field.defaultValue()))
.collect(toList());
try {
avroFields.add(AvroUtil.generateAvroSchema(newField));
} catch (SchemaParseException e) {
throw new RakamException("Couldn't create new column: "+e.getMessage(), BAD_REQUEST);
}
conditionalMagicFields.keySet().stream()
.filter(s -> !avroFields.stream().anyMatch(af -> af.name().equals(s)))
.map(n -> new Schema.Field(n, Schema.create(NULL), "", null))
.forEach(x -> avroFields.add(x));
Schema avroSchema = Schema.createRecord("collection", null, null, false);
avroSchema.setFields(avroFields);
return avroSchema;
}
private Object getValueOfMagicField(JsonParser jp) throws IOException {
switch (jp.getCurrentToken()) {
case VALUE_TRUE:
return Boolean.TRUE;
case VALUE_FALSE:
return Boolean.FALSE;
case VALUE_NUMBER_FLOAT:
return jp.getValueAsDouble();
case VALUE_NUMBER_INT:
return jp.getValueAsLong();
case VALUE_STRING:
return jp.getValueAsString();
case VALUE_NULL:
return null;
default:
throw new RakamException("The value of magic field is unknown", BAD_REQUEST);
}
}
private Object getValue(JsonParser jp, FieldType type, Schema schema, boolean passInitialToken) throws IOException {
if(type == null) {
return getValueOfMagicField(jp);
}
switch (type) {
case STRING:
// TODO: is it a good idea to cast the value automatically?
// if (t == JsonToken.VALUE_STRING)
return jp.getValueAsString();
case BOOLEAN:
return jp.getValueAsBoolean();
case LONG:
return jp.getValueAsLong();
case TIME:
return (long) LocalTime.parse(jp.getValueAsString()).get(ChronoField.MILLI_OF_DAY);
case DOUBLE:
return jp.getValueAsDouble();
case TIMESTAMP:
if (jp.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
return jp.getValueAsLong();
}
try {
return Instant.parse(jp.getValueAsString()).toEpochMilli();
} catch (DateTimeParseException e) {
return null;
}
case DATE:
try {
return Ints.checkedCast(LocalDate.parse(jp.getValueAsString()).toEpochDay());
} catch (DateTimeParseException e) {
return null;
}
default:
Schema actualSchema = schema.getTypes().get(1);
if (type.isMap()) {
JsonToken t = jp.getCurrentToken();
Map<String, Object> map = new HashMap<>();
Schema elementType = actualSchema.getValueType();
if(!passInitialToken) {
if(t != JsonToken.START_OBJECT) {
return null;
} else {
t = jp.nextToken();
}
} else {
// In order to determine the value type of map, getType method performed an extra
// jp.nextToken() so the cursor should be at VALUE_STRING token.
String key = jp.getParsingContext().getCurrentName();
map.put(key, getValue(jp, type.getMapValueType(), elementType, false));
t = jp.nextToken();
}
for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
String key = jp.getCurrentName();
jp.nextToken();
map.put(key, getValue(jp, type.getMapValueType(), elementType, false));
}
return map;
}
if (type.isArray()) {
JsonToken t = jp.getCurrentToken();
// if the passStartArrayToken is true, we already performed jp.nextToken
// so there is no need to check if the current token is
if(!passInitialToken) {
if(t != JsonToken.START_ARRAY) {
return null;
} else {
t = jp.nextToken();
}
}
Schema elementType = actualSchema.getElementType();
List<Object> objects = new ArrayList<>();
for (; t != JsonToken.END_ARRAY; t = jp.nextToken()) {
objects.add(getValue(jp, type.getArrayElementType(), elementType, false));
}
return new GenericData.Array(actualSchema, objects);
}
throw new JsonMappingException(format("type is not supported."));
}
}
private FieldType getType(JsonParser jp) throws IOException {
switch (jp.getCurrentToken()) {
case VALUE_NULL:
return null;
case VALUE_STRING:
String value = jp.getValueAsString();
if (DATE_PATTERN.matcher(value).matches()) {
return FieldType.DATE;
}
if (TIMESTAMP_PATTERN.matcher(value).matches()) {
return FieldType.TIMESTAMP;
}
// if (TIME_PATTERN.matcher(value).matches()) {
// return FieldType.TIME;
return FieldType.STRING;
case VALUE_FALSE:
return FieldType.BOOLEAN;
case VALUE_NUMBER_FLOAT:
case VALUE_NUMBER_INT:
return FieldType.DOUBLE;
case VALUE_TRUE:
return FieldType.BOOLEAN;
case START_ARRAY:
JsonToken t = jp.nextToken();
if(t == JsonToken.END_ARRAY) {
// if the array is null, return null as value.
// TODO: if the key already has a type, return that type instead of null.
return null;
}
return getType(jp).convertToArrayType();
case START_OBJECT:
t = jp.nextToken();
if(t == JsonToken.END_OBJECT) {
// if the map is null, return null as value.
// TODO: if the key already has a type, return that type instead of null.
return null;
}
if(t != JsonToken.FIELD_NAME) {
throw new IllegalArgumentException();
}
jp.nextToken();
return getType(jp).convertToMapValueType();
default:
throw new JsonMappingException(format("the type is not supported: %s", jp.getValueAsString()));
}
}
}
|
package com.helpmobile.forms;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.bean.ManagedBean;
/**
*
* @author Tanman
*/
@ManagedBean
@ApplicationScoped
public class Data {
public Faculty[] getFacultys() {
return Faculty.values();
}
public DegreeLevel[] getDegreeLevels() {
return DegreeLevel.values();
}
public YearLevel[] getYearLevels() {
return YearLevel.values();
}
public Residency[] getResidencys() {
return Residency.values();
}
public Gender[] getGenders() {
return Gender.values();
}
public Country[] getCountrys() {
return Country.values();
}
public Language[] getLanguages() {
return Language.values();
}
public ActivityType[] getActivityTypes() {
return ActivityType.values();
}
}
|
package storm.modules;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
import storm.RobotState;
import storm.interfaces.IShooter;
import storm.utility.Print;
/**
*
* @author Storm
*/
public class Shooter implements IShooter {
SpeedController shooterMotor, transferMotor;
DigitalInput ready, hallEffect;
Counter counter;
boolean shooting,
readyTripped;
double motorSpeed,
calculatedMotorSpeed,
wantedRPM,
period,
RPMcurrent,
RPMdifference,
RPMthreshold;
int state,
timeDifference,
currentTime,
goodRangeCount,
debugCounter,
modFactor;
public Shooter(int shooterMotorChannel,int transferMotorChannel, int IRready, int hallEffectSensor) {
shooterMotor = new Jaguar(shooterMotorChannel);
transferMotor = new Victor(transferMotorChannel);
ready = new DigitalInput(IRready);
hallEffect = new DigitalInput(hallEffectSensor);
readyTripped = false;
counter = new Counter(EncodingType.k1X, hallEffect, hallEffect, false);
counter.clearDownSource();
counter.setUpSourceEdge(true, false);
}
public void startShoot(double distance) {
motorSpeed = getMotorSpeed(distance);
counter.start();
state = 0;
debugCounter = 0;
shooting = true;
goodRangeCount = 0;
modFactor = 10;
startTime = System.currentTimeMillis();
}
long startTime = -1;
public void doShoot() {
// set motor speed, check when ready, move ball into shooter, stop once IR sensor is clear
if (!shooting) return;
switch (state){
case 0:
transferMotor.set(-1);
shooterMotor.set(motorSpeed);
startTime = System.currentTimeMillis();
state ++;
break;
case 1:
if (!ready.get() == true){
transferMotor.set(0);
state ++;}
break ;
case 2:
if (checkRPM() == true){
state ++;
}
break;
case 3:
transferMotor.set(-1);
if (!ready.get() == false) {
startTime = System.currentTimeMillis();
state ++;
}
break;
case 4:
if ((System.currentTimeMillis() - startTime) >= 2000){
state ++;
}
break;
case 5:
endShoot();
RobotState.BALL_CONTAINMENT_COUNT
break;
default:
break;
}
}
private double getMotorSpeed(double distance) {
//convert distance into rpm into motor speed value
wantedRPM = 333.33*distance + 850.63 ;
calculatedMotorSpeed = .0003*wantedRPM + 0.0457;
return calculatedMotorSpeed;
}
private boolean checkRPM(){
//check what the current RPM is
period = counter.getPeriod();
if ((System.currentTimeMillis() - startTime) >= 10000)
{
return true;
}
debugCounter ++;
if (debugCounter % modFactor != 0)
{
return false;
}
if (Double.isInfinite(period) || period <= 0)
{
return false;
}
RPMcurrent = 60/period;
if (RPMcurrent > 3500) return false;
if (RPMcurrent > 1200) modFactor = 5;
else modFactor = 10;
RPMthreshold = wantedRPM / 100;
RPMdifference = wantedRPM - RPMcurrent;
motorSpeed += .00003*RPMdifference;
if (motorSpeed <0) motorSpeed = 0;
if (motorSpeed >1) motorSpeed = 1;
shooterMotor.set(motorSpeed);
if (Math.abs(RPMdifference) < RPMthreshold)
{
goodRangeCount ++;
}else goodRangeCount = 0;
if(goodRangeCount > 10)
{
return true;
}else return false;
}
private void endShoot(){
shooterMotor.set(0);
transferMotor.set(0);
state = 0;
shooting = false;
debugCounter = 0;
}
public boolean isShooting() {
return shooting;
}
}
|
package org.jasig.portal.layout;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.jasig.portal.PortalException;
import org.jasig.portal.layout.restrictions.IUserLayoutRestriction;
import org.jasig.portal.layout.restrictions.PriorityRestriction;
import org.jasig.portal.layout.restrictions.RestrictionTypes;
import org.jasig.portal.utils.CommonUtils;
import org.jasig.portal.utils.GuidGenerator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* The aggregated user layout implementation.
*
* @author <a href="mailto:mvi@immagic.com">Michael Ivanov</a>
* @version $Revision$
*/
public class AggregatedLayout implements IAggregatedLayout {
// The hashtable with the layout nodes
private Hashtable layout = null;
// The layout ID value
private String layoutId;
// The restriction mask
private int restrictionMask = 0;
// The IDs and names of the fragments which a user is owner of
private Hashtable fragments = null;
// The layout manager
private IAggregatedUserLayoutManager layoutManager = null;
// GUID generator
private static GuidGenerator guid = null;
private String cacheKey = null;
public AggregatedLayout ( String layoutId, IAggregatedUserLayoutManager layoutManager ) throws PortalException {
this ( layoutId );
this.layoutManager = layoutManager;
restrictionMask = layoutManager.getRestrictionMask();
}
public AggregatedLayout ( String layoutId ) throws PortalException {
this.layoutId = layoutId;
try {
if ( guid == null )
guid = new GuidGenerator();
updateCacheKey();
} catch ( Exception e ) {
throw new PortalException(e);
}
}
public void setLayoutManager ( IAggregatedUserLayoutManager layoutManager ) {
this.layoutManager = layoutManager;
}
public void setLayoutData ( Hashtable layout ) throws PortalException {
this.layout = layout;
}
public Hashtable getLayoutData() throws PortalException {
return layout;
}
private void updateCacheKey() {
cacheKey = guid.getNewGuid();
}
private void bindRestrictions( IALNodeDescription nodeDesc, ContentHandler contentHandler ) throws SAXException {
Hashtable restrictions = nodeDesc.getRestrictions();
for ( Enumeration e = restrictions.keys(); e.hasMoreElements(); ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction ) e.nextElement();
if ( ( restriction.getRestrictionType() & restrictionMask ) > 0 ) {
AttributesImpl paramAttrs = new AttributesImpl();
paramAttrs.addAttribute("","path","path","CDATA",restriction.getRestrictionPath());
// we have to re-scale the priority restriction for the UI
if ( ( restriction.getRestrictionType() & RestrictionTypes.PRIORITY_RESTRICTION ) > 0 ) {
PriorityRestriction priorRestriction = (PriorityRestriction) restriction;
paramAttrs.addAttribute("","value","value","CDATA",((int)priorRestriction.getMinValue()/IAggregatedUserLayoutManager.PRIORITY_COEFF)+"-"+
((int)priorRestriction.getMaxValue()/IAggregatedUserLayoutManager.PRIORITY_COEFF));
} else
paramAttrs.addAttribute("","value","value","CDATA",restriction.getRestrictionExpression());
paramAttrs.addAttribute("","type","type","CDATA",restriction.getRestrictionType()+"");
contentHandler.startElement("",RESTRICTION,RESTRICTION,paramAttrs);
contentHandler.endElement("",RESTRICTION,RESTRICTION);
}
}
}
public ALNode getLayoutNode(String nodeId) {
if ( nodeId != null )
return (ALNode)layout.get(nodeId);
return null;
}
public ALFolder getLayoutFolder(String folderId) {
if ( folderId != null )
return (ALFolder)layout.get(folderId);
return null;
}
public ALNode getLastSiblingNode ( String nodeId ) {
ALNode node = null;
for ( String nextId = nodeId; nextId != null; ) {
node = getLayoutNode(nextId);
nextId = node.getNextNodeId();
}
return node;
}
public ALNode getFirstSiblingNode ( String nodeId ) {
ALNode node = null;
for ( String prevId = nodeId; prevId != null; ) {
node = getLayoutNode(prevId);
prevId = node.getPreviousNodeId();
}
return node;
}
private void createMarkingLeaf(ContentHandler contentHandler, String leafName, String parentNodeId, String nextNodeId) throws PortalException {
try {
AttributesImpl attributes = new AttributesImpl();
attributes.addAttribute("","parentID","parentID","CDATA",parentNodeId);
attributes.addAttribute("","nextID","nextID","CDATA",CommonUtils.nvl(nextNodeId));
contentHandler.startElement("",leafName,leafName,attributes);
contentHandler.endElement("",leafName,leafName);
} catch ( SAXException saxe ) {
throw new PortalException(saxe.getMessage());
}
}
private void createMarkingLeaf(Document document, String leafName, String parentNodeId, String nextNodeId, Node node) throws PortalException {
try {
Element markingLeaf = document.createElement(leafName);
markingLeaf.setAttribute("parentID",parentNodeId);
markingLeaf.setAttribute("nextID",nextNodeId);
node.appendChild(markingLeaf);
} catch ( Exception saxe ) {
throw new PortalException(saxe.getMessage());
}
}
private void createFragmentList(Document document, Node rootNode) throws PortalException {
try {
Element alternateLayouts = document.createElement("alternateLayouts");
if ( fragments != null ) {
for ( Enumeration fragEnum = fragments.keys(); fragEnum.hasMoreElements(); ) {
Element alternate = document.createElement("alternate");
String key = (String) fragEnum.nextElement();
alternate.setAttribute("ID",key);
alternate.setAttribute("name",(String) fragments.get(key));
alternateLayouts.appendChild(alternate);
}
}
rootNode.appendChild(alternateLayouts);
} catch ( Exception saxe ) {
throw new PortalException(saxe.getMessage());
}
}
private void createFragmentList(ContentHandler contentHandler) throws PortalException {
try {
contentHandler.startElement("","alternateLayouts","alternateLayouts",new AttributesImpl());
if ( fragments != null ) {
for ( Enumeration fragEnum = fragments.keys(); fragEnum.hasMoreElements(); ) {
AttributesImpl attributes = new AttributesImpl();
String key = (String) fragEnum.nextElement();
attributes.addAttribute("","ID","ID","CDATA",key);
attributes.addAttribute("","name","name","CDATA",(String) fragments.get(key));
contentHandler.startElement("","alternate","alternate",attributes);
contentHandler.endElement("","alternate","alternate");
}
}
contentHandler.endElement("","alternateLayouts","alternateLayouts");
} catch ( SAXException saxe ) {
throw new PortalException(saxe.getMessage());
}
}
/**
* Build the DOM consistent of folders and channels using the internal representation
* @param domLayout a <code>Document</code> a user layout document.
* @param node a <code>Element</code> a node that will be used as a root for the tree construction
* @param nodeId a <code>String</code> a nodeId from the user layout internal representation
* @exception PortalException if an error occurs
*/
private void appendDescendants(Document domLayout,Node node, String nodeId) throws PortalException {
ALNode layoutNode = getLayoutNode(nodeId);
IALNodeDescription nodeDesc = layoutNode.getNodeDescription();
Element markingMoveLeaf = null, markingAddLeaf = null;
Element newNode = domLayout.createElement((layoutNode.getNodeType()==IUserLayoutNodeDescription.FOLDER)?FOLDER:CHANNEL);
layoutNode.addNodeAttributes(newNode);
String parentId = layoutNode.getParentNodeId();
String nextId = layoutNode.getNextNodeId();
if ( layoutManager != null && parentId != null && layoutNode.getPreviousNodeId() == null ) {
if ( !nodeDesc.isHidden() && !getLayoutNode(parentId).getNodeDescription().isHidden() ) {
IALNodeDescription moveTargetsNodeDesc = layoutManager.getNodeBeingMoved();
String moveTargetsNodeId = ( moveTargetsNodeDesc != null ) ? moveTargetsNodeDesc.getId() : null;
IALNodeDescription addTargetsNodeDesc = layoutManager.getNodeBeingAdded();
if ( addTargetsNodeDesc != null && layoutManager.canAddNode(addTargetsNodeDesc,parentId,nodeId) )
createMarkingLeaf(domLayout,ADD_TARGET,parentId,nodeId,node);
if ( moveTargetsNodeId != null && layoutManager.canMoveNode(moveTargetsNodeId,parentId,nodeId) )
createMarkingLeaf(domLayout,MOVE_TARGET,parentId,nodeId,node);
}
}
// Appending a new node
node.appendChild(newNode);
if ( parentId != null ) {
boolean isNodeMarkable = false;
if ( nextId != null && !getLayoutNode(nextId).getNodeDescription().isHidden() )
isNodeMarkable = true;
else if ( nextId == null )
isNodeMarkable = true;
if ( layoutManager != null && isNodeMarkable && !getLayoutNode(parentId).getNodeDescription().isHidden() ) {
IALNodeDescription moveTargetsNodeDesc = layoutManager.getNodeBeingMoved();
String moveTargetsNodeId = ( moveTargetsNodeDesc != null ) ? moveTargetsNodeDesc.getId() : null;
IALNodeDescription addTargetsNodeDesc = layoutManager.getNodeBeingAdded();
if ( addTargetsNodeDesc != null && layoutManager.canAddNode(addTargetsNodeDesc,parentId,nextId) )
createMarkingLeaf(domLayout,ADD_TARGET,parentId,nextId,node);
if ( moveTargetsNodeId != null && !moveTargetsNodeId.equals(nextId) &&
layoutManager.canMoveNode(moveTargetsNodeId,parentId,nextId) )
createMarkingLeaf(domLayout,MOVE_TARGET,parentId,nextId,node);
}
}
// Adding restrictions to the node
nodeDesc.addRestrictionChildren(newNode,domLayout);
if ( layoutNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
// Loop for all children
String firstChildId = ((ALFolder)layoutNode).getFirstChildNodeId();
for ( String nextNodeId = firstChildId; nextNodeId != null; ) {
appendDescendants(domLayout,newNode,nextNodeId);
nextNodeId = getLayoutNode(nextNodeId).getNextNodeId();
}
} else if ( layoutNode.getNodeType() == IUserLayoutNodeDescription.CHANNEL ) {
ALChannelDescription channelDesc = (ALChannelDescription) nodeDesc;
// Adding channel parameters
channelDesc.addParameterChildren(newNode,domLayout);
}
}
/**
* Returns a list of fragment Ids existing in the layout.
*
* @return a <code>List</code> of <code>String</code> fragment Ids.
* @exception PortalException if an error occurs
*/
public Enumeration getFragmentIds() throws PortalException {
return null;
}
/**
* Returns an fragment Id for a given node.
* Returns null if the node is not part of any fragments.
*
* @param nodeId a <code>String</code> value
* @return a <code>String</code> fragment Id
* @exception PortalException if an error occurs
*/
public String getFragmentId(String nodeId) throws PortalException {
return null;
}
/**
* Returns an fragment root Id for a given fragment.
*
* @param fragmentId a <code>String</code> value
* @return a <code>String</code> fragment root Id
* @exception PortalException if an error occurs
*/
public String getFragmentRootId(String fragmentId) throws PortalException {
return null;
}
/**
* Writes user layout content (with appropriate markings) into
* a <code>ContentHandler</code>
*
* @param ch a <code>ContentHandler</code> value
* @exception PortalException if an error occurs
*/
public void writeTo(ContentHandler ch) throws PortalException {
writeTo ( getRootId(), ch );
}
/**
* Writes subtree of a user layout (with appropriate markings) defined by a particular node into
* a <code>ContentHandler</code>
*
* @param nodeId a <code>String</code> a node determining a user layout subtree.
* @param contentHandler a <code>ContentHandler</code> value
* @exception PortalException if an error occurs
*/
public void writeTo(String nodeId, ContentHandler contentHandler ) throws PortalException {
IALFolderDescription folderDescription = null;
IALChannelDescription channelDescription = null;
if ( contentHandler != null && nodeId != null ) {
try {
ALNode node = getLayoutNode(nodeId);
AttributesImpl attributes = new AttributesImpl();
// If we have a folder
if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
// Start document if we have the root node
if (nodeId.equals(getRootId())) contentHandler.startDocument();
if (nodeId.equals(getRootId())) {
contentHandler.startElement("",LAYOUT,LAYOUT,new AttributesImpl());
// Create a fragment list that the user owns
createFragmentList(contentHandler);
}
ALFolder folder = (ALFolder) node;
folderDescription = (IALFolderDescription) node.getNodeDescription();
attributes.addAttribute("","ID","ID","ID",nodeId);
attributes.addAttribute("","type","type","CDATA",
IUserLayoutFolderDescription.folderTypeNames[folderDescription.getFolderType()]);
attributes.addAttribute("","hidden","hidden","CDATA",CommonUtils.boolToStr(folderDescription.isHidden()));
attributes.addAttribute("","unremovable","unremovable","CDATA",CommonUtils.boolToStr(folderDescription.isUnremovable()));
attributes.addAttribute("","immutable","immutable","CDATA",CommonUtils.boolToStr(folderDescription.isImmutable()));
attributes.addAttribute("","name","name","CDATA",folderDescription.getName());
contentHandler.startElement("",FOLDER,FOLDER,attributes);
// Loop for all children
String firstChildId = folder.getFirstChildNodeId();
for ( String nextNodeId = firstChildId; nextNodeId != null; ) {
// if necessary we add marking nodes
if ( layoutManager != null ) {
if ( !node.getNodeDescription().isHidden() && !getLayoutNode(nextNodeId).getNodeDescription().isHidden() ) {
IALNodeDescription nodeDesc = layoutManager.getNodeBeingMoved();
String moveTargetsNodeId = ( nodeDesc != null ) ? nodeDesc.getId() : null;
IALNodeDescription addTargetsNodeDesc = layoutManager.getNodeBeingAdded();
if ( addTargetsNodeDesc != null && layoutManager.canAddNode(addTargetsNodeDesc,nodeId,nextNodeId) )
createMarkingLeaf(contentHandler,ADD_TARGET,nodeId,nextNodeId);
if ( moveTargetsNodeId != null && !moveTargetsNodeId.equals(nextNodeId) && layoutManager.canMoveNode(moveTargetsNodeId,nodeId,nextNodeId) )
createMarkingLeaf(contentHandler,MOVE_TARGET,nodeId,nextNodeId);
}
}
// Recurrence
writeTo (nextNodeId,contentHandler);
nextNodeId = getLayoutNode(nextNodeId).getNextNodeId();
}
// if necessary we add marking nodes to the end of the sibling line
if ( layoutManager != null && !node.getNodeDescription().isHidden() ) {
IALNodeDescription nodeDesc = layoutManager.getNodeBeingMoved();
String moveTargetsNodeId = ( nodeDesc != null ) ? nodeDesc.getId() : null;
IALNodeDescription addTargetsNodeDesc = layoutManager.getNodeBeingAdded();
if ( addTargetsNodeDesc != null && layoutManager.canAddNode(addTargetsNodeDesc,nodeId,null) )
createMarkingLeaf(contentHandler,ADD_TARGET,nodeId,null);
if ( moveTargetsNodeId != null && layoutManager.canMoveNode(moveTargetsNodeId,nodeId,null) )
createMarkingLeaf(contentHandler,MOVE_TARGET,nodeId,null);
}
// Putting restrictions to the content handler
if ( restrictionMask > 0 )
bindRestrictions(folderDescription,contentHandler);
contentHandler.endElement("",FOLDER,FOLDER);
// Start document if we have the root node
if (nodeId.equals(getRootId())) contentHandler.endElement("",LAYOUT,LAYOUT);
if (nodeId.equals(getRootId())) contentHandler.endDocument();
// If we have a channel
} else {
channelDescription = (IALChannelDescription) node.getNodeDescription();
attributes.addAttribute("","ID","ID","ID",nodeId);
attributes.addAttribute("","typeID","typeID","CDATA",channelDescription.getChannelTypeId());
attributes.addAttribute("","hidden","hidden","CDATA",CommonUtils.boolToStr(channelDescription.isHidden()));
attributes.addAttribute("","editable","editable","CDATA",CommonUtils.boolToStr(channelDescription.isEditable()));
attributes.addAttribute("","unremovable","unremovable","CDATA",CommonUtils.boolToStr(channelDescription.isUnremovable()));
attributes.addAttribute("","immutable","immutable","CDATA",CommonUtils.boolToStr(channelDescription.isImmutable()));
attributes.addAttribute("","name","name","CDATA",channelDescription.getName());
attributes.addAttribute("","description","description","CDATA",channelDescription.getDescription());
attributes.addAttribute("","title","title","CDATA",channelDescription.getTitle());
attributes.addAttribute("","class","class","CDATA",channelDescription.getClassName());
attributes.addAttribute("","chanID","chanID","CDATA",channelDescription.getChannelPublishId());
attributes.addAttribute("","fname","fname","CDATA",channelDescription.getFunctionalName());
attributes.addAttribute("","timeout","timeout","CDATA",String.valueOf(channelDescription.getTimeout()));
attributes.addAttribute("","hasHelp","hasHelp","CDATA",CommonUtils.boolToStr(channelDescription.hasHelp()));
attributes.addAttribute("","hasAbout","hasAbout","CDATA",CommonUtils.boolToStr(channelDescription.hasAbout()));
attributes.addAttribute("","secure","secure","CDATA",CommonUtils.boolToStr(channelDescription.isSecure()));
contentHandler.startElement("",CHANNEL,CHANNEL,attributes);
if ( channelDescription.hasParameters() ) {
Enumeration paramNames = channelDescription.getParameterNames();
while ( paramNames.hasMoreElements() ) {
String name = (String) paramNames.nextElement();
String value = channelDescription.getParameterValue(name);
AttributesImpl paramAttrs = new AttributesImpl();
paramAttrs.addAttribute("","name","name","CDATA",name);
paramAttrs.addAttribute("","value","value","CDATA",value);
paramAttrs.addAttribute("","override","override","CDATA",
channelDescription.canOverrideParameter(name)?"yes":"no");
contentHandler.startElement("",PARAMETER,PARAMETER,paramAttrs);
contentHandler.endElement("",PARAMETER,PARAMETER);
}
}
// Putting restrictions to the content handler
if ( restrictionMask > 0 )
bindRestrictions(channelDescription,contentHandler);
contentHandler.endElement("",CHANNEL,CHANNEL);
}
} catch ( SAXException saxe ) {
throw new PortalException(saxe.getMessage());
}
}
}
/**
* Writes user layout content (with appropriate markings) into
* a <code>Document</code> object
*
* @param document a <code>Document</code> value
* @exception PortalException if an error occurs
*/
public void writeTo(Document document) throws PortalException {
writeTo ( getRootId(), document );
}
/**
* Writes subtree of a user layout (with appropriate markings) defined by a particular node into
* a <code>Document</code>
*
* @param nodeId a <code>String</code> a node determining a user layout subtree.
* @param document a <code>Document</code> object
* @exception PortalException if an error occurs
*/
public void writeTo(String nodeId, Document document) throws PortalException {
try {
Element layoutNode = document.createElement((nodeId.equals(getRootId()))?LAYOUT:FRAGMENT);
document.appendChild(layoutNode);
// Create a fragment list which the user owns
if (nodeId.equals(getRootId()))
createFragmentList(document,layoutNode);
// Build the DOM
appendDescendants(document,layoutNode,nodeId);
} catch ( Exception e ) {
e.printStackTrace();
throw new PortalException ("Couldn't create the DOM representation: " + e );
}
}
/**
* Obtain a description of a node (channel or a folder) in a given user layout.
*
* @param nodeId a <code>String</code> channel subscribe id or folder id.
* @return an <code>UserLayoutNodeDescription</code> value
* @exception PortalException if an error occurs
*/
public IUserLayoutNodeDescription getNodeDescription(String nodeId) throws PortalException {
ALNode node = getLayoutNode(nodeId);
if ( node != null )
return node.getNodeDescription();
throw new PortalException ( "The node with nodeID="+nodeId+" does not exist in the layout!" );
}
/**
* Returns a node specified by a node ID.
*
* @param nodeId a <code>String</code> value
* @return a <code>ALNode</code> object
* @exception PortalException if an error occurs
*/
public ALNode getNode( String nodeId) throws PortalException {
return getLayoutNode(nodeId);
}
/**
* Returns an Id of a parent user layout node.
* The user layout root node always has ID="root"
*
* @param nodeId a <code>String</code> value
* @return a <code>String</code> value
* @exception PortalException if an error occurs
*/
public String getParentId(String nodeId) throws PortalException {
ALNode node = getLayoutNode(nodeId);
if ( node != null )
return node.getParentNodeId();
throw new PortalException ( "The node with nodeID="+nodeId+" does not exist in the layout!" );
}
/**
* Returns a list of child node Ids for a given node.
*
* @param nodeId a <code>String</code> value
* @return a <code>Enumeration</code> of <code>String</code> child node Ids.
* @exception PortalException if an error occurs
*/
public Enumeration getChildIds(String nodeId) throws PortalException {
Vector childIds = new Vector();
String firstChildId = getLayoutFolder(nodeId).getFirstChildNodeId();
for ( String nextNodeId = firstChildId; nextNodeId != null; ) {
childIds.add(nextNodeId);
nextNodeId = getLayoutNode(nextNodeId).getNextNodeId();
}
return childIds.elements();
}
/**
* Determine an Id of a next sibling node.
*
* @param nodeId a <code>String</code> value
* @return a <code>String</code> Id value of a next sibling node, or <code>null</code> if this is the last sibling.
* @exception PortalException if an error occurs
*/
public String getNextSiblingId(String nodeId) throws PortalException {
ALNode node = getLayoutNode(nodeId);
if ( node != null )
return node.getNextNodeId();
throw new PortalException ( "The node with nodeID="+nodeId+" does not exist in the layout!" );
}
/**
* Determine an Id of a previous sibling node.
*
* @param nodeId a <code>String</code> value
* @return a <code>String</code> Id value of a previous sibling node, or <code>null</code> if this is the first sibling.
* @exception PortalException if an error occurs
*/
public String getPreviousSiblingId(String nodeId) throws PortalException {
ALNode node = getLayoutNode(nodeId);
if ( node != null )
return node.getPreviousNodeId();
throw new PortalException ( "The node with nodeID="+nodeId+" does not exist in the layout!" );
}
/**
* Return a cache key, uniqly corresponding to the composition and the structure of the user layout.
*
* @return a <code>String</code> value
* @exception PortalException if an error occurs
*/
public String getCacheKey() throws PortalException {
return cacheKey;
}
/**
* Register a layout event listener
*
* @param l a <code>LayoutEventListener</code> object
* @return a <code>boolean</code> success status
*/
public boolean addLayoutEventListener(LayoutEventListener l) {
// TO IMPLEMENT
return false;
}
/**
* Remove a registered layout event listener.
*
* @param l a <code>LayoutEventListener</code> object
* @return a <code>boolean</code> success status
*/
public boolean removeLayoutEventListener(LayoutEventListener l) {
// TO IMPLEMENT
return false;
}
/**
* Returns a layout Id associated with this manager/
*
* @return an <code>String</code> layout Id value;
*/
public String getId() {
return layoutId;
}
/**
* Returns a node id associated with the supplied functional name.
*
* @param fname the functional name to lookup
* @return a <code>String</code> subscription id
* @exception PortalException if an error occurs
*/
public String getNodeId(String fname) throws PortalException {
for ( Enumeration nodeIds = layout.keys(); nodeIds.hasMoreElements() ;) {
String nodeId = nodeIds.nextElement().toString();
ALNode node = getLayoutNode(nodeId);
if ( node.getNodeType() == IUserLayoutNodeDescription.CHANNEL ) {
ALChannelDescription channelDesc = (ALChannelDescription) node.getNodeDescription();
if ( fname.equals(channelDesc.getFunctionalName()) )
return node.getId();
}
}
return null;
}
/**
* Returns a list of node Ids in the layout.
*
* @return a <code>Enumeration</code> of node Ids
* @exception PortalException if an error occurs
*/
public Enumeration getNodeIds() throws PortalException {
if ( layout == null )
throw new PortalException ( "The layout is NULL!" );
return layout.keys();
}
/**
* Returns an id of the root node.
*
* @return a <code>String</code> value
*/
public String getRootId() {
return IALFolderDescription.ROOT_FOLDER_ID;
}
}
|
package org.jasig.portal.services;
import org.jasig.portal.security.*;
import org.jasig.portal.security.provider.PersonImpl;
/**
* @author Ken Weiner, kweiner@interactivebusiness.com
* @version $Revision$
*/
public class Authentication
{
protected org.jasig.portal.security.IPerson m_Person = null;
protected ISecurityContext ic = null;
/**
* Authenticate a user.
* @param sUserName User name
* @param sPassword User password
* @return true if successful, otherwise false.
*/
public boolean authenticate (String sUserName, String sPassword)
throws PortalSecurityException
{
IPrincipal me;
IOpaqueCredentials op;
ic = new InitialSecurityContext("root");
me = ic.getPrincipalInstance();
op = ic.getOpaqueCredentialsInstance();
me.setUID(sUserName);
op.setCredentials(sPassword);
ic.authenticate();
me=ic.getPrincipal(); /* get the principal which may have changed */
// Check to see if the user is authenticated
boolean bAuthenticated = ic.isAuthenticated ();
if(bAuthenticated)
{
// Get the AdditionalDescriptor from the security context
// IPerson object
IAdditionalDescriptor addInfo = ic.getAdditionalDescriptor();
// Create a new IPerson if the descriptor is missing or is not an IPerson
if (addInfo == null || !(addInfo instanceof PersonImpl))
{
// Create a new IPerson
m_Person = new PersonImpl();
// Make sure the user's global ID is set
m_Person.setID(me.getGlobalUID());
// Set the user's full name
m_Person.setFullName(me.getFullName());
}
else
{
// Set the IPerson to be the AdditionalDescriptor object
m_Person = (IPerson)addInfo;
}
}
return (bAuthenticated);
}
/**
* Returns an IPerson object that can be used to hold site-specific attributes
* about the logged on user. This information is established during
* authentication.
* @return An object that implements the
* <code>org.jasig.portal.security.IPerson</code> interface.
*/
public IPerson getPerson ()
{
return m_Person;
}
/**
* Returns an ISecurityContext object that can be used
* later. This object is passed as part of the IChannel Interface.
* The security context may be used to gain authorized access to
* services.
* @return An object that implements the
* <code>org.jasig.portal.security.ISecurityContext</code> interface.
*/
public ISecurityContext getSecurityContext ()
{
return ic;
}
}
|
package jsaf.intf.service;
import java.util.Collection;
import jsaf.intf.net.IService;
/**
* An interface describing a machine that hosts network services (i.e., /etc/services).
*
* Classes implementing ISession may optionally implement this IServiceHost interface as well.
*
* @author David A. Solin
* @version %I% %G%
* @since 1.4
*/
public interface IServiceHost {
/**
* Returns a collection of IService instances running on the host.
*/
Collection<IService> getServices();
}
|
package kilim.plugins;
import kilim.tools.Weaver;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import java.io.File;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
/**
* maven plugin for ahead-of-time weaving of class files
*/
@Mojo(name = "weave", defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES,
requiresDependencyResolution=ResolutionScope.RUNTIME)
public class KilimMavenPlugin extends AbstractMojo {
/**
* Location of the class files.
*/
@Parameter(defaultValue = "${project.build.outputDirectory}", property = "kilimIn", required = true)
private File inputDirectory;
@Parameter(defaultValue = "${project.build.testOutputDirectory}", property = "kilimTin", required = true)
private File testDirectory;
/**
* Location of the woven class files.
*/
@Parameter(defaultValue = "${project.build.outputDirectory}", property = "kilimOut", required = true)
private File outputDirectory;
@Parameter(defaultValue = "${project.build.testOutputDirectory}", property = "kilimTout", required = true)
private File testOutputDirectory;
@Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject project;
public void execute() throws MojoExecutionException {
try {
String indir = inputDirectory.getAbsolutePath();
String tindir = testDirectory.getAbsolutePath();
String outdir = outputDirectory.getAbsolutePath();
String toutdir = testOutputDirectory.getAbsolutePath();
{
getLog().info("kilim weaver input/output dirs are: " + indir + ", " + outdir);
String [] roots = project.getCompileClasspathElements().toArray(new String[0]);
Weaver.outputDir = outdir;
int err = Weaver.doMain(new String []{ indir },roots);
getLog().info("kilim weaver done");
if (err > 0)
throw new MojoExecutionException("Error while weaving the classes");
}
{
getLog().info("kilim weaver test input/output dirs are: " + tindir + ", " + toutdir);
String [] troots = project.getTestClasspathElements().toArray(new String[0]);
Weaver.outputDir = toutdir;
int err = Weaver.doMain(new String []{ tindir },troots);
getLog().info("kilim weaver done - tests");
if (err > 0)
throw new MojoExecutionException("Error while weaving the test classes");
}
} catch (Exception e) {
throw new MojoExecutionException("Error while weaving the classes", e);
}
}
}
|
package test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.ios.IOSDriver;
import java.io.File;
import java.net.URL;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
*
*
* @author Feliks Rozenberg frozenbe@alumni.uwo.ca
*/
@SuppressWarnings("deprecation")
public class SimpleAppiumTest {
private AppiumDriver<WebElement> driver;
@Before
public void setUp() throws Exception {
// set up appium
String appPath = System.getProperty("appPath");
System.out.println("appPath: " + appPath);
File app = new File(appPath);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformVersion", "9.0");
capabilities.setCapability("deviceName", "iPhone 6s");
capabilities.setCapability("app", app.getAbsolutePath());
driver = new IOSDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
@After
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void testLaunch() throws Exception {
Thread.sleep(3000);
assertTrue(true);
}
}
|
package testsuite.group;
import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import testsuite.exception.BrowsePackageException;
import testsuite.manager.AbstractManager;
import testsuite.result.ResultsCollections;
import testsuite.test.AbstractTest;
import testsuite.test.Benchmark;
import testsuite.timer.Timeable;
/** It is a collection of tests.
* @author Alexandre di Costanzo
*/
public class Group {
/** A group name.
*/
private String name = "Group with no name";
/** A group description.
*/
private String description = "Group with no description.";
/** A logger for a group.
*/
protected static Logger logger = null;
/** All results of a group.
*/
private ResultsCollections results = new ResultsCollections();
/** All the tests of a group.
*/
private ArrayList<AbstractTest> tests = new ArrayList<AbstractTest>();
/** To construct a new group with default params.
*/
public Group() {
logger = ProActiveLogger.getLogger("testsuite");
}
/** To construct a new group from an another group.
* @param group an ancestor group.
*/
public Group(Group group) {
logger = ProActiveLogger.getLogger("testsuite");
this.results = new ResultsCollections(group.getResults());
this.tests = new ArrayList<AbstractTest>(group.tests);
this.name = group.name;
this.description = group.description;
}
/** To construct a new group.
* @param name a string name for a group.
* @param description a string description for a group.
*/
public Group(String name, String description) {
logger = ProActiveLogger.getLogger("testsuite");
this.name = name;
this.description = description;
}
/** To construct a new group from tests in a specified package.
* @param name a group name
* @param description a group description.
* @param directory the root of the package to scan.
* @param packageName the package name to add : com.toto.gui.
* @param params params for construct test.
* @param useInitFile true if you want to build tests with their init's files.
* @throws BrowsePackageException if some errors.
*/
public Group(String name, String description, File directory,
String packageName, Object[] params, boolean useInitFile,
AbstractManager manager) throws BrowsePackageException {
logger = ProActiveLogger.getLogger("testsuite");
this.name = name;
this.description = description;
addTests(directory, packageName, packageName, params, useInitFile,
manager);
}
public Group(File directory, String packageName, Object[] params,
boolean useInitFile, AbstractManager manager)
throws BrowsePackageException {
logger = Logger.getLogger("testsuite");
addTests(directory, packageName, packageName, params, useInitFile,
manager);
}
private static FileFilter dirFilter = new FileFilter() {
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
} else {
return false;
}
}
};
private static FileFilter dirClassFilter = new FileFilter() {
public boolean accept(File pathname) {
if (pathname.getName().endsWith(".class") ||
pathname.isDirectory()) {
return true;
} else {
return false;
}
}
};
/** Private method to construct group with tests from a package.
* @param directory the root directory of a package.
* @param packageName the package name to add : com.toto.gui.
* @param params params for construct test.
* @param useInitFile true if you want to init tests with their init file.
* @throws BrowsePackageException if an error.
*/
private void addTests(File directory, String packageName,
String parentPackage, Object[] params, boolean useInitFile,
AbstractManager manager) throws BrowsePackageException {
if (!directory.isDirectory()) {
throw new BrowsePackageException("Directory " +
directory.getPath() + " is not a valid directory");
}
if ((packageName != null) && (packageName.length() != 0)) {
// Find files package
File[] files = directory.listFiles(dirFilter);
String nextRep = null;
if (packageName.indexOf('.') != -1) {
nextRep = packageName.substring(0, packageName.indexOf('.'));
} else {
nextRep = packageName;
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.getName().compareTo(nextRep) == 0) {
String nextPackageName = "";
if (packageName.indexOf('.') != -1) {
nextPackageName = packageName.substring(packageName.indexOf(
'.') + 1);
} else {
nextPackageName = null;
}
addTests(file, nextPackageName, parentPackage, params,
useInitFile, manager);
} else {
continue;
}
}
} else {
// Files package founded
File[] files = directory.listFiles(dirClassFilter);
Class[] parameterTypes = null;
if ((params != null) && (params.length != 0)) {
parameterTypes = new Class[params.length];
for (int j = 0; j < params.length; j++)
parameterTypes[j] = params[j].getClass();
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
addTests(file, null, parentPackage + "." + file.getName(),
params, useInitFile, manager);
} else {
String fileTest = parentPackage + "." +
file.getName().replaceAll("\\.class", "");
try {
Class c = getClass().getClassLoader().loadClass(fileTest);
// if (file.getName().matches("Test.*") ||
// file.getName().matches("Bench.*")) {
Class superClass = c;
while ((superClass.getSuperclass() != null) &&
(superClass.getSuperclass() != Object.class))
superClass = superClass.getSuperclass();
if (superClass.getName().compareTo(AbstractTest.class.getName()) == 0) {
AbstractTest test = null;
if (Modifier.isAbstract(c.getModifiers())) {
// class is abstract
continue;
}
if (parameterTypes != null) {
Constructor constructor = c.getConstructor(parameterTypes);
test = (AbstractTest) constructor.newInstance(params);
} else {
test = (AbstractTest) c.newInstance();
}
test.setManager(manager);
if (logger.isDebugEnabled()) {
logger.debug(test.getName() +
" added in group " + name);
}
if (useInitFile) {
test.loadAttributes();
}
tests.add(test);
} else {
continue;
}
} catch (Exception e) {
throw new BrowsePackageException(e);
}
}
}
}
}
public void initGroup(Timeable timer) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Beginning groupTest " + name + "' initialization");
}
Iterator<AbstractTest> it = tests.iterator();
while (it.hasNext()) {
AbstractTest test = it.next();
test.uponInitOfGroupOfTests();
if (timer != null) {
((Benchmark) test).setTimer(timer);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Finnishing groupTest " + name + "' initialization");
}
}
/** Run the init method of all tests and set the tests loggers with the group logger.
* @throws Exception if error during the initialization of tests.
*/
public void initGroup() throws Exception {
this.initGroup(null);
}
/** run the end method of all tests.
* @throws Exception if errors during ending a tests.
*/
public void endGroup() throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Beginning groupTest " + name + "' ending");
}
Iterator<AbstractTest> it = tests.iterator();
while (it.hasNext()) {
AbstractTest test = it.next();
test.uponEndOfGroupOfTests();
}
if (logger.isDebugEnabled()) {
logger.debug("Finnishing groupTest " + name + "' ending");
}
}
/** To get the group description
* @return a description.
*/
public String getDescription() {
return description;
}
/** To get the group name.
* @return the name.
*/
public String getName() {
return name;
}
/** To set the description.
* @param string a new description.
*/
public void setDescription(String string) {
description = string;
}
/** to set the name.
* @param string a new name.
*/
public void setName(String string) {
name = string;
}
/** Name and description of a group.
* @see java.lang.Object#toString()
* @return a string with the name and the description.
*/
public String toString() {
return name + " : " + description;
}
/** to get the group logger.
* @return a logger.
*/
public Logger getLogger() {
return logger;
}
/** To get all results of the group.
* @return all the results.
*/
public ResultsCollections getResults() {
return results;
}
/** Inserts the specified test at the specified position in this list. Shifts the test currently at that position (if any) and any subsequent tests to the right (adds one to their indices).
* @param index index at which the specified test is to be inserted.
* @param test test to be inserted.
*/
public void add(int index, AbstractTest test) {
tests.add(index, test);
}
/** Appends the specified test to the end of this list.
* @param test test to be appended to this list.
* @return true (as per the general contract of Collection.add).
*/
public boolean add(AbstractTest test) {
return tests.add(test);
}
/** Appends all of the tests in the specified Collection to the end of this list, in the order that they are returned by the specified Collection's Iterator. The behavior of this operation is undefined if the specified Collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified Collection is this list, and this list is nonempty.)
* @param c the tests to be inserted into this list.
* @return true if this list changed as a result of the call.
*/
public boolean addAll(Collection<AbstractTest> c) {
return tests.addAll(c);
}
/** Inserts all of the tests in the specified Collection into this list, starting at the specified position. Shifts the test currently at that position (if any) and any subsequent tests to the right (increases their indices). The new tests will appear in the list in the order that they are returned by the specified Collection's iterator.
* @param index index at which to insert first test from the specified collection.
* @param c tests to be inserted into this list.
* @return true if this list changed as a result of the call.
*/
public boolean addAll(int index, Collection<AbstractTest> c) {
return tests.addAll(index, c);
}
/** Removes all of the tests from this list. The list will be empty after this call returns.
*
*
*/
public void clear() {
tests.clear();
}
/** Returns an iterator over the tests in this list in proper sequence.Returns an iterator over the tests in this list in proper sequence.
* @return an iterator over the tests in this list in proper sequence.
*/
public Iterator<AbstractTest> iterator() {
return tests.iterator();
}
/** Returns true if this list contains the specified test.
* @param test test whose presence in this List is to be tested.
* @return true if the specified test is present; false otherwise.
*/
public boolean contains(AbstractTest test) {
return tests.contains(test);
}
/** Returns the test at the specified position in this list.
* @param index index of test to return.
* @return the test at the specified position in this list.
*/
public AbstractTest get(int index) {
return tests.get(index);
}
/** Searches for the first occurence of the given argument, testing for equality using the equals method.
* @param test an test.
* @return the index of the first occurrence of the argument in this list; returns -1 if the test is not found.
*/
public int indexOf(AbstractTest test) {
return tests.indexOf(test);
}
/** Tests if this list has no tests.
* @return true if this list has no tests; false otherwise.
*/
public boolean isEmpty() {
return tests.isEmpty();
}
/** Removes the test at the specified position in this list. Shifts any subsequent tests to the left (subtracts one from their indices).
* @param index the index of the test to removed.
* @return the test that was removed from the list.
*/
public AbstractTest remove(int index) {
return tests.remove(index);
}
/** Replaces the test at the specified position in this list with the specified test.
* @param index index of test to replace.
* @param test test to be stored at the specified position.
* @return the test previously at the specified position.
*/
public AbstractTest set(int index, AbstractTest test) {
return tests.set(index, test);
}
/** Returns the number of tests in this list.
* @return the number of tests in this list.
*
*
*/
public int size() {
return tests.size();
}
/** Returns an array containing all of the tests in this list in the correct order.
* @return an array containing all of the tests in this list in the correct order.
*/
public AbstractTest[] toArray() {
return tests.toArray(new AbstractTest[size()]);
}
}
|
package traffic.model;
/**
*
* The vehicle object represents a single vehicle on the graph, and holds an info object
* with important information about itself. The vehicle is given a graph traversal strategy
* that it will use to select its path from start to end
*
* @author Jonathan Ramaswamy - ramaswamyj12@gmail.com
* @author Jochen Wuttke - wuttkej@gmail.com
*/
import org.apache.log4j.Logger;
import traffic.graph.GraphNode;
import traffic.strategy.VehicleStrategy;
public class Vehicle extends AbstractAdasimAgent {
private GraphNode start; //Starting position
private GraphNode end; //Destination position
private GraphNode currentNode; //Current position
private int id; //This vehicle's number in the list of vehicles
protected VehicleInfo info; //Info for the vehicle
private VehicleStrategy cs; //Strategy the vehicle uses to traverse the graph
private static Logger logger = Logger.getLogger(Vehicle.class);
protected Vehicle( int id ) {
info = new VehicleInfo();
}
public Vehicle(GraphNode start, GraphNode end, VehicleStrategy strat, int num) {
setStartNode(start);
setEndNode(end);
id = num;
setStrategy(strat);
}
/**
* @return The starting node for the vehicle
*/
public GraphNode getStartNode() {
return start;
}
/**
* @param start the start to set
*/
public void setStartNode(GraphNode start) {
this.start = start;
this.currentNode = start;
//reset the strategy
setStrategy(cs);
}
/**
* @return The ending node for the vehicle
*/
public GraphNode getEndNode() {
return end;
}
/**
* @param end the end to set
*/
public void setEndNode(GraphNode end) {
this.end = end;
//reset the strategy
setStrategy(cs);
}
/**
* @return The current node of the vehicle
*/
public GraphNode getCurrentPosition() {
return currentNode;
}
/**
* Sets the current position to the given variable c
*/
void setCurrentPosition(GraphNode c) {
currentNode = c;
}
/**
* @return The number of this vehicle
*/
public int getID() {
return id;
}
/**
* @return the cs
*/
public VehicleStrategy getStrategy() {
return cs;
}
/**
* @param cs the cs to set
*/
public void setStrategy(VehicleStrategy cs) {
this.cs = cs;
if ( cs != null ) {
cs.setStartNode(start);
cs.setEndNode(end);
cs.setVehicleId(id);
}
}
/**
* @return the position of the car as a string
*/
public String vehiclePosition() {
StringBuffer buf = new StringBuffer( "Vehicle: ");
buf.append( getID() );
buf.append(" At: " );
buf.append( getCurrentPosition().getID() );
return buf.toString();
}
/**
* @return the info
*/
public VehicleInfo getInfo() {
return info;
}
/* (non-Javadoc)
* @see traffic.model.AdasimAgent#takeSimulationStep()
*/
@Override
public void takeSimulationStep( long cycle ) {
if (isFinished()) return; //quick end if we are done
GraphNode nextNode = cs.getNextNode();
if ( nextNode == null ) {
fakeFinish();
logger.info( "STOP: " + vehiclePosition() );
} else {
logger.info( "MOVE: " + vehiclePosition() + " To:" + nextNode.getID() );
//TODO: technically, the nodes should set the vehicles position
setCurrentPosition(nextNode);
nextNode.enterNode(this);
}
}
private void fakeFinish() {
//TODO: replace with correct code in GraphNode
getCurrentPosition().park(this);
setCurrentPosition(end);
}
/* (non-Javadoc)
* @see traffic.model.AbstractAdasimAgent#isFinished()
*/
@Override
public boolean isFinished() {
return currentNode != null && currentNode.equals(end);
}
}
|
package ui;
import dao.PetrukStateXMLDao;
import dao.SetupDialogXMLDAOFactory;
import ui.editor.EditorPanel;
import ui.dialog.StylesSetupDialog;
import ui.dialog.RolesSetupDialog;
import ui.dialog.PinnedTextSetupDialog;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.logging.Logger;
import javax.swing.event.*;
import javax.swing.*;
import model.PetrukState;
import model.PinnedText;
import model.Role;
import model.Style;
import ui.action.PinnedTextTriggerAction;
import ui.action.RoleTriggerAction;
import ui.dialog.FileDialogs;
import ui.dialog.TriggerablesDialog;
public class PetrukUI extends JFrame {
private EditorPanel editorPanel;
private JMenuBar menuBar;
private JMenuItem save_menu_item;
private static AppExitAction exitAction = new AppExitAction();
private static String DEFAULT_TITLE = "Petruk";
private PetrukState petrukState;
private static Logger logger = Logger.getLogger(PetrukUI.class.getPackage().getName());
public PetrukUI(PetrukState petrukState) {
// Force SwingSet to come up in the Cross Platform L&F
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exc) {
System.err.println("Error loading L&F: " + exc);
}
this.petrukState = petrukState;
_setInitialState();
}
protected void _setInitialState() {
// TODO set title to include performance file name
// SET INITIAL BACKGROUND COLOR
this.setBackground(Color.lightGray);
this.getContentPane().setLayout(new BorderLayout());
editorPanel = new EditorPanel();
editorPanel.setCurrentTextStyle(petrukState.getStyles().getFirst());
editorPanel.setStatusBarText("current role: default");
this.getContentPane().add("Center", editorPanel);
menuBar = _createMenuBar();
this.setJMenuBar(menuBar);
this.addWindowListener(exitAction);
this.pack();
// TODO set to meaningful size
this.setSize(500, 600);
_updateUIFromState();
}
protected JMenuBar _createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file_menu = new JMenu("File");
JMenu setup_menu = new JMenu("Setup");
JMenu text_menu = new JMenu("Text");
JMenu display_menu = new JMenu("Display");
// file menu
JMenuItem new_menu_item = new JMenuItem("New Performance Setup");
JMenuItem open_menu_item = new JMenuItem("Open Performance Setup");
save_menu_item = new JMenuItem("Save Performance Setup");
JMenuItem save_as_menu_item = new JMenuItem("Save Performance Setup As");
new_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
_newAction();
}
});
open_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
_openAction();
}
});
save_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
_saveAction();
}
});
save_as_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
_saveAsAction();
}
});
JMenuItem quit_menu_item = new JMenuItem("Quit");
quit_menu_item.addActionListener(exitAction);
// setup menu
JMenuItem setup_styles_menu_item = new JMenuItem("Setup Styles");
JMenuItem setup_roles_menu_item = new JMenuItem("Setup Roles");
JMenuItem setup_pinned_text_menu_item = new JMenuItem("Setup Pinned Text");
JMenuItem edit_hotkeys_menu_item = new JMenuItem("Edit Hotkeys");
JMenuItem change_background_item = new JMenuItem("Change Background Color");
JMenuItem change_caret_item = new JMenuItem("Change Caret Color");
setup_styles_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boolean result = StylesSetupDialog.showStylesSetupDialog(PetrukUI.this, petrukState.getStyles(),
SetupDialogXMLDAOFactory.Instance().getDAO(Style.class, "styles.xml"),
petrukState.getBackgroundColor());
if (result == true) {
petrukState.setModifiedSinceLastSave(true);
_updateUIFromState();
}
}
});
setup_roles_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boolean result = RolesSetupDialog.showRolesSetupDialog(PetrukUI.this, petrukState.getRoles(),
SetupDialogXMLDAOFactory.Instance().getDAO(Role.class, "roles.xml"),
petrukState.getBackgroundColor(), petrukState.getStyles());
if (result == true) {
petrukState.setModifiedSinceLastSave(true);
_updateUIFromState();
}
}
});
setup_pinned_text_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boolean result = PinnedTextSetupDialog.showPinnedTextSetupDialog(PetrukUI.this, petrukState.getPinnedText(),
SetupDialogXMLDAOFactory.Instance().getDAO(PinnedText.class, "pinned_text.xml"),
petrukState.getBackgroundColor(), petrukState.getStyles());
if (result == true) {
petrukState.setModifiedSinceLastSave(true);
_updateUIFromState();
}
}
});
edit_hotkeys_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boolean result = TriggerablesDialog.showDialog(PetrukUI.this, petrukState.getTriggerables());
if (result == true) {
petrukState.setModifiedSinceLastSave(true);
_updateUIFromState();
}
}
});
change_background_item.addActionListener(new ChangeBackgroundColorAction());
change_caret_item.addActionListener(new ChangeCaretColorAction());
// text menu
JMenuItem clear_text_menu_item = new JMenuItem("Clear Text");
JMenuItem export_menu_item = new JMenuItem("Export As Script");
clear_text_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
_clearTextAction();
}
});
export_menu_item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
_exportAction();
}
});
// Display menu
JMenuItem go_fullscreen_menu_item = new JMenuItem("Go Fullscreen");
go_fullscreen_menu_item.addActionListener(new ChangeFullScreenModeAction());
file_menu.add(new_menu_item);
file_menu.add(open_menu_item);
file_menu.add(save_menu_item);
file_menu.add(save_as_menu_item);
file_menu.add(quit_menu_item);
setup_menu.add(setup_styles_menu_item);
setup_menu.add(setup_roles_menu_item);
setup_menu.add(setup_pinned_text_menu_item);
setup_menu.add(edit_hotkeys_menu_item);
setup_menu.add(change_background_item);
setup_menu.add(change_caret_item);
text_menu.add(clear_text_menu_item);
text_menu.add(export_menu_item);
display_menu.add(go_fullscreen_menu_item);
menubar.add(file_menu);
menubar.add(setup_menu);
menubar.add(text_menu);
menubar.add(display_menu);
return menubar;
}
protected void _updateUIFromState() {
this.setTitle(_getTitle());
this.save_menu_item.setEnabled(petrukState.isModifiedSinceLastSave());
editorPanel.setEditorBackground(this.petrukState.getBackgroundColor());
editorPanel.setCaretColor(petrukState.getCaretColor());
Hashtable<KeyStroke, Action> keyBindings = new Hashtable<KeyStroke, Action>();
for (Role role : petrukState.getRoles()) {
if (role.getHotKey() != null) {
keyBindings.put(role.getHotKey(), new RoleTriggerAction(role, editorPanel));
logger.info("Adding trigger for " + role.getHotKey().toString());
}
}
HashSet<PinnedTextTriggerAction> pinnedTextTriggers = new HashSet<PinnedTextTriggerAction>();
for (PinnedText pinnedText : petrukState.getPinnedText()) {
if (pinnedText.getHotKey() != null) {
PinnedTextTriggerAction action = new PinnedTextTriggerAction(pinnedText, editorPanel);
pinnedTextTriggers.add(action);
keyBindings.put(pinnedText.getHotKey(), action);
logger.info("Adding trigger for " + pinnedText.getHotKey().toString());
}
}
// so ugly
PinnedTextTriggerAction.setAllActions(pinnedTextTriggers);
editorPanel.setKeyBindings(keyBindings);
// TODO deprecate
editorPanel.refreshTextSyle();
}
protected String _getTitle() {
String title = DEFAULT_TITLE;
title = title + " - " + petrukState.getSaveFile().getName();
if (petrukState.isModifiedSinceLastSave()) {
title = title + "* (Modified)";
}
return title;
}
protected void _newAction() {
if (editorPanel.hasData()) {
Object[] options = {"OK", "CANCEL"};
int result = JOptionPane.showOptionDialog(this, "This will clear all the text that you have entered. Continue?", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
if (result != JOptionPane.OK_OPTION) {
return;
} else {
editorPanel.clearTextAndStyles();
}
}
// TODO refactor and make more DRY
petrukState.setToDefaults();
editorPanel.setCurrentTextStyle(petrukState.getStyles().getFirst());
editorPanel.setStatusBarText("current role: default");
_updateUIFromState();
}
protected void _openAction() {
File openFile =
FileDialogs.showOpenDialog(this, "Open Performance Setup", petrukState.getSaveFile());
if (openFile != null) {
try {
PetrukState state = PetrukStateXMLDao.loadState(openFile);
PetrukState.setState(state);
petrukState = PetrukState.GetInstance();
petrukState.setSaveFile(openFile);
petrukState.setSaveFileChosen(true);
petrukState.setModifiedSinceLastSave(false);
} catch (Exception e) {
e.printStackTrace();
// TODO pop up error message
}
}
_updateUIFromState();
}
protected void _saveAction() {
if (!petrukState.isSaveFileChosen()) {
_saveAsAction();
} else {
_save(petrukState.getSaveFile());
}
}
protected void _saveAsAction() {
File newFile =
FileDialogs.showSaveDialog(this,
"Save Performance Setup As", petrukState.getSaveFile());
_save(newFile);
}
protected void _save(File saveFile) {
if (saveFile != null) {
try {
PetrukStateXMLDao.saveState(petrukState, saveFile);
petrukState.setSaveFile(saveFile);
petrukState.setSaveFileChosen(true);
petrukState.setModifiedSinceLastSave(false);
} catch (Exception e) {
e.printStackTrace();
// TODO pop up error mesg
}
}
_updateUIFromState();
}
protected void _clearTextAction(){
if (editorPanel.hasData()) {
Object[] options = {"OK", "CANCEL"};
int result = JOptionPane.showOptionDialog(this, "This will clear all the text that you have entered. Continue?", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
if (result != JOptionPane.OK_OPTION) {
return;
} else {
editorPanel.clearTextAndStyles();
}
}
}
protected void _exportAction() {
File newFile =
FileDialogs.showSaveDialog(this,
"Export Script", new File(System.getProperty("user.dir"), "performance.txt"));
if (newFile != null) {
FileWriter output = null;
try {
output = new FileWriter(newFile);
output.write(editorPanel.getFullText());
output.flush();
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
// TODO popup error mesg
} finally {
if (output != null) {
try {
output.close();
} catch (java.io.IOException ioe2) {
ioe2.printStackTrace();
}
}
}
}
}
/**
* TODO: Hook for checking if save needed?
*/
protected static final class AppExitAction extends WindowAdapter implements ActionListener {
public void windowClosing(WindowEvent e) {
_doExit();
}
public void actionPerformed(ActionEvent e) {
_doExit();
}
protected void _doExit() {
System.exit(0);
}
}
protected class ChangeBackgroundColorAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
Color chosen_color = JColorChooser.showDialog(PetrukUI.this, "Change Background Color",
petrukState.getBackgroundColor());
if (chosen_color != null) {
petrukState.setBackgroundColor(chosen_color);
petrukState.setModifiedSinceLastSave(true);
_updateUIFromState();
}
}
}
protected class ChangeCaretColorAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
Color chosen_color = JColorChooser.showDialog(PetrukUI.this, "Change Caret Color",
petrukState.getCaretColor());
if (chosen_color != null) {
petrukState.setCaretColor(chosen_color);
petrukState.setModifiedSinceLastSave(true);
_updateUIFromState();
}
}
}
protected class ChangeFullScreenModeAction extends AbstractAction implements MenuListener {
protected boolean isInFullScreenMode;
protected Frame frame;
private int oldScreenWidth;
private int oldScreenHeight;
public ChangeFullScreenModeAction() {
this.isInFullScreenMode = false;
this.frame = PetrukUI.this;
}
public void actionPerformed(ActionEvent e) {
logger.info("full screen action triggered through actionlistener interface");
_doChange();
}
public void menuSelected(MenuEvent e) {
logger.info("full screen action triggered through menulistener interface");
_doChange();
}
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
}
protected void _doChange() {
logger.info("performing full screen change action!");
KeyStroke esc_key = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (!gd.isFullScreenSupported()){
logger.info("full screen is not supported!");
return;
}
if (!isInFullScreenMode) {
menuBar.setVisible(false);
menuBar.setEnabled(false);
oldScreenWidth = frame.getWidth();
oldScreenHeight = frame.getHeight();
frame.setVisible(false);
frame.dispose();
frame.setUndecorated(true);
//Window w = gd.getFullScreenWindow();
//gd.setFullScreenWindow(frame);
//DisplayMode dm = gd.getDisplayMode();
//frame.setSize(dm.getWidth(), dm.getHeight());
/*Toolkit tk = Toolkit.getDefaultToolkit();
frame.setLocation(0, 0);
frame.setBounds(new Rectangle(new Point(0, 0), tk.getScreenSize()));
frame.setSize(tk.getScreenSize());
frame.setResizable(false);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
//frame.pack();
*/
gd.setFullScreenWindow(frame);
frame.setVisible(false);
frame.setVisible(true);
frame.setEnabled(true);
frame.toFront();
editorPanel.convertToFullScreen(esc_key, this);
isInFullScreenMode = true;
} else {
frame.setVisible(false);
frame.dispose();
frame.setSize(oldScreenWidth, oldScreenHeight);
frame.setLocation(0, 0);
//Toolkit tk = Toolkit.getDefaultToolkit();
//frame.setBounds(new Rectangle(new Point(0, 0), tk.getScreenSize()));
//GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//GraphicsDevice gd = ge.getDefaultScreenDevice();
//gd.setFullScreenWindow(null);
menuBar.setVisible(true);
menuBar.setEnabled(true);
frame.setUndecorated(false);
frame.setExtendedState(Frame.NORMAL);
//frame.pack();
gd.setFullScreenWindow(null);
frame.setResizable(true);
frame.setVisible(true);
frame.toFront();
frame.setEnabled(true);
editorPanel.revertFromFullScreen(esc_key);
isInFullScreenMode = false;
}
}
}
}
|
package turtle.gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import turtle.Kernel;
import turtle.entity.Game;
import turtle.entity.field.Field;
import turtle.gui.view.BallView;
import turtle.gui.view.FieldView;
public class GameWindow extends AbstractWindow
{
protected Graphics mBuffer;
protected Image mImage;
public GameWindow(Kernel kernel, Game game, AbstractWindow parent)
{
super(kernel, game, parent);
initialize();
setVisible(true);
}
private void initialize()
{
setTitle("Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(mGame.getField().getDimension());
setLocationRelativeTo(null);
setResizable(false);
}
@Override
public void paint(Graphics g)
{
Field field = mGame.getField();
// Double buffering software
if (mBuffer == null) {
mImage = createImage((int) field.getDimension().getWidth(), (int) field.getDimension().getHeight());
mBuffer = mImage.getGraphics();
}
// Anti aliasing
((Graphics2D) mBuffer).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
FieldView.paint(field, mBuffer);
if (mGame.isLaunched()) {
BallView.paint(field.getBall(), mBuffer);
}
g.drawImage(mImage, 0, 0, this);
}
@Override
public void updateView(Object arg)
{
repaint();
}
}
|
package abra.cadabra;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import abra.CompareToReference2;
import abra.ReadAdjuster;
import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.TextCigarCodec;
public class Cadabra {
private static final int MIN_SUPPORTING_READS = 2;
private static final int MIN_DISTANCE_FROM_READ_END = 3;
private ReadLocusReader normal;
private ReadLocusReader tumor;
private CompareToReference2 c2r;
public void callSomatic(String reference, String normal, String tumor) throws IOException {
c2r = new CompareToReference2();
c2r.init(reference);
this.normal = new ReadLocusReader(normal);
this.tumor = new ReadLocusReader(tumor);
outputHeader();
process();
}
private void outputHeader() {
System.out.println("##fileformat=VCFv4.1");
System.out.println("#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NORMAL TUMOR");
}
private void process() {
Iterator<ReadsAtLocus> normalIter = normal.iterator();
Iterator<ReadsAtLocus> tumorIter = tumor.iterator();
ReadsAtLocus normalReads = null;
ReadsAtLocus tumorReads = null;
int count = 0;
while (normalIter.hasNext() && tumorIter.hasNext()) {
if (normalReads != null && tumorReads != null) {
int compare = normalReads.compareLoci(tumorReads, normal.getSamHeader().getSequenceDictionary());
if (compare < 0) {
normalReads = normalIter.next();
} else if (compare > 0) {
tumorReads = tumorIter.next();
} else {
processLocus(normalReads, tumorReads);
normalReads = normalIter.next();
tumorReads = tumorIter.next();
}
if ((count % 1000000) == 0) {
System.err.println("Position: " + normalReads.getChromosome() + ":" + normalReads.getPosition());
}
count += 1;
} else {
normalReads = normalIter.next();
tumorReads = tumorIter.next();
}
}
}
private void processLocus(ReadsAtLocus normalReads, ReadsAtLocus tumorReads) {
String chromosome = normalReads.getChromosome();
int position = normalReads.getPosition();
CigarElement tumorIndel = null;
int tumorCount = 0;
int mismatch0Count = 0;
int mismatch1Count = 0;
int totalMismatchCount = 0;
boolean hasSufficientDistanceFromReadEnd = false;
int maxContigMapq = 0;
int minReadIndex = Integer.MAX_VALUE;
int maxReadIndex = Integer.MIN_VALUE;
Map<String, Integer> insertBasesMap = new HashMap<String, Integer>();
for (SAMRecord read : tumorReads.getReads()) {
IndelInfo readElement = checkForIndelAtLocus(read, position);
if (readElement != null) {
Integer ymInt = (Integer) read.getAttribute(ReadAdjuster.MISMATCHES_TO_CONTIG_TAG);
if (ymInt != null) {
int ym = ymInt;
if (ym == 0) {
mismatch0Count++;
}
if (ym <= 1) {
mismatch1Count++;
}
totalMismatchCount += ym;
}
}
if (tumorIndel == null && readElement != null) {
tumorIndel = readElement.getCigarElement();
tumorCount = 1;
maxContigMapq = Math.max(maxContigMapq, read.getIntegerAttribute(ReadAdjuster.CONTIG_QUALITY_TAG));
if (readElement.getInsertBases() != null) {
updateInsertBases(insertBasesMap, readElement.getInsertBases());
}
minReadIndex = readElement.getReadIndex() < minReadIndex ? readElement.getReadIndex() : minReadIndex;
maxReadIndex = readElement.getReadIndex() > maxReadIndex ? readElement.getReadIndex() : maxReadIndex;
} else if (tumorIndel != null && readElement != null) {
if (tumorIndel.equals(readElement.getCigarElement())) {
// Increment tumor indel support count
tumorCount += 1;
maxContigMapq = Math.max(maxContigMapq, read.getIntegerAttribute(ReadAdjuster.CONTIG_QUALITY_TAG));
if (readElement.getInsertBases() != null) {
updateInsertBases(insertBasesMap, readElement.getInsertBases());
}
minReadIndex = readElement.getReadIndex() < minReadIndex ? readElement.getReadIndex() : minReadIndex;
maxReadIndex = readElement.getReadIndex() > maxReadIndex ? readElement.getReadIndex() : maxReadIndex;
} else {
// We will not deal with multiple indels at a single locus for now.
tumorIndel = null;
tumorCount = 0;
break;
}
}
if (!hasSufficientDistanceFromReadEnd && tumorIndel != null && readElement != null && readElement.getCigarElement().equals(tumorIndel)) {
hasSufficientDistanceFromReadEnd = sufficientDistanceFromReadEnd(read, readElement.getReadIndex());
}
}
if (tumorCount >= MIN_SUPPORTING_READS && hasSufficientDistanceFromReadEnd) {
int normalCount = 0;
for (SAMRecord read : normalReads.getReads()) {
IndelInfo normalInfo = checkForIndelAtLocus(read.getAlignmentStart(), read.getCigar(), position);
if (normalInfo != null && sufficientDistanceFromReadEnd(read, normalInfo.getReadIndex())) {
normalCount += 1;
if (normalCount >= MIN_SUPPORTING_READS && ((float) normalCount / (float) tumorCount > 0.1)) {
// Don't allow call if normal indels exists at this position.
tumorIndel = null;
tumorCount = 0;
break;
}
}
}
if (tumorIndel != null && !isNormalCountOK(normalCount, normalReads.getReads().size(), tumorCount)) {
tumorIndel = null;
tumorCount = 0;
}
}
if (tumorCount >= MIN_SUPPORTING_READS && hasSufficientDistanceFromReadEnd) {
String insertBases = null;
if (tumorIndel.getOperator() == CigarOperator.I) {
insertBases = getInsertBaseConsensus(insertBasesMap, tumorIndel.getLength());
}
outputRecord(chromosome, position, normalReads, tumorReads, tumorIndel,
tumorCount, insertBases, maxContigMapq, mismatch0Count, mismatch1Count, totalMismatchCount, minReadIndex, maxReadIndex);
}
}
private void updateInsertBases(Map<String, Integer> insertBases, String bases) {
if (insertBases.containsKey(bases)) {
insertBases.put(bases, insertBases.get(bases) + 1);
} else {
insertBases.put(bases, 1);
}
}
private String getInsertBaseConsensus(Map<String, Integer> insertBases, int length) {
int maxCount = -1;
String maxBases = null;
for (String bases : insertBases.keySet()) {
int count = insertBases.get(bases);
if (count > maxCount) {
maxCount = count;
maxBases = bases;
}
}
if (maxBases == null) {
StringBuffer buf = new StringBuffer(length);
for (int i=0; i<length; i++) {
buf.append('N');
}
maxBases = buf.toString();
}
return maxBases;
}
private boolean isNormalCountOK(int normalObs, int numNormalReads, int tumorObs) {
// Magic numbers here.
// Allow a single normal observation if >= 20 tumor observations and >= 20 normal reads
return normalObs == 0 || (tumorObs >= 20 && numNormalReads >= 20);
}
private boolean sufficientDistanceFromReadEnd(SAMRecord read, int readIdx) {
boolean ret = false;
if (readIdx >= MIN_DISTANCE_FROM_READ_END &&
readIdx <= read.getReadLength()-MIN_DISTANCE_FROM_READ_END-1) {
ret = true;
}
return ret;
}
private String getDelRefField(String chromosome, int position, int length) {
return c2r.getSequence(chromosome, position, length+1);
}
private String getInsRefField(String chromosome, int position) {
return c2r.getSequence(chromosome, position, 1);
}
private void outputRecord(String chromosome, int position,
ReadsAtLocus normalReads, ReadsAtLocus tumorReads, CigarElement indel,
int tumorObs, String insertBases, int maxContigMapq, int ym0, int ym1, int totalYm,
int minReadIndex, int maxReadIndex) {
int normalDepth = normalReads.getReads().size();
int tumorDepth = tumorReads.getReads().size();
String context = c2r.getSequence(chromosome, position-10, 20);
StringBuffer buf = new StringBuffer();
buf.append(chromosome);
buf.append('\t');
buf.append(position);
buf.append("\t.\t");
String ref = ".";
String alt = ".";
if (indel.getOperator() == CigarOperator.D) {
ref = getDelRefField(chromosome, position, indel.getLength());
alt = ref.substring(0, 1);
} else if (indel.getOperator() == CigarOperator.I) {
ref = getInsRefField(chromosome, position);
alt = ref + insertBases;
}
buf.append(ref);
buf.append('\t');
buf.append(alt);
buf.append("\t.\tPASS\t");
buf.append("SOMATIC;CMQ=" + maxContigMapq + ";CTX=" + context);
buf.append("\tDP:YM0:YM1:YM:OBS:MIRI:MARI\t");
buf.append(normalDepth);
buf.append(":0:0:0:0:0:0");
buf.append('\t');
buf.append(tumorDepth);
buf.append(':');
buf.append(ym0);
buf.append(':');
buf.append(ym1);
buf.append(':');
buf.append(totalYm);
buf.append(':');
buf.append(tumorObs);
buf.append(':');
buf.append(minReadIndex);
buf.append(':');
buf.append(maxReadIndex);
System.out.println(buf.toString());
}
private IndelInfo checkForIndelAtLocus(SAMRecord read, int refPos) {
IndelInfo elem = null;
String contigInfo = read.getStringAttribute("YA");
if (contigInfo != null) {
// Get assembled contig info.
String[] fields = contigInfo.split(":");
int contigPos = Integer.parseInt(fields[1]);
Cigar contigCigar = TextCigarCodec.getSingleton().decode(fields[2]);
// Check to see if contig contains indel at current locus
elem = checkForIndelAtLocus(contigPos, contigCigar, refPos);
if (elem != null) {
// Now check to see if this read supports the indel
IndelInfo readElem = checkForIndelAtLocus(read.getAlignmentStart(),
read.getCigar(), refPos);
// Allow partially overlapping indels to support contig
// (Should only matter for inserts)
if (readElem == null || readElem.getCigarElement().getOperator() != elem.getCigarElement().getOperator()) {
// Read element doesn't match contig indel
elem = null;
} else {
elem.setReadIndex(readElem.getReadIndex());
// If this read overlaps the entire insert, capture the bases.
if (elem.getCigarElement().getOperator() == CigarOperator.I &&
elem.getCigarElement().getLength() == readElem.getCigarElement().getLength()) {
String insertBases = read.getReadString().substring(readElem.getReadIndex(), readElem.getReadIndex()+readElem.getCigarElement().getLength());
elem.setInsertBases(insertBases);
}
}
}
}
return elem;
}
private IndelInfo checkForIndelAtLocus(int alignmentStart, Cigar cigar, int refPos) {
IndelInfo ret = null;
int readIdx = 0;
int currRefPos = alignmentStart;
for (CigarElement element : cigar.getCigarElements()) {
if (element.getOperator() == CigarOperator.M) {
readIdx += element.getLength();
currRefPos += element.getLength();
} else if (element.getOperator() == CigarOperator.I) {
if (currRefPos == refPos+1) {
ret = new IndelInfo(element, readIdx);
break;
}
readIdx += element.getLength();
} else if (element.getOperator() == CigarOperator.D) {
if (currRefPos == refPos+1) {
ret = new IndelInfo(element, readIdx);
break;
}
currRefPos += element.getLength();
} else if (element.getOperator() == CigarOperator.S) {
readIdx += element.getLength();
}
}
return ret;
}
private char getReadBase(SAMRecord read, int index) {
return (char) read.getReadBases()[index];
}
public static void main(String[] args) throws Exception {
// String normal = "/home/lmose/dev/abra/cadabra/normal_test2.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/tumor_test2.bam";
// String normal = "/home/lmose/dev/abra/cadabra/normal.abra4.sort.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/tumor.abra4.sort.bam";
// String reference = "/home/lmose/reference/chr1/chr1.fa";
// String normal = "/home/lmose/dev/abra/cadabra/t2/ntest.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/t2/ttest.bam";
// String reference = "/home/lmose/reference/chr1/chr1.fa";
// String normal = "/home/lmose/dev/abra/cadabra/ins/ntest.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/ins/ttest.bam";
String reference = args[0];
String normal = args[1];
String tumor = args[2];
new Cadabra().callSomatic(reference, normal, tumor);
}
}
|
package gr.charos.mailer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import gr.charos.mailer.model.CommandResult;
import gr.charos.mailer.model.Email;
import gr.charos.mailer.service.AddressExtractor;
import gr.charos.mailer.service.AddressReader;
import gr.charos.mailer.service.ApplicationManager;
import gr.charos.mailer.service.MailSender;
import gr.charos.mailer.service.impl.AddressReaderImpl;
import gr.charos.mailer.service.impl.CommandManagerImpl;
import gr.charos.mailer.service.impl.ExcelAddressExtractor;
import gr.charos.mailer.service.impl.MailSenderImpl;
import gr.charos.mailer.service.impl.PDFAddressExtractor;
import gr.charos.mailer.service.impl.RegexAddressParser;
import gr.charos.mailer.service.impl.TextAddressExtractor;
public class App {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java -jar mailer*.jar $propFileLocation");
System.out.println("Sample config file : ");
System.out.println("mail.server=your_smtp_server\n" +
"\n" +
"mail.port=your_smtp_server_port\n" +
"\n" +
"mail.defaultSubject=default_subject(you can enter via the command prompt as well)\n" +
"\n" +
"mail.defaultBody=default_body(you can enter via the command prompt as well)\n" +
"\n" +
"mail.defaultSender=default_sender(you can enter via the command prompt as well)\n" +
"\n" +
"preloaded=paths_to_preloaded_files_with_emails (optional)");
System.exit(-1);
}
String propFile = args[0];
System.out.println("Loading props from :" + propFile);
Properties props = getProperties(propFile);
if (props == null) {
System.out.println("No props file loaded. Please load file by setting the 'propFile' argument variable.");
System.exit(-1);
}
ApplicationManager am = configureByProperties(props);
Scanner scanner = new Scanner(System.in);
CommandResult cr = null;
String command = null;
am.status();
am.help();
while (cr != CommandResult.exit) {
System.out.println("Enter Command: ");
command = scanner.next();
cr = am.manageCommand(command);
if(cr.equals(CommandResult.failure)) {
System.out.println("There was an error!");
}
}
scanner.close();
}
private static ApplicationManager configureByProperties(Properties props){
MailSender ms = new MailSenderImpl(props.getProperty("mail.server"), props.getProperty("mail.port", ""));
AddressReader ar = new AddressReaderImpl();
ApplicationManager cm = new CommandManagerImpl(ms, ar);
Set<String> paths = new HashSet<String>();
String[] preloaded = props.get("preloaded").toString().split(",");
for (String preload : preloaded) {
paths.add(preload);
}
for (String path : paths) {
cm.addMails(ar.readAddresses(path));
}
String sender = props.getProperty("mail.defaultSender");
String subject = props.getProperty("mail.defaultSubject");
String body = props.getProperty("mail.defaultBody");
if (sender != null) {
cm.setSenderEmail(sender);
}
if (subject != null) {
cm.setSubject(subject);
}
if (body != null) {
cm.setBody(body);
}
return cm;
}
private static Properties getProperties(String propFileName) {
Properties prop = null;
try {
InputStream inputStream = new FileInputStream(propFileName);
prop = new Properties();
prop.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
System.out.print("Property file not found! Exiting...");
System.exit(-1);
}
return prop;
}
private static void sendMails(MailSender sender, Set<String> mails, Email mail) {
System.out.println(mails.size() + " Total Addresses: ");
int counter = 1;
for (String email : mails) {
System.out.println("Sending " + counter++ + " of " + mails.size() + " (" + email + ")");
mail.setRecipientEmail(email);
boolean sent = sender.sendMail(mail);
if (sent) {
System.out.println("Sent!");
} else {
System.out.println("Not Sent... Waiting for 5 seconds and trying again");
try {
Thread.sleep(5 * 1000);
sent = sender.sendMail(mail);
System.out.println("Not Sent... Giving up at :" + email);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static Set<String> readByFilename(String filename) {
Set<String> mails = new HashSet<String>();
AddressExtractor ae = getExtractorByFilename(filename);
Set<String> mailsCommand = (ae.extractAddresses(new File(filename)));
System.out.print(mailsCommand.size() + " Addresses extracted. ");
mails.addAll(mailsCommand);
System.out.println("...Added");
return mails;
}
private static AddressExtractor getExtractorByFilename(String filename) {
String ext = filename.split("\\.(?=[^\\.]+$)")[1];
if (ext.equalsIgnoreCase("xls")) {
return new ExcelAddressExtractor(new RegexAddressParser());
} else if (ext.equalsIgnoreCase("pdf")) {
return new PDFAddressExtractor(new RegexAddressParser());
} else if (ext.equalsIgnoreCase("txt") || ext.equalsIgnoreCase("html")) {
return new TextAddressExtractor(new RegexAddressParser());
} else {
throw new RuntimeException("Unsupported file type!");
}
}
}
|
package leetcode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.NavigableSet;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
public class Problem1169 {
public List<String> invalidTransactions(String[] transactions) {
Set<Integer> invalid = new HashSet<>();
TreeSet<Transaction> set = new TreeSet<>();
for (int i = 0; i < transactions.length; i++) {
String[] t = transactions[i].split(",");
String name = t[0];
int time = Integer.parseInt(t[1]);
int amount = Integer.parseInt(t[2]);
String city = t[3];
set.add(new Transaction(i, name, time, amount, city));
if (amount > 1000) {
invalid.add(i);
}
}
for (Transaction t1 : set) {
NavigableSet<Transaction> within60Mins = set.subSet(
t1, true, /* we only care about t1.time + 60 */
new Transaction(0, "", t1.time + 60, 0, ""), true);
for (Transaction t2 : within60Mins) {
if (t1.name.equals(t2.name) && !t1.city.equals(t2.city)) {
invalid.add(t1.index);
invalid.add(t2.index);
}
}
}
List<String> answer = new ArrayList<>();
for (int i : invalid) {
answer.add(transactions[i]);
}
return answer;
}
private static class Transaction implements Comparable<Transaction> {
private final int index;
private final String name;
private final int time;
private final int amount;
private final String city;
public Transaction(int index, String name, int time, int amount, String city) {
this.index = index;
this.name = name;
this.time = time;
this.amount = amount;
this.city = city;
}
@Override
public int compareTo(Transaction o) {
return Integer.compare(time, o.time);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Transaction that = (Transaction) o;
return index == that.index;
}
@Override
public int hashCode() {
return Objects.hash(index);
}
}
public static void main(String[] args) {
Problem1169 prob = new Problem1169();
System.out.println(prob.invalidTransactions(new String[]{
"alice,20,800,mtv","alice,50,100,beijing"})); // ["alice,20,800,mtv","alice,50,100,beijing"]
System.out.println(prob.invalidTransactions(new String[]{
"alice,20,800,mtv","alice,50,100,beijing","alice,5,100,beijing"})); // ["alice,20,800,mtv","alice,50,100,beijing","alice,5,100,beijing"]
System.out.println(prob.invalidTransactions(new String[]{
"alice,20,800,mtv","alice,50,1200,mtv"})); // ["alice,50,1200,mtv"]
System.out.println(prob.invalidTransactions(new String[]{
"alice,20,800,mtv","bob,50,1200,mtv"})); // ["bob,50,1200,mtv"]
System.out.println(prob.invalidTransactions(new String[]{
"alice,5,100,beijing","alice,50,100,beijing"}));
System.out.println(prob.invalidTransactions(new String[]{
"alice,5,100,beijing","alice,50,100,beijing","alice,80,800,mtv"})); // ["alice,50,100,beijing","alice,80,800,mtv"]
}
}
|
package net.halflite.hiq;
import static net.halflite.hiq.config.AppConfig.RESOURCES_PATH;
import static net.halflite.hiq.config.AppConfig.VIEW_PATH;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.halflite.hiq.config.AppConfig;
/**
*
*
* @author halflite
*
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
String envPort = System.getProperties().getOrDefault("server.port", "9998").toString();
int port = Integer.valueOf(envPort);
LOGGER.info("Server PORT:{}", port);
URI uri = UriBuilder.fromUri("http://localhost/").port(port).build();
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(uri, AppConfig.create(), false);
HttpHandler handler = new CLStaticHttpHandler(HttpServer.class.getClassLoader(), RESOURCES_PATH, VIEW_PATH);
server.getServerConfiguration().addHttpHandler(handler, "/");
try {
server.start();
} catch (Exception e) {
LOGGER.warn("Server fault.", e);
server.shutdownNow();
}
}
}
|
package net.sf.gaboto;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import net.sf.gaboto.event.GabotoEvent;
import net.sf.gaboto.event.InsertionGabotoEvent;
import net.sf.gaboto.event.RemovalGabotoEvent;
import net.sf.gaboto.event.UpdateListener;
import net.sf.gaboto.node.GabotoEntity;
import net.sf.gaboto.node.GabotoTimeBasedEntity;
import net.sf.gaboto.time.TimeDimensionIndexer;
import net.sf.gaboto.time.TimeInstant;
import net.sf.gaboto.time.TimeSpan;
import net.sf.gaboto.vocabulary.RDFContext;
import net.sf.gaboto.vocabulary.RDFGraph;
import net.sf.gaboto.vocabulary.TimeVocab;
import org.apache.log4j.Logger;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.RDF;
import de.fuberlin.wiwiss.ng4j.NamedGraph;
import de.fuberlin.wiwiss.ng4j.NamedGraphSet;
import de.fuberlin.wiwiss.ng4j.Quad;
public class Gaboto {
private static Logger logger = Logger.getLogger(Gaboto.class.getName());
private GabotoConfiguration config;
/**
* The next entity id.
*/
long id = 23232322;
/**
* Update listeners.
*/
private List<UpdateListener> updateListener = new ArrayList<UpdateListener>();
/**
* Named graph set.
*/
private NamedGraphSet namedGraphSet;
/** Context Description Graph */
private Model contextDescriptionGraph;
private TimeDimensionIndexer timeDimensionIndexer;
/**
* Creates a new Gaboto object using the passed graphset.
*
* <p>
* Only accessible from within the package. Objects should be created via the
* Gaboto factory.
* </p>
*
* @param namedGraphSet
* The data.
*/
Gaboto(Model cdg, NamedGraphSet namedGraphSet) {
this(cdg, namedGraphSet, null);
}
/**
* Creates a new Gaboto object using the passed graphset for its data and
* creating an index on the time dimension.
*
* <p>
* Only accessible from within the package. Objects should be created via the
* Gaboto factory.
* </p>
*
* @param graphset
* The data.
* @param idx
* A time dimension indexer.
*
*/
public Gaboto(Model cdg, NamedGraphSet graphset, TimeDimensionIndexer idx) {
this.contextDescriptionGraph = cdg;
this.namedGraphSet = graphset;
this.config = GabotoFactory.getConfig();
if (idx != null) {
// create an index on the time dimension
idx.createIndex(cdg);
this.timeDimensionIndexer = idx;
}
}
/**
* Returns the time dimension indexer.
*
* @return The time dimension indexer.
* @throws NoTimeIndexSetException
* Thrown if no time dimension index was created.
*/
public TimeDimensionIndexer getTimeDimensionIndexer() {
if (timeDimensionIndexer == null)
throw new NoTimeIndexSetException();
return timeDimensionIndexer;
}
/**
* Sets a time dimension indexer.
*
* @param idx
* The indexer.
*/
public void setTimeDimensionIndexer(TimeDimensionIndexer idx) {
this.timeDimensionIndexer = idx;
}
/**
* Triggers a recreation of the time dimension index.
*/
public void recreateTimeDimensionIndex() {
this.getTimeDimensionIndexer().createIndex(getContextDescriptionGraph());
}
/**
* Attaches a listener that is informed on updates to the graph.
*
* @param listener
* The update listener to be attached.
*/
public void attachUpdateListener(UpdateListener listener) {
updateListener.add(listener);
}
/**
* Detaches an update listener.
*
* @param listener
* The update listener to be detached.
*/
public void detachUpdateListener(UpdateListener listener) {
updateListener.remove(listener);
}
/**
* Generates a new id unique within this Gaboto.
*
* @return A new unique new.
*/
public String generateID() {
String tmpId = generateId();
while (containsResource(tmpId))
tmpId = generateId();
return tmpId;
}
private String generateId() {
return config.getNSData() + new Long(++id).toString();
}
/**
* Creates a {@link GabotoSnapshot} that only contains flat RDF.
*
* <p>
* This method adds all information that was true at the given point in time
* to the snapshot.
* </p>
*
* @param ti
* The time instant.
* @return A snapshot only containing flat RDF.
*
* @throws NoTimeIndexSetException
*/
public GabotoSnapshot getSnapshot(TimeInstant ti)
throws NoTimeIndexSetException {
System.err.println("Creating snapshot for time instant " + ti);
Collection<String> graphURIs = getTimeDimensionIndexer().getGraphsForInstant(ti);
return getSnapshot(graphURIs);
}
/**
* Creates an {@link GabotoSnapshot} that only contains the data from the
* passed graph.
*
* @param graph
* The graph that contains the data.
*
* @return A snapshot.
*/
public GabotoSnapshot getSnapshot(NamedGraph graph) {
Collection<String> uris = new HashSet<String>();
uris.add(graph.getGraphName().getURI());
return getSnapshot(uris);
}
/**
* Creates an {@link GabotoSnapshot} that only contains the data from the
* passed graph.
*
* @param graphURI
* The graph that contains the data.
*
* @return A snapshot.
*/
public GabotoSnapshot getSnapshot(String graphURI) {
Collection<String> uris = new HashSet<String>();
uris.add(graphURI);
return getSnapshot(uris);
}
/**
* Creates an {@link GabotoSnapshot} that contains the data from all the
* specified graphs.
*
* @param graphURIs
* The graphs to use.
*
* @return A snapshot.
*/
public GabotoSnapshot getSnapshot(Collection<String> graphURIs) {
// create model
Model model = ModelFactory.createDefaultModel();
Graph newModelsDefaultGraph = model.getGraph();
// create snapshot
GabotoSnapshot snapshot = new GabotoSnapshot(model, this);
logger.debug("Adding " + graphURIs.size() + " graphs to snapshot");
// fill model
for (String g : graphURIs) {
logger.debug("Adding graph to snapshot: " + g);
NamedGraph graph = namedGraphSet.getGraph(g);
if (graph == null)
throw new IllegalArgumentException("Unknown graph: " + g);
// add statements to snapshot model
ExtendedIterator<Triple> it = graph.find(Node.ANY, Node.ANY, Node.ANY);
while (it.hasNext()) {
Triple t = it.next();
// add triple to model's graph
newModelsDefaultGraph.add(t);
}
}
// add gdg
Graph gkg = getGlobalKnowledgeGraph();
ExtendedIterator<Triple> it = gkg.find(Node.ANY, Node.ANY, Node.ANY);
while (it.hasNext())
newModelsDefaultGraph.add(it.next());
return snapshot;
}
/**
* Informs listeners of update.
*
* @param e
*/
private void triggerUpdateEvent(GabotoEvent e) {
for (UpdateListener u : updateListener)
u.updateOccured(e);
}
/**
* Adds a time bound entity to the data.
*
* @param entityTB
* The entity to be added
* @throws EntityAlreadyExistsException
* If the entity already exists in the model.
*/
synchronized public void add(GabotoTimeBasedEntity entityTB)
throws EntityAlreadyExistsException {
if (containsEntity(entityTB.getUri()))
throw new EntityAlreadyExistsException(entityTB.getUri());
logger.debug("Adding time based entity to gaboto: " + entityTB);
logger.debug("TimeSpans in tbEntity: " + entityTB.getTimeSpansSorted());
// add triple denoting entities type and lifespan
add(entityTB.getTimeSpan(), entityTB.getRDFTypeTriple());
// loop over "internal" entities and add them
Iterator<GabotoEntity> it = entityTB.iterator();
while (it.hasNext()) {
GabotoEntity entity = it.next();
add(entity, false);
}
}
/**
* Changes an {@link GabotoEntity}. If entity did not exist, it is added to
* the data.
*
* <p>
* Same as: <code>purge(entity); add(entity);</code>
* </p>
*
* @param entity
* The entity that is to be changed
*/
synchronized public void change(GabotoEntity entity) {
try {
purge(entity);
} catch (EntityDoesNotExistException e) {
// Add is a change
}
try {
add(entity);
} catch (EntityAlreadyExistsException e) {
throw new IncoherenceException(
"Something went terribly wrong .. I just purged " + entity.getUri()
+ ". It should not exist.", e);
}
}
/**
* Changes an {@link GabotoEntity}. If entity did not exist, it is added to
* the data.
*
* <p>
* Same as: <code>purge(entity); add(entity);</code>
* </p>
*
* @param entity
* The entity that is to be changed
*/
synchronized public void change(GabotoTimeBasedEntity entity) {
try {
purge(entity);
add(entity);
} catch (EntityDoesNotExistException e) {
} catch (EntityAlreadyExistsException e) {
throw new IncoherenceException(
"Something went teribly wrong .. I just purged " + entity.getUri()
+ ". It should not exist.", e);
}
}
/**
* Adds an {@link GabotoEntity} to the data.
*
* <p>
* Same as: <code>add(entity, true)</code>.
* </p>
*
* @param entity
* The entity to be added.
*
* @throws EntityAlreadyExistsException
* If the entity already exists in the model.
*
* @see #add(GabotoEntity, boolean)
*/
synchronized public void add(GabotoEntity entity) throws EntityAlreadyExistsException {
System.err.println("Adding:"+entity);
add(entity, true);
}
/**
* Adds an {@link GabotoEntity} to the data.
*
* @param entity
* The entity to be added.
* @param includeType
* Defines whether or not a triple that denotes the type should be
* added.
*
* @throws EntityAlreadyExistsException
* If the entity already exists in the model.
*
* @see #add(GabotoEntity, boolean)
*/
synchronized private void add(GabotoEntity entity, boolean includeType)
throws EntityAlreadyExistsException {
if (containsEntity(entity) && includeType)
throw new EntityAlreadyExistsException(entity);
logger.debug("Adding entity to gaboto: " + entity);
TimeSpan ts = entity.getTimeSpan().canonicalize();
for (Triple t : entity.getTriplesFor(includeType))
add(ts, t);
}
/**
* Removes all direct information about the supplied entity.
*
* @param entity
* The entity that is to be removed.
*
*/
synchronized public void purge(GabotoEntity entity) {
purge(entity.getUri());
}
/**
* Removes all direct information about the supplied entity.
*
* @param entity
* The entity that is to be removed.
*
*/
synchronized public void purge(GabotoTimeBasedEntity entity) {
purge(entity.getUri());
}
/**
* Removes all direct information about the supplied entity.
*
* @param entityURI
* The entity referenced by its URI.
*
*/
synchronized public void purge(String entityURI) {
if (!containsEntity(entityURI))
throw new EntityDoesNotExistException(entityURI);
logger.debug("Attempting to purge " + entityURI);
// load time-based entity
Iterator<?> it = getNamedGraphSet().findQuads(Node.ANY,
Node.createURI(entityURI), Node.ANY, Node.ANY);
while (it.hasNext()) {
Quad q = (Quad)it.next();
remove(q);
// old way
// TimeSpan ts = TimeSpan.createFromGraphName(q.getGraphName().getURI(),
// this);
// remove(ts, q.getTriple());
}
}
/**
* This method removes an entity from the graph described by its lifetime. For
* more information see {@link #remove(GabotoEntity, TimeSpan)}.
*
* @see #remove(GabotoEntity, TimeSpan)
* @see #purge(GabotoEntity)
*
* @param entity
* The entity to be removed.
*/
synchronized public void remove(GabotoEntity entity) {
remove(entity, entity.getTimeSpan());
}
/**
* This method removes an entity from the graph described by the supplied
* timespan.
*
* <p>
* Be careful, this method does not make sure that there are no other
* references to this entity in other graphs. It may well be that other graphs
* still contain triples that define properties for this entity. If you want
* to remove all defining triples for this entity use
* {@link #purge(GabotoEntity)}
* </p>
*
* @see #purge(GabotoEntity)
*
* @param entity
* The entity to be removed
* @param ts
* Defines the graph from which the entity should be removed.
*/
synchronized public void remove(GabotoEntity entity, TimeSpan ts) {
for (Triple t : entity.getTriplesFor(true))
remove(ts, t);
}
synchronized public void add(Triple triple) {
getGlobalKnowledgeGraph().add(triple);
// inform listeners
triggerUpdateEvent(new InsertionGabotoEvent(triple));
}
synchronized public void remove(Triple triple) {
getGlobalKnowledgeGraph().delete(triple);
// inform listeners
triggerUpdateEvent(new RemovalGabotoEvent(triple));
}
/**
* Adds a triple to that graph corresponding to the supplied time span.
*
* <p>
* If this model does not yet contain a graph that corresponds to the supplied
* time span, a new named graph is created.
* </p>
*
* <p>
* Update listeners are informed.
* </p>
*
* @param ts
* The time span in which the triple is valid. if the time span is
* null, then the triple will be added to the gkg.
* @param triple
* The information that is to be saved.
*
* @return The NamedGraph the triple was added to.
*
* @see #attachUpdateListener(UpdateListener)
* @see #detachUpdateListener(UpdateListener)
* @see UpdateListener
* @see InsertionGabotoEvent
*/
synchronized public NamedGraph add(TimeSpan ts, Triple triple) {
if (ts == null || ts.equals(TimeSpan.EXISTENCE)) {
add(triple);
return null;
}
NamedGraph graph;
if (containsGraph(ts))
graph = getGraph(ts);
else {
graph = createNewGraph(ts);
// update the index
try {
getTimeDimensionIndexer().add(graph, ts);
} catch (NoTimeIndexSetException e) {
}
}
logger.debug("Adding triple " + triple + " to graph "
+ graph.getGraphName().getURI());
graph.add(triple);
// inform listeners
triggerUpdateEvent(new InsertionGabotoEvent(ts, triple));
return graph;
}
/**
* Removes an RDF triple from that graph corresponding to the supplied time
* span.
*
* <p>
* Update listeners are informed.
* </p>
*
* @param ts
* The time span in which the triple is valid. if the time span is
* null, then the triple will be removed from the gkg.
* @param triple
* The information that is to be removed.
*
* @see #attachUpdateListener(UpdateListener)
* @see #detachUpdateListener(UpdateListener)
* @see UpdateListener
* @see RemovalGabotoEvent
*/
synchronized public void remove(TimeSpan ts, Triple triple) {
if (ts == null || ts.equals(TimeSpan.EXISTENCE)) {
remove(triple);
return;
}
if (containsGraph(ts)) {
NamedGraph graph = getGraph(ts);
graph.delete(triple);
triggerUpdateEvent(new RemovalGabotoEvent(ts, triple));
}
}
/**
* Removes a quad from Gaboto and triggers and update event.
*
* @param q
* the quad.
*/
synchronized public void remove(Quad q) {
getNamedGraphSet().removeQuad(q);
triggerUpdateEvent(new RemovalGabotoEvent(q));
}
/**
* Returns the name of a potential graph for this timespan. The graph may or
* may not exist in this instance of Gaboto.
*
* @param ts
* The timespan/TimeInstant
* @return the name a graph for this timespan would have
*/
private String getGraphNameFor(TimeSpan ts) {
return config.getNSGraphs() + "tg-" + ts.toString();
}
/**
* Creates a new graph and sets all necessary triples in the CDG
*
* @param ts
* the time span
*
* @return The newly created named graph.
*/
private NamedGraph createNewGraph(TimeSpan ts) {
if (containsGraph(ts))
throw new IllegalArgumentException("The graph for timespan " + ts
+ " already exists.");
// calculate name and create graph
String name = getGraphNameFor(ts);
NamedGraph graph = getNamedGraphSet().createGraph(name);
// put information about graph in cdg
Model cdgModel = getContextDescriptionGraph();
Graph cdgGraph = cdgModel.getGraph();
// say that the graph is a graph. We do that in the cdg as well to have all
// the information on the graph in the cdg
cdgGraph.add(new Triple(Node.createURI(name), Node.createURI(RDF.type
.getURI()), Node.createURI(RDFGraph.Graph.getURI())));
// say that the graph is actually a graph
cdgGraph.add(new Triple(Node.createURI(name), Node.createURI(RDF.type
.getURI()), Node.createURI(RDFGraph.Graph.getURI())));
// attach a temporal dimension to the graph
Node tempD = Node.createAnon();
cdgGraph.add(new Triple(Node.createURI(name), Node
.createURI(RDFContext.hasTemporalDimension.getURI()), tempD));
// Say that the temporal dimension is actually a Interval
cdgGraph.add(new Triple(tempD, Node.createURI(RDF.type.getURI()), Node
.createURI(TimeVocab.Interval.getURI())));
// attach a beginning to the interval
Node beginning = Node.createAnon();
cdgGraph.add(new Triple(tempD, Node.createURI(TimeVocab.hasBeginning
.getURI()), beginning));
// say that the beginning is an instant
cdgGraph.add(new Triple(beginning, Node.createURI(RDF.type.getURI()), Node
.createURI(TimeVocab.Instant.getURI())));
// attach a time description to the beginning
Node beginningDesc = Node.createAnon();
cdgGraph.add(new Triple(beginning, Node
.createURI(TimeVocab.hasDateTimeDescription.getURI()), beginningDesc));
// set the type of the time description
cdgGraph.add(new Triple(beginningDesc, Node.createURI(RDF.type.getURI()),
Node.createURI(TimeVocab.DateTimeDescription.getURI())));
// now actually describe the time description
String unitType = "";
if (ts.getStartUnit() == TimeSpan.START_UNIT_DAY)
unitType = TimeVocab.unitDay.getURI();
else if (ts.getStartUnit() == TimeSpan.START_UNIT_MONTH)
unitType = TimeVocab.unitMonth.getURI();
else
unitType = TimeVocab.unitYear.getURI();
cdgGraph.add(new Triple(beginningDesc, Node.createURI(TimeVocab.unitType
.getURI()), Node.createURI(unitType)));
cdgGraph.add(new Triple(beginningDesc, Node.createURI(TimeVocab.year
.getURI()), Node.createLiteral(String.valueOf(ts.getStartYear()), null,
XSDDatatype.XSDinteger)));
if (null != ts.getStartMonth()) {
cdgGraph.add(new Triple(beginningDesc, Node.createURI(TimeVocab.month
.getURI()), Node.createLiteral(String.valueOf(ts.getStartMonth()),
null, XSDDatatype.XSDinteger)));
}
if (null != ts.getStartDay()) {
cdgGraph.add(new Triple(beginningDesc, Node.createURI(TimeVocab.day
.getURI()), Node.createLiteral(String.valueOf(ts.getStartDay()),
null, XSDDatatype.XSDinteger)));
}
// / duration
if (ts.hasFixedDuration()) {
Node durationDesc = Node.createAnon();
cdgGraph.add(new Triple(tempD, Node
.createURI(TimeVocab.hasDurationDescription.getURI()), durationDesc));
cdgGraph.add(new Triple(durationDesc, Node.createURI(RDF.type.getURI()),
Node.createURI(TimeVocab.DurationDescription.getURI())));
if (ts.getDurationYear() != null) {
cdgGraph
.add(new Triple(durationDesc, Node.createURI(TimeVocab.years
.getURI()), Node.createLiteral(String.valueOf(ts
.getDurationYear()), null, XSDDatatype.XSDinteger)));
}
if (ts.getDurationMonth() != null) {
cdgGraph.add(new Triple(durationDesc, Node.createURI(TimeVocab.months
.getURI()), Node.createLiteral(String
.valueOf(ts.getDurationMonth()), null, XSDDatatype.XSDinteger)));
}
if (ts.getDurationDay() != null) {
cdgGraph.add(new Triple(durationDesc, Node.createURI(TimeVocab.days
.getURI()), Node.createLiteral(String.valueOf(ts.getDurationDay()),
null, XSDDatatype.XSDinteger)));
}
}
return graph;
}
/**
* Returns the underlying named graph set.
*
* @return The named graph set.
*/
public NamedGraphSet getNamedGraphSet() {
return this.namedGraphSet;
}
/**
* Tests if this Gaboto instance knows of a graph described by this timespan
* object
*
* @param ts
* The time span.
* @return True if Gaboto contains a graph for this time span
*/
public boolean containsGraph(TimeSpan ts) {
return this.getNamedGraphSet().containsGraph(getGraphNameFor(ts));
}
/**
* Tests if Gaboto contains a graph with the passed URI.
*
* @param uri
* The graph's name.
*
* @return True if Gaboto contains the graph.
*/
public boolean containsGraph(String uri) {
return this.getNamedGraphSet().containsGraph(uri);
}
/**
* Returns the named graph or null.
*
* @param uri
* The graph's name.
*
* @return The named graph or null.
*/
public NamedGraph getGraph(String uri) {
return this.getNamedGraphSet().getGraph(uri);
}
/**
* Returns the corresponding graph.
*
* @param ts
* The time span defining the graph.
*
* @return The corresponding graph or null.
*/
public NamedGraph getGraph(TimeSpan ts) {
return this.getNamedGraphSet().getGraph(getGraphNameFor(ts));
}
public NamedGraph getGlobalKnowledgeGraph() {
return namedGraphSet.getGraph(config.getGlobalKnowledgeGraphURI());
}
public Model getContextDescriptionGraph() {
return contextDescriptionGraph;
}
public Model getJenaModelViewOnNamedGraphSet() {
return getNamedGraphSet().asJenaModel(config.getDefaultGraphURI());
}
/**
* Tests whether the passed entity exists.
*
* <p>
* It is not tested whether the system has a copy of the entity in that
* particular form (all the attributes set to specific values). It will just
* be checked if there is a triple in the system that assigns the entity an
* RDF type:
*
* <pre>
* uri rdf:type ?t .
* </pre>
*
* </p>
*
* @param entity
* The entity to test.
*
* @return True, if there is some information about this entity stored in the
* system.
*/
public boolean containsEntity(GabotoEntity entity) {
return containsEntity(entity.getUri());
}
/**
* Tests whether the passed entity exists.
*
* <p>
* It is not tested whether the system has a copy of the entity in that
* particular form (all the attributes set to specific values). It will just
* be checked if there is a triple in the system that assigns the entity an
* RDF type:
*
* <pre>
* uri rdf:type ?t .
* </pre>
*
* </p>
*
* @param uri
* The entity's URI.
*
* @return True, if there is some information about this entity stored in the
* system.
*/
public boolean containsEntity(String uri) {
if (uri == null)
throw new IllegalArgumentException("URI may not be null.");
return getNamedGraphSet().containsQuad(
new Quad(Node.ANY, Node.createURI(uri), Node.createURI(RDF.type
.getURI()), Node.ANY));
}
/**
* Loads an entity at a given point in time.
*
* @param uri
* The entity's URI.
* @param ti
* The time instant.
*
* @return The entity.
*
* @throws NoTimeIndexSetException
*/
public GabotoEntity getEntity(String uri, TimeInstant ti) {
if (!containsEntity(uri))
throw new EntityDoesNotExistException(uri);
GabotoSnapshot snap = getSnapshot(ti);
return snap.loadEntity(uri);
}
/**
* Loads an entity with all its data.
*
* @param uri
* The entity's URI.
* @return A full representation of the entity.
*/
public GabotoTimeBasedEntity getEntityOverTime(String uri) {
if (!containsEntity(uri))
throw new EntityDoesNotExistException(uri);
return GabotoTimeBasedEntity.loadEntity(uri, this);
}
/**
* Tests whether the system contains data about the specified resource.
*
* <p>
* It is tested if there is any triple that has the resource's URI as its
* subject.
* </p>
*
* @param res
* The resource.
*
* @return True, if the resource exists.
*/
public boolean containsResource(Resource res) {
return containsResource(res.getURI());
}
/**
* Tests whether the system contains data about the specified resource.
*
* <p>
* It is tested if there is any triple that has the resource's URI as its
* subject.
* </p>
*
* @param uri
* The resource's URI.
*
* @return True, if the resource exists.
*/
public boolean containsResource(String uri) {
return getNamedGraphSet().containsQuad(
new Quad(Node.ANY, Node.createURI(uri), Node.ANY, Node.ANY));
}
/**
* Tries to figure out the ontology type of an entity identified by its URI.
*
* @param uri
* The entity's URI.
*
*/
public String getTypeOf(String uri) {
if (!containsEntity(uri))
throw new EntityDoesNotExistException(uri);
Iterator<?> it = getNamedGraphSet().findQuads(Node.ANY, Node.createURI(uri),
Node.createURI(RDF.type.getURI()), Node.ANY);
if (it.hasNext()) {
Quad quad = (Quad)it.next();
if (it.hasNext())
throw new IncoherenceException("Corrupted data. " + uri
+ " has two triples defining its type");
if (!quad.getObject().isURI()) {
throw new IncoherenceException("Corrupted data. " + uri
+ " has an invalid type.");
}
return quad.getObject().getURI();
} else
throw new GabotoRuntimeException("No quad found");
}
/**
* Returns an entity's life time.
*
* <p>
* The life time of an entity is described by the graph that contains its type
* definition.
* </p>
*
* @param uri
* The entity's URI
*
* @return The life time
*
*/
public TimeSpan getEntitysLifetime(String uri) {
if (!containsEntity(uri))
throw new EntityDoesNotExistException(uri);
Iterator<?> it = getNamedGraphSet().findQuads(Node.ANY, Node.createURI(uri),
Node.createURI(RDF.type.getURI()), Node.ANY);
if (it.hasNext()) {
Quad quad = (Quad)it.next();
if (it.hasNext())
logger.error("Corrupted data. " + uri
+ " has to triples defining its type");
if (!quad.getObject().isURI()) {
logger.error("Corrupted data. " + uri + " has has not a valid type.");
throw new IncoherenceException("Corrupted data. " + uri
+ " has has not a valid type.");
}
return TimeSpan.createFromGraphName(quad.getGraphName().getURI(), this);
} else
throw new RuntimeException("No quad found");
}
/**
* Returns a list of URIs for entities that have the specified property.
*
* @param prop
* The property
*
* @return A collection of uris.
*/
public Collection<String> getEntityURIsFor(Property prop) {
Collection<String> uris = new HashSet<String>();
// find in named graphs
Iterator<?> it = getNamedGraphSet().findQuads(Node.ANY, Node.ANY,
Node.createURI(prop.getURI()), Node.ANY);
while (it.hasNext()) {
Quad q = (Quad)it.next();
uris.add(q.getSubject().getURI());
}
return uris;
}
/**
* Returns a list of URIs for entities that have the specified property.
*
* @param prop
* The property
* @param value
* The property's value
*
* @return A collection of uris.
*/
public Collection<String> getEntityURIsFor(Property prop, String value) {
Collection<String> uris = new HashSet<String>();
// find in named graphs
Iterator<?> it = getNamedGraphSet().findQuads(Node.ANY, Node.ANY,
Node.createURI(prop.getURI()), Node.createLiteral(value));
while (it.hasNext()) {
Quad q = (Quad)it.next();
uris.add(q.getSubject().getURI());
}
return uris;
}
/**
* Returns a list of URIs for entities that have the specified property.
*
* @param prop
* The property
* @param value
* The property's value
*
* @return A collection of uris.
*/
public Collection<String> getEntityURIsFor(Property prop, Node value) {
Collection<String> uris = new HashSet<String>();
// find in named graphs
Iterator<?> it = getNamedGraphSet().findQuads(Node.ANY, Node.ANY,
Node.createURI(prop.getURI()), value);
while (it.hasNext()) {
Quad q = (Quad)it.next();
uris.add(q.getSubject().getURI());
}
return uris;
}
/**
* Loads entities that have a certain property.
*
* @param prop
* The property
* @return An entity pool with all entities that have this property.
*/
public Collection<GabotoTimeBasedEntity> loadEntitiesOverTimeWithProperty(
Property prop) {
Collection<GabotoTimeBasedEntity> entities = new HashSet<GabotoTimeBasedEntity>();
for (String uri : getEntityURIsFor(prop)) {
try {
entities.add(getEntityOverTime(uri));
} catch (EntityDoesNotExistException e) {
throw new GabotoRuntimeException(e);
}
}
return entities;
}
/**
* Loads entities that have a certain property.
*
* @param prop
* The property
* @param value
* The property's value.
*
* @return An entity pool with all entities that have this property/value
* pair.
*/
public Collection<GabotoTimeBasedEntity> loadEntitiesOverTimeWithProperty(
Property prop, String value) {
Collection<GabotoTimeBasedEntity> entities = new HashSet<GabotoTimeBasedEntity>();
for (String uri : getEntityURIsFor(prop, value)) {
entities.add(getEntityOverTime(uri));
}
return entities;
}
/**
* Loads entities that have a certain property.
*
* @param prop
* The property
* @param value
* The property's value.
*
* @return An entity pool with all entities that have this property/value
* pair.
*/
public Collection<GabotoTimeBasedEntity> loadEntitiesOverTimeWithProperty(
Property prop, Node value) {
Collection<GabotoTimeBasedEntity> entities = new HashSet<GabotoTimeBasedEntity>();
for (String uri : getEntityURIsFor(prop, value)) {
entities.add(getEntityOverTime(uri));
}
return entities;
}
/**
*
* @param os
* The OutputStream to write to.
*/
public void write(OutputStream os) {
getNamedGraphSet().write(os, "TRIG", null);
}
/**
*
* @param os
* The OutputStream to write to.
* @param format
* The output format to use.
*/
public void write(OutputStream os, String format) {
getNamedGraphSet().write(os, format, null);
}
/**
*
* @param os
* The OutputStream to write to.
*/
public void writeCDG(OutputStream os) {
getContextDescriptionGraph().write(os);
}
/**
*
* @param os
* The OutputStream to write to.
* @param format
* The RDF format.
*/
public void writeCDG(OutputStream os, String format) {
getContextDescriptionGraph().write(os, format);
}
public void read(InputStream oxpIS, InputStream cdgIS) {
if (oxpIS == null)
throw new NullPointerException();
if (cdgIS == null)
throw new NullPointerException();
getNamedGraphSet().read(oxpIS, "TRIG", null);
getContextDescriptionGraph().read(cdgIS, "RDF/XML");
}
/**
*
* @param oxpIS
* @param oxpFormat
* @param cdgIS
* @param cdgFormat
*/
public void read(InputStream oxpIS, String oxpFormat, InputStream cdgIS,
String cdgFormat) {
getNamedGraphSet().read(oxpIS, oxpFormat, null);
getContextDescriptionGraph().read(cdgIS, cdgFormat);
}
public OntologyLookup getOntologyLookup() {
return GabotoFactory.getConfig().getGabotoOntologyLookup();
}
/**
* @return the config
*/
public GabotoConfiguration getConfig() {
return config;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (! (obj instanceof Gaboto))
return false;
else {
if (getContextDescriptionGraph().isIsomorphicWith(((Gaboto)obj).getContextDescriptionGraph())) {
if (getJenaModelViewOnNamedGraphSet().
isIsomorphicWith(((Gaboto)obj).getJenaModelViewOnNamedGraphSet())) {
return true;
} else {
Model us = getJenaModelViewOnNamedGraphSet();
Model them = ((Gaboto)obj).getJenaModelViewOnNamedGraphSet();
StmtIterator ours = us.listStatements();
System.err.println("unique to us");
while (ours.hasNext()) {
Statement s = ours.next();
if (!them.contains(s))
System.err.println(s);
}
System.err.println("unique to them");
StmtIterator theirs = them.listStatements();
while (theirs.hasNext()) {
Statement s = theirs.next();
if (!us.contains(s))
System.err.println(s);
}
return false;
}
} else {
if (getJenaModelViewOnNamedGraphSet().
isIsomorphicWith(((Gaboto)obj).getJenaModelViewOnNamedGraphSet())) {
System.err.println("CDGs only differ ");
}
return false;
}
}
}
}
|
package ublu.command;
import ublu.AS400Factory;
import ublu.util.ArgArray;
import ublu.util.DataSink;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JPing;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
/**
* Command to create an AS400 instance to be kept in a Tuple.
*
* @author jwoehr
*/
public class CmdAS400 extends Command {
{
setNameAndDescription("as400",
"/3? [-to @var] [--,-as400,-from @var] [-instance | -alive | -alivesvc ~@{[CENTRAL|COMMAND|DATABASE|DATAQUEUE|FILE|PRINT|RECORDACCESS|SIGNON]} | -connectsvc ~@{[CENTRAL|COMMAND|DATABASE|DATAQUEUE|FILE|PRINT|RECORDACCESS|SIGNON]} | -connectedsvc ~@{[CENTRAL|COMMAND|DATABASE|DATAQUEUE|FILE|PRINT|RECORDACCESS|SIGNON]} | -connected | -disconnect | -disconnectsvc ~@{[CENTRAL|COMMAND|DATABASE|DATAQUEUE|FILE|PRINT|RECORDACCESS|SIGNON]} | -ping sysname ~@{[ALL|CENTRAL|COMMAND|DATABASE|DATAQUEUE|FILE|PRINT|RECORDACCESS|SIGNON]} | -svcport ~@{[CENTRAL|COMMAND|DATABASE|DATAQUEUE|FILE|PRINT|RECORDACCESS|SIGNON]} ~@portnum | -svcportdefault | -proxy ~@{server[:portnum]} | -vrm ] ~@{system} ~@{user} ~@{password} : instance, connect to, query connection, or disconnect from an as400 system");
}
/**
* Operations we know
*/
protected enum OPERATIONS {
/**
* Create instance
*/
INSTANCE,
/**
* Are any connections alive?
*/
ALIVE,
/**
* Is the connection to the specified service alive?
*/
ALIVESVC,
/**
* Connect to service
*/
CONNECTSVC,
/**
* Is connected to specific service?
*/
CONNECTEDSVC,
/**
* Is connected at all?
*/
CONNECTED,
/**
* Disconnect
*/
DISCONNECT,
/**
* Disconnect from specific service
*/
DISCONNECTSVC,
/**
* Ping server or services
*/
PING,
/**
* Indicate server port for service
*/
SVCPORT,
/**
* Set ports to default
*/
SVCPORTDEFAULT,
/**
* Indicate JTOpen Proxy server
*/
PROXY,
/**
* Get version/revision/mod of server
*/
VRM
}
/**
* Create an AS400 instance to be kept in a Tuple and perform control
* operations thereupon.
*
* @param argArray arguments in interpreter buffer
* @return what's left of arguments
*/
public ArgArray as400(ArgArray argArray) {
OPERATIONS operation = OPERATIONS.INSTANCE; // the default
String systemName = "";
String serviceName = "";
String proxyServer = "";
int servicePort = -1;
while (argArray.hasDashCommand()) {
String dashCommand = argArray.parseDashCommand();
switch (dashCommand) {
case "-to":
setDataDest(DataSink.fromSinkName(argArray.next()));
break;
case "
case "-as400":
case "-from":
setAs400(getAS400Tuple(argArray.next()));
break;
case "-instance":
operation = OPERATIONS.INSTANCE;
break;
case "-alive":
operation = OPERATIONS.ALIVE;
break;
case "-alivesvc":
operation = OPERATIONS.CONNECTEDSVC;
serviceName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-connectsvc":
operation = OPERATIONS.CONNECTSVC;
serviceName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-connectedsvc":
operation = OPERATIONS.CONNECTEDSVC;
serviceName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-connected":
operation = OPERATIONS.CONNECTED;
break;
case "-disconnect":
operation = OPERATIONS.DISCONNECT;
break;
case "-disconnectsvc":
operation = OPERATIONS.DISCONNECTSVC;
serviceName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-ping":
operation = OPERATIONS.PING;
systemName = argArray.nextMaybeQuotationTuplePopString();
serviceName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-svcport":
operation = OPERATIONS.SVCPORT;
serviceName = argArray.nextMaybeQuotationTuplePopString();
servicePort = argArray.nextIntMaybeQuotationTuplePopString();
break;
case "-svcportdefault":
operation = OPERATIONS.SVCPORTDEFAULT;
break;
case "-proxy":
operation = OPERATIONS.PROXY;
proxyServer = argArray.nextMaybeQuotationTuplePopString();
break;
case "-vrm":
operation = OPERATIONS.VRM;
break;
default:
unknownDashCommand(dashCommand);
}
}
if (havingUnknownDashCommand()) {
setCommandResult(COMMANDRESULT.FAILURE);
} else {
Integer serviceInteger;
switch (operation) {
case INSTANCE:
if (getAs400() != null) {
getLogger().log(Level.INFO, "AS400 object {0} already instanced.", getAs400());
try {
put(getAs400());
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE,
"Encountered an exception putting the AS400 object " + getAs400() + " to the destination datasink in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
try {
setAs400(instanceAS400(argArray));
put(getAs400());
} catch (PropertyVetoException | RequestNotSupportedException | SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) {
getLogger().log(Level.SEVERE,
"Encountered an exception putting the AS400 object " + getAs400() + " to the destination datasink in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
break;
case ALIVE:
if (getAs400() != null) {
try {
put(getAs400().isConnectionAlive());
} catch (RequestNotSupportedException | SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) {
getLogger().log(Level.SEVERE,
"Encountered an exception putting the connection alive state of AS400 object " + getAs400() + " to the destination datasink in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No instance of AS400 object in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case ALIVESVC:
serviceInteger = AS400Factory.serviceNameToInteger(serviceName);
if (serviceInteger != null) {
if (getAs400() != null) {
try {
put(getAs400().isConnectionAlive(serviceInteger));
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Exception querying connection to service " + serviceName + " in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No AS400 object provided to query live connection to service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "Unknown service name provided to query live connection to service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case CONNECTSVC:
serviceInteger = AS400Factory.serviceNameToInteger(serviceName);
if (serviceInteger != null) {
if (getAs400() != null) {
try {
getAs400().connectService(serviceInteger);
} catch (AS400SecurityException | IOException ex) {
getLogger().log(Level.SEVERE, "Exception connecting to service in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No AS400 object provided to connect service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "Unknown service name provided to connect service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case CONNECTEDSVC:
serviceInteger = AS400Factory.serviceNameToInteger(serviceName);
if (serviceInteger != null) {
if (getAs400() != null) {
try {
put(getAs400().isConnected(serviceInteger));
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Exception querying connection to service " + serviceName + " in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No AS400 object provided to query connection to service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "Unknown service name provided to query connection to service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case CONNECTED:
if (getAs400() != null) {
try {
put(getAs400().isConnected());
} catch (RequestNotSupportedException | SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) {
getLogger().log(Level.SEVERE,
"Encountered an exception putting the connected state of AS400 object " + getAs400() + " to the destination datasink in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No instance of AS400 object in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case DISCONNECT:
if (getAs400() != null) {
getAs400().disconnectAllServices();
} else {
getLogger().log(Level.SEVERE, "No instance of AS400 object in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case DISCONNECTSVC:
serviceInteger = AS400Factory.serviceNameToInteger(serviceName);
if (serviceInteger != null) {
if (getAs400() != null) {
getAs400().disconnectService(serviceInteger);
} else {
getLogger().log(Level.SEVERE, "No AS400 object provided to disconnect service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "Unknown service name provided to disconnect service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case PING:
if (serviceName.toUpperCase().equals("ALL")) {
serviceInteger = AS400JPing.ALL_SERVICES;
} else {
serviceInteger = AS400Factory.serviceNameToInteger(serviceName);
}
if (serviceInteger != null) {
AS400JPing jping = new AS400JPing(systemName, serviceInteger);
try {
put(jping.ping());
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Couldn't put result of AS400 ping in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "Unknown service name provided to ping service in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case SVCPORT:
serviceInteger = AS400Factory.serviceNameToInteger(serviceName);
if (serviceInteger != null) {
if (getAs400() != null) {
getAs400().setServicePort(serviceInteger, servicePort);
} else {
getLogger().log(Level.SEVERE, "No instance of AS400 object to set service port in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "Unknown service name provided to service port in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case SVCPORTDEFAULT:
if (getAs400() != null) {
getAs400().setServicePortsToDefault();
} else {
getLogger().log(Level.SEVERE, "No instance of AS400 object to set service ports to default in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case PROXY:
if (getAs400() != null) {
try {
getAs400().setProxyServer(proxyServer);
} catch (PropertyVetoException ex) {
getLogger().log(Level.SEVERE, "Couldn't set proxy server " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No AS400 object provided to proxy in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case VRM:
if (getAs400() != null) {
try {
put(Integer.toHexString((getAs400().getVRM())));
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Couldn't put result of AS400 VRM in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No AS400 object provided to VRM in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
}
}
return argArray;
}
/**
* Create the AS400 instance after checking that we have enough args.
*
* @param args the argument array
* @return the AS400 instance or null
* @throws PropertyVetoException
*/
public AS400 instanceAS400(ArgArray args) throws PropertyVetoException {
AS400 as400 = null;
if (args.size() < 3) {
logArgArrayTooShortError(args);
setCommandResult(COMMANDRESULT.FAILURE);
} else {
as400 = as400FromArgs(args);
}
return as400;
}
@Override
public ArgArray cmd(ArgArray args) {
reinit();
return as400(args);
}
@Override
public COMMANDRESULT getResult() {
return getCommandResult();
}
}
|
package org.lantern;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;
import java.security.Security;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;
import javax.security.auth.login.CredentialException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.spi.LoggingEvent;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.widgets.Display;
import org.json.simple.JSONObject;
import org.lantern.exceptional4j.ExceptionalAppender;
import org.lantern.exceptional4j.ExceptionalAppenderCallback;
import org.lantern.http.JettyLauncher;
import org.lantern.privacy.InvalidKeyException;
import org.lantern.privacy.LocalCipherProvider;
import org.lantern.state.InternalState;
import org.lantern.state.Location;
import org.lantern.state.Modal;
import org.lantern.state.Model;
import org.lantern.state.ModelIo;
import org.lantern.state.ModelUtils;
import org.lantern.state.Settings;
import org.lantern.state.Settings.Mode;
import org.lantern.state.StaticSettings;
import org.lantern.state.SyncService;
import org.lantern.util.GlobalLanternServerTrafficShapingHandler;
import org.lantern.util.LanternHttpClient;
import org.lastbamboo.common.offer.answer.IceConfig;
import org.lastbamboo.common.stun.client.PublicIpAddress;
import org.lastbamboo.common.stun.client.StunServerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Launches a new Lantern HTTP proxy.
*/
public class Launcher {
private static Logger LOG;
private boolean lanternStarted = false;
private LanternHttpProxyServer localProxy;
private PlainTestRelayHttpProxyServer plainTextAnsererRelayProxy;
private JettyLauncher jettyLauncher;
private XmppHandler xmpp;
private BrowserService browserService;
private StatsUpdater statsUpdater;
private SslHttpProxyServer sslProxy;
private LocalCipherProvider localCipherProvider;
private MessageService messageService;
private Injector injector;
private SystemTray systemTray;
private Model model;
private ModelUtils modelUtils;
private Settings set;
private Censored censored;
private InternalState internalState;
private LanternHttpClient httpClient;
private final String[] commandLineArgs;
private SyncService syncService;
public Launcher(final String... args) {
this.commandLineArgs = args;
Thread.currentThread().setName("Lantern-Main-Thread");
//Connection.DEBUG_ENABLED = true;
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
handleError(e, false);
}
});
}
public void run() {
LOG = LoggerFactory.getLogger(Launcher.class);
try {
launch(this.commandLineArgs);
} catch (final Throwable t) {
handleError(t, true);
}
}
/**
* Starts the proxy from the command line.
*
* @param args Any command line arguments.
*/
public static void main(final String... args) {
main(true, args);
}
/**
* Starts the proxy from the command line.
*
* @param args Any command line arguments.
*/
public static void main(final boolean configureLogger, final String... args) {
final Launcher launcher = new Launcher(args);
if (configureLogger) {
launcher.configureDefaultLogger();
}
launcher.run();
}
private void launch(final String... args) {
LOG.info("Starting Lantern...");
configureCipherSuites();
// first apply any command line settings
final Options options = buildOptions();
final CommandLineParser parser = new PosixParser();
final CommandLine cmd;
try {
cmd = parser.parse(options, args);
if (cmd.getArgs().length > 0) {
throw new UnrecognizedOptionException("Extra arguments were provided");
}
}
catch (final ParseException e) {
printHelp(options, e.getMessage()+" args: "+Arrays.asList(args));
return;
}
if (cmd.hasOption(OPTION_HELP)) {
printHelp(options, null);
return;
} else if (cmd.hasOption(OPTION_VERSION)) {
printVersion();
return;
}
injector = Guice.createInjector(new LanternModule());
model = instance(Model.class);
set = model.getSettings();
// We parse this one separately because we need this value right away.
if (cmd.hasOption(OPTION_DISABLE_UI)) {
LOG.info("Disabling UI");
set.setUiEnabled(false);
}
else {
set.setUiEnabled(true);
}
censored = instance(Censored.class);
LOG.debug("Creating display...");
final Display display;
if (set.isUiEnabled()) {
// We initialize this super early in case there are any errors
// during startup we have to display to the user.
Display.setAppName("Lantern");
//display = injector.getInstance(Display.class);;
display = DisplayWrapper.getDisplay();
// Also, We need the system tray to listen for events early on.
//LanternHub.systemTray().createTray();
}
else {
display = null;
}
messageService = instance(MessageService.class);
instance(Proxifier.class);
if (set.isUiEnabled()) {
browserService = instance(BrowserService.class);
systemTray = instance(SystemTray.class);
}
// We need to make sure the trust store is initialized before we
// do our public IP lookup as well as modelUtils.
instance(LanternTrustStore.class);
xmpp = instance(DefaultXmppHandler.class);
jettyLauncher = instance(JettyLauncher.class);
sslProxy = instance(SslHttpProxyServer.class);
localCipherProvider = instance(LocalCipherProvider.class);
plainTextAnsererRelayProxy = instance(PlainTestRelayHttpProxyServer.class);
modelUtils = instance(ModelUtils.class);
localProxy = instance(LanternHttpProxyServer.class);
internalState = instance(InternalState.class);
httpClient = instance(LanternHttpClient.class);
syncService = instance(SyncService.class);
final ProxyTracker proxyTracker = instance(ProxyTracker.class);
// We do this to make sure it's added to the shutdown list.
instance(GlobalLanternServerTrafficShapingHandler.class);
LOG.debug("Processing command line options...");
processCommandLineOptions(cmd);
LOG.debug("Processed command line options...");
threadPublicIpLookup();
if (set.isUiEnabled()) {
LOG.debug("Starting system tray..");
try {
systemTray.start();
} catch (final Exception e) {
LOG.error("Error starting tray?", e);
}
LOG.debug("Started system tray..");
}
shutdownable(ModelIo.class);
try {
proxyTracker.start();
} catch (final Exception e) {
LOG.error("Could not start proxy tracker?", e);
}
jettyLauncher.start();
xmpp.start();
sslProxy.start(false, false);
localProxy.start();
plainTextAnsererRelayProxy.start(true, false);
syncService.start();
statsUpdater = instance(StatsUpdater.class);
statsUpdater.start();
gnomeAutoStart();
// Use our stored STUN servers if available.
final Collection<String> stunServers = set.getStunServers();
if (stunServers != null && !stunServers.isEmpty()) {
LOG.info("Using stored STUN servers: {}", stunServers);
StunServerRepository.setStunServers(toSocketAddresses(stunServers));
}
if (LanternUtils.hasNetworkConnection()) {
LOG.info("Got internet...");
launchWithOrWithoutUi();
} else {
// If we're running on startup, it's quite likely we just haven't
// connected to the internet yet. Let's wait for an internet
// connection and then start Lantern.
if (model.isLaunchd() || !set.isUiEnabled()) {
LOG.info("Waiting for internet connection...");
LanternUtils.waitForInternet();
launchWithOrWithoutUi();
}
// If setup is complete and we're not running on startup, open
// the dashboard.
else if (model.isSetupComplete()) {
if (set.isUiEnabled()) {
browserService.openBrowserWhenPortReady();
}
//jettyLauncher.openBrowserWhenReady();
// Wait for an internet connection before starting the XMPP
// connection.
LOG.info("Waiting for internet connection...");
LanternUtils.waitForInternet();
launchWithOrWithoutUi();
} else {
// If we haven't configured Lantern and don't have an internet
// connection, the problem is that we can't verify the user's
// user name and password when they try to login, so we just
// let them know we can't start Lantern until they have a
// connection.
// TODO: i18n
final String msg =
"We're sorry, but you cannot configure Lantern without " +
"an active connection to the internet. Please try again " +
"when you have an internet connection.";
messageService.showMessage("No Internet", msg);
System.exit(0);
// The new-ui wants to allow the user to configure this later?
//launchWithOrWithoutUi();
}
}
// This is necessary to keep the tray/menu item up in the case
// where we're not launching a browser.
if (display != null) {
while (!display.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
}
}
/**
* We thread this because otherwise looking up our public IP address
* over the network can delay the creation of settings altogether. That's
* problematic if the UI is waiting on them, for example.
*/
private void threadPublicIpLookup() {
if (LanternConstants.ON_APP_ENGINE) {
return;
}
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// This performs the public IP lookup so by the time we set
// GET versus GIVE mode we already know the IP and don't have
// to wait.
// We get the address here to set it in Connectivity.
final InetAddress ip =
new PublicIpAddress().getPublicIpAddress();
if (ip == null) {
LOG.info("No IP -- possibly no internet connection");
return;
}
model.getConnectivity().setIp(ip.getHostAddress());
final GeoData geo = modelUtils.getGeoData(ip.getHostAddress());
final Location loc = model.getLocation();
loc.setCountry(geo.getCountrycode());
loc.setLat(geo.getLatitude());
loc.setLon(geo.getLongitude());
// The IP is cached at this point.
/*
try {
final Country count = censored.country();
model.getLocation().setCountry(count.getCode());
} catch (final IOException e) {
LOG.error("Could not get country", e);
}
*/
// If the mode isn't set in the model, set the default.
if (set.getMode() == null || set.getMode() == Mode.none) {
if (censored.isCensored()) {
set.setMode(Mode.get);
} else {
set.setMode(Mode.give);
}
}
}
}, "Public-IP-Lookup-Thread");
thread.setDaemon(true);
thread.start();
}
private <T> void shutdownable(final Class<T> clazz) {
instance(clazz);
}
private <T> T instance(final Class<T> clazz) {
final T inst = injector.getInstance(clazz);
if (Shutdownable.class.isAssignableFrom(clazz)) {
addShutdownHook((Shutdownable) inst);
}
if (inst == null) {
LOG.error("Could not load instance of "+clazz);
throw new NullPointerException("Could not load instance of "+clazz);
}
return inst;
}
private void addShutdownHook(final Shutdownable service) {
LOG.info("Adding shutdown hook for {}", service);
// TODO: Add these all to a single list of things to do on shutdown.
final Thread serviceHook = new Thread(new Runnable() {
@Override
public void run() {
service.stop();
}
}, "ShutdownHook-For-Service-"+service.getClass().getSimpleName());
Runtime.getRuntime().addShutdownHook(serviceHook);
}
private void gnomeAutoStart() {
// Before setup we should just do the default, which is to run on
// startup. The user can configure this differently at any point
// hereafter.
if (SystemUtils.IS_OS_LINUX &&
!LanternClientConstants.GNOME_AUTOSTART.isFile()) {
final File lanternDesktop;
final File candidate1 =
new File(LanternClientConstants.GNOME_AUTOSTART.getName());
final File candidate2 =
new File("install/linux", LanternClientConstants.GNOME_AUTOSTART.getName());
if (candidate1.isFile()) {
lanternDesktop = candidate1;
} else if (candidate2.isFile()){
lanternDesktop = candidate2;
} else {
LOG.error("Could not find lantern.desktop file");
return;
}
try {
final File parent = LanternClientConstants.GNOME_AUTOSTART.getParentFile();
if (!parent.isDirectory()) {
if (!parent.mkdirs()) {
LOG.error("Could not make dir for gnome autostart: "+parent);
return;
}
}
FileUtils.copyFileToDirectory(lanternDesktop, parent);
LOG.info("Copied {} to {}", lanternDesktop, parent);
} catch (final IOException e) {
LOG.error("Could not configure gnome autostart", e);
}
}
}
public static String CIPHER_SUITE_LOW_BIT =
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA";
public static String CIPHER_SUITE_HIGH_BIT =
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA";
public static void configureCipherSuites() {
Security.addProvider(new BouncyCastleProvider());
if (!LanternUtils.isUnlimitedKeyStrength()) {
if (!SystemUtils.IS_OS_WINDOWS_VISTA) {
log("No policy files on non-Vista machine!!");
}
log("Reverting to weaker ciphers on Vista");
IceConfig.setCipherSuites(new String[] {
CIPHER_SUITE_LOW_BIT
//"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
//"TLS_ECDHE_RSA_WITH_RC4_128_SHA"
});
} else {
// Note the following just sets what cipher suite the server
// side selects. DHE is for perfect forward secrecy.
// copy the unlimited strength policy files on Vista, so we have
// to revert back to 128.
IceConfig.setCipherSuites(new String[] {
CIPHER_SUITE_HIGH_BIT
//"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
//"TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
//"TLS_RSA_WITH_RC4_128_SHA"
//"TLS_ECDHE_RSA_WITH_RC4_128_SHA"
});
}
}
private static void log(final String msg) {
if (LOG != null) {
LOG.error(msg);
} else {
System.err.println(msg);
}
}
private static Collection<InetSocketAddress> toSocketAddresses(
final Collection<String> stunServers) {
final Collection<InetSocketAddress> isas =
new HashSet<InetSocketAddress>();
for (final String server : stunServers) {
final String host = StringUtils.substringBefore(server, ":");
final String port = StringUtils.substringAfter(server, ":");
isas.add(new InetSocketAddress(host, Integer.parseInt(port)));
}
return isas;
}
private boolean parseOptionDefaultTrue(final CommandLine cmd,
final String option) {
if (cmd.hasOption(option)) {
LOG.info("Found option: "+option);
return false;
}
// DEFAULTS TO TRUE!!
return true;
}
private void loadLocalPasswordFile(final String pwFilename) {
//final LocalCipherProvider lcp = localCipherProvider;
if (!localCipherProvider.requiresAdditionalUserInput()) {
LOG.error("Settings do not require a password to unlock.");
System.exit(1);
}
if (StringUtils.isBlank(pwFilename)) {
LOG.error("No filename specified to --{}", OPTION_PASSWORD_FILE);
System.exit(1);
}
final File pwFile = new File(pwFilename);
if (!(pwFile.exists() && pwFile.canRead())) {
LOG.error("Unable to read password from {}", pwFilename);
System.exit(1);
}
LOG.info("Reading local password from file \"{}\"", pwFilename);
try {
final String pw = FileUtils.readLines(pwFile, "US-ASCII").get(0);
final boolean init = !localCipherProvider.isInitialized();
localCipherProvider.feedUserInput(pw.toCharArray(), init);
}
catch (final IndexOutOfBoundsException e) {
LOG.error("Password in file \"{}\" was incorrect", pwFilename);
System.exit(1);
}
catch (final InvalidKeyException e) {
LOG.error("Password in file \"{}\" was incorrect", pwFilename);
System.exit(1);
}
catch (final GeneralSecurityException e) {
LOG.error("Failed to initialize using password in file \"{}\": {}", pwFilename, e);
System.exit(1);
}
catch (final IOException e) {
LOG.error("Failed to initialize using password in file \"{}\": {}", pwFilename, e);
System.exit(1);
}
}
private void launchWithOrWithoutUi() {
if (!set.isUiEnabled()) {
// We only run headless on Linux for now.
LOG.info("Running Lantern with no display...");
launchLantern();
//LanternHub.jettyLauncher();
return;
}
LOG.debug("Is launchd: {}", model.isLaunchd());
launchLantern();
model.getConnectivity().setInternet(
LanternUtils.hasNetworkConnection());
}
public void launchLantern() {
LOG.debug("Launching Lantern...");
if (!modelUtils.isConfigured()) {
model.setModal(Modal.welcome);
}
if (set.isUiEnabled()) {
browserService.openBrowserWhenPortReady();
}
autoConnect();
lanternStarted = true;
}
private void autoConnect() {
LOG.debug("Connecting if oauth is configured...");
// This won't connect in the case where the user hasn't entered
// their user name and password and the user is running with a UI.
// Otherwise, it will connect.
if (modelUtils.isConfigured()) {
final Runnable runner = new Runnable() {
@Override
public void run() {
try {
xmpp.connect();
if (model.getModal() == Modal.connecting) {
internalState.advanceModal(null);
}
} catch (final IOException e) {
LOG.debug("Could not login", e);
} catch (final CredentialException e) {
LOG.debug("Bad credentials");
} catch (final NotInClosedBetaException e) {
LOG.warn("Not in closed beta!!");
}
}
};
final Thread t = new Thread(runner, "Auto-Starting-Thread");
t.setDaemon(true);
t.start();
} else {
LOG.debug("Not auto-logging in with model:\n{}", model);
}
}
private void printHelp(Options options, String errorMessage) {
if (errorMessage != null) {
LOG.error(errorMessage);
System.err.println(errorMessage);
}
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("lantern", options);
}
private void printVersion() {
System.out.println("Lantern version "+LanternClientConstants.VERSION);
}
private void configureDefaultLogger() {
final String propsPath = "src/main/resources/log4j.properties";
final File props = new File(propsPath);
if (props.isFile()) {
System.out.println("Running from main line");
PropertyConfigurator.configure(propsPath);
} else {
System.out.println("Not on main line...");
configureProductionLogger();
}
}
private void configureProductionLogger() {
final File logDir = LanternClientConstants.LOG_DIR;
final File logFile = new File(logDir, "java.log");
final Properties props = new Properties();
try {
final String logPath = logFile.getCanonicalPath();
props.put("log4j.appender.RollingTextFile.File", logPath);
props.put("log4j.rootLogger", "warn, RollingTextFile");
props.put("log4j.appender.RollingTextFile",
"org.apache.log4j.RollingFileAppender");
props.put("log4j.appender.RollingTextFile.MaxFileSize", "1MB");
props.put("log4j.appender.RollingTextFile.MaxBackupIndex", "1");
props.put("log4j.appender.RollingTextFile.layout",
"org.apache.log4j.PatternLayout");
props.put(
"log4j.appender.RollingTextFile.layout.ConversionPattern",
"%-6r %d{ISO8601} %-5p [%t] %c{2}.%M (%F:%L) - %m%n");
// This throws and swallows a FileNotFoundException, but it
// doesn't matter. Just weird.
PropertyConfigurator.configure(props);
System.out.println("Set logger file to: " + logPath);
final ExceptionalAppenderCallback callback =
new ExceptionalAppenderCallback() {
@Override
public boolean addData(final JSONObject json,
final LoggingEvent le) {
if (!set.isAutoReport()) {
// Don't report anything if the user doesn't have
// it turned on.
return false;
}
json.put("version", LanternClientConstants.VERSION);
return true;
}
};
final Appender bugAppender = new ExceptionalAppender(
LanternClientConstants.GET_EXCEPTIONAL_API_KEY, callback,
httpClient);
BasicConfigurator.configure(bugAppender);
} catch (final IOException e) {
System.out.println("Exception setting log4j props with file: "
+ logFile);
e.printStackTrace();
}
}
private void handleError(final Throwable t, final boolean exit) {
final String msg = msg(t);
LOG.error("Uncaught exception: "+msg, t);
if (t instanceof SWTError || msg.contains("SWTError")) {
System.out.println(
"To run without a UI, run lantern with the
OPTION_DISABLE_UI +
" command line argument");
}
else if (t instanceof UnsatisfiedLinkError &&
msg.contains("Cannot load 32-bit SWT libraries on 64-bit JVM")) {
messageService.showMessage("Architecture Error",
"We're sorry, but it appears you're running 32-bit Lantern on a 64-bit JVM.");
}
else if (!lanternStarted && set.isUiEnabled()) {
LOG.info("Showing error to user...");
messageService.showMessage("Startup Error",
"We're sorry, but there was an error starting Lantern " +
"described as '"+msg+"'.");
}
if (exit) {
LOG.info("Exiting Lantern");
System.exit(1);
}
}
private static String msg(final Throwable t) {
final String msg = t.getMessage();
if (msg == null) {
return "";
}
return msg;
}
// the following are command line options
public static final String OPTION_DISABLE_UI = "disable-ui";
public static final String OPTION_HELP = "help";
public static final String OPTION_LAUNCHD = "launchd";
public static final String OPTION_PUBLIC_API = "public-api";
public static final String OPTION_API_PORT = "api-port";
public static final String OPTION_SERVER_PORT = "server-port";
public static final String OPTION_DISABLE_KEYCHAIN = "disable-keychain";
public static final String OPTION_PASSWORD_FILE = "password-file";
public static final String OPTION_TRUSTED_PEERS = "disable-trusted-peers";
public static final String OPTION_ANON_PEERS ="disable-anon-peers";
public static final String OPTION_LAE = "disable-lae";
public static final String OPTION_CENTRAL = "disable-central";
public static final String OPTION_UDP = "disable-udp";
public static final String OPTION_TCP = "disable-tcp";
public static final String OPTION_USER = "user";
public static final String OPTION_PASS = "pass";
public static final String OPTION_GET = "force-get";
public static final String OPTION_GIVE = "force-give";
public static final String OPTION_NO_CACHE = "no-cache";
public static final String OPTION_VERSION = "version";
public static final String OPTION_NEW_UI = "new-ui";
public static final String OPTION_REFRESH_TOK = "refresh-tok";
public static final String OPTION_ACCESS_TOK = "access-tok";
public static final String OPTION_OAUTH2_CLIENT_SECRETS_FILE = "oauth2-client-secrets-file";
public static final String OPTION_OAUTH2_USER_CREDENTIALS_FILE = "oauth2-user-credentials-file";
private static Options buildOptions() {
final Options options = new Options();
options.addOption(null, OPTION_DISABLE_UI, false,
"run without a graphical user interface.");
options.addOption(null, OPTION_API_PORT, true,
"the port to run the API server on.");
options.addOption(null, OPTION_SERVER_PORT, true,
"the port to run the give mode proxy server on.");
options.addOption(null, OPTION_PUBLIC_API, false,
"make the API server publicly accessible on non-localhost.");
options.addOption(null, OPTION_HELP, false,
"display command line help");
options.addOption(null, OPTION_LAUNCHD, false,
"running from launchd - not normally called from command line");
options.addOption(null, OPTION_DISABLE_KEYCHAIN, false,
"disable use of system keychain and ask for local password");
options.addOption(null, OPTION_PASSWORD_FILE, true,
"read local password from the file specified");
options.addOption(null, OPTION_TRUSTED_PEERS, false,
"disable use of trusted peer-to-peer connections for proxies.");
options.addOption(null, OPTION_ANON_PEERS, false,
"disable use of anonymous peer-to-peer connections for proxies.");
options.addOption(null, OPTION_LAE, false,
"disable use of app engine proxies.");
options.addOption(null, OPTION_CENTRAL, false,
"disable use of centralized proxies.");
options.addOption(null, OPTION_UDP, false,
"disable UDP for peer-to-peer connections.");
options.addOption(null, OPTION_TCP, false,
"disable TCP for peer-to-peer connections.");
options.addOption(null, OPTION_USER, true,
"Google user name -- WARNING INSECURE - ONLY USE THIS FOR TESTING!");
options.addOption(null, OPTION_PASS, true,
"Google password -- WARNING INSECURE - ONLY USE THIS FOR TESTING!");
options.addOption(null, OPTION_GET, false, "Force running in get mode");
options.addOption(null, OPTION_GIVE, false, "Force running in give mode");
options.addOption(null, OPTION_NO_CACHE, false,
"Don't allow caching of static files in the dashboard");
options.addOption(null, OPTION_VERSION, false,
"Print the Lantern version");
options.addOption(null, OPTION_NEW_UI, false,
"Use the new UI under the 'ui' directory");
options.addOption(null, OPTION_REFRESH_TOK, true,
"Specify the oauth2 refresh token");
options.addOption(null, OPTION_ACCESS_TOK, true,
"Specify the oauth2 access token");
options.addOption(null, OPTION_OAUTH2_CLIENT_SECRETS_FILE, true,
"read Google OAuth2 client secrets from the file specified");
options.addOption(null, OPTION_OAUTH2_USER_CREDENTIALS_FILE, true,
"read Google OAuth2 user credentials from the file specified");
return options;
}
private void processCommandLineOptions(final CommandLine cmd) {
final String secOpt = OPTION_OAUTH2_CLIENT_SECRETS_FILE;
if (cmd.hasOption(secOpt)) {
modelUtils.loadOAuth2ClientSecretsFile(
cmd.getOptionValue(secOpt));
}
final String credOpt = OPTION_OAUTH2_USER_CREDENTIALS_FILE;
if (cmd.hasOption(credOpt)) {
modelUtils.loadOAuth2UserCredentialsFile(
cmd.getOptionValue(credOpt));
}
//final Settings set = LanternHub.settings();
set.setUseTrustedPeers(parseOptionDefaultTrue(cmd, OPTION_TRUSTED_PEERS));
set.setUseAnonymousPeers(parseOptionDefaultTrue(cmd, OPTION_ANON_PEERS));
set.setUseLaeProxies(parseOptionDefaultTrue(cmd, OPTION_LAE));
set.setUseCentralProxies(parseOptionDefaultTrue(cmd, OPTION_CENTRAL));
IceConfig.setTcp(parseOptionDefaultTrue(cmd, OPTION_TCP));
IceConfig.setUdp(parseOptionDefaultTrue(cmd, OPTION_UDP));
/*
if (cmd.hasOption(OPTION_USER)) {
set.setUserId(cmd.getOptionValue(OPTION_USER));
}
if (cmd.hasOption(OPTION_PASS)) {
set.(cmd.getOptionValue(OPTION_PASS));
}
*/
if (cmd.hasOption(OPTION_REFRESH_TOK)) {
set.setRefreshToken(cmd.getOptionValue(OPTION_REFRESH_TOK));
}
if (cmd.hasOption(OPTION_ACCESS_TOK)) {
set.setAccessToken(cmd.getOptionValue(OPTION_ACCESS_TOK));
}
// option to disable use of keychains in local privacy
if (cmd.hasOption(OPTION_DISABLE_KEYCHAIN)) {
LOG.info("Disabling use of system keychains");
set.setKeychainEnabled(false);
}
else {
set.setKeychainEnabled(true);
}
if (cmd.hasOption(OPTION_PASSWORD_FILE)) {
loadLocalPasswordFile(cmd.getOptionValue(OPTION_PASSWORD_FILE));
}
if (cmd.hasOption(OPTION_PUBLIC_API)) {
set.setBindToLocalhost(false);
}
if (cmd.hasOption(OPTION_API_PORT)) {
final String apiPortStr =
cmd.getOptionValue(OPTION_API_PORT);
LOG.info("Using command-line port: "+ apiPortStr);
final int apiPort = Integer.parseInt(apiPortStr);
StaticSettings.setApiPort(apiPort);
} else {
LOG.debug("Using random port...");
}
LOG.info("Running API on port: {}", StaticSettings.getApiPort());
if (cmd.hasOption(OPTION_SERVER_PORT)) {
final String serverPortStr =
cmd.getOptionValue(OPTION_SERVER_PORT);
LOG.debug("Using command-line proxy port: "+serverPortStr);
final int serverPort = Integer.parseInt(serverPortStr);
set.setServerPort(serverPort);
} else {
final int existing = set.getServerPort();
if (existing < 1024) {
LOG.debug("Using random give mode proxy port...");
set.setServerPort(LanternUtils.randomPort());
}
}
LOG.info("Running give mode proxy on port: {}", set.getServerPort());
if (cmd.hasOption(OPTION_LAUNCHD)) {
LOG.debug("Running from launchd or launchd set on command line");
model.setLaunchd(true);
} else {
model.setLaunchd(false);
}
if (cmd.hasOption(OPTION_GIVE)) {
model.getSettings().setMode(Mode.give);
} else if (cmd.hasOption(OPTION_GET)) {
model.getSettings().setMode(Mode.get);
}
model.setCache(!LanternUtils.isDevMode());
if (cmd.hasOption(OPTION_NO_CACHE)) {
model.setCache(false);
}
}
}
|
package mondrian.xmla;
import mondrian.olap.*;
import mondrian.olap.Connection;
import mondrian.olap.DriverManager;
import mondrian.rolap.RolapConnection;
import mondrian.spi.CatalogLocator;
import mondrian.xmla.impl.DefaultSaxWriter;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.io.StringWriter;
import java.io.PrintWriter;
/**
* An <code>XmlaHandler</code> responds to XML for Analysis (XML/A) requests.
*
* @author jhyde, Gang Chen
* @version $Id$
* @since 27 April, 2003
*/
public class XmlaHandler implements XmlaConstants {
private static final Logger LOGGER = Logger.getLogger(XmlaHandler.class);
private final Map dataSourcesMap;
private CatalogLocator catalogLocator = null;
private static final String DatasetXmlSchema = computeRowsetXsd();
private static String computeRowsetXsd() {
final StringWriter sw = new StringWriter();
SaxWriter writer = new DefaultSaxWriter(new PrintWriter(sw), 3);
writeDatasetXmlSchema(writer);
writer.flush();
return sw.toString();
}
private static interface QueryResult {
public void unparse(SaxWriter res) throws SAXException;
}
public XmlaHandler(
DataSourcesConfig.DataSources dataSources,
CatalogLocator catalogLocator) {
this.catalogLocator = catalogLocator;
Map map = new HashMap();
for (int i = 0; i < dataSources.dataSources.length; i++) {
DataSourcesConfig.DataSource ds = dataSources.dataSources[i];
if (map.containsKey(ds.getDataSourceName())) {
throw Util.newError(
"duplicated data source name '" +
ds.getDataSourceName() + "'");
}
map.put(ds.getDataSourceName(), ds);
}
dataSourcesMap = Collections.unmodifiableMap(map);
}
public Map getDataSourceEntries() {
return dataSourcesMap;
}
/**
* Processes a request.
*
* @param request XML request, for example, "<SOAP-ENV:Envelope ...>".
* @param response Destination for response
*/
public void process(XmlaRequest request, XmlaResponse response) {
int method = request.getMethod();
switch (method) {
case METHOD_DISCOVER:
discover(request, response);
break;
case METHOD_EXECUTE:
execute(request, response);
break;
default:
throw new IllegalArgumentException("Unsupported XML/A method");
}
}
private void execute(XmlaRequest request, XmlaResponse response) {
// Check response's rowset format in request
String propertyName = null;
try {
if (request.isDrillThrough()) {
propertyName = PropertyDefinition.Format.name;
final String formatName = (String) request.getProperties().get(propertyName);
Enumeration.Format format = Enumeration.Format.getValue(formatName);
if (format != Enumeration.Format.Tabular) {
throw new UnsupportedOperationException("<Format>: only 'Tabular' allowed when drilling through");
}
} else {
propertyName = PropertyDefinition.Format.name;
final String formatName = (String) request.getProperties().get(propertyName);
Enumeration.Format format = Enumeration.Format.getValue(formatName);
propertyName = PropertyDefinition.AxisFormat.name;
final String axisFormatName = (String) request.getProperties().get(propertyName);
Enumeration.AxisFormat axisFormat = Enumeration.AxisFormat.getValue(axisFormatName);
if (format != Enumeration.Format.Multidimensional) {
throw new UnsupportedOperationException("<Format>: only 'Multidimensional' currently supported");
}
if (axisFormat != Enumeration.AxisFormat.TupleFormat) {
throw new UnsupportedOperationException("<AxisFormat>: only 'TupleFormat' currently supported");
}
}
} catch (Error e) {
throw new UnsupportedOperationException(
"Property <" + propertyName + "> must be provided");
}
// Handle execute
QueryResult result = null;
if (request.isDrillThrough()) {
result = executeDrillThroughQuery(request);
} else {
result = executeQuery(request);
}
SaxWriter writer = response.getWriter();
writer.startDocument();
writer.startElement("ExecuteResponse", new String[] {
"xmlns", NS_XMLA});
writer.startElement("return", new String[] {
"xmlns:xsi", NS_XSI,
"xmlns:xsd", NS_XSD,});
writer.startElement("root", new String[] {
"xmlns", request.isDrillThrough() ? NS_XMLA_ROWSET : NS_XMLA_MDDATASET});
writer.verbatim(DatasetXmlSchema);
try {
result.unparse(writer);
} catch (Throwable t) {
LOGGER.error("Errors when unparsing XML/A execute result", t);
response.error(t);
} finally {
writer.endElement();
writer.endElement();
writer.endElement();
}
writer.endDocument();
}
/**
* Computes the XML Schema for a dataset.
*
* @param writer SAX writer
* @see RowsetDefinition#writeRowsetXmlSchema(SaxWriter)
*/
static void writeDatasetXmlSchema(SaxWriter writer) {
writer.startElement("xsd:schema", new String[] {
"xmlns:xsd", XmlaConstants.NS_XSD,
"targetNamespace", XmlaConstants.NS_XMLA_MDDATASET,
"xmlns:xsi", XmlaConstants.NS_XSI,
"xmlns:sql", NS_SQL,
"elementFormDefault", "qualified"
});
// MemberType
writer.startElement("xsd:complexType", new String[] {
"name", "MemberType"
});
writer.element("xsd:attribute", new String[] {
"name", "Hierarchy",
"type", "xsd:string",
});
writer.startElement("xsd:sequence");
writer.element("xsd:element", new String[] {
"name", "UName",
"type", "xsd:string",
});
writer.element("xsd:element", new String[] {
"name", "Caption",
"type", "xsd:string",
});
writer.element("xsd:element", new String[] {
"name", "LName",
"type", "xsd:string",
});
writer.element("xsd:element", new String[] {
"name", "LNum",
"type", "xsd:unsignedInt",
});
writer.element("xsd:element", new String[] {
"name", "DisplayInfo",
"type", "xsd:unsignedInt",
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded",
"minOccurs", "0",
});
writer.element("xsd:any", new String[] {
"processContents", "lax",
"maxOccurs", "unbounded",
});
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType name="MemberType"
// PropType
writer.startElement("xsd:complexType", new String[] {
"name", "PropType",
});
writer.element("xsd:attribute", new String[] {
"name", "name",
"type", "xsd:string",
});
writer.endElement(); // xsd:complexType name="PropType"
// TupleType
writer.startElement("xsd:complexType", new String[] {
"name", "TupleType"
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
writer.element("xsd:element", new String[] {
"name", "Member",
"type", "MemberType",
});
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType name="TupleType"
// MembersType
writer.startElement("xsd:complexType", new String[] {
"name", "MembersType"
});
writer.element("xsd:attribute", new String[] {
"name", "Hierarchy",
"type", "xsd:string",
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded",
});
writer.element("xsd:element", new String[] {
"name", "Member",
"type", "MemberType",
});
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
// TuplesType
writer.startElement("xsd:complexType", new String[] {
"name", "TuplesType"
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded",
});
writer.element("xsd:element", new String[] {
"name", "Tuple",
"type", "TupleType",
});
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
// CrossProductType
writer.startElement("xsd:complexType", new String[] {
"name", "CrossProductType",
});
writer.startElement("xsd:choice", new String[] {
"minOccurs", "0",
"maxOccurs", "unbounded",
});
writer.element("xsd:element", new String[] {
"name", "Members",
"type", "MembersType"
});
writer.element("xsd:element", new String[] {
"name", "Tuples",
"type", "TuplesType"
});
writer.endElement(); // xsd:choice
writer.endElement(); // xsd:complexType
// OlapInfo
writer.startElement("xsd:complexType", new String[] {
"name", "OlapInfo",
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
{ // <AxesInfo>
writer.startElement("xsd:element", new String[] {
"name", "AxesInfo"
});
writer.startElement("xsd:complexType");
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
{ // <AxisInfo>
writer.startElement("xsd:element", new String[] {
"name", "AxisInfo"
});
writer.startElement("xsd:complexType");
writer.element("xsd:attribute", new String[] {
"name", "name",
"type", "xsd:string"
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
{ // <HierarchyInfo>
writer.startElement("xsd:element", new String[] {
"name", "HierarchyInfo"
});
writer.startElement("xsd:complexType");
writer.element("xsd:attribute", new String[] {
"name", "name",
"type", "xsd:string"
});
writer.startElement("xsd:sequence");
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
writer.element("xsd:element", new String[] {
"name", "UName",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "Caption",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "LName",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "LNum",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "DisplayInfo",
"type", "PropType"
});
writer.endElement(); // xsd:sequence
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded",
"minOccurs", "0"
});
writer.element("xsd:any", new String[] {
"processContents", "lax",
"maxOccurs", "unbounded"
});
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element name=HierarchyInfo
}
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element name=AxisInfo
}
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element name=AxesInfo
}
// CellInfo
{ // <CellInfo>
writer.startElement("xsd:element", new String[] {
"name", "CellInfo"
});
writer.startElement("xsd:complexType");
writer.startElement("xsd:sequence");
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
writer.startElement("xsd:choice");
writer.element("xsd:element", new String[] {
"name", "Value",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "FmtValue",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "BackColor",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "ForeColor",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "FontName",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "FontSize",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "FontFlags",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "FormatString",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "NonEmptyBehavior",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "SolveOrder",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "Updateable",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "Visible",
"type", "PropType"
});
writer.element("xsd:element", new String[] {
"name", "Expression",
"type", "PropType"
});
writer.endElement(); // xsd:choice
writer.endElement(); // xsd:sequence
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded",
"minOccurs", "0"
});
writer.element("xsd:any", new String[] {
"processContents", "lax",
"maxOccurs", "unbounded"
});
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element name=CellInfo
}
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
// Axes
writer.startElement("xsd:complexType", new String[] {
"name", "Axes"
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
{ // <Axis>
writer.startElement("xsd:element", new String[] {
"name", "Axis"
});
writer.startElement("xsd:complexType");
writer.element("xsd:attribute", new String[] {
"name", "name",
"type", "xsd:string"
});
writer.startElement("xsd:choice", new String[] {
"minOccurs", "0",
"maxOccurs", "unbounded"
});
writer.element("xsd:element", new String[] {
"name", "CrossProduct",
"type", "CrossProductType"
});
writer.element("xsd:element", new String[] {
"name", "Tuples",
"type", "TuplesType"
});
writer.element("xsd:element", new String[] {
"name", "Members",
"type", "MembersType"
});
writer.endElement(); // xsd:choice
writer.endElement(); // xsd:complexType
}
writer.endElement(); // xsd:element
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
// CellData
writer.startElement("xsd:complexType", new String[] {
"name", "CellData"
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
{ // <Cell>
writer.startElement("xsd:element", new String[] {
"name", "Cell"
});
writer.startElement("xsd:complexType");
writer.element("xsd:attribute", new String[] {
"name", "CellOrdinal",
"type", "xsd:unsignedInt"
});
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
writer.startElement("xsd:choice");
writer.element("xsd:element", new String[] {
"name", "Value"
});
writer.element("xsd:element", new String[] {
"name", "FmtValue",
"type", "xsd:string"
});
writer.element("xsd:element", new String[] {
"name", "BackColor",
"type", "xsd:unsignedInt"
});
writer.element("xsd:element", new String[] {
"name", "ForeColor",
"type", "xsd:unsignedInt"
});
writer.element("xsd:element", new String[] {
"name", "FontName",
"type", "xsd:string"
});
writer.element("xsd:element", new String[] {
"name", "FontSize",
"type", "xsd:unsignedShort"
});
writer.element("xsd:element", new String[] {
"name", "FontFlags",
"type", "xsd:unsignedInt"
});
writer.element("xsd:element", new String[] {
"name", "FormatString",
"type", "xsd:string"
});
writer.element("xsd:element", new String[] {
"name", "NonEmptyBehavior",
"type", "xsd:unsignedShort"
});
writer.element("xsd:element", new String[] {
"name", "SolveOrder",
"type", "xsd:unsignedInt"
});
writer.element("xsd:element", new String[] {
"name", "Updateable",
"type", "xsd:unsignedInt"
});
writer.element("xsd:element", new String[] {
"name", "Visible",
"type", "xsd:unsignedInt"
});
writer.element("xsd:element", new String[] {
"name", "Expression",
"type", "xsd:string"
});
writer.endElement(); // xsd:choice
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element name=Cell
}
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
{ // <root>
writer.startElement("xsd:element", new String[] {
"name", "root"
});
writer.startElement("xsd:complexType");
writer.startElement("xsd:sequence", new String[] {
"maxOccurs", "unbounded"
});
writer.element("xsd:element", new String[] {
"name", "OlapInfo",
"type", "OlapInfo"
});
writer.element("xsd:element", new String[] {
"name", "Axes",
"type", "Axes"
});
writer.element("xsd:element", new String[] {
"name", "CellData",
"type", "CellData"
});
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element name=root
}
writer.endElement(); // xsd:schema
}
private QueryResult executeDrillThroughQuery(XmlaRequest request) {
final String statement = request.getStatement();
final Connection connection = getConnection(request);
final Query query = connection.parseQuery(statement);
final Result result = connection.execute(query);
Cell dtCell = result.getCell(new int[] {0, 0});
if (!dtCell.canDrillThrough()) {
throw Util.newError("Cannot do DillThrough operation on the cell");
}
String dtSql = dtCell.getDrillThroughSQL(true);
TabularRowSet rowset = null;
java.sql.Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ((RolapConnection) connection).getDataSource().getConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
int count = -1;
if (MondrianProperties.instance().EnableTotalCount.booleanValue()) {
String temp = dtSql.toUpperCase();
int fromOff = temp.indexOf("FROM");
StringBuffer buf = new StringBuffer();
buf.append("select count(*) ");
buf.append(dtSql.substring(fromOff));
String countSql = buf.toString();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("drill through counting sql: " + countSql);
}
rs = stmt.executeQuery(countSql);
rs.next();
count = rs.getInt(1);
rs.close();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("drill through sql: " + dtSql);
}
rs = stmt.executeQuery(dtSql);
rowset = new TabularRowSet(rs, request.drillThroughMaxRows(),
request.drillThroughFirstRowset(), count);
} catch (SQLException sqle) {
throw Util.newError(sqle, "Errors when executing DrillThrough sql '" +
dtSql + "'");
} finally {
try {
if (rs != null) rs.close();
} catch (SQLException ignored) {
}
try {
if (stmt != null) stmt.close();
} catch (SQLException ignored) {
}
try {
if (conn != null && !conn.isClosed()) conn.close();
} catch (SQLException ignored) {
}
}
return rowset;
}
static class TabularRowSet implements QueryResult {
private String[] header;
private List rows;
private int totalCount;
public TabularRowSet(ResultSet rs,
int maxRows,
int firstRowset,
int totalCount) throws SQLException {
this.totalCount = totalCount;
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
// populate header
header = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
header[i] = md.getColumnName(i + 1);
}
// skip to first rowset specified in request
rs.absolute(firstRowset <= 0 ? 1 : firstRowset);
// populate data
rows = new ArrayList();
maxRows = (maxRows <= 0 ? Integer.MAX_VALUE : maxRows);
do {
Object[] row = new Object[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = rs.getObject(i + 1);
}
rows.add(row);
} while (rs.next() && --maxRows > 0);
}
public void unparse(SaxWriter writer) throws SAXException {
String[] encodedHeader = new String[header.length];
for (int i = 0; i < header.length; i++) {
// replace invalid XML element name, like " ", with "_x0020_" in
// column headers, otherwise will generate a badly-formatted xml doc.
encodedHeader[i] = XmlaUtil.encodeElementName(header[i]);
}
// write total count row if enabled
if (totalCount >= 0) {
String countStr = Integer.toString(totalCount);
writer.startElement("row");
for (int i = 0; i < encodedHeader.length; i++) {
writer.startElement(encodedHeader[i]);
writer.characters(countStr);
writer.endElement();
}
writer.endElement(); // row
}
for (Iterator it = rows.iterator(); it.hasNext();) {
Object[] row = (Object[]) it.next();
writer.startElement("row");
for (int i = 0; i < row.length; i++) {
writer.startElement(encodedHeader[i]);
Object value = row[i];
if (value == null) {
writer.characters("null");
} else {
if (value instanceof Number) {
writer.characters(XmlaUtil.normalizeNumricString(value.toString()));
} else {
writer.characters(row[i].toString());
}
}
writer.endElement();
}
writer.endElement(); // row
}
}
}
private QueryResult executeQuery(XmlaRequest request) {
final String statement = request.getStatement();
final Connection connection = getConnection(request);
final Query query = connection.parseQuery(statement);
final Result result = connection.execute(query);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("mdx: " + statement);
}
return new MDDataSet(result);
}
static class MDDataSet implements QueryResult {
private final Result result;
private static final String[] cellProps = new String[] {
"Value",
"FmtValue",
"FormatString"};
private static final String[] cellPropLongs = new String[] {
Property.VALUE.name,
Property.FORMATTED_VALUE.name,
Property.FORMAT_STRING.name};
private static final String[] props = new String[] {
"UName",
"Caption",
"LName",
"LNum",
"DisplayInfo",
"Depth"};
private static final String[] propLongs = new String[] {
Property.MEMBER_UNIQUE_NAME.name,
Property.MEMBER_CAPTION.name,
Property.LEVEL_UNIQUE_NAME.name,
Property.LEVEL_NUMBER.name,
Property.DISPLAY_INFO.name,
Property.DEPTH.name};
public MDDataSet(Result result) {
this.result = result;
}
public void unparse(SaxWriter writer) throws SAXException {
olapInfo(writer);
axes(writer);
cellData(writer);
}
private void olapInfo(SaxWriter writer) {
writer.startElement("OlapInfo");
writer.startElement("CubeInfo");
writer.startElement("Cube");
writer.startElement("CubeName");
writer.characters(result.getQuery().getCube().getName());
writer.endElement();
writer.endElement();
writer.endElement(); // CubeInfo
writer.startElement("AxesInfo");
final Axis[] axes = result.getAxes();
axisInfo(writer, result.getSlicerAxis(), "SlicerAxis");
for (int i = 0; i < axes.length; i++) {
axisInfo(writer, axes[i], "Axis" + i);
}
writer.endElement(); // AxesInfo
writer.startElement("CellInfo");
writer.element("Value", new String[] {
"name", "VALUE"});
writer.element("FmtValue", new String[] {
"name", "FORMATTED_VALUE"});
writer.element("FormatString", new String[] {
"name", "FORMAT_STRING"});
writer.endElement(); // CellInfo
writer.endElement(); // OlapInfo
}
private void axisInfo(SaxWriter writer, Axis axis, String axisName) {
writer.startElement("AxisInfo", new String[] {
"name", axisName});
Hierarchy[] hierarchies;
if (axis.positions.length > 0) {
final Position position = axis.positions[0];
hierarchies = new Hierarchy[position.members.length];
for (int j = 0; j < position.members.length; j++) {
Member member = position.members[j];
hierarchies[j] = member.getHierarchy();
}
} else {
hierarchies = new Hierarchy[0];
//final QueryAxis queryAxis = this.result.getQuery().axes[i];
// todo:
}
for (int j = 0; j < hierarchies.length; j++) {
writer.startElement("HierarchyInfo", new String[] {
"name", hierarchies[j].getName()});
for (int k = 0; k < props.length; k++) {
writer.element(props[k], new String[] {
"name", hierarchies[j].getUniqueName() + ".[" +
propLongs[k] + "]"});
}
writer.endElement(); // HierarchyInfo
}
writer.endElement(); // AxisInfo
}
private void axes(SaxWriter writer) {
writer.startElement("Axes");
axis(writer, result.getSlicerAxis(), "SlicerAxis");
final Axis[] axes = result.getAxes();
for (int i = 0; i < axes.length; i++) {
axis(writer, axes[i], "Axis" + i);
}
writer.endElement(); // Axes
}
private void axis(SaxWriter writer, Axis axis, String axisName) {
writer.startElement("Axis", new String[] {
"name", axisName});
writer.startElement("Tuples");
Position[] positions = axis.positions;
for (int j = 0; j < positions.length; j++) {
Position position = positions[j];
writer.startElement("Tuple");
for (int k = 0; k < position.members.length; k++) {
Member member = position.members[k];
writer.startElement("Member", new String[] {
"Hierarchy", member.getHierarchy().getName()});
for (int m = 0; m < props.length; m++) {
Object value = null;
if (propLongs[m].equals(Property.DISPLAY_INFO.name)) {
Integer childrenCard =
(Integer) member.getPropertyValue(Property.CHILDREN_CARDINALITY.name);
int displayInfo =
calculateDisplayInfo((j == 0 ? null : positions[j - 1]),
(j + 1 == positions.length ? null : positions[j + 1]),
member, k, childrenCard.intValue());
value = new Integer(displayInfo);
} else if (propLongs[m].equals(Property.DEPTH.name)) {
value = new Integer(member.getDepth());
} else {
value = member.getPropertyValue(propLongs[m]);
}
if (value != null) {
writer.startElement(props[m]); // Properties
writer.characters(value.toString());
writer.endElement(); // Properties
}
}
writer.endElement(); // Member
}
writer.endElement(); // Tuple
}
writer.endElement(); // Tuples
writer.endElement(); // Axis
}
private int calculateDisplayInfo(Position prevPosition, Position nextPosition,
Member currentMember, int memberOrdinal, int childrenCount) {
int displayInfo = 0xffff & childrenCount;
if (nextPosition != null) {
String currentUName = currentMember.getUniqueName();
String nextParentUName = nextPosition.members[memberOrdinal].getParentUniqueName();
displayInfo |= (currentUName.equals(nextParentUName) ? 0x10000 : 0);
}
if (prevPosition != null) {
String currentParentUName = currentMember.getParentUniqueName();
String prevParentUName = prevPosition.members[memberOrdinal].getParentUniqueName();
displayInfo |= (currentParentUName != null && currentParentUName.equals(prevParentUName) ? 0x20000 : 0);
}
return displayInfo;
}
private void cellData(SaxWriter writer) throws SAXException {
writer.startElement("CellData", new String[] {"xmlns:xsi", NS_XSI});
final int axisCount = result.getAxes().length;
int[] pos = new int[axisCount];
int[] cellOrdinal = new int[] {0};
if (axisCount == 0) { // For MDX like: SELECT FROM Sales
emitCell(writer, result.getCell(pos), cellOrdinal[0]);
} else {
recurse(writer, pos, axisCount - 1, cellOrdinal);
}
writer.endElement(); // CellData
}
private void recurse(SaxWriter writer, int[] pos, int axis, int[] cellOrdinal) throws SAXException {
final int axisLength = result.getAxes()[axis].positions.length;
for (int i = 0; i < axisLength; i++) {
pos[axis] = i;
if (axis == 0) {
final Cell cell = result.getCell(pos);
emitCell(writer, cell, cellOrdinal[0]++);
} else {
recurse(writer, pos, axis - 1, cellOrdinal);
}
}
}
private void emitCell(SaxWriter writer, Cell cell, int ordinal) {
if (cell.isNull()) {
// Ignore null cell like MS AS
return;
}
writer.startElement("Cell", new String[] {
"CellOrdinal", Integer.toString(ordinal)});
for (int i = 0; i < cellProps.length; i++) {
String cellPropLong = cellPropLongs[i];
final Object value = cell.getPropertyValue(cellPropLong);
// Deduce the XML datatype from the declared datatype
// of the measure, if present. (It comes from the
// "datatype" attribute of the "Measure" element.) If
// not present, use the value type to guess.
// The value type depends upon the RDBMS and the JDBC
// driver, so it tends to produce inconsistent results
// between platforms.
String valueType;
String datatype = (String)
cell.getPropertyValue(Property.DATATYPE.getName());
if (datatype != null) {
if (datatype.equals("Integer")) {
valueType = "xsd:int";
} else if (datatype.equals("Numeric")) {
valueType = "xsd:double";
} else {
valueType = "xsd:string";
}
} else if (value instanceof Integer || value instanceof Long) {
valueType = "xsd:int";
} else if (value instanceof Double || value instanceof BigDecimal) {
valueType = "xsd:double";
} else {
valueType = "xsd:string";
}
if (value != null) {
if (cellPropLong.equals(Property.VALUE.name)) {
writer.startElement(cellProps[i], new String[] {"xsi:type", valueType});
} else {
writer.startElement(cellProps[i]);
}
String valueString = value.toString();
if (cellPropLong.equals(Property.VALUE.name) &&
value instanceof Number) {
valueString = XmlaUtil.normalizeNumricString(valueString);
}
writer.characters(valueString);
writer.endElement();
}
}
writer.endElement(); // Cell
}
}
private void discover(XmlaRequest request, XmlaResponse response) {
final RowsetDefinition rowsetDefinition =
RowsetDefinition.getValue(request.getRequestType());
Rowset rowset = rowsetDefinition.getRowset(request, this);
try {
final String formatName =
(String) request.getProperties().get(PropertyDefinition.Format.name);
Enumeration.Format format = Enumeration.Format.getValue(formatName);
if (format != Enumeration.Format.Tabular) {
throw new UnsupportedOperationException("<Format>: only 'Tabular' allowed in Discover method type");
}
} catch (Error e) {
}
SaxWriter writer = response.getWriter();
writer.startDocument();
writer.startElement("DiscoverResponse", new String[] {
"xmlns", NS_XMLA});
writer.startElement("return");
writer.startElement("root", new String[] {
"xmlns", NS_XMLA_ROWSET});
rowset.rowsetDefinition.writeRowsetXmlSchema(writer);
try {
rowset.unparse(response);
} catch (Throwable t) { // MondrianException is subclass of RuntimeException
LOGGER.error("Errors when unparsing XML/A discover result", t);
response.error(t);
} finally {
// keep the tags balanced, even if there's an error
writer.endElement();
writer.endElement();
writer.endElement();
}
writer.endDocument();
}
/**
* Returns a Mondrian connection as specified by a set of properties
* (especially the "Connect string" property).
*/
Connection getConnection(XmlaRequest request) {
Map properties = request.getProperties();
final String dataSourceInfo =
(String) properties.get(PropertyDefinition.DataSourceInfo.name);
if (!dataSourcesMap.containsKey(dataSourceInfo)) {
throw Util.newError("no data source is configured with name '" + dataSourceInfo + "'");
}
DataSourcesConfig.DataSource ds =
(DataSourcesConfig.DataSource) dataSourcesMap.get(dataSourceInfo);
Util.PropertyList connectProperties =
Util.parseConnectString(ds.getDataSourceInfo());
connectProperties.put("catalog",
catalogLocator.locate(connectProperties.get("catalog")));
// Checking access
if (!DataSourcesConfig.DataSource.AUTH_MODE_UNAUTHENTICATED.equalsIgnoreCase(ds.getAuthenticationMode()) &&
null == request.getRole()) {
throw new SecurityException("Access denied for data source needing authentication");
}
connectProperties.put("role", request.getRole());
RolapConnection conn =
(RolapConnection) DriverManager.getConnection(connectProperties, null, false);
return conn;
}
}
// End XmlaHandler.java
|
package xmppclient;
import org.jivesoftware.smack.XMPPConnection;
/**
*
* @author Dean Wake
*/
public class XMPPClient {
public void testConnect() {
System.out.println("connect");
String serverIP = "openfire.fin-tech.com";
connectionHandler instance = new connectionHandler();
XMPPConnection result = instance.connect(serverIP);
System.out.println("Connection result: " + result);
}
/**
* Test of login method, of class connectionHandler.
*/
public void testLogin() {
System.out.println("login");
String userName = "user";
String password = "123456";
connectionHandler instance = new connectionHandler();
System.out.println("Is logged in: " + instance.login(userName, password));
}
/**
* Test of disconnect method, of class connectionHandler.
*/
public void testDisconnect() {
System.out.println("disconnect");
connectionHandler instance = new connectionHandler();
System.out.println("Is disconnected: " + instance.disconnect());
}
public static void main(String[] args) {
XMPPClient testClass = new XMPPClient();
testClass.testConnect();
testClass.testLogin();
testClass.testDisconnect();
}
}
|
package rhogenwizard.preferences;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import rhogenwizard.Activator;
import rhogenwizard.ConsoleHelper;
import rhogenwizard.buildfile.AppYmlFile;
import rhogenwizard.buildfile.SdkYmlAdapter;
import rhogenwizard.buildfile.SdkYmlFile;
/**
* Class used to initialize default preference values.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer
{
static PreferenceInitializer m_initPref = null;
private String m_defaultBbVer = null;
private SdkYmlFile m_ymlFile = null;
private List<String> m_bbVers = null;
private IProject m_currProject = null;
private String m_currRhodesPath = null;
static PreferenceInitializer getInstance()
{
try
{
if (m_initPref != null)
{
m_initPref.initFromFirstProject();
return m_initPref;
}
m_initPref = new PreferenceInitializer();
m_initPref.initFromFirstProject();
}
catch (Exception e)
{
ConsoleHelper.consolePrint(e.toString());
e.printStackTrace();
}
return m_initPref;
}
private void initFromFirstProject()
{
List<String> projectNames = getRhodesProjects();
if (projectNames == null)
return;
for (String projectName : projectNames)
{
IProject currProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (AppYmlFile.isExists(currProject.getLocation().toOSString()))
{
initFromProject(projectName);
}
}
}
public SdkYmlFile getYmlFile()
{
return m_ymlFile;
}
public List<String> getBbVersions()
{
return m_bbVers;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
public void initializeDefaultPreferences()
{
try
{
if (m_ymlFile != null)
{
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
String cabWizPath = m_ymlFile.getCabWizPath() != null ? m_ymlFile.getCabWizPath() : "";
String androidSdkPath = m_ymlFile.getAndroidSdkPath() != null ? m_ymlFile.getAndroidSdkPath() : "";
String androidNdkPath = m_ymlFile.getAndroidNdkPath() != null ? m_ymlFile.getAndroidNdkPath() : "";
String javaPath = m_ymlFile.getJavaPath() != null ? m_ymlFile.getJavaPath() : "";
String bbJdkPath = m_ymlFile.getBbJdkPath(m_defaultBbVer) != null ? m_ymlFile.getBbJdkPath(m_defaultBbVer) : "";
String bbMdsPath = m_ymlFile.getBbMdsPath(m_defaultBbVer) != null ? m_ymlFile.getBbMdsPath(m_defaultBbVer) : "";
String bbSimPort = m_ymlFile.getBbSimPort(m_defaultBbVer) != null ? m_ymlFile.getBbSimPort(m_defaultBbVer) : "";
store.setDefault(PreferenceConstants.BB_VERSION_NAME, m_defaultBbVer);
store.setDefault(PreferenceConstants.BB_JDK_PATH, bbJdkPath);
store.setDefault(PreferenceConstants.BB_MDS_PATH, bbMdsPath);
store.setDefault(PreferenceConstants.BB_SIM, bbSimPort);
store.setDefault(PreferenceConstants.JAVA_PATH, javaPath);
store.setDefault(PreferenceConstants.ANDROID_SDK_PATH, androidSdkPath);
store.setDefault(PreferenceConstants.ANDROID_NDK_PATH, androidNdkPath);
store.setDefault(PreferenceConstants.CAB_WIZARD_PATH, cabWizPath);
store.setValue(PreferenceConstants.BB_VERSION_NAME, m_defaultBbVer);
store.setValue(PreferenceConstants.BB_JDK_PATH, bbJdkPath);
store.setValue(PreferenceConstants.BB_MDS_PATH, bbMdsPath);
store.setValue(PreferenceConstants.BB_SIM, bbSimPort);
store.setValue(PreferenceConstants.JAVA_PATH, javaPath);
store.setValue(PreferenceConstants.ANDROID_SDK_PATH, androidSdkPath);
store.setValue(PreferenceConstants.ANDROID_NDK_PATH, androidNdkPath);
store.setValue(PreferenceConstants.CAB_WIZARD_PATH, cabWizPath);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void savePreferences()
{
try
{
if (m_ymlFile != null)
{
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
String cabWizPath = store.getString(PreferenceConstants.CAB_WIZARD_PATH);
String javaPath = store.getString(PreferenceConstants.JAVA_PATH);
String sdkPath = store.getString(PreferenceConstants.ANDROID_SDK_PATH);
String ndkPath = store.getString(PreferenceConstants.ANDROID_NDK_PATH);
String bbVersionName = store.getString(PreferenceConstants.BB_VERSION_NAME);
String bbJdkPath = store.getString(PreferenceConstants.BB_JDK_PATH);
String bbMdsPath = store.getString(PreferenceConstants.BB_MDS_PATH);
String bbSim = store.getString(PreferenceConstants.BB_SIM);
m_ymlFile.setJavaPath(javaPath);
m_ymlFile.setCabWizPath(cabWizPath);
m_ymlFile.setAndroidNdkPath(ndkPath);
m_ymlFile.setAndroidSdkPath(sdkPath);
m_ymlFile.setBbJdkPath(bbVersionName, bbJdkPath);
m_ymlFile.setBbMdsPath(bbVersionName, bbMdsPath);
m_ymlFile.setBbSimPort(bbVersionName, new Integer(bbSim));
m_ymlFile.save();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private File getAppSdkCongigPath(IProject project)
{
String configPath = project.getLocation() + File.separator + AppYmlFile.configFileName;
File cfgFile = new File(configPath);
return cfgFile;
}
public List<String> getRhodesProjects()
{
List<String> namesList = new ArrayList<String>();
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for(IProject p : projects)
{
File cfgFile = getAppSdkCongigPath(p);
if (cfgFile.exists())
{
namesList.add(p.getName());
}
}
return namesList;
}
public void initFromProject(String projectName)
{
try
{
m_currProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (m_currProject.isOpen())
{
AppYmlFile appYmlFile = AppYmlFile.createFromProject(m_currProject);
m_currRhodesPath = appYmlFile.getSdkConfigPath();
m_ymlFile = new SdkYmlFile(m_currRhodesPath );
m_bbVers = m_ymlFile.getBbVersions();
if (m_bbVers.size() == 0)
m_defaultBbVer = "";
else
m_defaultBbVer = m_bbVers.get(0);
initializeDefaultPreferences();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
private boolean isRhodesPathChanged()
{
try
{
AppYmlFile appYmlFile;
appYmlFile = AppYmlFile.createFromProject(m_currProject);
String sdkPath = appYmlFile.getSdkConfigPath();
if (m_currRhodesPath != null)
{
return !sdkPath.equals(m_currRhodesPath);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return false;
}
}
|
//This is a wrapper class around an TypeAnnotationVisitor that can be used
//to verify the information it visits specifies a valid [extended] annotation.
package annotations.io.classfile;
/*>>>
import org.checkerframework.checker.nullness.qual.*;
*/
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.TypeAnnotationVisitor;
import com.sun.tools.javac.code.TargetType;
import com.sun.tools.javac.code.TypeAnnotationPosition.TypePathEntry;
public class SafeTypeAnnotationVisitor
implements TypeAnnotationVisitor {
// The visitor this delegates all calls to.
private final TypeAnnotationVisitor xav;
// Each list keeps a record of what was passed in to the similarly-named
// method, and except for xLocationArgs, should all contain at most 1 element.
private final List<Integer> xIndexArgs;
private final List<Integer> xLengthArgs;
private final List<TypePathEntry> xLocationArgs;
private final List<Integer> xLocationLengthArgs;
private final List<Integer> xOffsetArgs;
private final List<Integer> xStartPcArgs;
private final List<Integer> xTargetTypeArgs;
private final List<Integer> xParamIndexArgs;
private final List<Integer> xBoundIndexArgs;
private final List<Integer> xTypeIndexArgs;
// Counts the number of times visitXNameAndArgsSize is called.
private int xNameAndArgsCount;
/**
* Constructs a new <code> SafeTypeAnnotationVisitor </code> that
* delegates all calls to the given visitor.
*
* @param xav the visitor to delegate all method calls to
*/
public SafeTypeAnnotationVisitor(TypeAnnotationVisitor xav) {
this.xav = xav;
// they should not contain more than one element.
xIndexArgs = new ArrayList<Integer>(1);
xLengthArgs = new ArrayList<Integer>(1);
xLocationArgs = new ArrayList<TypePathEntry>();
xLocationLengthArgs = new ArrayList<Integer>(1);
xOffsetArgs = new ArrayList<Integer>(1);
xStartPcArgs = new ArrayList<Integer>(1);
xTargetTypeArgs = new ArrayList<Integer>(1);
xParamIndexArgs = new ArrayList<Integer>(1);
xBoundIndexArgs = new ArrayList<Integer>(1);
xTypeIndexArgs = new ArrayList<Integer>(1);
xNameAndArgsCount = 0;
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.AnnotationVisitor#visit(java.lang.String, java.lang.Object)
*/
@Override
public void visit(String name, Object value) {
xav.visit(name, value);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.AnnotationVisitor#visitAnnotation(java.lang.String, java.lang.String)
*/
@Override
public AnnotationVisitor visitAnnotation(String name, String desc) {
return xav.visitAnnotation(name, desc);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.AnnotationVisitor#visitArray(java.lang.String)
*/
@Override
public AnnotationVisitor visitArray(String name) {
return xav.visitArray(name);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.AnnotationVisitor#visitEnum(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void visitEnum(String name, String desc, String value) {
xav.visitEnum(name, desc, value);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXIndex(int)
*/
@Override
public void visitXIndex(int index) {
xIndexArgs.add(index);
xav.visitXIndex(index);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXLength(int)
*/
@Override
public void visitXLength(int length) {
xLengthArgs.add(length);
xav.visitXLength(length);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXLocation(TypePathEntry)
*/
@Override
public void visitXLocation(TypePathEntry location) {
xLocationArgs.add(location);
xav.visitXLocation(location);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXLocationLength(int)
*/
@Override
public void visitXLocationLength(int location_length) {
xLocationLengthArgs.add(location_length);
xav.visitXLocationLength(location_length);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXOffset(int)
*/
@Override
public void visitXOffset(int offset) {
xOffsetArgs.add(offset);
xav.visitXOffset(offset);
}
@Override
public void visitXNumEntries(int num_entries) {
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXStartPc(int)
*/
@Override
public void visitXStartPc(int start_pc) {
xStartPcArgs.add(start_pc);
xav.visitXStartPc(start_pc);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXTargetType(int)
*/
@Override
public void visitXTargetType(int target_type) {
xTargetTypeArgs.add(target_type);
xav.visitXTargetType(target_type);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXParamIndex(int)
*/
@Override
public void visitXParamIndex(int param_index) {
xParamIndexArgs.add(param_index);
xav.visitXParamIndex(param_index);
}
/**
* {@inheritDoc}
* @see org.objectweb.asm.TypeAnnotationVisitor#visitXBoundIndex(int)
*/
@Override
public void visitXBoundIndex(int bound_index) {
if (bound_index != -1) {
xBoundIndexArgs.add(bound_index);
xav.visitXBoundIndex(bound_index);
}
}
@Override
public void visitXTypeIndex(int type_index) {
xTypeIndexArgs.add(type_index);
xav.visitXTypeIndex(type_index);
}
@Override
public void visitXExceptionIndex(int exception_index) {
// TODO
}
@Override
public void visitXNameAndArgsSize() {
xNameAndArgsCount++;
xav.visitXNameAndArgsSize();
}
@Override
public void visitEnd() {
if (xTargetTypeArgs.size() > 0) {
checkX();
} else {
// This has not visited an the target type of an extended annotation, so
// must ensure that all other extended information lists are empty.
if (xIndexArgs.size() != 0 ||
xLengthArgs.size() != 0 ||
xLocationArgs.size() != 0 ||
xLocationLengthArgs.size() != 0 ||
xOffsetArgs.size() != 0 ||
xStartPcArgs.size() != 0) {
throw new InvalidTypeAnnotationException(
"No target type was specified, yet other visitX* methods were still called.");
}
}
xav.visitEnd();
}
/**
* Checks that the extended information this has visited is valid.
*
* @throws InvalidTypeAnnotationException if extended information is
* not valid
*/
private void checkX() {
// First, check to see that only one target type was specified, and
// then dispatch to checkListSize() based on that target type.
if (xTargetTypeArgs.size() != 1) {
throw new
InvalidTypeAnnotationException("More than one target type visited.");
}
if (xNameAndArgsCount != 1) {
throw new InvalidTypeAnnotationException("Name and args count should "
+ " be visited 1 time, actually visited " + xNameAndArgsCount
+ " times.");
}
// Since the correct size of xLocationArgs is specified by
// xLocationLengthArgs, this information must be looked up first.
int c = 0;
if (xLocationLengthArgs.size() > 0) {
c = xLocationLengthArgs.get(0);
}
switch(TargetType.fromTargetTypeValue(xTargetTypeArgs.get(0))) {
case CAST:
checkListSize(0, 0, c, 1, 1, 0, 0, 0, 1,
"Invalid typecast annotation:");
break;
case INSTANCEOF:
checkListSize(0, 0, c, 1, 1, 0, 0, 0, 0,
"Invalid type test annotation:");
break;
case NEW:
checkListSize(0, 0, c, 1, 1, 0, 0, 0, 0,
"Invalid object creation annotation:");
break;
case METHOD_RECEIVER:
checkListSize(0, 0, c, 1, 0, 0, 0, 0, 0,
"Invalid method receiver annotation:");
break;
case LOCAL_VARIABLE:
checkListSize(1, 1, c, 1, 0, 1, 0, 0, 0,
"Invalid local variable annotation:");
break;
case METHOD_RETURN:
checkListSize(0, 0, c, 1, 0, 0, 0, 0, 0,
"Invalid method return type annotation:");
break;
case METHOD_FORMAL_PARAMETER:
checkListSize(0, 0, c, 1, 0, 0, 1, 0, 0,
"Invalid method parameter annotation:");
break;
case FIELD:
checkListSize(0, 0, c, 1, 0, 0, 0, 0, 0,
"Invalid field annotation:");
break;
case CLASS_TYPE_PARAMETER:
checkListSize(0, 0, c, 1, 0, 0, 1, 0, 0,
"Invalid class type parameter annotation:");
break;
case CLASS_TYPE_PARAMETER_BOUND:
checkListSize(0, 0, c, 1, 0, 0, 1, 1, 0,
"Invalid class type parameter bound annotation:");
break;
case METHOD_TYPE_PARAMETER:
checkListSize(0, 0, c, 1, 0, 0, 1, 0, 0,
"Invalid method type parameter annotation:");
break;
case METHOD_TYPE_PARAMETER_BOUND:
checkListSize(0, 0, c, 1, 0, 0, 1, 1, 0,
"Invalid method type parameter bound annotation:");
break;
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
// TODO
break;
case CLASS_EXTENDS:
checkListSize(0, 0, c, 1, 0, 0, 0, 0, 1,
"Invalid class extends/implements annotation:");
break;
case THROWS:
checkListSize(0, 0, c, 1, 0, 0, 0, 0, 1,
"Invalid exception type in throws annotation:");
break;
default:
throw new InvalidTypeAnnotationException(
"Unknown target type given: " + xTargetTypeArgs.get(0));
}
}
/**
* If list.size() != correctLength, appends a descriptive error message to sb
* specifying how many times methodName was supposed to be called and how
* many times it was actually called.
* Else, has no effect.
*
* @param list the list of arguments actually visited
* @param correctLength the correct length of list
* @param methodName the name of the method whose arguments went into list
* @param sb the StringBuilder to append error messages to
*/
private void appendMessage(List<?> list, int idealLength,
String methodName, StringBuilder sb) {
if (list.size() != idealLength) {
sb.append("\nInvalid method calls: ");
sb.append(methodName);
sb.append(" was called ");
sb.append(list.size());
sb.append(" times, but should have only been called ");
sb.append(idealLength);
sb.append(" times");
}
}
/**
* Checks that the seven lists containing extended annotation information are
* of the specified sizes. If at least one of the lists is not of the
* correct length, this throws an exception with a message equal to msg, plus
* information describing which lists were incorrect.
*
* @throws InvalidTypeAnnotationException if the extended information
* lists are not of the correct length
*/
private void checkListSize(
int correctLengthIndex,
int correctLengthLength,
int correctLengthLocation,
int correctLengthLocationLength,
int correctLengthOffset,
int correctLengthStartPc,
int correctLengthParamIndex,
int correctLengthBoundIndex,
int correctLengthTypeIndex,
String msg) {
StringBuilder sb = new StringBuilder();
appendMessage(xIndexArgs, correctLengthIndex, "visitXIndex", sb);
appendMessage(xLengthArgs, correctLengthLength, "visitXLength", sb);
appendMessage(xLocationArgs, correctLengthLocation, "visitXLocation", sb);
appendMessage(xLocationLengthArgs, correctLengthLocationLength,
"visitXLocationLength", sb);
appendMessage(xOffsetArgs, correctLengthOffset, "visitXOffset", sb);
appendMessage(xStartPcArgs, correctLengthStartPc, "visitXStartPc", sb);
appendMessage(xParamIndexArgs, correctLengthParamIndex, "visitXParamIndex", sb);
appendMessage(xBoundIndexArgs, correctLengthBoundIndex, "visitXBoundIndex", sb);
appendMessage(xTypeIndexArgs, correctLengthTypeIndex, "VisitXTypeIndex", sb);
// At this point, sb will contain Strings iff there is an error
// in the extended annotation information.
String s = sb.toString();
if (s.length() > 0) {
throw new InvalidTypeAnnotationException(msg + s);
}
}
}
|
package org.openscore.lang.cli;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.openscore.lang.cli.services.ScoreServices;
import org.openscore.lang.cli.utils.CompilerHelper;
import org.openscore.lang.entities.CompilationArtifact;
import org.openscore.lang.entities.bindings.Input;
import org.openscore.api.ExecutionPlan;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.shell.Bootstrap;
import org.springframework.shell.core.CommandResult;
import org.springframework.shell.core.JLineShellComponent;
import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
public class SlangCLITest {
private final static String[] CONTEXT_PATH = { "classpath*:/META-INF/spring/test-spring-shell-plugin.xml" };
private final static String FLOW_PATH_BACKSLASH_INPUT = "C:\\\\flow.yaml";
private final static String FLOW_PATH_BACKSLASH = "C:\\flow.yaml";
private final static String DEPENDENCIES_PATH_BACKSLASH = "C:\\\\flowsdir\\\\";
private static final long DEFAULT_TIMEOUT = 10000;
private JLineShellComponent shell;
private SlangCLI slangCLI;
private ScoreServices ScoreServicesMock;
private CompilerHelper compilerHelperMock;
public SlangCLITest() {
Bootstrap bootstrap = new Bootstrap(null, CONTEXT_PATH);
shell = bootstrap.getJLineShellComponent();
ScoreServicesMock = (ScoreServices) bootstrap.getApplicationContext().getBean("scoreServices");
compilerHelperMock = (CompilerHelper) bootstrap.getApplicationContext().getBean("compilerHelper");
slangCLI = bootstrap.getApplicationContext().getBean(SlangCLI.class);
}
@Before
public void before() throws IOException {
slangCLI.setEnvVar(false);
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testRunQuietlyValidFilePathAsync() throws URISyntaxException, IOException {
slangCLI.setEnvVar(true);
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.trigger(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT + " --q");
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
verify(ScoreServicesMock).trigger(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class));
Assert.assertEquals("method result mismatch", StringUtils.EMPTY, cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testRunQuietlyValidFilePathSync() throws URISyntaxException, IOException {
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(true))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT + " --q");
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
verify(ScoreServicesMock).triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(true));
Assert.assertEquals("method result mismatch", StringUtils.EMPTY, cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testRunValidFilePathSync() throws URISyntaxException, IOException {
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(false))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT);
// path may be processed as local in some environments
// in this case the local directory path is prepended to the actual path
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
verify(ScoreServicesMock).triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(false));
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testRunValidFilePathAsync() throws URISyntaxException, IOException {
//set async mode
slangCLI.setEnvVar(true);
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.trigger(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT);
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
verify(ScoreServicesMock).trigger(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class));
Assert.assertEquals("method result mismatch", SlangCLI.triggerAsyncMsg(executionID, compilationArtifact.getExecutionPlan().getName()), cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testRunValidWithOtherPathForDependencies() throws URISyntaxException, IOException {
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), anyListOf(String.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(false))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT + " --cp " + DEPENDENCIES_PATH_BACKSLASH);
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), anyListOf(String.class));
verify(ScoreServicesMock).triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(false));
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testRunSyncWithInputs() throws Exception {
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
String inputsString = "--i input1=value1,input2=value2";
Map<String, Serializable> inputsMap = new HashMap<>();
inputsMap.put("input1", "value1");
inputsMap.put("input2", "value2");
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.triggerSync(eq(compilationArtifact), eq(inputsMap), anyMapOf(String.class, Serializable.class), eq(false))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT + " " + inputsString);
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
verify(ScoreServicesMock).triggerSync(eq(compilationArtifact), eq(inputsMap), anyMapOf(String.class, Serializable.class), eq(false));
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testRunAsyncWithInputs() throws Exception {
//set async mode
slangCLI.setEnvVar(true);
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
String inputsString = "--i input1=value1,input2=value2";
Map<String, Serializable> inputsMap = new HashMap<>();
inputsMap.put("input1", "value1");
inputsMap.put("input2", "value2");
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.trigger(eq(compilationArtifact), eq(inputsMap), anyMapOf(String.class, Serializable.class))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT + " " + inputsString);
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
verify(ScoreServicesMock).trigger(eq(compilationArtifact), eq(inputsMap), anyMapOf(String.class, Serializable.class));
Assert.assertEquals("method result mismatch", SlangCLI.triggerAsyncMsg(executionID, compilationArtifact.getExecutionPlan().getName()), cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test(timeout = DEFAULT_TIMEOUT)
public void testRunSyncWithSystemProperties() throws Exception {
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), new ArrayList<Input>());
long executionID = 1;
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
when(ScoreServicesMock.triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(false))).thenReturn(executionID);
CommandResult cr = shell.executeCommand("run --f " + FLOW_PATH_BACKSLASH_INPUT + " --spf " + FLOW_PATH_BACKSLASH_INPUT);
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
verify(compilerHelperMock).loadSystemProperties(Arrays.asList(FLOW_PATH_BACKSLASH));
verify(ScoreServicesMock).triggerSync(eq(compilationArtifact), anyMapOf(String.class, Serializable.class), anyMapOf(String.class, Serializable.class), eq(false));
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testSetEnvVarTrue() {
CommandResult cr = shell.executeCommand("env --setAsync true");
Assert.assertEquals("method result mismatch", SlangCLI.setEnvMessage(true), cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testSetEnvVarFalse() {
CommandResult cr = shell.executeCommand("env --setAsync false");
Assert.assertEquals("method result mismatch", SlangCLI.setEnvMessage(false), cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testGetFlowInputs() throws URISyntaxException, IOException {
List<Input> inputsList = Lists.newArrayList(new Input("input1", "expression1"), new Input("input2", "expression2"));
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), inputsList);
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
CommandResult cr = shell.executeCommand("inputs --f " + FLOW_PATH_BACKSLASH_INPUT);
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
Assert.assertEquals("input list mismatch", Lists.newArrayList("input1", "input2"), cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testGetFlowInputsWithOverride() throws URISyntaxException, IOException {
List<Input> inputsList = Lists.newArrayList(new Input("input1", "expression1"),new Input("input_override", "expression_override", false, true, false, null) , new Input("input2", "expression2"));
CompilationArtifact compilationArtifact = new CompilationArtifact(new ExecutionPlan(), new HashMap<String, ExecutionPlan>(), inputsList);
when(compilerHelperMock.compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class))).thenReturn(compilationArtifact);
CommandResult cr = shell.executeCommand("inputs --f " + FLOW_PATH_BACKSLASH_INPUT);
verify(compilerHelperMock).compile(contains(FLOW_PATH_BACKSLASH), isNull(String.class), isNull(List.class));
Assert.assertEquals("input list mismatch", Lists.newArrayList("input1", "input2"), cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
@Test (timeout = DEFAULT_TIMEOUT)
public void testGetVersion() throws URISyntaxException, IOException {
CommandResult cr = shell.executeCommand("slang --version");
Assert.assertEquals("method result mismatch", slangCLI.version(), cr.getResult());
Assert.assertEquals("method threw exception", null, cr.getException());
Assert.assertEquals("success should be true", true, cr.isSuccess());
}
}
|
package team046;
import battlecode.common.*;
public class RobotPlayer {
private static RobotController rc;
private static int round;
private static double power;
private static int hoardNukeResearchMin = 50;
private static int zergRushChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
private static int zergRushCode = randomWithRange(2, GameConstants.BROADCAST_MAX_CHANNELS);
private static int EncampmentBuilderChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
private static int EncampmentSearchStartedChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
private static int SupplierBuilt = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
private static int researchNukeChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
public static void run(RobotController MyJohn12LongRC) {
rc = MyJohn12LongRC;
while (true) {
try {
round = Clock.getRoundNum();
power = rc.getTeamPower();
if (rc.getType() == RobotType.HQ) {
HQ();
}
else if (rc.getType() == RobotType.SOLDIER) {
Soldier();
}
else if (rc.getType() == RobotType.ARTILLERY) {
Artillery();
}
/*else if (rc.getType() == RobotType.SUPPLIER) {
Supplier();
}
else if (rc.getType() == RobotType.GENERATOR) {
Generator();
}*/
rc.yield();
}
catch (Exception e) {
e.printStackTrace();
break;
}
}
}
private static void HQ() throws GameActionException {
if (rc.isActive()) {
if (rc.senseEnemyNukeHalfDone()) {
if (rc.checkResearchProgress(Upgrade.NUKE) < 175
&& power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST * 2
&& rc.readBroadcast(zergRushChannel) != zergRushCode) {
rc.broadcast(zergRushChannel, zergRushCode);
rc.broadcast(researchNukeChannel, round);
}
}
/*else if (round > 50 && !rc.hasUpgrade(Upgrade.PICKAXE)) {
rc.researchUpgrade(Upgrade.PICKAXE);
return;
}
else if (round > 200 && !rc.hasUpgrade(Upgrade.FUSION)) {
rc.researchUpgrade(Upgrade.FUSION);
return;
}
else if (round > 250 && !rc.hasUpgrade(Upgrade.VISION)) {
rc.researchUpgrade(Upgrade.VISION);
return;
}*/
// Check the HQ's own surroundings
else if ((round > 100 && power < 100)
|| rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam()).length > hoardNukeResearchMin) {
rc.researchUpgrade(Upgrade.NUKE);
return;
}
// Last check for a nuke research cue
if (power > GameConstants.BROADCAST_READ_COST) {
int researchNuke = rc.readBroadcast(researchNukeChannel);
power -= GameConstants.BROADCAST_READ_COST;
if (researchNuke != 0 && round - researchNuke < 11) {
rc.researchUpgrade(Upgrade.NUKE);
return;
}
else if (power > GameConstants.BROADCAST_SEND_COST && researchNuke != 0) {
rc.broadcast(researchNukeChannel, 0);
power -= GameConstants.BROADCAST_SEND_COST;
}
}
// Find an available spawn direction
MapLocation hqLocation = rc.senseHQLocation();
MapLocation nextLoc;
for (Direction dir : Direction.values()) {
if (dir != Direction.NONE && dir != Direction.OMNI && rc.canMove(dir)) {
nextLoc = hqLocation.add(dir);
Team mine = rc.senseMine(nextLoc);
if (mine == null || mine == rc.getTeam()) {
rc.spawn(dir);
break;
}
}
}
}
}
private static void Soldier() throws GameActionException {
if (rc.isActive()) {
int EncampmentBuilderRobotID;
int EncampmentSearchStartedRound;
MapLocation rLoc = rc.getLocation();
MapLocation targetLoc = null;
// Get the Encampment builder robot ID (or zero)
if (power > GameConstants.BROADCAST_READ_COST * 2) {
EncampmentBuilderRobotID = rc.readBroadcast(EncampmentBuilderChannel);
EncampmentSearchStartedRound = rc.readBroadcast(EncampmentSearchStartedChannel);
power -= GameConstants.BROADCAST_READ_COST * 2;
}
else {
EncampmentBuilderRobotID = -1;
EncampmentSearchStartedRound = 0;
}
if (power > GameConstants.BROADCAST_SEND_COST * 2 && (EncampmentBuilderRobotID == 0
|| EncampmentSearchStartedRound + GameConstants.CAPTURE_ROUND_DELAY < round)) {
rc.broadcast(EncampmentBuilderChannel, rc.getRobot().getID());
rc.broadcast(EncampmentSearchStartedChannel, round);
power -= GameConstants.BROADCAST_SEND_COST * 2;
EncampmentBuilderRobotID = rc.getRobot().getID();
}
// Check for zerg command
if (power > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(zergRushChannel) == zergRushCode) {
targetLoc = rc.senseEnemyHQLocation();
power -= GameConstants.BROADCAST_READ_COST;
}
// Handle Encampment builder robot (including movement)
else if (EncampmentBuilderRobotID == rc.getRobot().getID()) {
BuildEncampment(rLoc);
return;
}
else {
RobotInfo roboData;
Robot[] assholes = rc.senseNearbyGameObjects(Robot.class, 3, rc.getTeam().opponent());
Robot[] baddies = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam().opponent());
Robot[] mypals = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam());
if (assholes.length > 0) {
// ATTACK!
if (assholes.length == 1) {
roboData = rc.senseRobotInfo(assholes[0]);
targetLoc = roboData.location;
}
// Ahhhhh!!~!~
else {
return;
}
}
// If we have greater numbers, be more aggressive
else if (baddies.length > 0 && mypals.length > baddies.length) {
roboData = rc.senseRobotInfo(baddies[0]);
targetLoc = roboData.location;
}
// If we are outnumbered, stop circling around like dumbasses
else if (mypals.length > 0 && mypals.length <= baddies.length) {
roboData = rc.senseRobotInfo(mypals[0]);
targetLoc = roboData.location;
}
// Check for and plant mines
else if (baddies.length == 0 && rc.senseMine(rLoc) == null) {
rc.layMine();
return;
}
}
// Set rally point
if (targetLoc == null) {
MapLocation goodHQ = rc.senseHQLocation();
if (goodHQ.x <= 2 || goodHQ.x >= rc.getMapWidth() - 2) {
MapLocation rudeHQ = rc.senseEnemyHQLocation();
Direction dir = goodHQ.directionTo(rudeHQ);
int xm = 1, ym = 1;
switch (dir) {
case NORTH: xm = 0; ym = -3; break;
case NORTH_EAST: xm = 3; ym = -3; break;
case EAST: xm = 3; ym = 0; break;
case SOUTH_EAST: xm = 3; ym = 3; break;
case SOUTH: xm = 0; ym = 3; break;
case SOUTH_WEST: xm = -3; ym = 3; break;
case WEST: xm = -3; ym = 0; break;
case NORTH_WEST: xm = -3; ym = -3; break;
}
targetLoc = new MapLocation(goodHQ.x + xm, goodHQ.y + ym);
}
else {
MapLocation rallyPoints[] = {
new MapLocation(goodHQ.x + randomWithRange(1,3), goodHQ.y + randomWithRange(1,3)),
new MapLocation(goodHQ.x - randomWithRange(1,3), goodHQ.y - randomWithRange(1,3))
};
targetLoc = rallyPoints[randomWithRange(0, rallyPoints.length - 1)];
}
}
// If already on targetLoc, sense buddies and send nuke research signal
if (power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST) {
int currentStatus = rc.readBroadcast(researchNukeChannel);
if (rLoc.equals(targetLoc)) {
Robot[] myFriends = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam());
if (myFriends.length > hoardNukeResearchMin && currentStatus == 0) {
rc.broadcast(researchNukeChannel, round);
}
else if (myFriends.length < hoardNukeResearchMin && currentStatus == 1) {
rc.broadcast(researchNukeChannel, 0);
}
return;
}
}
MoveRobot(rLoc, targetLoc);
}
}
private static void Artillery() throws GameActionException {
if (rc.isActive()) {
MapLocation target = null;
Robot[] baddies = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam().opponent());
if (baddies.length > 0) {
RobotInfo baddieInfo = rc.senseRobotInfo(baddies[0]);
target = baddieInfo.location;
}
if (target != null && rc.canAttackSquare(target)) {
rc.attackSquare(target);
}
}
}
private static void MoveRobot(MapLocation rLoc, MapLocation targetLoc) throws GameActionException {
Direction dir = rLoc.directionTo(targetLoc);
if (dir == Direction.NONE) {
return;
}
else if (dir == Direction.OMNI) {
dir = Direction.EAST;
}
// If the bot can't move in the default direction, test all other directions
if (!rc.canMove(dir)) {
int shortest = 1000, testDist;
Direction bestDir = dir;
MapLocation testLoc;
for (Direction testDir : Direction.values()) {
if (testDir != dir && testDir != Direction.NONE && testDir != Direction.OMNI
&& rc.canMove(testDir)) {
testLoc = rLoc.add(testDir);
testDist = testLoc.distanceSquaredTo(targetLoc);
if (testDist < shortest) {
shortest = testDist;
bestDir = testDir;
}
}
}
// If the direction hasn't changed, there is just no where to go.
if (bestDir == dir) {
return;
}
dir = bestDir;
}
MapLocation nextLoc = rLoc.add(dir);
Team mine = rc.senseMine(nextLoc);
if (mine == Team.NEUTRAL || mine == rc.getTeam().opponent()) {
rc.defuseMine(nextLoc);
}
else {
rc.move(dir);
}
}
private static void BuildEncampment(MapLocation rLoc) throws GameActionException {
if (power > rc.senseCaptureCost()) {
if (rc.senseEncampmentSquare(rLoc)) {
// Check how close the encampment is to HQ, if close build an artillery
MapLocation goodHQ = rc.senseHQLocation();
if (goodHQ.distanceSquaredTo(rLoc) < 60) {
rc.captureEncampment(RobotType.ARTILLERY);
}
// Otherwise, check status of supplier build and do another one or generator
else if (power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST) {
if (rc.readBroadcast(SupplierBuilt) == 0) {
rc.captureEncampment(RobotType.SUPPLIER);
rc.broadcast(SupplierBuilt, 1);
power -= GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST;
}
else {
rc.captureEncampment(RobotType.GENERATOR);
rc.broadcast(SupplierBuilt, 0);
power -= GameConstants.BROADCAST_SEND_COST;
}
}
}
else {
MapLocation encampmentSquares[] = rc.senseAllEncampmentSquares();
MapLocation goodEncampments[] = rc.senseAlliedEncampmentSquares();
MapLocation targetLoc = encampmentSquares[0];
int closest = 1000;
checkLocations:
for (MapLocation loc : encampmentSquares) {
int dist = rLoc.distanceSquaredTo(loc);
if (dist < closest) {
for (MapLocation goodLoc : goodEncampments) {
if (goodLoc.equals(loc)) {
continue checkLocations;
}
}
targetLoc = loc;
closest = dist;
}
}
MoveRobot(rLoc, targetLoc);
}
}
}
private static int randomWithRange(int min, int max) {
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
}
|
package com.smartdevicelink.proxy;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.Display;
import android.view.MotionEvent;
import android.view.Surface;
import com.smartdevicelink.Dispatcher.IDispatchingStrategy;
import com.smartdevicelink.Dispatcher.ProxyMessageDispatcher;
import com.smartdevicelink.SdlConnection.ISdlConnectionListener;
import com.smartdevicelink.SdlConnection.SdlConnection;
import com.smartdevicelink.SdlConnection.SdlSession;
import com.smartdevicelink.encoder.VirtualDisplayEncoder;
import com.smartdevicelink.exception.SdlException;
import com.smartdevicelink.exception.SdlExceptionCause;
import com.smartdevicelink.haptic.HapticInterfaceManager;
import com.smartdevicelink.marshal.JsonRPCMarshaller;
import com.smartdevicelink.protocol.ProtocolMessage;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.protocol.enums.MessageType;
import com.smartdevicelink.protocol.enums.SessionType;
import com.smartdevicelink.protocol.heartbeat.HeartbeatMonitor;
import com.smartdevicelink.proxy.LockScreenManager.OnLockScreenIconDownloadedListener;
import com.smartdevicelink.proxy.callbacks.InternalProxyMessage;
import com.smartdevicelink.proxy.callbacks.OnError;
import com.smartdevicelink.proxy.callbacks.OnProxyClosed;
import com.smartdevicelink.proxy.callbacks.OnServiceEnded;
import com.smartdevicelink.proxy.callbacks.OnServiceNACKed;
import com.smartdevicelink.proxy.interfaces.IAudioStreamListener;
import com.smartdevicelink.proxy.interfaces.IProxyListenerBase;
import com.smartdevicelink.proxy.interfaces.IPutFileResponseListener;
import com.smartdevicelink.proxy.interfaces.ISdl;
import com.smartdevicelink.proxy.interfaces.ISdlServiceListener;
import com.smartdevicelink.proxy.interfaces.IVideoStreamListener;
import com.smartdevicelink.proxy.interfaces.OnSystemCapabilityListener;
import com.smartdevicelink.proxy.rpc.*;
import com.smartdevicelink.proxy.rpc.enums.AppHMIType;
import com.smartdevicelink.proxy.rpc.enums.AudioStreamingState;
import com.smartdevicelink.proxy.rpc.enums.AudioType;
import com.smartdevicelink.proxy.rpc.enums.BitsPerSample;
import com.smartdevicelink.proxy.rpc.enums.ButtonName;
import com.smartdevicelink.proxy.rpc.enums.DriverDistractionState;
import com.smartdevicelink.proxy.rpc.enums.FileType;
import com.smartdevicelink.proxy.rpc.enums.GlobalProperty;
import com.smartdevicelink.proxy.rpc.enums.HMILevel;
import com.smartdevicelink.proxy.rpc.enums.ImageType;
import com.smartdevicelink.proxy.rpc.enums.InteractionMode;
import com.smartdevicelink.proxy.rpc.enums.Language;
import com.smartdevicelink.proxy.rpc.enums.PrerecordedSpeech;
import com.smartdevicelink.proxy.rpc.enums.RequestType;
import com.smartdevicelink.proxy.rpc.enums.Result;
import com.smartdevicelink.proxy.rpc.enums.SamplingRate;
import com.smartdevicelink.proxy.rpc.enums.SdlConnectionState;
import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason;
import com.smartdevicelink.proxy.rpc.enums.SdlInterfaceAvailability;
import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType;
import com.smartdevicelink.proxy.rpc.enums.TextAlignment;
import com.smartdevicelink.proxy.rpc.enums.TouchType;
import com.smartdevicelink.proxy.rpc.enums.UpdateMode;
import com.smartdevicelink.proxy.rpc.listeners.OnPutFileUpdateListener;
import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener;
import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener;
import com.smartdevicelink.security.SdlSecurityBase;
import com.smartdevicelink.streaming.audio.AudioStreamingCodec;
import com.smartdevicelink.streaming.audio.AudioStreamingParams;
import com.smartdevicelink.streaming.StreamRPCPacketizer;
import com.smartdevicelink.streaming.video.SdlRemoteDisplay;
import com.smartdevicelink.streaming.video.VideoStreamingParameters;
import com.smartdevicelink.trace.SdlTrace;
import com.smartdevicelink.trace.TraceDeviceInfo;
import com.smartdevicelink.trace.enums.InterfaceActivityDirection;
import com.smartdevicelink.transport.BaseTransportConfig;
import com.smartdevicelink.transport.SiphonServer;
import com.smartdevicelink.transport.enums.TransportType;
import com.smartdevicelink.util.DebugTool;
@SuppressWarnings({"WeakerAccess", "Convert2Diamond"})
public abstract class SdlProxyBase<proxyListenerType extends IProxyListenerBase> {
// Used for calls to Android Log class.
public static final String TAG = "SdlProxy";
private static final String SDL_LIB_TRACE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66";
private static final int PROX_PROT_VER_ONE = 1;
private static final int RESPONSE_WAIT_TIME = 2000;
private SdlSession sdlSession = null;
private proxyListenerType _proxyListener = null;
protected Service _appService = null;
private String sPoliciesURL = ""; //for testing only
// Protected Correlation IDs
private final int REGISTER_APP_INTERFACE_CORRELATION_ID = 65529,
UNREGISTER_APP_INTERFACE_CORRELATION_ID = 65530,
POLICIES_CORRELATION_ID = 65535;
// Sdlhronization Objects
private static final Object CONNECTION_REFERENCE_LOCK = new Object(),
INCOMING_MESSAGE_QUEUE_THREAD_LOCK = new Object(),
OUTGOING_MESSAGE_QUEUE_THREAD_LOCK = new Object(),
INTERNAL_MESSAGE_QUEUE_THREAD_LOCK = new Object(),
ON_UPDATE_LISTENER_LOCK = new Object(),
ON_NOTIFICATION_LISTENER_LOCK = new Object();
private final Object APP_INTERFACE_REGISTERED_LOCK = new Object();
private int iFileCount = 0;
private boolean navServiceStartResponseReceived = false;
private boolean navServiceStartResponse = false;
private List<String> navServiceStartRejectedParams = null;
private boolean pcmServiceStartResponseReceived = false;
private boolean pcmServiceStartResponse = false;
@SuppressWarnings("FieldCanBeLocal")
private List<String> pcmServiceStartRejectedParams = null;
private boolean navServiceEndResponseReceived = false;
private boolean navServiceEndResponse = false;
private boolean pcmServiceEndResponseReceived = false;
private boolean pcmServiceEndResponse = false;
private boolean rpcProtectedResponseReceived = false;
private boolean rpcProtectedStartResponse = false;
// Device Info for logging
private TraceDeviceInfo _traceDeviceInterrogator = null;
// Declare Queuing Threads
private ProxyMessageDispatcher<ProtocolMessage> _incomingProxyMessageDispatcher;
private ProxyMessageDispatcher<ProtocolMessage> _outgoingProxyMessageDispatcher;
private ProxyMessageDispatcher<InternalProxyMessage> _internalProxyMessageDispatcher;
// Flag indicating if callbacks should be called from UIThread
private Boolean _callbackToUIThread = false;
// UI Handler
private Handler _mainUIHandler = null;
final int HEARTBEAT_CORRELATION_ID = 65531;
// SdlProxy Advanced Lifecycle Management
protected Boolean _advancedLifecycleManagementEnabled = false;
// Parameters passed to the constructor from the app to register an app interface
private String _applicationName = null;
private final long instanceDateTime = System.currentTimeMillis();
private String sConnectionDetails = "N/A";
private Vector<TTSChunk> _ttsName = null;
private String _ngnMediaScreenAppName = null;
private Boolean _isMediaApp = null;
private Language _sdlLanguageDesired = null;
private Language _hmiDisplayLanguageDesired = null;
private Vector<AppHMIType> _appType = null;
private String _appID = null;
@SuppressWarnings({"FieldCanBeLocal", "unused"}) //Need to understand what this is used for
private String _autoActivateIdDesired = null;
private String _lastHashID = null;
private SdlMsgVersion _sdlMsgVersionRequest = null;
private Vector<String> _vrSynonyms = null;
private boolean _bAppResumeEnabled = false;
private OnSystemRequest lockScreenIconRequest = null;
private TelephonyManager telephonyManager = null;
private DeviceInfo deviceInfo = null;
/**
* Contains current configuration for the transport that was selected during
* construction of this object
*/
private BaseTransportConfig _transportConfig = null;
// Proxy State Variables
protected Boolean _appInterfaceRegisterd = false;
protected Boolean _preRegisterd = false;
@SuppressWarnings({"unused", "FieldCanBeLocal"})
private Boolean _haveReceivedFirstNonNoneHMILevel = false;
protected Boolean _haveReceivedFirstFocusLevel = false;
protected Boolean _haveReceivedFirstFocusLevelFull = false;
protected Boolean _proxyDisposed = false;
protected SdlConnectionState _sdlConnectionState = null;
protected SdlInterfaceAvailability _sdlIntefaceAvailablity = null;
protected HMILevel _hmiLevel = null;
protected AudioStreamingState _audioStreamingState = null;
// Variables set by RegisterAppInterfaceResponse
protected SdlMsgVersion _sdlMsgVersion = null;
protected String _autoActivateIdReturned = null;
protected Language _sdlLanguage = null;
protected Language _hmiDisplayLanguage = null;
protected List<PrerecordedSpeech> _prerecordedSpeech = null;
protected VehicleType _vehicleType = null;
protected String _systemSoftwareVersion = null;
protected List<Integer> _diagModes = null;
protected Boolean firstTimeFull = true;
protected String _proxyVersionInfo = null;
protected Boolean _bResumeSuccess = false;
protected List<Class<? extends SdlSecurityBase>> _secList = null;
protected SystemCapabilityManager _systemCapabilityManager;
private final CopyOnWriteArrayList<IPutFileResponseListener> _putFileListenerList = new CopyOnWriteArrayList<IPutFileResponseListener>();
protected byte _wiproVersion = 1;
protected SparseArray<OnRPCResponseListener> rpcResponseListeners = null;
protected SparseArray<CopyOnWriteArrayList<OnRPCNotificationListener>> rpcNotificationListeners = null;
protected VideoStreamingManager manager; //Will move to SdlSession once the class becomes public
// Interface broker
private SdlInterfaceBroker _interfaceBroker = null;
//We create an easily passable anonymous class of the interface so that we don't expose the internal interface to developers
private ISdl _internalInterface = new ISdl() {
@Override
public void start() {
try{
initializeProxy();
}catch (SdlException e){
e.printStackTrace();
}
}
@Override
public void stop() {
try{
dispose();
}catch (SdlException e){
e.printStackTrace();
}
}
@Override
public boolean isConnected() {
return getIsConnected();
}
@Override
public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) {
SdlProxyBase.this.addServiceListener(serviceType,sdlServiceListener);
}
@Override
public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) {
SdlProxyBase.this.removeServiceListener(serviceType,sdlServiceListener);
}
@Override
public void startVideoService(VideoStreamingParameters parameters, boolean encrypted) {
if(isConnected()){
sdlSession.setDesiredVideoParams(parameters);
sdlSession.startService(SessionType.NAV,sdlSession.getSessionId(),encrypted);
}
}
@Override
public void stopVideoService() {
if(isConnected()){
sdlSession.endService(SessionType.NAV,sdlSession.getSessionId());
}
}
@Override
public void startAudioService(boolean encrypted) {
if(isConnected()){
sdlSession.startService(SessionType.PCM,sdlSession.getSessionId(),encrypted);
}
}
@Override
public void stopAudioService() {
if(isConnected()){
sdlSession.endService(SessionType.PCM,sdlSession.getSessionId());
}
}
@Override
public void sendRPCRequest(RPCRequest message){
try {
SdlProxyBase.this.sendRPCRequest(message);
} catch (SdlException e) {
e.printStackTrace();
}
}
@Override
public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) {
SdlProxyBase.this.addOnRPCNotificationListener(notificationId,listener);
}
@Override
public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) {
return SdlProxyBase.this.removeOnRPCNotificationListener(notificationId,listener);
}
};
private void notifyPutFileStreamError(Exception e, String info)
{
for (IPutFileResponseListener _putFileListener : _putFileListenerList) {
_putFileListener.onPutFileStreamError(e, info);
}
}
private void notifyPutFileStreamResponse(PutFileResponse msg)
{
for (IPutFileResponseListener _putFileListener : _putFileListenerList) {
_putFileListener.onPutFileResponse(msg);
}
}
public void addPutFileResponseListener(IPutFileResponseListener _putFileListener)
{
_putFileListenerList.addIfAbsent(_putFileListener);
}
public void remPutFileResponseListener(IPutFileResponseListener _putFileListener)
{
_putFileListenerList.remove(_putFileListener);
}
// Private Class to Interface with SdlConnection
private class SdlInterfaceBroker implements ISdlConnectionListener {
@Override
public void onTransportDisconnected(String info) {
// proxyOnTransportDisconnect is called to alert the proxy that a requested
// disconnect has completed
notifyPutFileStreamError(null, info);
if (!_advancedLifecycleManagementEnabled) {
// If original model, notify app the proxy is closed so it will delete and reinstanciate
notifyProxyClosed(info, new SdlException("Transport disconnected.", SdlExceptionCause.SDL_UNAVAILABLE), SdlDisconnectedReason.TRANSPORT_DISCONNECT);
}// else If ALM, nothing is required to be done here
}
@Override
public void onTransportError(String info, Exception e) {
DebugTool.logError("Transport failure: " + info, e);
notifyPutFileStreamError(e, info);
if (_advancedLifecycleManagementEnabled) {
// Cycle the proxy
if(SdlConnection.isLegacyModeEnabled()){
cycleProxy(SdlDisconnectedReason.LEGACY_BLUETOOTH_MODE_ENABLED);
}else{
cycleProxy(SdlDisconnectedReason.TRANSPORT_ERROR);
}
} else {
notifyProxyClosed(info, e, SdlDisconnectedReason.TRANSPORT_ERROR);
}
}
@Override
public void onProtocolMessageReceived(ProtocolMessage msg) {
// AudioPathThrough is coming WITH BulkData but WITHOUT JSON Data
// Policy Snapshot is coming WITH BulkData and WITH JSON Data
if ((msg.getData() != null && msg.getData().length > 0) ||
(msg.getBulkData() != null && msg.getBulkData().length > 0)) {
queueIncomingMessage(msg);
}
}
@Override
public void onProtocolSessionStarted(SessionType sessionType,
byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStarted");
updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID);
updateBroadcastIntent(sendIntent, "COMMENT2", " ServiceType: " + sessionType.getName());
updateBroadcastIntent(sendIntent, "COMMENT3", " Encrypted: " + isEncrypted);
sendBroadcastIntent(sendIntent);
setWiProVersion(version);
if (sessionType.eq(SessionType.RPC)) {
if (!isEncrypted)
{
if ( (_transportConfig.getHeartBeatTimeout() != Integer.MAX_VALUE) && (version > 2))
{
HeartbeatMonitor outgoingHeartbeatMonitor = new HeartbeatMonitor();
outgoingHeartbeatMonitor.setInterval(_transportConfig.getHeartBeatTimeout());
sdlSession.setOutgoingHeartbeatMonitor(outgoingHeartbeatMonitor);
HeartbeatMonitor incomingHeartbeatMonitor = new HeartbeatMonitor();
incomingHeartbeatMonitor.setInterval(_transportConfig.getHeartBeatTimeout());
sdlSession.setIncomingHeartbeatMonitor(incomingHeartbeatMonitor);
}
startRPCProtocolSession();
}
else
{
RPCProtectedServiceStarted();
}
} else if (sessionType.eq(SessionType.NAV)) {
NavServiceStarted();
} else if (sessionType.eq(SessionType.PCM)) {
AudioServiceStarted();
} else if (sessionType.eq(SessionType.RPC)){
cycleProxy(SdlDisconnectedReason.RPC_SESSION_ENDED);
}
else if (_wiproVersion > 1) {
//If version is 2 or above then don't need to specify a Session Type
startRPCProtocolSession();
} //else{} Handle other protocol session types here
}
@Override
public void onProtocolSessionStartedNACKed(SessionType sessionType,
byte sessionID, byte version, String correlationID, List<String> rejectedParams) {
OnServiceNACKed message = new OnServiceNACKed(sessionType);
queueInternalMessage(message);
if (sessionType.eq(SessionType.NAV)) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStartedNACKed");
updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID);
updateBroadcastIntent(sendIntent, "COMMENT2", " NACK ServiceType: " + sessionType.getName());
sendBroadcastIntent(sendIntent);
NavServiceStartedNACK(rejectedParams);
}
else if (sessionType.eq(SessionType.PCM)) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStartedNACKed");
updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID);
updateBroadcastIntent(sendIntent, "COMMENT2", " NACK ServiceType: " + sessionType.getName());
sendBroadcastIntent(sendIntent);
AudioServiceStartedNACK(rejectedParams);
}
}
@Override
public void onProtocolSessionEnded(SessionType sessionType,
byte sessionID, String correlationID) {
OnServiceEnded message = new OnServiceEnded(sessionType);
queueInternalMessage(message);
if (sessionType.eq(SessionType.NAV)) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEnded");
updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID);
updateBroadcastIntent(sendIntent, "COMMENT2", " End ServiceType: " + sessionType.getName());
sendBroadcastIntent(sendIntent);
NavServiceEnded();
}
else if (sessionType.eq(SessionType.PCM)) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEnded");
updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID);
updateBroadcastIntent(sendIntent, "COMMENT2", " End ServiceType: " + sessionType.getName());
sendBroadcastIntent(sendIntent);
AudioServiceEnded();
}
}
@Override
public void onProtocolError(String info, Exception e) {
notifyPutFileStreamError(e, info);
passErrorToProxyListener(info, e);
}
@Override
public void onHeartbeatTimedOut(byte sessionID) {
final String msg = "Heartbeat timeout";
DebugTool.logInfo(msg);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onHeartbeatTimedOut");
updateBroadcastIntent(sendIntent, "COMMENT1", "Heartbeat timeout for SessionID: " + sessionID);
sendBroadcastIntent(sendIntent);
notifyProxyClosed(msg, new SdlException(msg, SdlExceptionCause.HEARTBEAT_PAST_DUE), SdlDisconnectedReason.HB_TIMEOUT);
}
@Override
public void onProtocolSessionEndedNACKed(SessionType sessionType,
byte sessionID, String correlationID) {
if (sessionType.eq(SessionType.NAV)) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEndedNACKed");
updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID);
updateBroadcastIntent(sendIntent, "COMMENT2", " End NACK ServiceType: " + sessionType.getName());
sendBroadcastIntent(sendIntent);
NavServiceEndedNACK();
}
else if (sessionType.eq(SessionType.PCM)) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEndedNACKed");
updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID);
updateBroadcastIntent(sendIntent, "COMMENT2", " End NACK ServiceType: " + sessionType.getName());
sendBroadcastIntent(sendIntent);
AudioServiceEndedNACK();
}
}
public void onProtocolServiceDataACK(SessionType sessionType, final int dataSize,
byte sessionID) {
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onServiceDataACK(dataSize);
}
});
} else {
_proxyListener.onServiceDataACK(dataSize);
}
}
}
/**
* Constructor.
*
* @param listener Type of listener for this proxy base.
* @param sdlProxyConfigurationResources Configuration resources for this proxy.
* @param enableAdvancedLifecycleManagement Flag that ALM should be enabled or not.
* @param appName Client application name.
* @param ttsName TTS name.
* @param ngnMediaScreenAppName Media Screen Application name.
* @param vrSynonyms List of synonyms.
* @param isMediaApp Flag that indicates that client application if media application or not.
* @param sdlMsgVersion Version of Sdl Message.
* @param languageDesired Desired language.
* @param hmiDisplayLanguageDesired Desired language for HMI.
* @param appType Type of application.
* @param appID Application identifier.
* @param autoActivateID Auto activation identifier.
* @param callbackToUIThread Flag that indicates that this proxy should send callback to UI thread or not.
* @param transportConfig Configuration of transport to be used by underlying connection.
* @throws SdlException if there is an unrecoverable error class might throw an exception.
*/
protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources,
boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName,
String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion,
Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID,
String autoActivateID, boolean callbackToUIThread, BaseTransportConfig transportConfig)
throws SdlException {
performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp,
sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, callbackToUIThread, null, null, null, transportConfig);
}
@SuppressWarnings("ConstantConditions")
private void performBaseCommon(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources,
boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName,
String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion,
Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID,
String autoActivateID, boolean callbackToUIThread, Boolean preRegister, String sHashID, Boolean bAppResumeEnab,
BaseTransportConfig transportConfig) throws SdlException
{
setWiProVersion((byte)PROX_PROT_VER_ONE);
if (preRegister != null && preRegister)
{
_appInterfaceRegisterd = preRegister;
_preRegisterd = preRegister;
}
if (bAppResumeEnab != null && bAppResumeEnab)
{
_bAppResumeEnabled = true;
_lastHashID = sHashID;
}
_interfaceBroker = new SdlInterfaceBroker();
_callbackToUIThread = callbackToUIThread;
if (_callbackToUIThread) {
_mainUIHandler = new Handler(Looper.getMainLooper());
}
// Set variables for Advanced Lifecycle Management
_advancedLifecycleManagementEnabled = enableAdvancedLifecycleManagement;
_applicationName = appName;
_ttsName = ttsName;
_ngnMediaScreenAppName = ngnMediaScreenAppName;
_isMediaApp = isMediaApp;
_sdlMsgVersionRequest = sdlMsgVersion;
_vrSynonyms = vrSynonyms;
_sdlLanguageDesired = languageDesired;
_hmiDisplayLanguageDesired = hmiDisplayLanguageDesired;
_appType = appType;
_appID = appID;
_autoActivateIdDesired = autoActivateID;
_transportConfig = transportConfig;
// Test conditions to invalidate the proxy
if (listener == null) {
throw new IllegalArgumentException("IProxyListener listener must be provided to instantiate SdlProxy object.");
}
if (_advancedLifecycleManagementEnabled) {
if (_isMediaApp == null) {
throw new IllegalArgumentException("isMediaApp must not be null when using SdlProxyALM.");
}
}
_proxyListener = listener;
// Get information from sdlProxyConfigurationResources
if (sdlProxyConfigurationResources != null) {
telephonyManager = sdlProxyConfigurationResources.getTelephonyManager();
}
// Use the telephonyManager to get and log phone info
if (telephonyManager != null) {
// Following is not quite thread-safe (because m_traceLogger could test null twice),
// so we need to fix this, but vulnerability (i.e. two instances of listener) is
// likely harmless.
if (_traceDeviceInterrogator == null) {
_traceDeviceInterrogator = new TraceDeviceInfo(telephonyManager);
} // end-if
} // end-if
// Setup Internal ProxyMessage Dispatcher
synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) {
// Ensure internalProxyMessageDispatcher is null
if (_internalProxyMessageDispatcher != null) {
_internalProxyMessageDispatcher.dispose();
_internalProxyMessageDispatcher = null;
}
_internalProxyMessageDispatcher = new ProxyMessageDispatcher<InternalProxyMessage>("INTERNAL_MESSAGE_DISPATCHER", new IDispatchingStrategy<InternalProxyMessage>() {
@Override
public void dispatch(InternalProxyMessage message) {
dispatchInternalMessage(message);
}
@Override
public void handleDispatchingError(String info, Exception ex) {
handleErrorsFromInternalMessageDispatcher(info, ex);
}
@Override
public void handleQueueingError(String info, Exception ex) {
handleErrorsFromInternalMessageDispatcher(info, ex);
}
});
}
// Setup Incoming ProxyMessage Dispatcher
synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) {
// Ensure incomingProxyMessageDispatcher is null
if (_incomingProxyMessageDispatcher != null) {
_incomingProxyMessageDispatcher.dispose();
_incomingProxyMessageDispatcher = null;
}
_incomingProxyMessageDispatcher = new ProxyMessageDispatcher<ProtocolMessage>("INCOMING_MESSAGE_DISPATCHER",new IDispatchingStrategy<ProtocolMessage>() {
@Override
public void dispatch(ProtocolMessage message) {
dispatchIncomingMessage(message);
}
@Override
public void handleDispatchingError(String info, Exception ex) {
handleErrorsFromIncomingMessageDispatcher(info, ex);
}
@Override
public void handleQueueingError(String info, Exception ex) {
handleErrorsFromIncomingMessageDispatcher(info, ex);
}
});
}
// Setup Outgoing ProxyMessage Dispatcher
synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) {
// Ensure outgoingProxyMessageDispatcher is null
if (_outgoingProxyMessageDispatcher != null) {
_outgoingProxyMessageDispatcher.dispose();
_outgoingProxyMessageDispatcher = null;
}
_outgoingProxyMessageDispatcher = new ProxyMessageDispatcher<ProtocolMessage>("OUTGOING_MESSAGE_DISPATCHER",new IDispatchingStrategy<ProtocolMessage>() {
@Override
public void dispatch(ProtocolMessage message) {
dispatchOutgoingMessage(message);
}
@Override
public void handleDispatchingError(String info, Exception ex) {
handleErrorsFromOutgoingMessageDispatcher(info, ex);
}
@Override
public void handleQueueingError(String info, Exception ex) {
handleErrorsFromOutgoingMessageDispatcher(info, ex);
}
});
}
rpcResponseListeners = new SparseArray<OnRPCResponseListener>();
rpcNotificationListeners = new SparseArray<CopyOnWriteArrayList<OnRPCNotificationListener>>();
// Initialize the proxy
try {
initializeProxy();
} catch (SdlException e) {
// Couldn't initialize the proxy
// Dispose threads and then rethrow exception
if (_internalProxyMessageDispatcher != null) {
_internalProxyMessageDispatcher.dispose();
_internalProxyMessageDispatcher = null;
}
if (_incomingProxyMessageDispatcher != null) {
_incomingProxyMessageDispatcher.dispose();
_incomingProxyMessageDispatcher = null;
}
if (_outgoingProxyMessageDispatcher != null) {
_outgoingProxyMessageDispatcher.dispose();
_outgoingProxyMessageDispatcher = null;
}
throw e;
}
// Trace that ctor has fired
SdlTrace.logProxyEvent("SdlProxy Created, instanceID=" + this.toString(), SDL_LIB_TRACE_KEY);
}
protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources,
boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName,
String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion,
Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID,
String autoActivateID, boolean callbackToUIThread, boolean preRegister, String sHashID, Boolean bEnableResume, BaseTransportConfig transportConfig)
throws SdlException
{
performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp,
sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, callbackToUIThread, preRegister, sHashID, bEnableResume, transportConfig);
}
/**
* Constructor.
*
* @param listener Type of listener for this proxy base.
* @param sdlProxyConfigurationResources Configuration resources for this proxy.
* @param enableAdvancedLifecycleManagement Flag that ALM should be enabled or not.
* @param appName Client application name.
* @param ttsName TTS name.
* @param ngnMediaScreenAppName Media Screen Application name.
* @param vrSynonyms List of synonyms.
* @param isMediaApp Flag that indicates that client application if media application or not.
* @param sdlMsgVersion Version of Sdl Message.
* @param languageDesired Desired language.
* @param hmiDisplayLanguageDesired Desired language for HMI.
* @param appType Type of application.
* @param appID Application identifier.
* @param autoActivateID Auto activation identifier.
* @param callbackToUIThread Flag that indicates that this proxy should send callback to UI thread or not.
* @param preRegister Flag that indicates that this proxy should be pre-registerd or not.
* @param transportConfig Configuration of transport to be used by underlying connection.
* @throws SdlException if there is an unrecoverable error class might throw an exception.
*/
protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources,
boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName,
String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion,
Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID,
String autoActivateID, boolean callbackToUIThread, boolean preRegister, BaseTransportConfig transportConfig)
throws SdlException
{
performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp,
sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, callbackToUIThread, preRegister, null, null, transportConfig);
}
private Intent createBroadcastIntent()
{
Intent sendIntent = new Intent();
sendIntent.setAction("com.smartdevicelink.broadcast");
sendIntent.putExtra("APP_NAME", this._applicationName);
sendIntent.putExtra("APP_ID", this._appID);
sendIntent.putExtra("RPC_NAME", "");
sendIntent.putExtra("TYPE", "");
sendIntent.putExtra("SUCCESS", true);
sendIntent.putExtra("CORRID", 0);
sendIntent.putExtra("FUNCTION_NAME", "");
sendIntent.putExtra("COMMENT1", "");
sendIntent.putExtra("COMMENT2", "");
sendIntent.putExtra("COMMENT3", "");
sendIntent.putExtra("COMMENT4", "");
sendIntent.putExtra("COMMENT5", "");
sendIntent.putExtra("COMMENT6", "");
sendIntent.putExtra("COMMENT7", "");
sendIntent.putExtra("COMMENT8", "");
sendIntent.putExtra("COMMENT9", "");
sendIntent.putExtra("COMMENT10", "");
sendIntent.putExtra("DATA", "");
sendIntent.putExtra("SHOW_ON_UI", true);
return sendIntent;
}
private void updateBroadcastIntent(Intent sendIntent, String sKey, String sValue)
{
if (sValue == null) sValue = "";
sendIntent.putExtra(sKey, sValue);
}
private void updateBroadcastIntent(Intent sendIntent, String sKey, boolean bValue)
{
sendIntent.putExtra(sKey, bValue);
}
private void updateBroadcastIntent(Intent sendIntent, String sKey, int iValue)
{
sendIntent.putExtra(sKey, iValue);
}
private Service getService()
{
Service myService = null;
if (_proxyListener != null && _proxyListener instanceof Service)
{
myService = (Service) _proxyListener;
}
else if (_appService != null)
{
myService = _appService;
}
if (myService != null)
{
try
{
return myService;
}
catch(Exception ex)
{
return null;
}
}
return null;
}
private void sendBroadcastIntent(Intent sendIntent)
{
Service myService;
if (_proxyListener != null && _proxyListener instanceof Service)
{
myService = (Service) _proxyListener;
}
else if (_appService != null)
{
myService = _appService;
}
else
{
return;
}
try
{
Context myContext = myService.getApplicationContext();
if (myContext != null) myContext.sendBroadcast(sendIntent);
}
catch(Exception ex)
{
//If the service or context has become unavailable unexpectedly, catch the exception and move on -- no broadcast log will occur.
}
}
private HttpURLConnection getURLConnection(Headers myHeader, String sURLString, int Timeout, int iContentLen)
{
String sContentType = "application/json";
int CONNECTION_TIMEOUT = Timeout * 1000;
int READ_TIMEOUT = Timeout * 1000;
boolean bDoOutput = true;
boolean bDoInput = true;
boolean bUsesCaches = false;
String sRequestMeth = "POST";
boolean bInstFolRed = false;
String sCharSet = "utf-8";
int iContentLength = iContentLen;
URL url;
HttpURLConnection urlConnection;
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "getURLConnection");
updateBroadcastIntent(sendIntent, "COMMENT1", "Actual Content Length: " + iContentLen);
if (myHeader != null)
{
//if the header isn't null, use it and replace the hardcoded params
int iTimeout;
int iReadTimeout;
sContentType = myHeader.getContentType();
iTimeout = myHeader.getConnectTimeout();
bDoOutput = myHeader.getDoOutput();
bDoInput = myHeader.getDoInput();
bUsesCaches = myHeader.getUseCaches();
sRequestMeth = myHeader.getRequestMethod();
iReadTimeout = myHeader.getReadTimeout();
bInstFolRed = myHeader.getInstanceFollowRedirects();
sCharSet = myHeader.getCharset();
iContentLength = myHeader.getContentLength();
CONNECTION_TIMEOUT = iTimeout*1000;
READ_TIMEOUT = iReadTimeout*1000;
updateBroadcastIntent(sendIntent, "COMMENT2", "\nHeader Defined Content Length: " + iContentLength);
}
try
{
url = new URL(sURLString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setDoOutput(bDoOutput);
urlConnection.setDoInput(bDoInput);
urlConnection.setRequestMethod(sRequestMeth);
urlConnection.setReadTimeout(READ_TIMEOUT);
urlConnection.setInstanceFollowRedirects(bInstFolRed);
urlConnection.setRequestProperty("Content-Type", sContentType);
urlConnection.setRequestProperty("charset", sCharSet);
urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(iContentLength));
urlConnection.setUseCaches(bUsesCaches);
return urlConnection;
}
catch (Exception e)
{
return null;
}
finally
{
sendBroadcastIntent(sendIntent);
}
}
private void sendOnSystemRequestToUrl(OnSystemRequest msg)
{
Intent sendIntent = createBroadcastIntent();
Intent sendIntent2 = createBroadcastIntent();
HttpURLConnection urlConnection = null;
boolean bLegacy = false;
String sURLString;
if (!getPoliciesURL().equals(""))
sURLString = sPoliciesURL;
else
sURLString = msg.getUrl();
Integer iTimeout = msg.getTimeout();
if (iTimeout == null)
iTimeout = 2000;
Headers myHeader = msg.getHeader();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "sendOnSystemRequestToUrl");
updateBroadcastIntent(sendIntent, "COMMENT5", "\r\nCloud URL: " + sURLString);
try
{
if (myHeader == null)
updateBroadcastIntent(sendIntent, "COMMENT7", "\r\nHTTPRequest Header is null");
String sBodyString = msg.getBody();
JSONObject jsonObjectToSendToServer;
String valid_json = "";
int length;
if (sBodyString == null)
{
if(RequestType.HTTP.equals(msg.getRequestType())){
length = msg.getBulkData().length;
Intent sendIntent3 = createBroadcastIntent();
updateBroadcastIntent(sendIntent3, "FUNCTION_NAME", "replace");
updateBroadcastIntent(sendIntent3, "COMMENT1", "Valid Json length before replace: " + length);
sendBroadcastIntent(sendIntent3);
}else{
List<String> legacyData = msg.getLegacyData();
JSONArray jsonArrayOfSdlPPackets = new JSONArray(legacyData);
jsonObjectToSendToServer = new JSONObject();
jsonObjectToSendToServer.put("data", jsonArrayOfSdlPPackets);
bLegacy = true;
updateBroadcastIntent(sendIntent, "COMMENT6", "\r\nLegacy SystemRequest: true");
valid_json = jsonObjectToSendToServer.toString().replace("\\", "");
length = valid_json.getBytes("UTF-8").length;
}
}
else
{
Intent sendIntent3 = createBroadcastIntent();
updateBroadcastIntent(sendIntent3, "FUNCTION_NAME", "replace");
updateBroadcastIntent(sendIntent3, "COMMENT1", "Valid Json length before replace: " + sBodyString.getBytes("UTF-8").length);
sendBroadcastIntent(sendIntent3);
valid_json = sBodyString.replace("\\", "");
length = valid_json.getBytes("UTF-8").length;
}
urlConnection = getURLConnection(myHeader, sURLString, iTimeout, length);
if (urlConnection == null)
{
Log.i(TAG, "urlConnection is null, check RPC input parameters");
updateBroadcastIntent(sendIntent, "COMMENT2", "urlConnection is null, check RPC input parameters");
return;
}
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
if(RequestType.HTTP.equals(msg.getRequestType())){
wr.write(msg.getBulkData());
}else{
wr.writeBytes(valid_json);
}
wr.flush();
wr.close();
long BeforeTime = System.currentTimeMillis();
long AfterTime = System.currentTimeMillis();
final long roundtriptime = AfterTime - BeforeTime;
updateBroadcastIntent(sendIntent, "COMMENT4", " Round trip time: " + roundtriptime);
updateBroadcastIntent(sendIntent, "COMMENT1", "Received response from cloud, response code=" + urlConnection.getResponseCode() + " ");
int iResponseCode = urlConnection.getResponseCode();
if (iResponseCode != HttpURLConnection.HTTP_OK)
{
Log.i(TAG, "Response code not HTTP_OK, returning from sendOnSystemRequestToUrl.");
updateBroadcastIntent(sendIntent, "COMMENT2", "Response code not HTTP_OK, aborting request. ");
return;
}
InputStream is = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null)
{
response.append(line);
response.append('\r');
}
rd.close();
//We've read the body
if(RequestType.HTTP.equals(msg.getRequestType())){
// Create the SystemRequest RPC to send to module.
PutFile putFile = new PutFile();
putFile.setFileType(FileType.JSON);
putFile.setCorrelationID(POLICIES_CORRELATION_ID);
putFile.setSdlFileName("response_data");
putFile.setFileData(response.toString().getBytes("UTF-8"));
updateBroadcastIntent(sendIntent, "DATA", "Data from cloud response: " + response.toString());
sendRPCRequestPrivate(putFile);
Log.i("sendSystemRequestToUrl", "sent to sdl");
updateBroadcastIntent(sendIntent2, "RPC_NAME", FunctionID.PUT_FILE.toString());
updateBroadcastIntent(sendIntent2, "TYPE", RPCMessage.KEY_REQUEST);
updateBroadcastIntent(sendIntent2, "CORRID", putFile.getCorrelationID());
}else{
Vector<String> cloudDataReceived = new Vector<String>();
final String dataKey = "data";
// Convert the response to JSON
JSONObject jsonResponse = new JSONObject(response.toString());
if(jsonResponse.has(dataKey)){
if (jsonResponse.get(dataKey) instanceof JSONArray)
{
JSONArray jsonArray = jsonResponse.getJSONArray(dataKey);
for (int i=0; i<jsonArray.length(); i++)
{
if (jsonArray.get(i) instanceof String)
{
cloudDataReceived.add(jsonArray.getString(i));
//Log.i("sendSystemRequestToUrl", "jsonArray.getString(i): " + jsonArray.getString(i));
}
}
}
else if (jsonResponse.get(dataKey) instanceof String)
{
cloudDataReceived.add(jsonResponse.getString(dataKey));
//Log.i("sendSystemRequestToUrl", "jsonResponse.getString(data): " + jsonResponse.getString("data"));
}
}
else
{
DebugTool.logError("sendSystemRequestToUrl: Data in JSON Object neither an array nor a string.");
//Log.i("sendSystemRequestToUrl", "sendSystemRequestToUrl: Data in JSON Object neither an array nor a string.");
return;
}
String sResponse = cloudDataReceived.toString();
if (sResponse.length() > 512)
{
sResponse = sResponse.substring(0, 511);
}
updateBroadcastIntent(sendIntent, "DATA", "Data from cloud response: " + sResponse);
// Send new SystemRequest to SDL
SystemRequest mySystemRequest;
if (bLegacy){
mySystemRequest = RPCRequestFactory.buildSystemRequestLegacy(cloudDataReceived, getPoliciesReservedCorrelationID());
}else{
mySystemRequest = RPCRequestFactory.buildSystemRequest(response.toString(), getPoliciesReservedCorrelationID());
}
if (getIsConnected())
{
sendRPCRequestPrivate(mySystemRequest);
Log.i("sendSystemRequestToUrl", "sent to sdl");
updateBroadcastIntent(sendIntent2, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString());
updateBroadcastIntent(sendIntent2, "TYPE", RPCMessage.KEY_REQUEST);
updateBroadcastIntent(sendIntent2, "CORRID", mySystemRequest.getCorrelationID());
}
}
}
catch (SdlException e)
{
DebugTool.logError("sendSystemRequestToUrl: Could not get data from JSONObject received.", e);
updateBroadcastIntent(sendIntent, "COMMENT3", " SdlException encountered sendOnSystemRequestToUrl: "+ e);
//Log.i("pt", "sendSystemRequestToUrl: Could not get data from JSONObject received."+ e);
}
catch (JSONException e)
{
DebugTool.logError("sendSystemRequestToUrl: JSONException: ", e);
updateBroadcastIntent(sendIntent, "COMMENT3", " JSONException encountered sendOnSystemRequestToUrl: "+ e);
//Log.i("pt", "sendSystemRequestToUrl: JSONException: "+ e);
}
catch (UnsupportedEncodingException e)
{
DebugTool.logError("sendSystemRequestToUrl: Could not encode string.", e);
updateBroadcastIntent(sendIntent, "COMMENT3", " UnsupportedEncodingException encountered sendOnSystemRequestToUrl: "+ e);
//Log.i("pt", "sendSystemRequestToUrl: Could not encode string."+ e);
}
catch (ProtocolException e)
{
DebugTool.logError("sendSystemRequestToUrl: Could not set request method to post.", e);
updateBroadcastIntent(sendIntent, "COMMENT3", " ProtocolException encountered sendOnSystemRequestToUrl: "+ e);
//Log.i("pt", "sendSystemRequestToUrl: Could not set request method to post."+ e);
}
catch (MalformedURLException e)
{
DebugTool.logError("sendSystemRequestToUrl: URL Exception when sending SystemRequest to an external server.", e);
updateBroadcastIntent(sendIntent, "COMMENT3", " MalformedURLException encountered sendOnSystemRequestToUrl: "+ e);
//Log.i("pt", "sendSystemRequestToUrl: URL Exception when sending SystemRequest to an external server."+ e);
}
catch (IOException e)
{
DebugTool.logError("sendSystemRequestToUrl: IOException: ", e);
updateBroadcastIntent(sendIntent, "COMMENT3", " IOException while sending to cloud: IOException: "+ e);
//Log.i("pt", "sendSystemRequestToUrl: IOException: "+ e);
}
catch (Exception e)
{
DebugTool.logError("sendSystemRequestToUrl: Unexpected Exception: ", e);
updateBroadcastIntent(sendIntent, "COMMENT3", " Exception encountered sendOnSystemRequestToUrl: "+ e);
//Log.i("pt", "sendSystemRequestToUrl: Unexpected Exception: " + e);
}
finally
{
sendBroadcastIntent(sendIntent);
sendBroadcastIntent(sendIntent2);
if (iFileCount < 10)
iFileCount++;
else
iFileCount = 0;
if(urlConnection != null)
{
urlConnection.disconnect();
}
}
}
private int getPoliciesReservedCorrelationID() {
return POLICIES_CORRELATION_ID;
}
// Test correlationID
private boolean isCorrelationIDProtected(Integer correlationID) {
return correlationID != null &&
(HEARTBEAT_CORRELATION_ID == correlationID
|| REGISTER_APP_INTERFACE_CORRELATION_ID == correlationID
|| UNREGISTER_APP_INTERFACE_CORRELATION_ID == correlationID
|| POLICIES_CORRELATION_ID == correlationID);
}
// Protected isConnected method to allow legacy proxy to poll isConnected state
public Boolean getIsConnected() {
return sdlSession != null && sdlSession.getIsConnected();
}
/**
* Returns whether the application is registered in SDL. Note: for testing
* purposes, it's possible that the connection is established, but the
* application is not registered.
*
* @return true if the application is registered in SDL
*/
public Boolean getAppInterfaceRegistered() {
return _appInterfaceRegisterd;
}
// Function to initialize new proxy connection
private void initializeProxy() throws SdlException {
// Reset all of the flags and state variables
_haveReceivedFirstNonNoneHMILevel = false;
_haveReceivedFirstFocusLevel = false;
_haveReceivedFirstFocusLevelFull = false;
_appInterfaceRegisterd = _preRegisterd;
_putFileListenerList.clear();
_sdlIntefaceAvailablity = SdlInterfaceAvailability.SDL_INTERFACE_UNAVAILABLE;
//Initialize _systemCapabilityManager here.
_systemCapabilityManager = new SystemCapabilityManager(_internalInterface);
// Setup SdlConnection
synchronized(CONNECTION_REFERENCE_LOCK) {
this.sdlSession = SdlSession.createSession(_wiproVersion,_interfaceBroker, _transportConfig);
}
synchronized(CONNECTION_REFERENCE_LOCK) {
this.sdlSession.startSession();
sendTransportBroadcast();
}
}
/**
* This method will fake the multiplex connection event
*/
@SuppressWarnings("unused")
public void forceOnConnected(){
synchronized(CONNECTION_REFERENCE_LOCK) {
if (sdlSession != null) {
if(sdlSession.getSdlConnection()==null){ //There is an issue when switching from v1 to v2+ where the connection is closed. So we restart the session during this call.
try {
sdlSession.startSession();
} catch (SdlException e) {
e.printStackTrace();
}
}
sdlSession.getSdlConnection().forceHardwareConnectEvent(TransportType.BLUETOOTH);
}
}
}
public void sendTransportBroadcast()
{
if (sdlSession == null || _transportConfig == null) return;
String sTransComment = sdlSession.getBroadcastComment(_transportConfig);
if (sTransComment == null || sTransComment.equals("")) return;
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "initializeProxy");
updateBroadcastIntent(sendIntent, "COMMENT1", sTransComment);
sendBroadcastIntent(sendIntent);
}
/**
* Public method to enable the siphon transport
*/
@SuppressWarnings("unused")
public void enableSiphonDebug() {
short enabledPortNumber = SiphonServer.enableSiphonServer();
String sSiphonPortNumber = "Enabled Siphon Port Number: " + enabledPortNumber;
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "enableSiphonDebug");
updateBroadcastIntent(sendIntent, "COMMENT1", sSiphonPortNumber);
sendBroadcastIntent(sendIntent);
}
/**
* Public method to disable the Siphon Trace Server
*/
@SuppressWarnings("unused")
public void disableSiphonDebug() {
short disabledPortNumber = SiphonServer.disableSiphonServer();
if (disabledPortNumber != -1) {
String sSiphonPortNumber = "Disabled Siphon Port Number: " + disabledPortNumber;
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "disableSiphonDebug");
updateBroadcastIntent(sendIntent, "COMMENT1", sSiphonPortNumber);
sendBroadcastIntent(sendIntent);
}
}
/**
* Public method to enable the Debug Tool
*/
public static void enableDebugTool() {
DebugTool.enableDebugTool();
}
/**
* Public method to disable the Debug Tool
*/
public static void disableDebugTool() {
DebugTool.disableDebugTool();
}
/**
* Public method to determine Debug Tool enabled
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean isDebugEnabled() {
return DebugTool.isDebugEnabled();
}
@SuppressWarnings("unused")
@Deprecated
public void close() throws SdlException {
dispose();
}
@SuppressWarnings("UnusedParameters")
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException {
try {
// ALM Specific Cleanup
if (_advancedLifecycleManagementEnabled) {
_sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED;
firstTimeFull = true;
// Should we wait for the interface to be unregistered?
Boolean waitForInterfaceUnregistered = false;
// Unregister app interface
synchronized(CONNECTION_REFERENCE_LOCK) {
if (getIsConnected() && getAppInterfaceRegistered()) {
waitForInterfaceUnregistered = true;
unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID);
}
}
// Wait for the app interface to be unregistered
if (waitForInterfaceUnregistered) {
synchronized(APP_INTERFACE_REGISTERED_LOCK) {
try {
APP_INTERFACE_REGISTERED_LOCK.wait(3000);
} catch (InterruptedException e) {
// Do nothing
}
}
}
}
if(rpcResponseListeners != null){
rpcResponseListeners.clear();
}
if(rpcNotificationListeners != null){
rpcNotificationListeners.clear();
}
// Clean up SDL Connection
synchronized(CONNECTION_REFERENCE_LOCK) {
if (sdlSession != null) sdlSession.close();
}
} finally {
SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY);
}
}
/**
* Terminates the App's Interface Registration, closes the transport connection, ends the protocol session, and frees any resources used by the proxy.
*/
public void dispose() throws SdlException
{
if (_proxyDisposed) {
throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED);
}
_proxyDisposed = true;
SdlTrace.logProxyEvent("Application called dispose() method.", SDL_LIB_TRACE_KEY);
try{
// Clean the proxy
cleanProxy(SdlDisconnectedReason.APPLICATION_REQUESTED_DISCONNECT);
// Close IncomingProxyMessageDispatcher thread
synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) {
if (_incomingProxyMessageDispatcher != null) {
_incomingProxyMessageDispatcher.dispose();
_incomingProxyMessageDispatcher = null;
}
}
// Close OutgoingProxyMessageDispatcher thread
synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) {
if (_outgoingProxyMessageDispatcher != null) {
_outgoingProxyMessageDispatcher.dispose();
_outgoingProxyMessageDispatcher = null;
}
}
// Close InternalProxyMessageDispatcher thread
synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) {
if (_internalProxyMessageDispatcher != null) {
_internalProxyMessageDispatcher.dispose();
_internalProxyMessageDispatcher = null;
}
}
_traceDeviceInterrogator = null;
rpcResponseListeners = null;
} finally {
SdlTrace.logProxyEvent("SdlProxy disposed.", SDL_LIB_TRACE_KEY);
}
} // end-method
private final static Object CYCLE_LOCK = new Object();
private boolean _cycling = false;
// Method to cycle the proxy, only called in ALM
protected void cycleProxy(SdlDisconnectedReason disconnectedReason) {
if (_cycling) return;
synchronized(CYCLE_LOCK)
{
try{
_cycling = true;
cleanProxy(disconnectedReason);
initializeProxy();
if(!SdlDisconnectedReason.LEGACY_BLUETOOTH_MODE_ENABLED.equals(disconnectedReason)){//We don't want to alert higher if we are just cycling for legacy bluetooth
notifyProxyClosed("Sdl Proxy Cycled", new SdlException("Sdl Proxy Cycled", SdlExceptionCause.SDL_PROXY_CYCLED), disconnectedReason);
}
}
catch (SdlException e) {
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "cycleProxy");
updateBroadcastIntent(sendIntent, "COMMENT1", "Proxy cycled, exception cause: " + e.getSdlExceptionCause());
sendBroadcastIntent(sendIntent);
switch(e.getSdlExceptionCause()) {
case BLUETOOTH_DISABLED:
notifyProxyClosed("Bluetooth is disabled. Bluetooth must be enabled to connect to SDL. Reattempt a connection once Bluetooth is enabled.",
new SdlException("Bluetooth is disabled. Bluetooth must be enabled to connect to SDL. Reattempt a connection once Bluetooth is enabled.", SdlExceptionCause.BLUETOOTH_DISABLED), SdlDisconnectedReason.BLUETOOTH_DISABLED);
break;
case BLUETOOTH_ADAPTER_NULL:
notifyProxyClosed("Cannot locate a Bluetooth adapater. A SDL connection is impossible on this device until a Bluetooth adapter is added.",
new SdlException("Cannot locate a Bluetooth adapater. A SDL connection is impossible on this device until a Bluetooth adapter is added.", SdlExceptionCause.BLUETOOTH_ADAPTER_NULL), SdlDisconnectedReason.BLUETOOTH_ADAPTER_ERROR);
break;
default :
notifyProxyClosed("Cycling the proxy failed.", e, SdlDisconnectedReason.GENERIC_ERROR);
break;
}
} catch (Exception e) {
notifyProxyClosed("Cycling the proxy failed.", e, SdlDisconnectedReason.GENERIC_ERROR);
}
_cycling = false;
}
}
private void dispatchIncomingMessage(ProtocolMessage message) {
try{
// Dispatching logic
if (message.getSessionType().equals(SessionType.RPC)
||message.getSessionType().equals(SessionType.BULK_DATA) ) {
try {
if (_wiproVersion == 1) {
if (message.getVersion() > 1) setWiProVersion(message.getVersion());
}
Hashtable<String, Object> hash = new Hashtable<String, Object>();
if (_wiproVersion > 1) {
Hashtable<String, Object> hashTemp = new Hashtable<String, Object>();
hashTemp.put(RPCMessage.KEY_CORRELATION_ID, message.getCorrID());
if (message.getJsonSize() > 0) {
final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData());
//hashTemp.put(Names.parameters, mhash.get(Names.parameters));
hashTemp.put(RPCMessage.KEY_PARAMETERS, mhash);
}
String functionName = FunctionID.getFunctionName(message.getFunctionID());
if (functionName != null) {
hashTemp.put(RPCMessage.KEY_FUNCTION_NAME, functionName);
} else {
DebugTool.logWarning("Dispatch Incoming Message - function name is null unknown RPC. FunctionId: " + message.getFunctionID());
return;
}
if (message.getRPCType() == 0x00) {
hash.put(RPCMessage.KEY_REQUEST, hashTemp);
} else if (message.getRPCType() == 0x01) {
hash.put(RPCMessage.KEY_RESPONSE, hashTemp);
} else if (message.getRPCType() == 0x02) {
hash.put(RPCMessage.KEY_NOTIFICATION, hashTemp);
}
if (message.getBulkData() != null) hash.put(RPCStruct.KEY_BULK_DATA, message.getBulkData());
if (message.getPayloadProtected()) hash.put(RPCStruct.KEY_PROTECTED, true);
} else {
hash = JsonRPCMarshaller.unmarshall(message.getData());
}
handleRPCMessage(hash);
} catch (final Exception excp) {
DebugTool.logError("Failure handling protocol message: " + excp.toString(), excp);
passErrorToProxyListener("Error handing incoming protocol message.", excp);
} // end-catch
} //else { Handle other protocol message types here}
} catch (final Exception e) {
// Pass error to application through listener
DebugTool.logError("Error handing proxy event.", e);
passErrorToProxyListener("Error handing incoming protocol message.", e);
}
}
private byte getWiProVersion() {
return this._wiproVersion;
}
private void setWiProVersion(byte version) {
this._wiproVersion = version;
}
public String serializeJSON(RPCMessage msg)
{
String sReturn;
try
{
sReturn = msg.serializeJSON(getWiProVersion()).toString(2);
}
catch (final Exception e)
{
DebugTool.logError("Error handing proxy event.", e);
passErrorToProxyListener("Error serializing message.", e);
return null;
}
return sReturn;
}
private void handleErrorsFromIncomingMessageDispatcher(String info, Exception e) {
passErrorToProxyListener(info, e);
}
private void dispatchOutgoingMessage(ProtocolMessage message) {
synchronized(CONNECTION_REFERENCE_LOCK) {
if (sdlSession != null) {
sdlSession.sendMessage(message);
}
}
SdlTrace.logProxyEvent("SdlProxy sending Protocol Message: " + message.toString(), SDL_LIB_TRACE_KEY);
}
private void handleErrorsFromOutgoingMessageDispatcher(String info, Exception e) {
passErrorToProxyListener(info, e);
}
void dispatchInternalMessage(final InternalProxyMessage message) {
try{
switch (message.getFunctionName()) {
case InternalProxyMessage.OnProxyError: {
final OnError msg = (OnError) message;
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onError(msg.getInfo(), msg.getException());
}
});
} else {
_proxyListener.onError(msg.getInfo(), msg.getException());
}
break;
}
case InternalProxyMessage.OnServiceEnded: {
final OnServiceEnded msg = (OnServiceEnded) message;
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onServiceEnded(msg);
}
});
} else {
_proxyListener.onServiceEnded(msg);
}
break;
}
case InternalProxyMessage.OnServiceNACKed: {
final OnServiceNACKed msg = (OnServiceNACKed) message;
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onServiceNACKed(msg);
}
});
} else {
_proxyListener.onServiceNACKed(msg);
}
break;
}
case InternalProxyMessage.OnProxyOpened:
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
((IProxyListener) _proxyListener).onProxyOpened();
}
});
} else {
((IProxyListener) _proxyListener).onProxyOpened();
}
break;
case InternalProxyMessage.OnProxyClosed: {
final OnProxyClosed msg = (OnProxyClosed) message;
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onProxyClosed(msg.getInfo(), msg.getException(), msg.getReason());
}
});
} else {
_proxyListener.onProxyClosed(msg.getInfo(), msg.getException(), msg.getReason());
}
break;
}
default:
// Diagnostics
SdlTrace.logProxyEvent("Unknown RPC Message encountered. Check for an updated version of the SDL Proxy.", SDL_LIB_TRACE_KEY);
DebugTool.logError("Unknown RPC Message encountered. Check for an updated version of the SDL Proxy.");
break;
}
SdlTrace.logProxyEvent("Proxy fired callback: " + message.getFunctionName(), SDL_LIB_TRACE_KEY);
} catch(final Exception e) {
// Pass error to application through listener
DebugTool.logError("Error handing proxy event.", e);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onError("Error handing proxy event.", e);
}
});
} else {
_proxyListener.onError("Error handing proxy event.", e);
}
}
}
private void handleErrorsFromInternalMessageDispatcher(String info, Exception e) {
DebugTool.logError(info, e);
// This error cannot be passed to the user, as it indicates an error
// in the communication between the proxy and the application.
DebugTool.logError("InternalMessageDispatcher failed.", e);
// Note, this is the only place where the _proxyListener should be referenced asdlhronously,
// with an error on the internalMessageDispatcher, we have no other reliable way of
// communicating with the application.
notifyProxyClosed("Proxy callback dispatcher is down. Proxy instance is invalid.", e, SdlDisconnectedReason.GENERIC_ERROR);
_proxyListener.onError("Proxy callback dispatcher is down. Proxy instance is invalid.", e);
}
// Private sendPRCRequest method. All RPCRequests are funneled through this method after
// error checking.
private void sendRPCRequestPrivate(RPCRequest request) throws SdlException {
try {
SdlTrace.logRPCEvent(InterfaceActivityDirection.Transmit, request, SDL_LIB_TRACE_KEY);
byte[] msgBytes = JsonRPCMarshaller.marshall(request, _wiproVersion);
ProtocolMessage pm = new ProtocolMessage();
pm.setData(msgBytes);
if (sdlSession != null)
pm.setSessionID(sdlSession.getSessionId());
pm.setMessageType(MessageType.RPC);
pm.setSessionType(SessionType.RPC);
pm.setFunctionID(FunctionID.getFunctionId(request.getFunctionName()));
pm.setPayloadProtected(request.isPayloadProtected());
if (request.getCorrelationID() == null)
{
//Log error here
throw new SdlException("CorrelationID cannot be null. RPC: " + request.getFunctionName(), SdlExceptionCause.INVALID_ARGUMENT);
}
pm.setCorrID(request.getCorrelationID());
if (request.getBulkData() != null){
pm.setBulkData(request.getBulkData());
}
if(request.getFunctionName().equalsIgnoreCase(FunctionID.PUT_FILE.name())){
pm.setPriorityCoefficient(1);
}
// Queue this outgoing message
synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) {
if (_outgoingProxyMessageDispatcher != null) {
_outgoingProxyMessageDispatcher.queueMessage(pm);
//Since the message is queued we can add it's listener to our list
OnRPCResponseListener listener = request.getOnRPCResponseListener();
if(request.getMessageType().equals(RPCMessage.KEY_REQUEST)){//We might want to include other message types in the future
addOnRPCResponseListener(listener, request.getCorrelationID(), msgBytes.length);
}
}
}
} catch (OutOfMemoryError e) {
SdlTrace.logProxyEvent("OutOfMemory exception while sending request " + request.getFunctionName(), SDL_LIB_TRACE_KEY);
throw new SdlException("OutOfMemory exception while sending request " + request.getFunctionName(), e, SdlExceptionCause.INVALID_ARGUMENT);
}
}
/**
* Only call this method for a PutFile response. It will cause a class cast exception if not.
* @param correlationId correlation id of the packet being updated
* @param bytesWritten how many bytes were written
* @param totalSize the total size in bytes
*/
@SuppressWarnings("unused")
public void onPacketProgress(int correlationId, long bytesWritten, long totalSize){
synchronized(ON_UPDATE_LISTENER_LOCK){
if(rpcResponseListeners !=null
&& rpcResponseListeners.indexOfKey(correlationId)>=0){
((OnPutFileUpdateListener)rpcResponseListeners.get(correlationId)).onUpdate(correlationId, bytesWritten, totalSize);
}
}
}
/**
* Will provide callback to the listener either onFinish or onError depending on the RPCResponses result code,
* <p>Will automatically remove the listener for the list of listeners on completion.
* @param msg The RPCResponse message that was received
* @return if a listener was called or not
*/
@SuppressWarnings("UnusedReturnValue")
private boolean onRPCResponseReceived(RPCResponse msg){
synchronized(ON_UPDATE_LISTENER_LOCK){
int correlationId = msg.getCorrelationID();
if(rpcResponseListeners !=null
&& rpcResponseListeners.indexOfKey(correlationId)>=0){
OnRPCResponseListener listener = rpcResponseListeners.get(correlationId);
if(msg.getSuccess()){
listener.onResponse(correlationId, msg);
}else{
listener.onError(correlationId, msg.getResultCode(), msg.getInfo());
}
rpcResponseListeners.remove(correlationId);
return true;
}
return false;
}
}
/**
* Add a listener that will receive the response to the specific RPCRequest sent with the corresponding correlation id
* @param listener that will get called back when a response is received
* @param correlationId of the RPCRequest that was sent
* @param totalSize only include if this is an OnPutFileUpdateListener. Otherwise it will be ignored.
*/
public void addOnRPCResponseListener(OnRPCResponseListener listener,int correlationId, int totalSize){
synchronized(ON_UPDATE_LISTENER_LOCK){
if(rpcResponseListeners!=null
&& listener !=null){
if(listener.getListenerType() == OnRPCResponseListener.UPDATE_LISTENER_TYPE_PUT_FILE){
((OnPutFileUpdateListener)listener).setTotalSize(totalSize);
}
listener.onStart(correlationId);
rpcResponseListeners.put(correlationId, listener);
}
}
}
@SuppressWarnings("unused")
public SparseArray<OnRPCResponseListener> getResponseListeners(){
synchronized(ON_UPDATE_LISTENER_LOCK){
return this.rpcResponseListeners;
}
}
@SuppressWarnings("UnusedReturnValue")
public boolean onRPCNotificationReceived(RPCNotification notification){
synchronized(ON_NOTIFICATION_LISTENER_LOCK){
CopyOnWriteArrayList<OnRPCNotificationListener> listeners = rpcNotificationListeners.get(FunctionID.getFunctionId(notification.getFunctionName()));
if(listeners!=null && listeners.size()>0) {
for (OnRPCNotificationListener listener : listeners) {
listener.onNotified(notification);
}
return true;
}
return false;
}
}
/**
* This will ad a listener for the specific type of notification. As of now it will only allow
* a single listener per notification function id
* @param notificationId The notification type that this listener is designated for
* @param listener The listener that will be called when a notification of the provided type is received
*/
@SuppressWarnings("unused")
public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener){
synchronized(ON_NOTIFICATION_LISTENER_LOCK){
if(notificationId != null && listener != null){
if(rpcNotificationListeners.indexOfKey(notificationId.getId()) < 0 ){
rpcNotificationListeners.put(notificationId.getId(),new CopyOnWriteArrayList<OnRPCNotificationListener>());
}
rpcNotificationListeners.get(notificationId.getId()).add(listener);
}
}
}
/**
* This method is no longer valid and will not remove the listener for the supplied notificaiton id
* @param notificationId n/a
* @see #removeOnRPCNotificationListener(FunctionID, OnRPCNotificationListener)
*/
@SuppressWarnings("unused")
@Deprecated
public void removeOnRPCNotificationListener(FunctionID notificationId){
synchronized(ON_NOTIFICATION_LISTENER_LOCK){
//rpcNotificationListeners.delete(notificationId.getId());
}
}
public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener){
synchronized(ON_NOTIFICATION_LISTENER_LOCK){
if(rpcNotificationListeners!= null
&& notificationId != null
&& listener != null
&& rpcNotificationListeners.indexOfKey(notificationId.getId()) >= 0){
return rpcNotificationListeners.get(notificationId.getId()).remove(listener);
}
}
return false;
}
private void processRaiResponse(RegisterAppInterfaceResponse rai)
{
if (rai == null) return;
VehicleType vt = rai.getVehicleType();
if (vt == null) return;
String make = vt.getMake();
if (make == null) return;
if (_secList == null) return;
SdlSecurityBase sec;
Service svc = getService();
SdlSecurityBase.setAppService(svc);
for (Class<? extends SdlSecurityBase> cls : _secList)
{
try
{
sec = cls.newInstance();
}
catch (Exception e)
{
continue;
}
if ( (sec != null) && (sec.getMakeList() != null) )
{
if (sec.getMakeList().contains(make))
{
setSdlSecurity(sec);
sec.setAppId(_appID);
if (sdlSession != null)
sec.handleSdlSession(sdlSession);
return;
}
}
}
}
private void handleRPCMessage(Hashtable<String, Object> hash) {
RPCMessage rpcMsg = new RPCMessage(hash);
String functionName = rpcMsg.getFunctionName();
String messageType = rpcMsg.getMessageType();
if (messageType.equals(RPCMessage.KEY_RESPONSE)) {
SdlTrace.logRPCEvent(InterfaceActivityDirection.Receive, new RPCResponse(rpcMsg), SDL_LIB_TRACE_KEY);
// Check to ensure response is not from an internal message (reserved correlation ID)
if (isCorrelationIDProtected((new RPCResponse(hash)).getCorrelationID())) {
// This is a response generated from an internal message, it can be trapped here
// The app should not receive a response for a request it did not send
if ((new RPCResponse(hash)).getCorrelationID() == REGISTER_APP_INTERFACE_CORRELATION_ID
&& _advancedLifecycleManagementEnabled
&& functionName.equals(FunctionID.REGISTER_APP_INTERFACE.toString())) {
final RegisterAppInterfaceResponse msg = new RegisterAppInterfaceResponse(hash);
if (msg.getSuccess()) {
_appInterfaceRegisterd = true;
}
processRaiResponse(msg);
//Populate the system capability manager with the RAI response
_systemCapabilityManager.parseRAIResponse(msg);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.REGISTER_APP_INTERFACE.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE);
updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess());
updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo());
updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString());
updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg));
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
sendBroadcastIntent(sendIntent);
//_autoActivateIdReturned = msg.getAutoActivateID();
/*Place holder for legacy support*/ _autoActivateIdReturned = "8675309";
_prerecordedSpeech = msg.getPrerecordedSpeech();
_sdlLanguage = msg.getLanguage();
_hmiDisplayLanguage = msg.getHmiDisplayLanguage();
_sdlMsgVersion = msg.getSdlMsgVersion();
_vehicleType = msg.getVehicleType();
_systemSoftwareVersion = msg.getSystemSoftwareVersion();
_proxyVersionInfo = msg.getProxyVersionInfo();
if (_bAppResumeEnabled)
{
if ( (_sdlMsgVersion.getMajorVersion() > 2) && (_lastHashID != null) && (msg.getSuccess()) && (msg.getResultCode() != Result.RESUME_FAILED) )
_bResumeSuccess = true;
else
{
_bResumeSuccess = false;
_lastHashID = null;
}
}
_diagModes = msg.getSupportedDiagModes();
String sVersionInfo = "SDL Proxy Version: " + _proxyVersionInfo;
if (!isDebugEnabled())
{
enableDebugTool();
DebugTool.logInfo(sVersionInfo, false);
disableDebugTool();
}
else
DebugTool.logInfo(sVersionInfo, false);
sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "RAI_RESPONSE");
updateBroadcastIntent(sendIntent, "COMMENT1", sVersionInfo);
sendBroadcastIntent(sendIntent);
// Send onSdlConnected message in ALM
_sdlConnectionState = SdlConnectionState.SDL_CONNECTED;
// If registerAppInterface failed, exit with OnProxyUnusable
if (!msg.getSuccess()) {
notifyProxyClosed("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: ",
new SdlException("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: " + msg.getResultCode(), SdlExceptionCause.SDL_REGISTRATION_ERROR), SdlDisconnectedReason.SDL_REGISTRATION_ERROR);
}
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
if (_proxyListener instanceof IProxyListener) {
((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg);
}
onRPCResponseReceived(msg);
}
});
} else {
if (_proxyListener instanceof IProxyListener) {
((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg);
}
onRPCResponseReceived(msg);
}
} else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID
&& functionName.equals(FunctionID.ON_ENCODED_SYNC_P_DATA.toString())) {
Log.i("pt", "POLICIES_CORRELATION_ID SystemRequest Notification (Legacy)");
final OnSystemRequest msg = new OnSystemRequest(hash);
// If url is not null, then send to URL
if ( (msg.getUrl() != null) )
{
// URL has data, attempt to post request to external server
Thread handleOffboardTransmissionThread = new Thread() {
@Override
public void run() {
sendOnSystemRequestToUrl(msg);
}
};
handleOffboardTransmissionThread.start();
}
}
else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID
&& functionName.equals(FunctionID.ENCODED_SYNC_P_DATA.toString())) {
Log.i("pt", "POLICIES_CORRELATION_ID SystemRequest Response (Legacy)");
final SystemRequestResponse msg = new SystemRequestResponse(hash);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE);
updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess());
updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo());
updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString());
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
sendBroadcastIntent(sendIntent);
}
else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID
&& functionName.equals(FunctionID.SYSTEM_REQUEST.toString())) {
final SystemRequestResponse msg = new SystemRequestResponse(hash);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE);
updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess());
updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo());
updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString());
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
updateBroadcastIntent(sendIntent, "DATA", serializeJSON(msg));
sendBroadcastIntent(sendIntent);
}
else if (functionName.equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) {
// UnregisterAppInterface
_appInterfaceRegisterd = false;
synchronized(APP_INTERFACE_REGISTERED_LOCK) {
APP_INTERFACE_REGISTERED_LOCK.notify();
}
final UnregisterAppInterfaceResponse msg = new UnregisterAppInterfaceResponse(hash);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE);
updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess());
updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo());
updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString());
updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg));
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
sendBroadcastIntent(sendIntent);
}
return;
}
if (functionName.equals(FunctionID.REGISTER_APP_INTERFACE.toString())) {
final RegisterAppInterfaceResponse msg = new RegisterAppInterfaceResponse(hash);
if (msg.getSuccess()) {
_appInterfaceRegisterd = true;
}
processRaiResponse(msg);
//Populate the system capability manager with the RAI response
_systemCapabilityManager.parseRAIResponse(msg);
//_autoActivateIdReturned = msg.getAutoActivateID();
/*Place holder for legacy support*/ _autoActivateIdReturned = "8675309";
_prerecordedSpeech = msg.getPrerecordedSpeech();
_sdlLanguage = msg.getLanguage();
_hmiDisplayLanguage = msg.getHmiDisplayLanguage();
_sdlMsgVersion = msg.getSdlMsgVersion();
_vehicleType = msg.getVehicleType();
_systemSoftwareVersion = msg.getSystemSoftwareVersion();
_proxyVersionInfo = msg.getProxyVersionInfo();
if (_bAppResumeEnabled)
{
if ( (_sdlMsgVersion.getMajorVersion() > 2) && (_lastHashID != null) && (msg.getSuccess()) && (msg.getResultCode() != Result.RESUME_FAILED) )
_bResumeSuccess = true;
else
{
_bResumeSuccess = false;
_lastHashID = null;
}
}
_diagModes = msg.getSupportedDiagModes();
if (!isDebugEnabled())
{
enableDebugTool();
DebugTool.logInfo("SDL Proxy Version: " + _proxyVersionInfo);
disableDebugTool();
}
else
DebugTool.logInfo("SDL Proxy Version: " + _proxyVersionInfo);
// RegisterAppInterface
if (_advancedLifecycleManagementEnabled) {
// Send onSdlConnected message in ALM
_sdlConnectionState = SdlConnectionState.SDL_CONNECTED;
// If registerAppInterface failed, exit with OnProxyUnusable
if (!msg.getSuccess()) {
notifyProxyClosed("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: ",
new SdlException("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: " + msg.getResultCode(), SdlExceptionCause.SDL_REGISTRATION_ERROR), SdlDisconnectedReason.SDL_REGISTRATION_ERROR);
}
} else {
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
if (_proxyListener instanceof IProxyListener) {
((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg);
}
onRPCResponseReceived(msg);
}
});
} else {
if (_proxyListener instanceof IProxyListener) {
((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg);
}
onRPCResponseReceived(msg);
}
}
} else if (functionName.equals(FunctionID.SPEAK.toString())) {
// SpeakResponse
final SpeakResponse msg = new SpeakResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSpeakResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSpeakResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.ALERT.toString())) {
// AlertResponse
final AlertResponse msg = new AlertResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onAlertResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onAlertResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SHOW.toString())) {
// ShowResponse
final ShowResponse msg = new ShowResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onShowResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onShowResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.ADD_COMMAND.toString())) {
// AddCommand
final AddCommandResponse msg = new AddCommandResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onAddCommandResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onAddCommandResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.DELETE_COMMAND.toString())) {
// DeleteCommandResponse
final DeleteCommandResponse msg = new DeleteCommandResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onDeleteCommandResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onDeleteCommandResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.ADD_SUB_MENU.toString())) {
// AddSubMenu
final AddSubMenuResponse msg = new AddSubMenuResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onAddSubMenuResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onAddSubMenuResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.DELETE_SUB_MENU.toString())) {
// DeleteSubMenu
final DeleteSubMenuResponse msg = new DeleteSubMenuResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onDeleteSubMenuResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onDeleteSubMenuResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SUBSCRIBE_BUTTON.toString())) {
// SubscribeButton
final SubscribeButtonResponse msg = new SubscribeButtonResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSubscribeButtonResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSubscribeButtonResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.UNSUBSCRIBE_BUTTON.toString())) {
// UnsubscribeButton
final UnsubscribeButtonResponse msg = new UnsubscribeButtonResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onUnsubscribeButtonResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onUnsubscribeButtonResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SET_MEDIA_CLOCK_TIMER.toString())) {
// SetMediaClockTimer
final SetMediaClockTimerResponse msg = new SetMediaClockTimerResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSetMediaClockTimerResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSetMediaClockTimerResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.ENCODED_SYNC_P_DATA.toString())) {
final SystemRequestResponse msg = new SystemRequestResponse(hash);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE);
updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess());
updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo());
updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString());
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
sendBroadcastIntent(sendIntent);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSystemRequestResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSystemRequestResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.CREATE_INTERACTION_CHOICE_SET.toString())) {
// CreateInteractionChoiceSet
final CreateInteractionChoiceSetResponse msg = new CreateInteractionChoiceSetResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onCreateInteractionChoiceSetResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onCreateInteractionChoiceSetResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.DELETE_INTERACTION_CHOICE_SET.toString())) {
// DeleteInteractionChoiceSet
final DeleteInteractionChoiceSetResponse msg = new DeleteInteractionChoiceSetResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onDeleteInteractionChoiceSetResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onDeleteInteractionChoiceSetResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.PERFORM_INTERACTION.toString())) {
// PerformInteraction
final PerformInteractionResponse msg = new PerformInteractionResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onPerformInteractionResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onPerformInteractionResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SET_GLOBAL_PROPERTIES.toString())) {
// SetGlobalPropertiesResponse
final SetGlobalPropertiesResponse msg = new SetGlobalPropertiesResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSetGlobalPropertiesResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSetGlobalPropertiesResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.RESET_GLOBAL_PROPERTIES.toString())) {
// ResetGlobalProperties
final ResetGlobalPropertiesResponse msg = new ResetGlobalPropertiesResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onResetGlobalPropertiesResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onResetGlobalPropertiesResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) {
// UnregisterAppInterface
_appInterfaceRegisterd = false;
synchronized(APP_INTERFACE_REGISTERED_LOCK) {
APP_INTERFACE_REGISTERED_LOCK.notify();
}
final UnregisterAppInterfaceResponse msg = new UnregisterAppInterfaceResponse(hash);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE);
updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess());
updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo());
updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString());
updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg));
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
sendBroadcastIntent(sendIntent);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
if (_proxyListener instanceof IProxyListener) {
((IProxyListener)_proxyListener).onUnregisterAppInterfaceResponse(msg);
}
onRPCResponseReceived(msg);
}
});
} else {
if (_proxyListener instanceof IProxyListener) {
((IProxyListener)_proxyListener).onUnregisterAppInterfaceResponse(msg);
}
onRPCResponseReceived(msg);
}
notifyProxyClosed("UnregisterAppInterfaceResponse", null, SdlDisconnectedReason.APP_INTERFACE_UNREG);
} else if (functionName.equals(FunctionID.GENERIC_RESPONSE.toString())) {
// GenericResponse (Usually and error)
final GenericResponse msg = new GenericResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onGenericResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onGenericResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SLIDER.toString())) {
// Slider
final SliderResponse msg = new SliderResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSliderResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSliderResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.PUT_FILE.toString())) {
// PutFile
final PutFileResponse msg = new PutFileResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onPutFileResponse(msg);
onRPCResponseReceived(msg);
notifyPutFileStreamResponse(msg);
}
});
} else {
_proxyListener.onPutFileResponse(msg);
onRPCResponseReceived(msg);
notifyPutFileStreamResponse(msg);
}
} else if (functionName.equals(FunctionID.DELETE_FILE.toString())) {
// DeleteFile
final DeleteFileResponse msg = new DeleteFileResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onDeleteFileResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onDeleteFileResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.LIST_FILES.toString())) {
// ListFiles
final ListFilesResponse msg = new ListFilesResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onListFilesResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onListFilesResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SET_APP_ICON.toString())) {
// SetAppIcon
final SetAppIconResponse msg = new SetAppIconResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSetAppIconResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSetAppIconResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SCROLLABLE_MESSAGE.toString())) {
// ScrollableMessage
final ScrollableMessageResponse msg = new ScrollableMessageResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onScrollableMessageResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onScrollableMessageResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.CHANGE_REGISTRATION.toString())) {
// ChangeLanguageRegistration
final ChangeRegistrationResponse msg = new ChangeRegistrationResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onChangeRegistrationResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onChangeRegistrationResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SET_DISPLAY_LAYOUT.toString())) {
// SetDisplayLayout
final SetDisplayLayoutResponse msg = new SetDisplayLayoutResponse(hash);
// successfully changed display layout - update layout capabilities
if(msg.getSuccess() && _systemCapabilityManager!=null){
_systemCapabilityManager.setCapability(SystemCapabilityType.DISPLAY, msg.getDisplayCapabilities());
_systemCapabilityManager.setCapability(SystemCapabilityType.BUTTON, msg.getButtonCapabilities());
_systemCapabilityManager.setCapability(SystemCapabilityType.PRESET_BANK, msg.getPresetBankCapabilities());
_systemCapabilityManager.setCapability(SystemCapabilityType.SOFTBUTTON, msg.getSoftButtonCapabilities());
}
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSetDisplayLayoutResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSetDisplayLayoutResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.PERFORM_AUDIO_PASS_THRU.toString())) {
// PerformAudioPassThru
final PerformAudioPassThruResponse msg = new PerformAudioPassThruResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onPerformAudioPassThruResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onPerformAudioPassThruResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.END_AUDIO_PASS_THRU.toString())) {
// EndAudioPassThru
final EndAudioPassThruResponse msg = new EndAudioPassThruResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onEndAudioPassThruResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onEndAudioPassThruResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SUBSCRIBE_VEHICLE_DATA.toString())) {
// SubscribeVehicleData
final SubscribeVehicleDataResponse msg = new SubscribeVehicleDataResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSubscribeVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSubscribeVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.UNSUBSCRIBE_VEHICLE_DATA.toString())) {
// UnsubscribeVehicleData
final UnsubscribeVehicleDataResponse msg = new UnsubscribeVehicleDataResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onUnsubscribeVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onUnsubscribeVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.GET_VEHICLE_DATA.toString())) {
// GetVehicleData
final GetVehicleDataResponse msg = new GetVehicleDataResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onGetVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onGetVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SUBSCRIBE_WAY_POINTS.toString())) {
// SubscribeWayPoints
final SubscribeWayPointsResponse msg = new SubscribeWayPointsResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSubscribeWayPointsResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSubscribeWayPointsResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.UNSUBSCRIBE_WAY_POINTS.toString())) {
// UnsubscribeWayPoints
final UnsubscribeWayPointsResponse msg = new UnsubscribeWayPointsResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onUnsubscribeWayPointsResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onUnsubscribeWayPointsResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.GET_WAY_POINTS.toString())) {
// GetWayPoints
final GetWayPointsResponse msg = new GetWayPointsResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onGetWayPointsResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onGetWayPointsResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.READ_DID.toString())) {
final ReadDIDResponse msg = new ReadDIDResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onReadDIDResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onReadDIDResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.GET_DTCS.toString())) {
final GetDTCsResponse msg = new GetDTCsResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onGetDTCsResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onGetDTCsResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.DIAGNOSTIC_MESSAGE.toString())) {
final DiagnosticMessageResponse msg = new DiagnosticMessageResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onDiagnosticMessageResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onDiagnosticMessageResponse(msg);
onRPCResponseReceived(msg);
}
}
else if (functionName.equals(FunctionID.SYSTEM_REQUEST.toString())) {
final SystemRequestResponse msg = new SystemRequestResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSystemRequestResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSystemRequestResponse(msg);
onRPCResponseReceived(msg);
}
}
else if (functionName.equals(FunctionID.SEND_LOCATION.toString())) {
final SendLocationResponse msg = new SendLocationResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSendLocationResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSendLocationResponse(msg);
onRPCResponseReceived(msg);
}
}
else if (functionName.equals(FunctionID.DIAL_NUMBER.toString())) {
final DialNumberResponse msg = new DialNumberResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onDialNumberResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onDialNumberResponse(msg);
onRPCResponseReceived(msg);
}
}
else if (functionName.equals(FunctionID.SHOW_CONSTANT_TBT.toString())) {
final ShowConstantTbtResponse msg = new ShowConstantTbtResponse(hash);
if (_callbackToUIThread) {
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onShowConstantTbtResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onShowConstantTbtResponse(msg);
onRPCResponseReceived(msg);
}
}
else if (functionName.equals(FunctionID.ALERT_MANEUVER.toString())) {
final AlertManeuverResponse msg = new AlertManeuverResponse(hash);
if (_callbackToUIThread) {
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onAlertManeuverResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onAlertManeuverResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.UPDATE_TURN_LIST.toString())) {
final UpdateTurnListResponse msg = new UpdateTurnListResponse(hash);
if (_callbackToUIThread) {
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onUpdateTurnListResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onUpdateTurnListResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SET_INTERIOR_VEHICLE_DATA.toString())) {
final SetInteriorVehicleDataResponse msg = new SetInteriorVehicleDataResponse(hash);
if (_callbackToUIThread) {
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSetInteriorVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSetInteriorVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.GET_INTERIOR_VEHICLE_DATA.toString())) {
final GetInteriorVehicleDataResponse msg = new GetInteriorVehicleDataResponse(hash);
if (_callbackToUIThread) {
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onGetInteriorVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onGetInteriorVehicleDataResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.GET_SYSTEM_CAPABILITY.toString())) {
// GetSystemCapabilityResponse
final GetSystemCapabilityResponse msg = new GetSystemCapabilityResponse(hash);
if (_callbackToUIThread) {
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onGetSystemCapabilityResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onGetSystemCapabilityResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.BUTTON_PRESS.toString())) {
final ButtonPressResponse msg = new ButtonPressResponse(hash);
if (_callbackToUIThread) {
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onButtonPressResponse(msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onButtonPressResponse(msg);
onRPCResponseReceived(msg);
}
} else if (functionName.equals(FunctionID.SEND_HAPTIC_DATA.toString())) {
final SendHapticDataResponse msg = new SendHapticDataResponse(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onSendHapticDataResponse( msg);
onRPCResponseReceived(msg);
}
});
} else {
_proxyListener.onSendHapticDataResponse( msg);
onRPCResponseReceived(msg);
}
}
else {
if (_sdlMsgVersion != null) {
DebugTool.logError("Unrecognized response Message: " + functionName +
" SDL Message Version = " + _sdlMsgVersion);
} else {
DebugTool.logError("Unrecognized response Message: " + functionName);
}
} // end-if
} else if (messageType.equals(RPCMessage.KEY_NOTIFICATION)) {
SdlTrace.logRPCEvent(InterfaceActivityDirection.Receive, new RPCNotification(rpcMsg), SDL_LIB_TRACE_KEY);
if (functionName.equals(FunctionID.ON_HMI_STATUS.toString())) {
// OnHMIStatus
final OnHMIStatus msg = new OnHMIStatus(hash);
//setup lockscreeninfo
if (sdlSession != null)
{
sdlSession.getLockScreenMan().setHMILevel(msg.getHmiLevel());
}
msg.setFirstRun(firstTimeFull);
if (msg.getHmiLevel() == HMILevel.HMI_FULL) firstTimeFull = false;
if (msg.getHmiLevel() != _hmiLevel || msg.getAudioStreamingState() != _audioStreamingState) {
_hmiLevel = msg.getHmiLevel();
_audioStreamingState = msg.getAudioStreamingState();
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnHMIStatus(msg);
_proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj());
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnHMIStatus(msg);
_proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj());
onRPCNotificationReceived(msg);
}
}
} else if (functionName.equals(FunctionID.ON_COMMAND.toString())) {
// OnCommand
final OnCommand msg = new OnCommand(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnCommand(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnCommand(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_DRIVER_DISTRACTION.toString())) {
// OnDriverDistration
final OnDriverDistraction msg = new OnDriverDistraction(hash);
//setup lockscreeninfo
if (sdlSession != null)
{
DriverDistractionState drDist = msg.getState();
sdlSession.getLockScreenMan().setDriverDistStatus(drDist == DriverDistractionState.DD_ON);
}
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnDriverDistraction(msg);
_proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj());
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnDriverDistraction(msg);
_proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj());
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_ENCODED_SYNC_P_DATA.toString())) {
final OnSystemRequest msg = new OnSystemRequest(hash);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.ON_SYSTEM_REQUEST.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_NOTIFICATION);
// If url is null, then send notification to the app, otherwise, send to URL
if (msg.getUrl() == null) {
updateBroadcastIntent(sendIntent, "COMMENT1", "URL is a null value (received)");
sendBroadcastIntent(sendIntent);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnSystemRequest(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnSystemRequest(msg);
onRPCNotificationReceived(msg);
}
} else {
updateBroadcastIntent(sendIntent, "COMMENT1", "Sending to cloud: " + msg.getUrl());
sendBroadcastIntent(sendIntent);
Log.i("pt", "send to url");
if ( (msg.getUrl() != null) )
{
Thread handleOffboardTransmissionThread = new Thread() {
@Override
public void run() {
sendOnSystemRequestToUrl(msg);
}
};
handleOffboardTransmissionThread.start();
}
}
} else if (functionName.equals(FunctionID.ON_PERMISSIONS_CHANGE.toString())) {
final OnPermissionsChange msg = new OnPermissionsChange(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnPermissionsChange(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnPermissionsChange(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_TBT_CLIENT_STATE.toString())) {
// OnTBTClientState
final OnTBTClientState msg = new OnTBTClientState(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnTBTClientState(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnTBTClientState(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_BUTTON_PRESS.toString())) {
// OnButtonPress
final OnButtonPress msg = new OnButtonPress(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnButtonPress(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnButtonPress(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_BUTTON_EVENT.toString())) {
// OnButtonEvent
final OnButtonEvent msg = new OnButtonEvent(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnButtonEvent(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnButtonEvent(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_LANGUAGE_CHANGE.toString())) {
// OnLanguageChange
final OnLanguageChange msg = new OnLanguageChange(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnLanguageChange(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnLanguageChange(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_HASH_CHANGE.toString())) {
// OnLanguageChange
final OnHashChange msg = new OnHashChange(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnHashChange(msg);
onRPCNotificationReceived(msg);
if (_bAppResumeEnabled)
{
_lastHashID = msg.getHashID();
}
}
});
} else {
_proxyListener.onOnHashChange(msg);
onRPCNotificationReceived(msg);
if (_bAppResumeEnabled)
{
_lastHashID = msg.getHashID();
}
}
} else if (functionName.equals(FunctionID.ON_SYSTEM_REQUEST.toString())) {
// OnSystemRequest
final OnSystemRequest msg = new OnSystemRequest(hash);
if ((msg.getUrl() != null) &&
(((msg.getRequestType() == RequestType.PROPRIETARY) && (msg.getFileType() == FileType.JSON))
|| ((msg.getRequestType() == RequestType.HTTP) && (msg.getFileType() == FileType.BINARY)))){
Thread handleOffboardTransmissionThread = new Thread() {
@Override
public void run() {
sendOnSystemRequestToUrl(msg);
}
};
handleOffboardTransmissionThread.start();
}
if(msg.getRequestType() == RequestType.LOCK_SCREEN_ICON_URL &&
msg.getUrl() != null){
lockScreenIconRequest = msg;
}
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnSystemRequest(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnSystemRequest(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_AUDIO_PASS_THRU.toString())) {
// OnAudioPassThru
final OnAudioPassThru msg = new OnAudioPassThru(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnAudioPassThru(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnAudioPassThru(msg);
onRPCNotificationReceived(msg);
}
} else if (functionName.equals(FunctionID.ON_VEHICLE_DATA.toString())) {
// OnVehicleData
final OnVehicleData msg = new OnVehicleData(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnVehicleData(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnVehicleData(msg);
onRPCNotificationReceived(msg);
}
}
else if (functionName.equals(FunctionID.ON_APP_INTERFACE_UNREGISTERED.toString())) {
// OnAppInterfaceUnregistered
_appInterfaceRegisterd = false;
synchronized(APP_INTERFACE_REGISTERED_LOCK) {
APP_INTERFACE_REGISTERED_LOCK.notify();
}
final OnAppInterfaceUnregistered msg = new OnAppInterfaceUnregistered(hash);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.ON_APP_INTERFACE_UNREGISTERED.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_NOTIFICATION);
updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg));
sendBroadcastIntent(sendIntent);
if (_advancedLifecycleManagementEnabled) {
// This requires the proxy to be cycled
cycleProxy(SdlDisconnectedReason.convertAppInterfaceUnregisteredReason(msg.getReason()));
} else {
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
((IProxyListener)_proxyListener).onOnAppInterfaceUnregistered(msg);
onRPCNotificationReceived(msg);
}
});
} else {
((IProxyListener)_proxyListener).onOnAppInterfaceUnregistered(msg);
onRPCNotificationReceived(msg);
}
notifyProxyClosed("OnAppInterfaceUnregistered", null, SdlDisconnectedReason.APP_INTERFACE_UNREG);
}
}
else if (functionName.equals(FunctionID.ON_KEYBOARD_INPUT.toString())) {
final OnKeyboardInput msg = new OnKeyboardInput(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnKeyboardInput(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnKeyboardInput(msg);
onRPCNotificationReceived(msg);
}
}
else if (functionName.equals(FunctionID.ON_TOUCH_EVENT.toString())) {
final OnTouchEvent msg = new OnTouchEvent(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnTouchEvent(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnTouchEvent(msg);
onRPCNotificationReceived(msg);
}
}
else if (functionName.equals(FunctionID.ON_WAY_POINT_CHANGE.toString())) {
final OnWayPointChange msg = new OnWayPointChange(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnWayPointChange(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnWayPointChange(msg);
onRPCNotificationReceived(msg);
}
}
else if (functionName.equals(FunctionID.ON_INTERIOR_VEHICLE_DATA.toString())) {
final OnInteriorVehicleData msg = new OnInteriorVehicleData(hash);
if (_callbackToUIThread) {
// Run in UI thread
_mainUIHandler.post(new Runnable() {
@Override
public void run() {
_proxyListener.onOnInteriorVehicleData(msg);
onRPCNotificationReceived(msg);
}
});
} else {
_proxyListener.onOnInteriorVehicleData(msg);
onRPCNotificationReceived(msg);
}
}
else {
if (_sdlMsgVersion != null) {
DebugTool.logInfo("Unrecognized notification Message: " + functionName +
" connected to SDL using message version: " + _sdlMsgVersion.getMajorVersion() + "." + _sdlMsgVersion.getMinorVersion());
} else {
DebugTool.logInfo("Unrecognized notification Message: " + functionName);
}
} // end-if
} // end-if notification
SdlTrace.logProxyEvent("Proxy received RPC Message: " + functionName, SDL_LIB_TRACE_KEY);
}
/**
* Takes an RPCRequest and sends it to SDL. Responses are captured through callback on IProxyListener.
*
* @param request is the RPCRequest being sent
* @throws SdlException if an unrecoverable error is encountered if an unrecoverable error is encountered
*/
public void sendRPCRequest(RPCRequest request) throws SdlException {
if (_proxyDisposed) {
throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED);
}
// Test if request is null
if (request == null) {
SdlTrace.logProxyEvent("Application called sendRPCRequest method with a null RPCRequest.", SDL_LIB_TRACE_KEY);
throw new IllegalArgumentException("sendRPCRequest cannot be called with a null request.");
}
SdlTrace.logProxyEvent("Application called sendRPCRequest method for RPCRequest: ." + request.getFunctionName(), SDL_LIB_TRACE_KEY);
// Test if SdlConnection is null
synchronized(CONNECTION_REFERENCE_LOCK) {
if (!getIsConnected()) {
SdlTrace.logProxyEvent("Application attempted to send and RPCRequest without a connected transport.", SDL_LIB_TRACE_KEY);
throw new SdlException("There is no valid connection to SDL. sendRPCRequest cannot be called until SDL has been connected.", SdlExceptionCause.SDL_UNAVAILABLE);
}
}
if (isCorrelationIDProtected(request.getCorrelationID())) {
SdlTrace.logProxyEvent("Application attempted to use the reserved correlation ID, " + request.getCorrelationID(), SDL_LIB_TRACE_KEY);
throw new SdlException("Invalid correlation ID. The correlation ID, " + request.getCorrelationID()
+ " , is a reserved correlation ID.", SdlExceptionCause.RESERVED_CORRELATION_ID);
}
// Throw exception if RPCRequest is sent when SDL is unavailable
if (!_appInterfaceRegisterd && !request.getFunctionName().equals(FunctionID.REGISTER_APP_INTERFACE.toString())) {
SdlTrace.logProxyEvent("Application attempted to send an RPCRequest (non-registerAppInterface), before the interface was registerd.", SDL_LIB_TRACE_KEY);
throw new SdlException("SDL is currently unavailable. RPC Requests cannot be sent.", SdlExceptionCause.SDL_UNAVAILABLE);
}
if (_advancedLifecycleManagementEnabled) {
if (request.getFunctionName().equals(FunctionID.REGISTER_APP_INTERFACE.toString())
|| request.getFunctionName().equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) {
SdlTrace.logProxyEvent("Application attempted to send a RegisterAppInterface or UnregisterAppInterface while using ALM.", SDL_LIB_TRACE_KEY);
throw new SdlException("The RPCRequest, " + request.getFunctionName() +
", is unallowed using the Advanced Lifecycle Management Model.", SdlExceptionCause.INCORRECT_LIFECYCLE_MODEL);
}
}
sendRPCRequestPrivate(request);
} // end-method
protected void notifyProxyClosed(final String info, final Exception e, final SdlDisconnectedReason reason) {
SdlTrace.logProxyEvent("NotifyProxyClose", SDL_LIB_TRACE_KEY);
OnProxyClosed message = new OnProxyClosed(info, e, reason);
queueInternalMessage(message);
}
private void passErrorToProxyListener(final String info, final Exception e) {
OnError message = new OnError(info, e);
queueInternalMessage(message);
}
private void startRPCProtocolSession() {
// Set Proxy Lifecyclek Available
if (_advancedLifecycleManagementEnabled) {
try {
registerAppInterfacePrivate(
_sdlMsgVersionRequest,
_applicationName,
_ttsName,
_ngnMediaScreenAppName,
_vrSynonyms,
_isMediaApp,
_sdlLanguageDesired,
_hmiDisplayLanguageDesired,
_appType,
_appID,
REGISTER_APP_INTERFACE_CORRELATION_ID);
} catch (Exception e) {
notifyProxyClosed("Failed to register application interface with SDL. Check parameter values given to SdlProxy constructor.", e, SdlDisconnectedReason.SDL_REGISTRATION_ERROR);
}
} else {
InternalProxyMessage message = new InternalProxyMessage(InternalProxyMessage.OnProxyOpened);
queueInternalMessage(message);
}
}
// Queue internal callback message
private void queueInternalMessage(InternalProxyMessage message) {
synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) {
if (_internalProxyMessageDispatcher != null) {
_internalProxyMessageDispatcher.queueMessage(message);
}
}
}
// Queue incoming ProtocolMessage
private void queueIncomingMessage(ProtocolMessage message) {
synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) {
if (_incomingProxyMessageDispatcher != null) {
_incomingProxyMessageDispatcher.queueMessage(message);
}
}
}
private FileInputStream getFileInputStream(String sLocalFile)
{
FileInputStream is = null;
try
{
is = new FileInputStream(sLocalFile);
}
catch (IOException e1)
{
e1.printStackTrace();
}
return is;
}
private Long getFileInputStreamSize(FileInputStream is)
{
Long lSize = null;
try
{
lSize = is.getChannel().size();
}
catch (IOException e)
{
e.printStackTrace();
}
return lSize;
}
private void closeFileInputStream(FileInputStream is)
{
try
{
is.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private RPCStreamController startRPCStream(String sLocalFile, PutFile request, SessionType sType, byte rpcSessionID, byte wiproVersion)
{
if (sdlSession == null) return null;
FileInputStream is = getFileInputStream(sLocalFile);
if (is == null) return null;
Long lSize = getFileInputStreamSize(is);
if (lSize == null)
{
closeFileInputStream(is);
return null;
}
try {
StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer((SdlProxyBase<IProxyListenerBase>) this, sdlSession, is, request, sType, rpcSessionID, wiproVersion, lSize, sdlSession);
rpcPacketizer.start();
return new RPCStreamController(rpcPacketizer, request.getCorrelationID());
} catch (Exception e) {
Log.e("SyncConnection", "Unable to start streaming:" + e.toString());
return null;
}
}
@SuppressWarnings({"unchecked", "UnusedReturnValue"})
private RPCStreamController startRPCStream(InputStream is, PutFile request, SessionType sType, byte rpcSessionID, byte wiproVersion)
{
if (sdlSession == null) return null;
Long lSize = request.getLength();
if (lSize == null)
{
return null;
}
try {
StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer((SdlProxyBase<IProxyListenerBase>) this, sdlSession, is, request, sType, rpcSessionID, wiproVersion, lSize, sdlSession);
rpcPacketizer.start();
return new RPCStreamController(rpcPacketizer, request.getCorrelationID());
} catch (Exception e) {
Log.e("SyncConnection", "Unable to start streaming:" + e.toString());
return null;
}
}
private RPCStreamController startPutFileStream(String sPath, PutFile msg) {
if (sdlSession == null) return null;
return startRPCStream(sPath, msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion);
}
private RPCStreamController startPutFileStream(InputStream is, PutFile msg) {
if (sdlSession == null) return null;
if (is == null) return null;
return startRPCStream(is, msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion);
}
@SuppressWarnings("UnusedReturnValue")
public boolean startRPCStream(InputStream is, RPCRequest msg) {
if (sdlSession == null) return false;
sdlSession.startRPCStream(is, msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion);
return true;
}
public OutputStream startRPCStream(RPCRequest msg) {
if (sdlSession == null) return null;
return sdlSession.startRPCStream(msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion);
}
public void endRPCStream() {
if (sdlSession == null) return;
sdlSession.stopRPCStream();
}
private class CallableMethod implements Callable<Void> {
private final long waitTime;
public CallableMethod(int timeInMillis){
this.waitTime=timeInMillis;
}
@Override
public Void call() {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
public FutureTask<Void> createFutureTask(CallableMethod callMethod){
return new FutureTask<Void>(callMethod);
}
public ScheduledExecutorService createScheduler(){
return Executors.newSingleThreadScheduledExecutor();
}
@SuppressWarnings("unused")
public void startService(SessionType serviceType, boolean isEncrypted){
sdlSession.startService(serviceType, sdlSession.getSessionId(), isEncrypted);
}
@SuppressWarnings("unused")
public void endService(SessionType serviceType){
sdlSession.endService(serviceType, sdlSession.getSessionId());
}
/**
* @deprecated
*Opens the video service (serviceType 11) and subsequently streams raw H264 video from an InputStream provided by the app
*@return true if service is opened successfully and stream is started, return false otherwise
* @see #startRemoteDisplayStream(Context, Class, VideoStreamingParameters, boolean) startRemoteDisplayStream
* @see #startVideoStream(boolean, VideoStreamingParameters) startVideoStream
* @see #createOpenGLInputSurface(int, int, int, int, int, boolean) createOpenGLInputSurface
*/
@SuppressWarnings("unused")
@Deprecated
public boolean startH264(InputStream is, boolean isEncrypted) {
if (sdlSession == null) return false;
navServiceStartResponseReceived = false;
navServiceStartResponse = false;
navServiceStartRejectedParams = null;
// When startH264() API is used, we will not send video format / width / height information
// with StartService. (Reasons: InputStream does not provide timestamp information so RTP
// cannot be used. startH264() does not provide with/height information.)
VideoStreamingParameters emptyParam = new VideoStreamingParameters();
emptyParam.setResolution(null);
emptyParam.setFormat(null);
sdlSession.setDesiredVideoParams(emptyParam);
sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted);
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!navServiceStartResponseReceived && !fTask.isDone());
scheduler.shutdown();
if (navServiceStartResponse) {
try {
sdlSession.startStream(is, SessionType.NAV, sdlSession.getSessionId());
return true;
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
/**
* @deprecated
*Opens the video service (serviceType 11) and subsequently provides an OutputStream to the app to use for a raw H264 video stream
*@return OutputStream if service is opened successfully and stream is started, return null otherwise
* @see #startRemoteDisplayStream(Context, Class, VideoStreamingParameters, boolean) startRemoteDisplayStream
* @see #startVideoStream(boolean, VideoStreamingParameters) startVideoStream
* @see #createOpenGLInputSurface(int, int, int, int, int, boolean) createOpenGLInputSurface
*/
@SuppressWarnings("unused")
@Deprecated
public OutputStream startH264(boolean isEncrypted) {
if (sdlSession == null) return null;
navServiceStartResponseReceived = false;
navServiceStartResponse = false;
navServiceStartRejectedParams = null;
// When startH264() API is used, we will not send video format / width / height information
// with StartService. (Reasons: OutputStream does not provide timestamp information so RTP
// cannot be used. startH264() does not provide with/height information.)
VideoStreamingParameters emptyParam = new VideoStreamingParameters();
emptyParam.setResolution(null);
emptyParam.setFormat(null);
sdlSession.setDesiredVideoParams(emptyParam);
sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted);
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!navServiceStartResponseReceived && !fTask.isDone());
scheduler.shutdown();
if (navServiceStartResponse) {
try {
return sdlSession.startStream(SessionType.NAV, sdlSession.getSessionId());
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
/**
*Closes the opened video service (serviceType 11)
*@return true if the video service is closed successfully, return false otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public boolean endH264() {
return endVideoStream();
}
/**
*Pauses the stream for the opened audio service (serviceType 10)
*@return true if the audio service stream is paused successfully, return false otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public boolean pausePCM() {
return pauseAudioStream();
}
/**
*Pauses the stream for the opened video service (serviceType 11)
*@return true if the video service stream is paused successfully, return false otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public boolean pauseH264() {
return pauseVideoStream();
}
/**
*Resumes the stream for the opened audio service (serviceType 10)
*@return true if the audio service stream is resumed successfully, return false otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public boolean resumePCM() {
return resumeAudioStream();
}
/**
*Resumes the stream for the opened video service (serviceType 11)
*@return true if the video service is resumed successfully, return false otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public boolean resumeH264() {
return resumeVideoStream();
}
/**
*Opens the audio service (serviceType 10) and subsequently streams raw PCM audio from an InputStream provided by the app
*@return true if service is opened successfully and stream is started, return false otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public boolean startPCM(InputStream is, boolean isEncrypted) {
if (sdlSession == null) return false;
pcmServiceStartResponseReceived = false;
pcmServiceStartResponse = false;
sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted);
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!pcmServiceStartResponseReceived && !fTask.isDone());
scheduler.shutdown();
if (pcmServiceStartResponse) {
try {
sdlSession.startStream(is, SessionType.PCM, sdlSession.getSessionId());
return true;
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
/**
*Opens the audio service (serviceType 10) and subsequently provides an OutputStream to the app
*@return OutputStream if service is opened successfully and stream is started, return null otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public OutputStream startPCM(boolean isEncrypted) {
if (sdlSession == null) return null;
pcmServiceStartResponseReceived = false;
pcmServiceStartResponse = false;
sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted);
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!pcmServiceStartResponseReceived && !fTask.isDone());
scheduler.shutdown();
if (pcmServiceStartResponse) {
try {
return sdlSession.startStream(SessionType.PCM, sdlSession.getSessionId());
} catch (Exception e) {
return null;
}
} else {
if (pcmServiceStartRejectedParams != null) {
StringBuilder builder = new StringBuilder();
for (String paramName : pcmServiceStartRejectedParams) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(paramName);
}
DebugTool.logWarning("StartService for nav failed. Rejected params: " + builder.toString());
} else {
DebugTool.logWarning("StartService for nav failed (rejected params not supplied)");
}
return null;
}
}
/**
*Closes the opened audio service (serviceType 10)
*@return true if the audio service is closed successfully, return false otherwise
*/
@SuppressWarnings("unused")
@Deprecated
public boolean endPCM() {
return endAudioStream();
}
/**
* Opens a video service (service type 11) and subsequently provides an IVideoStreamListener
* to the app to send video data. The supplied VideoStreamingParameters will be set as desired paramaters
* that will be used to negotiate
*
* @param isEncrypted Specify true if packets on this service have to be encrypted
* @param parameters Video streaming parameters including: codec which will be used for streaming (currently, only
* VideoStreamingCodec.H264 is accepted), height and width of the video in pixels.
*
* @return IVideoStreamListener interface if service is opened successfully and streaming is
* started, null otherwise
*/
@SuppressWarnings("unused")
public IVideoStreamListener startVideoStream(boolean isEncrypted, VideoStreamingParameters parameters) {
if (sdlSession == null) {
DebugTool.logWarning("SdlSession is not created yet.");
return null;
}
if (sdlSession.getSdlConnection() == null) {
DebugTool.logWarning("SdlConnection is not available.");
return null;
}
sdlSession.setDesiredVideoParams(parameters);
VideoStreamingParameters acceptedParams = tryStartVideoStream(isEncrypted, parameters);
if (acceptedParams != null) {
return sdlSession.startVideoStream();
} else if(getWiProVersion() < 5){
sdlSession.setAcceptedVideoParams(new VideoStreamingParameters());
return sdlSession.startVideoStream();
} else {
return null;
}
}
/**
*Closes the opened video service (serviceType 11)
*@return true if the video service is closed successfully, return false otherwise
*/
@SuppressWarnings("unused")
public boolean endVideoStream() {
if (sdlSession == null){ return false; }
navServiceEndResponseReceived = false;
navServiceEndResponse = false;
sdlSession.stopVideoStream();
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!navServiceEndResponseReceived && !fTask.isDone());
scheduler.shutdown();
return navServiceEndResponse;
}
/**
*Pauses the stream for the opened video service (serviceType 11)
*@return true if the video service stream is paused successfully, return false otherwise
*/
@SuppressWarnings("unused")
public boolean pauseVideoStream() {
return sdlSession != null && sdlSession.pauseVideoStream();
}
/**
*Resumes the stream for the opened video service (serviceType 11)
*@return true if the video service is resumed successfully, return false otherwise
*/
@SuppressWarnings("unused")
public boolean resumeVideoStream() {
return sdlSession != null && sdlSession.resumeVideoStream();
}
/**
* Opens the video service (serviceType 11) and creates a Surface (used for streaming video) with input parameters provided by the app
* @param frameRate - specified rate of frames to utilize for creation of Surface
* @param iFrameInterval - specified interval to utilize for creation of Surface
* @param width - specified width to utilize for creation of Surface
* @param height - specified height to utilize for creation of Surface
* @param bitrate - specified bitrate to utilize for creation of Surface
*@return Surface if service is opened successfully and stream is started, return null otherwise
*/
@SuppressWarnings("unused")
public Surface createOpenGLInputSurface(int frameRate, int iFrameInterval, int width,
int height, int bitrate, boolean isEncrypted) {
if (sdlSession == null || sdlSession.getSdlConnection() == null){
return null;
}
VideoStreamingParameters desired = new VideoStreamingParameters();
desired.setFrameRate(frameRate);
desired.setInterval(iFrameInterval);
ImageResolution resolution = new ImageResolution();
resolution.setResolutionWidth(width);
resolution.setResolutionHeight(height);
desired.setResolution(resolution);
desired.setBitrate(bitrate);
VideoStreamingParameters acceptedParams = tryStartVideoStream(isEncrypted, desired);
if (acceptedParams != null) {
return sdlSession.createOpenGLInputSurface(frameRate, iFrameInterval, width,
height, bitrate, SessionType.NAV, sdlSession.getSessionId());
} else {
return null;
}
}
/**
* Starts streaming a remote display to the module if there is a connected session. This method of streaming requires the device to be on API level 19 or higher
* @param context a context that can be used to create the remote display
* @param remoteDisplay class object of the remote display. This class will be used to create an instance of the remote display and will be projected to the module
* @param parameters streaming parameters to be used when streaming. If null is sent in, the default/optimized options will be used.
* If you are unsure about what parameters to be used it is best to just send null and let the system determine what
* works best for the currently connected module.
*
* @param encrypted a flag of if the stream should be encrypted. Only set if you have a supplied encryption library that the module can understand.
*/
@TargetApi(19)
public void startRemoteDisplayStream(Context context, final Class<? extends SdlRemoteDisplay> remoteDisplay, final VideoStreamingParameters parameters, final boolean encrypted){
if(getWiProVersion() >= 5 && !_systemCapabilityManager.isCapabilitySupported(SystemCapabilityType.VIDEO_STREAMING)){
Log.e(TAG, "Video streaming not supported on this module");
return;
}
//Create streaming manager
if(manager == null){
manager = new VideoStreamingManager(context,this._internalInterface);
}
if(parameters == null){
if(getWiProVersion() >= 5) {
_systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING, new OnSystemCapabilityListener() {
@Override
public void onCapabilityRetrieved(Object capability) {
VideoStreamingParameters params = new VideoStreamingParameters();
params.update((VideoStreamingCapability)capability); //Streaming parameters are ready time to stream
sdlSession.setDesiredVideoParams(params);
manager.startVideoStreaming(remoteDisplay, params, encrypted);
}
@Override
public void onError(String info) {
Log.e(TAG, "Error retrieving video streaming capability: " + info);
}
});
}else{
//We just use default video streaming params
VideoStreamingParameters params = new VideoStreamingParameters();
DisplayCapabilities dispCap = (DisplayCapabilities)_systemCapabilityManager.getCapability(SystemCapabilityType.DISPLAY);
if(dispCap !=null){
params.setResolution(dispCap.getScreenParams().getImageResolution());
}
sdlSession.setDesiredVideoParams(params);
manager.startVideoStreaming(remoteDisplay,params, encrypted);
}
}else{
sdlSession.setDesiredVideoParams(parameters);
manager.startVideoStreaming(remoteDisplay,parameters, encrypted);
}
}
/**
* Stops the remote display stream if one has been started
*/
public void stopRemoteDisplayStream(){
if(manager!=null){
manager.dispose();
}
manager = null;
}
/**
* Try to open a video service by using the video streaming parameters supplied.
*
* Only information from codecs, width and height are used during video format negotiation.
*
* @param isEncrypted Specify true if packets on this service have to be encrypted
* @param parameters VideoStreamingParameters that are desired. Does not guarantee this is what will be accepted.
*
* @return If the service is opened successfully, an instance of VideoStreamingParams is
* returned which contains accepted video format. If the service is opened with legacy
* mode (i.e. without any negotiation) then an instance of VideoStreamingParams is
* returned. If the service was not opened then null is returned.
*/
@SuppressWarnings("unused")
private VideoStreamingParameters tryStartVideoStream(boolean isEncrypted, VideoStreamingParameters parameters) {
if (sdlSession == null) {
DebugTool.logWarning("SdlSession is not created yet.");
return null;
}
if(getWiProVersion() >= 5 && !_systemCapabilityManager.isCapabilitySupported(SystemCapabilityType.VIDEO_STREAMING)){
DebugTool.logWarning("Module doesn't support video streaming.");
return null;
}
if (parameters == null) {
DebugTool.logWarning("Video parameters were not supplied.");
return null;
}
sdlSession.setDesiredVideoParams(parameters);
navServiceStartResponseReceived = false;
navServiceStartResponse = false;
navServiceStartRejectedParams = null;
sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted);
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!navServiceStartResponseReceived && !fTask.isDone());
scheduler.shutdown();
if (navServiceStartResponse) {
return sdlSession.getAcceptedVideoParams();
}
if (navServiceStartRejectedParams != null) {
StringBuilder builder = new StringBuilder();
for (String paramName : navServiceStartRejectedParams) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(paramName);
}
DebugTool.logWarning("StartService for nav failed. Rejected params: " + builder.toString());
} else {
DebugTool.logWarning("StartService for nav failed (rejected params not supplied)");
}
return null;
}
/**
*Starts the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method
*/
@SuppressWarnings("unused")
public void startEncoder () {
if (sdlSession == null) return;
SdlConnection sdlConn = sdlSession.getSdlConnection();
if (sdlConn == null) return;
sdlSession.startEncoder();
}
/**
*Releases the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method
*/
@SuppressWarnings("unused")
public void releaseEncoder() {
if (sdlSession == null) return;
SdlConnection sdlConn = sdlSession.getSdlConnection();
if (sdlConn == null) return;
sdlSession.releaseEncoder();
}
/**
*Releases the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method
*/
@SuppressWarnings("unused")
public void drainEncoder(boolean endOfStream) {
if (sdlSession == null) return;
SdlConnection sdlConn = sdlSession.getSdlConnection();
if (sdlConn == null) return;
sdlSession.drainEncoder(endOfStream);
}
/**
* Opens a audio service (service type 10) and subsequently provides an IAudioStreamListener
* to the app to send audio data.
*
* Currently information passed by "params" are ignored, since Audio Streaming feature lacks
* capability negotiation mechanism. App should configure audio stream data to align with
* head unit's capability by checking (upcoming) pcmCapabilities. The default format is in
* 16kHz and 16 bits.
*
* @param isEncrypted Specify true if packets on this service have to be encrypted
* @param codec Audio codec which will be used for streaming. Currently, only
* AudioStreamingCodec.LPCM is accepted.
* @param params (Reserved for future use) Additional configuration information for each
* codec. If "codec" is AudioStreamingCodec.LPCM, "params" must be an
* instance of LPCMParams class.
*
* @return IAudioStreamListener interface if service is opened successfully and streaming is
* started, null otherwise
*/
@SuppressWarnings("unused")
public IAudioStreamListener startAudioStream(boolean isEncrypted, AudioStreamingCodec codec,
AudioStreamingParams params) {
if (sdlSession == null) {
DebugTool.logWarning("SdlSession is not created yet.");
return null;
}
if (sdlSession.getSdlConnection() == null) {
DebugTool.logWarning("SdlConnection is not available.");
return null;
}
if (codec != AudioStreamingCodec.LPCM) {
DebugTool.logWarning("Audio codec " + codec + " is not supported.");
return null;
}
pcmServiceStartResponseReceived = false;
pcmServiceStartResponse = false;
sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted);
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!pcmServiceStartResponseReceived && !fTask.isDone());
scheduler.shutdown();
if (pcmServiceStartResponse) {
DebugTool.logInfo("StartService for audio succeeded");
return sdlSession.startAudioStream();
} else {
if (pcmServiceStartRejectedParams != null) {
StringBuilder builder = new StringBuilder();
for (String paramName : pcmServiceStartRejectedParams) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(paramName);
}
DebugTool.logWarning("StartService for audio failed. Rejected params: " + builder.toString());
} else {
DebugTool.logWarning("StartService for audio failed (rejected params not supplied)");
}
return null;
}
}
/**
*Closes the opened audio service (serviceType 10)
*@return true if the audio service is closed successfully, return false otherwise
*/
@SuppressWarnings("unused")
public boolean endAudioStream() {
if (sdlSession == null) return false;
SdlConnection sdlConn = sdlSession.getSdlConnection();
if (sdlConn == null) return false;
pcmServiceEndResponseReceived = false;
pcmServiceEndResponse = false;
sdlSession.stopAudioStream();
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!pcmServiceEndResponseReceived && !fTask.isDone());
scheduler.shutdown();
return pcmServiceEndResponse;
}
/**
*Pauses the stream for the opened audio service (serviceType 10)
*@return true if the audio service stream is paused successfully, return false otherwise
*/
@SuppressWarnings("unused")
public boolean pauseAudioStream() {
return sdlSession != null && sdlSession.pauseAudioStream();
}
/**
*Resumes the stream for the opened audio service (serviceType 10)
*@return true if the audio service stream is resumed successfully, return false otherwise
*/
@SuppressWarnings("unused")
public boolean resumeAudioStream() {
return sdlSession != null && sdlSession.resumeAudioStream();
}
private void NavServiceStarted() {
navServiceStartResponseReceived = true;
navServiceStartResponse = true;
}
private void NavServiceStartedNACK(List<String> rejectedParams) {
navServiceStartResponseReceived = true;
navServiceStartResponse = false;
navServiceStartRejectedParams = rejectedParams;
}
private void AudioServiceStarted() {
pcmServiceStartResponseReceived = true;
pcmServiceStartResponse = true;
}
private void RPCProtectedServiceStarted() {
rpcProtectedResponseReceived = true;
rpcProtectedStartResponse = true;
}
private void AudioServiceStartedNACK(List<String> rejectedParams) {
pcmServiceStartResponseReceived = true;
pcmServiceStartResponse = false;
pcmServiceStartRejectedParams = rejectedParams;
}
private void NavServiceEnded() {
navServiceEndResponseReceived = true;
navServiceEndResponse = true;
}
private void NavServiceEndedNACK() {
navServiceEndResponseReceived = true;
navServiceEndResponse = false;
}
private void AudioServiceEnded() {
pcmServiceEndResponseReceived = true;
pcmServiceEndResponse = true;
}
private void AudioServiceEndedNACK() {
pcmServiceEndResponseReceived = true;
pcmServiceEndResponse = false;
}
public void setAppService(Service mService)
{
_appService = mService;
}
@SuppressWarnings("unused")
public boolean startProtectedRPCService() {
rpcProtectedResponseReceived = false;
rpcProtectedStartResponse = false;
sdlSession.startService(SessionType.RPC, sdlSession.getSessionId(), true);
FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME));
ScheduledExecutorService scheduler = createScheduler();
scheduler.execute(fTask);
//noinspection StatementWithEmptyBody
while (!rpcProtectedResponseReceived && !fTask.isDone());
scheduler.shutdown();
return rpcProtectedStartResponse;
}
@SuppressWarnings("unused")
public void getLockScreenIcon(final OnLockScreenIconDownloadedListener l){
if(lockScreenIconRequest == null){
l.onLockScreenIconDownloadError(new SdlException("This version of SDL core may not support lock screen icons.",
SdlExceptionCause.LOCK_SCREEN_ICON_NOT_SUPPORTED));
return;
}
LockScreenManager lockMan = sdlSession.getLockScreenMan();
Bitmap bitmap = lockMan.getLockScreenIcon();
// read bitmap if it was already downloaded so we don't have to download it every time
if(bitmap != null){
l.onLockScreenIconDownloaded(bitmap);
}
else{
String url = lockScreenIconRequest.getUrl();
sdlSession.getLockScreenMan().downloadLockScreenIcon(url, l);
}
}
/*Begin V1 Enhanced helper*/
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param parentID -Menu parent ID for optional sub value containing menu parameters.
*@param position -Menu position for optional sub value containing menu parameters.
*@param vrCommands -VR synonyms for this AddCommand.
*@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC).
*@param IconType -Describes whether the image is static or dynamic
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("SameParameterValue")
public void addCommand(Integer commandID,
String menuText, Integer parentID, Integer position,
Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID)
throws SdlException {
AddCommand msg = RPCRequestFactory.buildAddCommand(commandID, menuText, parentID, position,
vrCommands, IconValue, IconType, correlationID);
sendRPCRequest(msg);
}
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param position -Menu position for optional sub value containing menu parameters.
*@param vrCommands -VR synonyms for this AddCommand.
*@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC).
*@param IconType -Describes whether the image is static or dynamic
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, Integer position,
Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, position, vrCommands, IconValue, IconType, correlationID);
}
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param position -Menu position for optional sub value containing menu parameters.
*@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC).
*@param IconType -Describes whether the image is static or dynamic
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, Integer position, String IconValue, ImageType IconType,
Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, position, null, IconValue, IconType, correlationID);
}
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC).
*@param IconType -Describes whether the image is static or dynamic
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, String IconValue, ImageType IconType, Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, null, null, IconValue, IconType, correlationID);
}
/**
* Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param commandID -Unique command ID of the command to add.
* @param menuText -Menu text for optional sub value containing menu parameters.
* @param vrCommands -VR synonyms for this AddCommand.
* @param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC).
* @param IconType -Describes whether the image is static or dynamic
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, null, vrCommands, IconValue, IconType, correlationID);
}
/**
* Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param commandID -Unique command ID of the command to add.
* @param vrCommands -VR synonyms for this AddCommand.
* @param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC).
* @param IconType -Describes whether the image is static or dynamic
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID)
throws SdlException {
addCommand(commandID, null, null, null, vrCommands, IconValue, IconType, correlationID);
}
/*End V1 Enhanced helper*/
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param parentID -Menu parent ID for optional sub value containing menu parameters.
*@param position -Menu position for optional sub value containing menu parameters.
*@param vrCommands -VR synonyms for this AddCommand.
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("SameParameterValue")
public void addCommand(Integer commandID,
String menuText, Integer parentID, Integer position,
Vector<String> vrCommands, Integer correlationID)
throws SdlException {
AddCommand msg = RPCRequestFactory.buildAddCommand(commandID, menuText, parentID, position,
vrCommands, correlationID);
sendRPCRequest(msg);
}
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param position -Menu position for optional sub value containing menu parameters.
*@param vrCommands -VR synonyms for this AddCommand.
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, Integer position,
Vector<String> vrCommands, Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, position, vrCommands, correlationID);
}
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param position -Menu position for optional sub value containing menu parameters.
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, Integer position,
Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, position, null, correlationID);
}
/**
*Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, null, (Vector<String>)null, correlationID);
}
/**
* Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param menuText -Menu text for optional sub value containing menu parameters.
*@param vrCommands -VR synonyms for this AddCommand.
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
String menuText, Vector<String> vrCommands, Integer correlationID)
throws SdlException {
addCommand(commandID, menuText, null, null, vrCommands, correlationID);
}
/**
* Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
*@param commandID -Unique command ID of the command to add.
*@param vrCommands -VR synonyms for this AddCommand.
*@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addCommand(Integer commandID,
Vector<String> vrCommands, Integer correlationID)
throws SdlException {
addCommand(commandID, null, null, null, vrCommands, correlationID);
}
/**
* Sends an AddSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param menuID -Unique ID of the sub menu to add.
* @param menuName -Text to show in the menu for this sub menu.
* @param position -Position within the items that are are at top level of the in application menu.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("SameParameterValue")
public void addSubMenu(Integer menuID, String menuName,
Integer position, Integer correlationID)
throws SdlException {
AddSubMenu msg = RPCRequestFactory.buildAddSubMenu(menuID, menuName,
position, correlationID);
sendRPCRequest(msg);
}
/**
* Sends an AddSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param menuID -Unique ID of the sub menu to add.
* @param menuName -Text to show in the menu for this sub menu.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void addSubMenu(Integer menuID, String menuName,
Integer correlationID) throws SdlException {
addSubMenu(menuID, menuName, null, correlationID);
}
/*Begin V1 Enhanced helper*/
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsText -The text to speech message in the form of a string.
* @param alertText1 -The first line of the alert text field.
* @param alertText2 -The second line of the alert text field.
* @param alertText3 -The optional third line of the alert text field.
* @param playTone -Defines if tone should be played.
* @param duration -Timeout in milliseconds.
* @param softButtons -A list of App defined SoftButtons.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("SameParameterValue")
public void alert(String ttsText, String alertText1,
String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons,
Integer correlationID) throws SdlException {
Alert msg = RPCRequestFactory.buildAlert(ttsText, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID);
sendRPCRequest(msg);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsChunks -Text/phonemes to speak in the form of ttsChunks.
* @param alertText1 -The first line of the alert text field.
* @param alertText2 -The second line of the alert text field.
* @param alertText3 -The optional third line of the alert text field.
* @param playTone -Defines if tone should be played.
* @param duration -Timeout in milliseconds.
* @param softButtons -A list of App defined SoftButtons.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
public void alert(Vector<TTSChunk> ttsChunks,
String alertText1, String alertText2, String alertText3, Boolean playTone,
Integer duration, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException {
Alert msg = RPCRequestFactory.buildAlert(ttsChunks, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID);
sendRPCRequest(msg);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsText -The text to speech message in the form of a string.
* @param playTone -Defines if tone should be played.
* @param softButtons -A list of App defined SoftButtons.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void alert(String ttsText, Boolean playTone, Vector<SoftButton> softButtons,
Integer correlationID) throws SdlException {
alert(ttsText, null, null, null, playTone, null, softButtons, correlationID);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param chunks -A list of text/phonemes to speak in the form of ttsChunks.
* @param playTone -Defines if tone should be played.
* @param softButtons -A list of App defined SoftButtons.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void alert(Vector<TTSChunk> chunks, Boolean playTone, Vector<SoftButton> softButtons,
Integer correlationID) throws SdlException {
alert(chunks, null, null, null, playTone, null, softButtons, correlationID);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param alertText1 -The first line of the alert text field.
* @param alertText2 -The second line of the alert text field.
* @param alertText3 -The optional third line of the alert text field.
* @param playTone -Defines if tone should be played.
* @param duration -Timeout in milliseconds.
* @param softButtons -A list of App defined SoftButtons.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void alert(String alertText1, String alertText2, String alertText3,
Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID)
throws SdlException {
alert((Vector<TTSChunk>)null, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID);
}
/*End V1 Enhanced helper*/
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsText -The text to speech message in the form of a string.
* @param alertText1 -The first line of the alert text field.
* @param alertText2 -The second line of the alert text field.
* @param playTone -Defines if tone should be played.
* @param duration -Timeout in milliseconds.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("SameParameterValue")
public void alert(String ttsText, String alertText1,
String alertText2, Boolean playTone, Integer duration,
Integer correlationID) throws SdlException {
Alert msg = RPCRequestFactory.buildAlert(ttsText, alertText1, alertText2,
playTone, duration, correlationID);
sendRPCRequest(msg);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsChunks -A list of text/phonemes to speak in the form of ttsChunks.
* @param alertText1 -The first line of the alert text field.
* @param alertText2 -The second line of the alert text field.
* @param playTone -Defines if tone should be played.
* @param duration -Timeout in milliseconds.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
public void alert(Vector<TTSChunk> ttsChunks,
String alertText1, String alertText2, Boolean playTone,
Integer duration, Integer correlationID) throws SdlException {
Alert msg = RPCRequestFactory.buildAlert(ttsChunks, alertText1, alertText2, playTone,
duration, correlationID);
sendRPCRequest(msg);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsText -The text to speech message in the form of a string.
* @param playTone -Defines if tone should be played.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void alert(String ttsText, Boolean playTone,
Integer correlationID) throws SdlException {
alert(ttsText, null, null, playTone, null, correlationID);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param chunks -A list of text/phonemes to speak in the form of ttsChunks.
* @param playTone -Defines if tone should be played.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void alert(Vector<TTSChunk> chunks, Boolean playTone,
Integer correlationID) throws SdlException {
alert(chunks, null, null, playTone, null, correlationID);
}
/**
* Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param alertText1 -The first line of the alert text field.
* @param alertText2 -The second line of the alert text field.
* @param playTone -Defines if tone should be played.
* @param duration -Timeout in milliseconds.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void alert(String alertText1, String alertText2,
Boolean playTone, Integer duration, Integer correlationID)
throws SdlException {
alert((Vector<TTSChunk>)null, alertText1, alertText2, playTone, duration, correlationID);
}
/**
* Sends a CreateInteractionChoiceSet RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param choiceSet to be sent to the module
* @param interactionChoiceSetID to be used in reference to the supplied choiceSet
* @param correlationID to be set to the RPCRequest
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void createInteractionChoiceSet(
Vector<Choice> choiceSet, Integer interactionChoiceSetID,
Integer correlationID) throws SdlException {
CreateInteractionChoiceSet msg = RPCRequestFactory.buildCreateInteractionChoiceSet(
choiceSet, interactionChoiceSetID, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a DeleteCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param commandID -ID of the command(s) to delete.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void deleteCommand(Integer commandID,
Integer correlationID) throws SdlException {
DeleteCommand msg = RPCRequestFactory.buildDeleteCommand(commandID, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a DeleteInteractionChoiceSet RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param interactionChoiceSetID -ID of the interaction choice set to delete.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void deleteInteractionChoiceSet(
Integer interactionChoiceSetID, Integer correlationID)
throws SdlException {
DeleteInteractionChoiceSet msg = RPCRequestFactory.buildDeleteInteractionChoiceSet(
interactionChoiceSetID, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a DeleteSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param menuID -The menuID of the submenu to delete.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void deleteSubMenu(Integer menuID,
Integer correlationID) throws SdlException {
DeleteSubMenu msg = RPCRequestFactory.buildDeleteSubMenu(menuID, correlationID);
sendRPCRequest(msg);
}
/*Begin V1 Enhanced helper*/
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initPrompt -Intial prompt spoken to the user at the start of an interaction.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction.
* @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(String initPrompt,
String displayText, Integer interactionChoiceSetID, Vector<VrHelpItem> vrHelp,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt,
displayText, interactionChoiceSetID, vrHelp, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initPrompt -Intial prompt spoken to the user at the start of an interaction.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction.
* @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction.
* @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out.
* @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both).
* @param timeout -Timeout in milliseconds.
* @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(String initPrompt,
String displayText, Integer interactionChoiceSetID,
String helpPrompt, String timeoutPrompt,
InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(
initPrompt, displayText, interactionChoiceSetID,
helpPrompt, timeoutPrompt, interactionMode,
timeout, vrHelp, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initPrompt -Intial prompt spoken to the user at the start of an interaction.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction.
* @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction.
* @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out.
* @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both).
* @param timeout -Timeout in milliseconds.
* @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(String initPrompt,
String displayText, Vector<Integer> interactionChoiceSetIDList,
String helpPrompt, String timeoutPrompt,
InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt,
displayText, interactionChoiceSetIDList,
helpPrompt, timeoutPrompt, interactionMode, timeout, vrHelp,
correlationID);
sendRPCRequest(msg);
}
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initChunks -A list of text/phonemes to speak for the initial prompt in the form of ttsChunks.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction.
* @param helpChunks -A list of text/phonemes to speak for the help text that is spoken when a user speaks "help" during the interaction.
* @param timeoutChunks A list of text/phonems to speak for the timeout text that is spoken when a VR interaction times out.
* @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both).
* @param timeout -Timeout in milliseconds.
* @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(
Vector<TTSChunk> initChunks, String displayText,
Vector<Integer> interactionChoiceSetIDList,
Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks,
InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(
initChunks, displayText, interactionChoiceSetIDList,
helpChunks, timeoutChunks, interactionMode, timeout,vrHelp,
correlationID);
sendRPCRequest(msg);
}
/*End V1 Enhanced*/
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initPrompt -Intial prompt spoken to the user at the start of an interaction.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(String initPrompt,
String displayText, Integer interactionChoiceSetID,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt,
displayText, interactionChoiceSetID, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initPrompt -Intial prompt spoken to the user at the start of an interaction.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction.
* @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction.
* @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out.
* @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both).
* @param timeout -Timeout in milliseconds.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(String initPrompt,
String displayText, Integer interactionChoiceSetID,
String helpPrompt, String timeoutPrompt,
InteractionMode interactionMode, Integer timeout,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(
initPrompt, displayText, interactionChoiceSetID,
helpPrompt, timeoutPrompt, interactionMode,
timeout, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initPrompt -Intial prompt spoken to the user at the start of an interaction.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction.
* @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction.
* @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out.
* @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both).
* @param timeout -Timeout in milliseconds.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(String initPrompt,
String displayText, Vector<Integer> interactionChoiceSetIDList,
String helpPrompt, String timeoutPrompt,
InteractionMode interactionMode, Integer timeout,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt,
displayText, interactionChoiceSetIDList,
helpPrompt, timeoutPrompt, interactionMode, timeout,
correlationID);
sendRPCRequest(msg);
}
/**
* Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param initChunks -A list of text/phonemes to speak for the initial prompt in the form of ttsChunks.
* @param displayText -Text to be displayed first.
* @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction.
* @param helpChunks -A list of text/phonemes to speak for the help text that is spoken when a user speaks "help" during the interaction.
* @param timeoutChunks A list of text/phonems to speak for the timeout text that is spoken when a VR interaction times out.
* @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both).
* @param timeout -Timeout in milliseconds.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performInteraction(
Vector<TTSChunk> initChunks, String displayText,
Vector<Integer> interactionChoiceSetIDList,
Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks,
InteractionMode interactionMode, Integer timeout,
Integer correlationID) throws SdlException {
PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(
initChunks, displayText, interactionChoiceSetIDList,
helpChunks, timeoutChunks, interactionMode, timeout,
correlationID);
sendRPCRequest(msg);
}
// Protected registerAppInterface used to ensure only non-ALM applications call
// reqisterAppInterface
protected void registerAppInterfacePrivate(
SdlMsgVersion sdlMsgVersion, String appName, Vector<TTSChunk> ttsName,
String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp,
Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType,
String appID, Integer correlationID)
throws SdlException {
String carrierName = null;
if(telephonyManager != null){
carrierName = telephonyManager.getNetworkOperatorName();
}
deviceInfo = RPCRequestFactory.BuildDeviceInfo(carrierName);
RegisterAppInterface msg = RPCRequestFactory.buildRegisterAppInterface(
sdlMsgVersion, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp,
languageDesired, hmiDisplayLanguageDesired, appType, appID, correlationID, deviceInfo);
if (_bAppResumeEnabled)
{
if (_lastHashID != null)
msg.setHashID(_lastHashID);
}
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.REGISTER_APP_INTERFACE.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_REQUEST);
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg));
sendBroadcastIntent(sendIntent);
sendRPCRequestPrivate(msg);
}
/*Begin V1 Enhanced helper function*/
/**
* Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param helpPrompt that will be used for the VR screen
* @param timeoutPrompt string to be displayed after timeout
* @param vrHelpTitle string that may be displayed on VR prompt dialog
* @param vrHelp a list of VR synonyms that may be displayed to user
* @param correlationID to be attached to the request
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void setGlobalProperties(
String helpPrompt, String timeoutPrompt, String vrHelpTitle, Vector<VrHelpItem> vrHelp, Integer correlationID)
throws SdlException {
SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties(helpPrompt,
timeoutPrompt, vrHelpTitle, vrHelp, correlationID);
sendRPCRequest(req);
}
/**
* Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param helpChunks tts chunks that should be used when prompting the user
* @param timeoutChunks tts chunks that will be used when a timeout occurs
* @param vrHelpTitle string that may be displayed on VR prompt dialog
* @param vrHelp a list of VR synonyms that may be displayed to user
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void setGlobalProperties(
Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, String vrHelpTitle, Vector<VrHelpItem> vrHelp,
Integer correlationID) throws SdlException {
SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties(
helpChunks, timeoutChunks, vrHelpTitle, vrHelp, correlationID);
sendRPCRequest(req);
}
/*End V1 Enhanced helper function*/
/**
* Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param helpPrompt that will be used for the VR screen
* @param timeoutPrompt string to be displayed after timeout
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void setGlobalProperties(
String helpPrompt, String timeoutPrompt, Integer correlationID)
throws SdlException {
SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties(helpPrompt,
timeoutPrompt, correlationID);
sendRPCRequest(req);
}
/**
* Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param helpChunks tts chunks that should be used when prompting the user
* @param timeoutChunks tts chunks that will be used when a timeout occurs
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void setGlobalProperties(
Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks,
Integer correlationID) throws SdlException {
SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties(
helpChunks, timeoutChunks, correlationID);
sendRPCRequest(req);
}
@SuppressWarnings("unused")
public void resetGlobalProperties(Vector<GlobalProperty> properties,
Integer correlationID) throws SdlException {
ResetGlobalProperties req = new ResetGlobalProperties();
req.setCorrelationID(correlationID);
req.setProperties(properties);
sendRPCRequest(req);
}
/**
* Sends a SetMediaClockTimer RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param hours integer for hours
* @param minutes integer for minutes
* @param seconds integer for seconds
* @param updateMode mode in which the media clock timer should be updated
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void setMediaClockTimer(Integer hours,
Integer minutes, Integer seconds, UpdateMode updateMode,
Integer correlationID) throws SdlException {
SetMediaClockTimer msg = RPCRequestFactory.buildSetMediaClockTimer(hours,
minutes, seconds, updateMode, correlationID);
sendRPCRequest(msg);
}
/**
* Pauses the media clock. Responses are captured through callback on IProxyListener.
*
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void pauseMediaClockTimer(Integer correlationID)
throws SdlException {
SetMediaClockTimer msg = RPCRequestFactory.buildSetMediaClockTimer(0,
0, 0, UpdateMode.PAUSE, correlationID);
sendRPCRequest(msg);
}
/**
* Resumes the media clock. Responses are captured through callback on IProxyListener.
*
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void resumeMediaClockTimer(Integer correlationID)
throws SdlException {
SetMediaClockTimer msg = RPCRequestFactory.buildSetMediaClockTimer(0,
0, 0, UpdateMode.RESUME, correlationID);
sendRPCRequest(msg);
}
/**
* Clears the media clock. Responses are captured through callback on IProxyListener.
*
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void clearMediaClockTimer(Integer correlationID)
throws SdlException {
Show msg = RPCRequestFactory.buildShow(null, null, null, " ", null, null, correlationID);
sendRPCRequest(msg);
}
/*Begin V1 Enhanced helper*/
/**
* Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param mainText1 text displayed in a single or upper display line.
* @param mainText2 text displayed on the second display line.
* @param mainText3 text displayed on the second "page" first display line.
* @param mainText4 text displayed on the second "page" second display line.
* @param statusBar text is placed in the status bar area (Only valid for NAVIGATION apps)
* @param mediaClock text value for MediaClock field.
* @param mediaTrack text displayed in the track field.
* @param graphic image struct determining whether static or dynamic image to display in app.
* @param softButtons app defined SoftButtons.
* @param customPresets app labeled on-screen presets.
* @param alignment specifies how mainText1 and mainText2s texts should be aligned on display.
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("SameParameterValue")
public void show(String mainText1, String mainText2, String mainText3, String mainText4,
String statusBar, String mediaClock, String mediaTrack,
Image graphic, Vector<SoftButton> softButtons, Vector <String> customPresets,
TextAlignment alignment, Integer correlationID)
throws SdlException {
Show msg = RPCRequestFactory.buildShow(mainText1, mainText2, mainText3, mainText4,
statusBar, mediaClock, mediaTrack, graphic, softButtons, customPresets,
alignment, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param mainText1 -Text displayed in a single or upper display line.
* @param mainText2 -Text displayed on the second display line.
* @param mainText3 -Text displayed on the second "page" first display line.
* @param mainText4 -Text displayed on the second "page" second display line.
* @param graphic -Image struct determining whether static or dynamic image to display in app.
* @param softButtons -App defined SoftButtons.
* @param customPresets -App labeled on-screen presets.
* @param alignment -Specifies how mainText1 and mainText2s texts should be aligned on display.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void show(String mainText1, String mainText2, String mainText3, String mainText4,
Image graphic, Vector<SoftButton> softButtons, Vector <String> customPresets,
TextAlignment alignment, Integer correlationID)
throws SdlException {
show(mainText1, mainText2, mainText3, mainText4, null, null, null, graphic, softButtons, customPresets, alignment, correlationID);
}
/*End V1 Enhanced helper*/
/**
* Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param mainText1 text displayed in a single or upper display line.
* @param mainText2 text displayed on the second display line.
* @param statusBar text is placed in the status bar area (Only valid for NAVIGATION apps)
* @param mediaClock text value for MediaClock field.
* @param mediaTrack text displayed in the track field.
* @param alignment specifies how mainText1 and mainText2s texts should be aligned on display.
* @param correlationID unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("SameParameterValue")
public void show(String mainText1, String mainText2,
String statusBar, String mediaClock, String mediaTrack,
TextAlignment alignment, Integer correlationID)
throws SdlException {
Show msg = RPCRequestFactory.buildShow(mainText1, mainText2,
statusBar, mediaClock, mediaTrack,
alignment, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param mainText1 -Text displayed in a single or upper display line.
* @param mainText2 -Text displayed on the second display line.
* @param alignment -Specifies how mainText1 and mainText2s texts should be aligned on display.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void show(String mainText1, String mainText2,
TextAlignment alignment, Integer correlationID)
throws SdlException {
show(mainText1, mainText2, null, null, null, alignment, correlationID);
}
/**
* Sends a Speak RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsText -The text to speech message in the form of a string.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void speak(String ttsText, Integer correlationID)
throws SdlException {
Speak msg = RPCRequestFactory.buildSpeak(TTSChunkFactory.createSimpleTTSChunks(ttsText),
correlationID);
sendRPCRequest(msg);
}
/**
* Sends a Speak RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param ttsChunks -Text/phonemes to speak in the form of ttsChunks.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void speak(Vector<TTSChunk> ttsChunks,
Integer correlationID) throws SdlException {
Speak msg = RPCRequestFactory.buildSpeak(ttsChunks, correlationID);
sendRPCRequest(msg);
}
/**
* Sends a SubscribeButton RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param buttonName -Name of the button to subscribe.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void subscribeButton(ButtonName buttonName,
Integer correlationID) throws SdlException {
SubscribeButton msg = RPCRequestFactory.buildSubscribeButton(buttonName,
correlationID);
sendRPCRequest(msg);
}
// Protected unregisterAppInterface used to ensure no non-ALM app calls
// unregisterAppInterface.
protected void unregisterAppInterfacePrivate(Integer correlationID)
throws SdlException {
UnregisterAppInterface msg =
RPCRequestFactory.buildUnregisterAppInterface(correlationID);
Intent sendIntent = createBroadcastIntent();
updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString());
updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_REQUEST);
updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID());
updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg));
sendBroadcastIntent(sendIntent);
sendRPCRequestPrivate(msg);
}
/**
* Sends an UnsubscribeButton RPCRequest to SDL. Responses are captured through callback on IProxyListener.
*
* @param buttonName -Name of the button to unsubscribe.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void unsubscribeButton(ButtonName buttonName,
Integer correlationID) throws SdlException {
UnsubscribeButton msg = RPCRequestFactory.buildUnsubscribeButton(
buttonName, correlationID);
sendRPCRequest(msg);
}
/**
* Creates a choice to be added to a choiceset. Choice has both a voice and a visual menu component.
*
* @param choiceID -Unique ID used to identify this choice (returned in callback).
* @param choiceMenuName -Text name displayed for this choice.
* @param choiceVrCommands -Vector of vrCommands used to select this choice by voice. Must contain
* at least one non-empty element.
* @return Choice created.
*/
@SuppressWarnings("unused")
public Choice createChoiceSetChoice(Integer choiceID, String choiceMenuName,
Vector<String> choiceVrCommands) {
Choice returnChoice = new Choice();
returnChoice.setChoiceID(choiceID);
returnChoice.setMenuName(choiceMenuName);
returnChoice.setVrCommands(choiceVrCommands);
return returnChoice;
}
/**
* Starts audio pass thru session. Responses are captured through callback on IProxyListener.
*
* @param initialPrompt -SDL will speak this prompt before opening the audio pass thru session.
* @param audioPassThruDisplayText1 -First line of text displayed during audio capture.
* @param audioPassThruDisplayText2 -Second line of text displayed during audio capture.
* @param samplingRate -Allowable values of 8 khz or 16 or 22 or 44 khz.
* @param maxDuration -The maximum duration of audio recording in milliseconds.
* @param bitsPerSample -Specifies the quality the audio is recorded. Currently 8 bit or 16 bit.
* @param audioType -Specifies the type of audio data being requested.
* @param muteAudio -Defines if the current audio source should be muted during the APT session.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void performaudiopassthru(String initialPrompt, String audioPassThruDisplayText1, String audioPassThruDisplayText2,
SamplingRate samplingRate, Integer maxDuration, BitsPerSample bitsPerSample,
AudioType audioType, Boolean muteAudio, Integer correlationID) throws SdlException {
PerformAudioPassThru msg = RPCRequestFactory.BuildPerformAudioPassThru(initialPrompt, audioPassThruDisplayText1, audioPassThruDisplayText2,
samplingRate, maxDuration, bitsPerSample, audioType, muteAudio, correlationID);
sendRPCRequest(msg);
}
/**
* Ends audio pass thru session. Responses are captured through callback on IProxyListener.
*
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void endaudiopassthru(Integer correlationID) throws SdlException
{
EndAudioPassThru msg = RPCRequestFactory.BuildEndAudioPassThru(correlationID);
sendRPCRequest(msg);
}
/**
* Subscribes for specific published data items. The data will be only sent if it has changed.
* Responses are captured through callback on IProxyListener.
*
* @param gps -Subscribes to GPS data.
* @param speed -Subscribes to vehicle speed data in kilometers per hour.
* @param rpm -Subscribes to number of revolutions per minute of the engine.
* @param fuelLevel -Subscribes to fuel level in the tank (percentage).
* @param fuelLevel_State -Subscribes to fuel level state.
* @param instantFuelConsumption -Subscribes to instantaneous fuel consumption in microlitres.
* @param externalTemperature -Subscribes to the external temperature in degrees celsius.
* @param prndl -Subscribes to PRNDL data that houses the selected gear.
* @param tirePressure -Subscribes to the TireStatus data containing status and pressure of tires.
* @param odometer -Subscribes to Odometer data in km.
* @param beltStatus -Subscribes to status of the seat belts.
* @param bodyInformation -Subscribes to body information including power modes.
* @param deviceStatus -Subscribes to device status including signal and battery strength.
* @param driverBraking -Subscribes to the status of the brake pedal.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void subscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State,
boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure,
boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus,
boolean driverBraking, Integer correlationID) throws SdlException
{
SubscribeVehicleData msg = RPCRequestFactory.BuildSubscribeVehicleData(gps, speed, rpm, fuelLevel, fuelLevel_State, instantFuelConsumption, externalTemperature, prndl, tirePressure,
odometer, beltStatus, bodyInformation, deviceStatus, driverBraking, correlationID);
sendRPCRequest(msg);
}
/**
* Unsubscribes for specific published data items.
* Responses are captured through callback on IProxyListener.
*
* @param gps -Unsubscribes to GPS data.
* @param speed -Unsubscribes to vehicle speed data in kilometers per hour.
* @param rpm -Unsubscribes to number of revolutions per minute of the engine.
* @param fuelLevel -Unsubscribes to fuel level in the tank (percentage).
* @param fuelLevel_State -Unsubscribes to fuel level state.
* @param instantFuelConsumption -Unsubscribes to instantaneous fuel consumption in microlitres.
* @param externalTemperature -Unsubscribes to the external temperature in degrees celsius.
* @param prndl -Unsubscribes to PRNDL data that houses the selected gear.
* @param tirePressure -Unsubscribes to the TireStatus data containing status and pressure of tires.
* @param odometer -Unsubscribes to Odometer data in km.
* @param beltStatus -Unsubscribes to status of the seat belts.
* @param bodyInformation -Unsubscribes to body information including power modes.
* @param deviceStatus -Unsubscribes to device status including signal and battery strength.
* @param driverBraking -Unsubscribes to the status of the brake pedal.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void unsubscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State,
boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure,
boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus,
boolean driverBraking, Integer correlationID) throws SdlException
{
UnsubscribeVehicleData msg = RPCRequestFactory.BuildUnsubscribeVehicleData(gps, speed, rpm, fuelLevel, fuelLevel_State, instantFuelConsumption, externalTemperature, prndl, tirePressure,
odometer, beltStatus, bodyInformation, deviceStatus, driverBraking, correlationID);
sendRPCRequest(msg);
}
/**
* Performs a Non periodic vehicle data read request.
* Responses are captured through callback on IProxyListener.
*
* @param gps -Performs an ad-hoc request for GPS data.
* @param speed -Performs an ad-hoc request for vehicle speed data in kilometers per hour.
* @param rpm -Performs an ad-hoc request for number of revolutions per minute of the engine.
* @param fuelLevel -Performs an ad-hoc request for fuel level in the tank (percentage).
* @param fuelLevel_State -Performs an ad-hoc request for fuel level state.
* @param instantFuelConsumption -Performs an ad-hoc request for instantaneous fuel consumption in microlitres.
* @param externalTemperature -Performs an ad-hoc request for the external temperature in degrees celsius.
* @param vin -Performs an ad-hoc request for the Vehicle identification number
* @param prndl -Performs an ad-hoc request for PRNDL data that houses the selected gear.
* @param tirePressure -Performs an ad-hoc request for the TireStatus data containing status and pressure of tires.
* @param odometer -Performs an ad-hoc request for Odometer data in km.
* @param beltStatus -Performs an ad-hoc request for status of the seat belts.
* @param bodyInformation -Performs an ad-hoc request for body information including power modes.
* @param deviceStatus -Performs an ad-hoc request for device status including signal and battery strength.
* @param driverBraking -Performs an ad-hoc request for the status of the brake pedal.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void getvehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State,
boolean instantFuelConsumption, boolean externalTemperature, boolean vin, boolean prndl, boolean tirePressure,
boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus,
boolean driverBraking, Integer correlationID) throws SdlException
{
GetVehicleData msg = RPCRequestFactory.BuildGetVehicleData(gps, speed, rpm, fuelLevel, fuelLevel_State, instantFuelConsumption, externalTemperature, vin, prndl, tirePressure, odometer,
beltStatus, bodyInformation, deviceStatus, driverBraking, correlationID);
sendRPCRequest(msg);
}
/**
* Creates a full screen overlay containing a large block of formatted text that can be scrolled with up to 8 SoftButtons defined.
* Responses are captured through callback on IProxyListener.
*
* @param scrollableMessageBody -Body of text that can include newlines and tabs.
* @param timeout -App defined timeout. Indicates how long of a timeout from the last action.
* @param softButtons -App defined SoftButtons.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void scrollablemessage(String scrollableMessageBody, Integer timeout, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException
{
ScrollableMessage msg = RPCRequestFactory.BuildScrollableMessage(scrollableMessageBody, timeout, softButtons, correlationID);
sendRPCRequest(msg);
}
/**
* Creates a full screen or pop-up overlay (depending on platform) with a single user controlled slider.
* Responses are captured through callback on IProxyListener.
*
* @param numTicks -Number of selectable items on a horizontal axis.
* @param position -Initial position of slider control (cannot exceed numTicks).
* @param sliderHeader -Text header to display.
* @param sliderFooter - Text footer to display (meant to display min/max threshold descriptors).
* @param timeout -App defined timeout. Indicates how long of a timeout from the last action.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void slider(Integer numTicks, Integer position, String sliderHeader, Vector<String> sliderFooter, Integer timeout, Integer correlationID) throws SdlException
{
Slider msg = RPCRequestFactory.BuildSlider(numTicks, position, sliderHeader, sliderFooter, timeout, correlationID);
sendRPCRequest(msg);
}
/**
* Responses are captured through callback on IProxyListener.
*
* @param language requested SDL voice engine (VR+TTS) language registration
* @param hmiDisplayLanguage request display language registration.
* @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void changeregistration(Language language, Language hmiDisplayLanguage, Integer correlationID) throws SdlException
{
ChangeRegistration msg = RPCRequestFactory.BuildChangeRegistration(language, hmiDisplayLanguage, correlationID);
sendRPCRequest(msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile device.
* Responses are captured through callback on IProxyListener.
*
* @param is - The input stream of byte data that putFileStream will read from
* @param sdlFileName - The file reference name used by the putFile RPC.
* @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of the file.
* A value greater than zero is used for resuming partial data chunks.
* @param iLength - The total length of the file being sent.
* @throws SdlException if an unrecoverable error is encountered
* @see #putFileStream(InputStream, String, Long, Long)
*/
@SuppressWarnings("unused")
@Deprecated
public void putFileStream(InputStream is, String sdlFileName, Integer iOffset, Integer iLength) throws SdlException
{
@SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength);
startRPCStream(is, msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile
* device. Responses are captured through callback on IProxyListener.
*
* @param inputStream The input stream of byte data that will be read from.
* @param fileName The SDL file reference name used by the RPC.
* @param offset The data offset in bytes. A value of zero is used to
* indicate data starting from the beginning of the file and a value greater
* than zero is used for resuming partial data chunks.
* @param length The total length of the file being sent.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void putFileStream(InputStream inputStream, String fileName, Long offset, Long length) throws SdlException {
PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length);
startRPCStream(inputStream, msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile device.
* Responses are captured through callback on IProxyListener.
*
* @param sdlFileName - The file reference name used by the putFile RPC.
* @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file.
* A value greater than zero is used for resuming partial data chunks.
* @param iLength - The total length of the file being sent.
*
* @return OutputStream - The output stream of byte data that is written to by the app developer
* @throws SdlException if an unrecoverable error is encountered
* @see #putFileStream(String, Long, Long)
*/
@SuppressWarnings("unused")
@Deprecated
public OutputStream putFileStream(String sdlFileName, Integer iOffset, Integer iLength) throws SdlException
{
@SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength);
return startRPCStream(msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile
* device. Responses are captured through callback on IProxyListener.
*
* @param fileName The SDL file reference name used by the RPC.
* @param offset The data offset in bytes. A value of zero is used to
* indicate data starting from the beginning of the file and a value greater
* than zero is used for resuming partial data chunks.
* @param length The total length of the file being sent.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public OutputStream putFileStream(String fileName, Long offset, Long length) throws SdlException {
PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length);
return startRPCStream(msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile device.
* Responses are captured through callback on IProxyListener.
*
* @param is - The input stream of byte data that PutFileStream will read from
* @param sdlFileName - The file reference name used by the putFile RPC.
* @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of the file.
* A value greater than zero is used for resuming partial data chunks.
* @param iLength - The total length of the file being sent.
* @param fileType - The selected file type -- see the FileType enumeration for details
* @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles.
* @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system.
* @throws SdlException if an unrecoverable error is encountered
* @see #putFileStream(InputStream, String, Long, Long, FileType, Boolean, Boolean, OnPutFileUpdateListener)
*/
@SuppressWarnings("unused")
@Deprecated
public void putFileStream(InputStream is, String sdlFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) throws SdlException
{
@SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength, fileType, bPersistentFile, bSystemFile);
startRPCStream(is, msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile
* device. Responses are captured through callback on IProxyListener.
*
* @param inputStream The input stream of byte data that will be read from.
* @param fileName The SDL file reference name used by the RPC.
* @param offset The data offset in bytes. A value of zero is used to
* indicate data starting from the beginning of the file and a value greater
* than zero is used for resuming partial data chunks.
* @param length The total length of the file being sent.
* @param fileType The selected file type. See the {@link FileType} enum for
* details.
* @param isPersistentFile Indicates if the file is meant to persist between
* sessions / ignition cycles.
* @param isSystemFile Indicates if the file is meant to be passed through
* core to elsewhere in the system.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void putFileStream(InputStream inputStream, String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) throws SdlException {
PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length);
msg.setOnPutFileUpdateListener(cb);
startRPCStream(inputStream, msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile device.
* Responses are captured through callback on IProxyListener.
*
* @param sdlFileName - The file reference name used by the putFile RPC.
* @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file.
* A value greater than zero is used for resuming partial data chunks.
* @param iLength - The total length of the file being sent.
* @param fileType - The selected file type -- see the FileType enumeration for details
* @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles.
* @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system.
* @return OutputStream - The output stream of byte data that is written to by the app developer
* @throws SdlException if an unrecoverable error is encountered
* @see #putFileStream(String, Long, Long, FileType, Boolean, Boolean, OnPutFileUpdateListener)
*/
@SuppressWarnings("unused")
@Deprecated
public OutputStream putFileStream(String sdlFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) throws SdlException
{
@SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength, fileType, bPersistentFile, bSystemFile);
return startRPCStream(msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile
* device. Responses are captured through callback on IProxyListener.
*
* @param fileName The SDL file reference name used by the RPC.
* @param offset The data offset in bytes. A value of zero is used to
* indicate data starting from the beginning of the file and a value greater
* than zero is used for resuming partial data chunks.
* @param length The total length of the file being sent.
* @param fileType The selected file type. See the {@link FileType} enum for
* details.
* @param isPersistentFile Indicates if the file is meant to persist between
* sessions / ignition cycles.
* @param isSystemFile Indicates if the file is meant to be passed through
* core to elsewhere in the system.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public OutputStream putFileStream(String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) throws SdlException {
PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length);
msg.setOnPutFileUpdateListener(cb);
return startRPCStream(msg);
}
/**
* Used to push a stream of putfile RPC's containing binary data from a mobile device to the module.
* Responses are captured through callback on IProxyListener.
*
* @param sPath - The physical file path on the mobile device.
* @param sdlFileName - The file reference name used by the putFile RPC.
* @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file.
* A value greater than zero is used for resuming partial data chunks.
* @param fileType - The selected file type -- see the FileType enumeration for details
* @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles.
* @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system.
* @param iCorrelationID - A unique ID that correlates each RPCRequest and RPCResponse.
* @return RPCStreamController - If the putFileStream was not started successfully null is returned, otherwise a valid object reference is returned
* @throws SdlException if an unrecoverable error is encountered
* @see #putFileStream(String, String, Long, FileType, Boolean, Boolean, Boolean, Integer, OnPutFileUpdateListener)
*/
@SuppressWarnings("unused")
@Deprecated
public RPCStreamController putFileStream(String sPath, String sdlFileName, Integer iOffset, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Integer iCorrelationID) throws SdlException
{
@SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, 0, fileType, bPersistentFile, bSystemFile, iCorrelationID);
return startPutFileStream(sPath, msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile
* device. Responses are captured through callback on IProxyListener.
*
* @param path The physical file path on the mobile device.
* @param fileName The SDL file reference name used by the RPC.
* @param offset The data offset in bytes. A value of zero is used to
* indicate data starting from the beginning of the file and a value greater
* than zero is used for resuming partial data chunks.
* @param fileType The selected file type. See the {@link FileType} enum for
* details.
* @param isPersistentFile Indicates if the file is meant to persist between
* sessions / ignition cycles.
* @param isSystemFile Indicates if the file is meant to be passed through
* core to elsewhere in the system.
* @param correlationId A unique id that correlates each RPCRequest and
* RPCResponse.
* @return RPCStreamController If the putFileStream was not started
* successfully null is returned, otherwise a valid object reference is
* returned .
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public RPCStreamController putFileStream(String path, String fileName, Long offset, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId, OnPutFileUpdateListener cb ) throws SdlException {
PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, 0L, fileType, isPersistentFile, isSystemFile, isPayloadProtected, correlationId);
msg.setOnPutFileUpdateListener(cb);
return startPutFileStream(path,msg);
}
/**
* Used to push a stream of putfile RPC's containing binary data from a mobile device to the module.
* Responses are captured through callback on IProxyListener.
*
* @param is - The input stream of byte data that putFileStream will read from.
* @param sdlFileName - The file reference name used by the putFile RPC.
* @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file.
* A value greater than zero is used for resuming partial data chunks.
* @param fileType - The selected file type -- see the FileType enumeration for details
* @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles.
* @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system.
* @param iCorrelationID - A unique ID that correlates each RPCRequest and RPCResponse.
* @return RPCStreamController - If the putFileStream was not started successfully null is returned, otherwise a valid object reference is returned
* @throws SdlException if an unrecoverable error is encountered
* @see #putFileStream(InputStream, String, Long, Long, FileType, Boolean, Boolean, Boolean, Integer)
*/
@SuppressWarnings("unused")
@Deprecated
public RPCStreamController putFileStream(InputStream is, String sdlFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Integer iCorrelationID) throws SdlException
{
@SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength, fileType, bPersistentFile, bSystemFile, iCorrelationID);
return startPutFileStream(is, msg);
}
/**
* Used to push a binary stream of file data onto the module from a mobile
* device. Responses are captured through callback on IProxyListener.
*
* @param inputStream The input stream of byte data that will be read from.
* @param fileName The SDL file reference name used by the RPC.
* @param offset The data offset in bytes. A value of zero is used to
* indicate data starting from the beginning of the file and a value greater
* than zero is used for resuming partial data chunks.
* @param length The total length of the file being sent.
* @param fileType The selected file type. See the {@link FileType} enum for
* details.
* @param isPersistentFile Indicates if the file is meant to persist between
* sessions / ignition cycles.
* @param isSystemFile Indicates if the file is meant to be passed through
* core to elsewhere in the system.
* @param correlationId A unique id that correlates each RPCRequest and
* RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public RPCStreamController putFileStream(InputStream inputStream, String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId) throws SdlException {
PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length, fileType, isPersistentFile, isSystemFile, isPayloadProtected, correlationId);
return startPutFileStream(inputStream, msg);
}
/**
*
* Used to end an existing putFileStream that was previously initiated with any putFileStream method.
*
*/
@SuppressWarnings("unused")
public void endPutFileStream()
{
endRPCStream();
}
/**
* Used to push a binary data onto the SDL module from a mobile device, such as icons and album art. Not supported on first generation SDL vehicles.
* Responses are captured through callback on IProxyListener.
*
* @param sdlFileName -File reference name.
* @param fileType -Selected file type.
* @param persistentFile -Indicates if the file is meant to persist between sessions / ignition cycles.
* @param fileData byte array of data of the file that is to be sent
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void putfile(String sdlFileName, FileType fileType, Boolean persistentFile, byte[] fileData, Integer correlationID) throws SdlException
{
PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, fileType, persistentFile, fileData, correlationID);
sendRPCRequest(msg);
}
/**
* Used to delete a file resident on the SDL module in the app's local cache. Not supported on first generation SDL vehicles.
* Responses are captured through callback on IProxyListener.
*
* @param sdlFileName -File reference name.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void deletefile(String sdlFileName, Integer correlationID) throws SdlException
{
DeleteFile msg = RPCRequestFactory.buildDeleteFile(sdlFileName, correlationID);
sendRPCRequest(msg);
}
/**
* Requests the current list of resident filenames for the registered app. Not supported on first generation SDL vehicles.
* Responses are captured through callback on IProxyListener.
*
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void listfiles(Integer correlationID) throws SdlException
{
ListFiles msg = RPCRequestFactory.buildListFiles(correlationID);
sendRPCRequest(msg);
}
/**
* Used to set existing local file on SDL as the app's icon. Not supported on first generation SDL vehicles.
* Responses are captured through callback on IProxyListener.
*
* @param sdlFileName -File reference name.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void setappicon(String sdlFileName, Integer correlationID) throws SdlException
{
SetAppIcon msg = RPCRequestFactory.buildSetAppIcon(sdlFileName, correlationID);
sendRPCRequest(msg);
}
/**
* Set an alternate display layout. If not sent, default screen for given platform will be shown.
* Responses are captured through callback on IProxyListener.
*
* @param displayLayout -Predefined or dynamically created screen layout.
* @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse.
* @throws SdlException if an unrecoverable error is encountered
*/
@SuppressWarnings("unused")
public void setdisplaylayout(String displayLayout, Integer correlationID) throws SdlException
{
SetDisplayLayout msg = RPCRequestFactory.BuildSetDisplayLayout(displayLayout, correlationID);
sendRPCRequest(msg);
}
@SuppressWarnings("unused")
public boolean isCapabilitySupported(SystemCapabilityType systemCapabilityType) {
return _systemCapabilityManager != null && _systemCapabilityManager.isCapabilitySupported(systemCapabilityType);
}
@SuppressWarnings("unused")
public void getCapability(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener scListener){
if(_systemCapabilityManager != null){
_systemCapabilityManager.getCapability(systemCapabilityType, scListener);
}
}
@SuppressWarnings("unused")
public Object getCapability(SystemCapabilityType systemCapabilityType){
if(_systemCapabilityManager != null ){
return _systemCapabilityManager.getCapability(systemCapabilityType);
}else{
return null;
}
}
/**
* Gets type of transport currently used by this SdlProxy.
*
* @return One of TransportType enumeration values.
*
* @see TransportType
*/
@SuppressWarnings("unused")
public TransportType getCurrentTransportType() throws IllegalStateException {
if (sdlSession == null) {
throw new IllegalStateException("Incorrect state of SdlProxyBase: Calling for getCurrentTransportType() while connection is not initialized");
}
return sdlSession.getCurrentTransportType();
}
public void setSdlSecurityClassList(List<Class<? extends SdlSecurityBase>> list) {
_secList = list;
}
private void setSdlSecurity(SdlSecurityBase sec) {
if (sdlSession != null)
{
sdlSession.setSdlSecurity(sec);
}
}
@SuppressWarnings("unused")
public boolean isServiceTypeProtected(SessionType sType) {
return sdlSession != null && sdlSession.isServiceProtected(sType);
}
public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener){
if(serviceType != null && sdlSession != null && sdlServiceListener != null){
sdlSession.addServiceListener(serviceType, sdlServiceListener);
}
}
public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener){
if(serviceType != null && sdlSession != null && sdlServiceListener != null){
sdlSession.removeServiceListener(serviceType, sdlServiceListener);
}
}
@SuppressWarnings("unused")
public VideoStreamingParameters getAcceptedVideoParams(){
return sdlSession.getAcceptedVideoParams();
}
public IProxyListenerBase getProxyListener()
{
return _proxyListener;
}
@SuppressWarnings("unused")
public String getAppName()
{
return _applicationName;
}
@SuppressWarnings("unused")
public String getNgnAppName()
{
return _ngnMediaScreenAppName;
}
@SuppressWarnings("unused")
public String getAppID()
{
return _appID;
}
@SuppressWarnings("unused")
public DeviceInfo getDeviceInfo()
{
return deviceInfo;
}
@SuppressWarnings("unused")
public long getInstanceDT()
{
return instanceDateTime;
}
@SuppressWarnings("unused")
public void setConnectionDetails(String sDetails)
{
sConnectionDetails = sDetails;
}
@SuppressWarnings("unused")
public String getConnectionDetails()
{
return sConnectionDetails;
}
//for testing only
@SuppressWarnings("unused")
public void setPoliciesURL(String sText)
{
sPoliciesURL = sText;
}
//for testing only
public String getPoliciesURL()
{
return sPoliciesURL;
}
/**
* VideoStreamingManager houses all the elements needed to create a scoped, streaming manager for video projection. It is only a private, instance
* dependant class at the moment until it can become public. Once the class is public and API defined, it will be moved into the SdlSession class
*/
@TargetApi(19)
private class VideoStreamingManager implements ISdlServiceListener{
Context context;
ISdl internalInterface;
volatile VirtualDisplayEncoder encoder;
private Class<? extends SdlRemoteDisplay> remoteDisplayClass = null;
SdlRemoteDisplay remoteDisplay;
IVideoStreamListener streamListener;
float[] touchScalar = {1.0f,1.0f}; //x, y
private HapticInterfaceManager hapticManager;
public VideoStreamingManager(Context context,ISdl iSdl){
this.context = context;
this.internalInterface = iSdl;
encoder = new VirtualDisplayEncoder();
internalInterface.addServiceListener(SessionType.NAV,this);
//Take care of the touch events
internalInterface.addOnRPCNotificationListener(FunctionID.ON_TOUCH_EVENT, new OnRPCNotificationListener() {
@Override
public void onNotified(RPCNotification notification) {
if(notification !=null && remoteDisplay != null){
MotionEvent event = convertTouchEvent((OnTouchEvent)notification);
if(event!=null){
remoteDisplay.handleMotionEvent(event);
}
}
}
});
VideoStreamingCapability capability = (VideoStreamingCapability)_systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING);
if(capability != null && capability.getIsHapticSpatialDataSupported()){
hapticManager = new HapticInterfaceManager(iSdl);
}
}
public void startVideoStreaming(Class<? extends SdlRemoteDisplay> remoteDisplayClass, VideoStreamingParameters parameters, boolean encrypted){
streamListener = startVideoStream(encrypted,parameters);
if(streamListener == null){
Log.e(TAG, "Error starting video service");
return;
}
this.remoteDisplayClass = remoteDisplayClass;
try {
encoder.init(context,streamListener,parameters);
//We are all set so we can start streaming at at this point
encoder.start();
//Encoder should be up and running
createRemoteDisplay(encoder.getVirtualDisplay());
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, parameters.toString());
}
public void stopStreaming(){
if(remoteDisplay!=null){
remoteDisplay.stop();
}
if(encoder!=null){
encoder.shutDown();
}
}
public void dispose(){
stopStreaming();
internalInterface.removeServiceListener(SessionType.NAV,this);
}
private void createRemoteDisplay(final Display disp){
try{
if (disp == null){
return;
}
// Dismiss the current presentation if the display has changed.
if (remoteDisplay != null && remoteDisplay.getDisplay() != disp) {
remoteDisplay.dismissPresentation();
}
FutureTask<Boolean> fTask = new FutureTask<Boolean>( new SdlRemoteDisplay.Creator(context, disp, remoteDisplay, remoteDisplayClass, new SdlRemoteDisplay.Callback(){
@Override
public void onCreated(final SdlRemoteDisplay remoteDisplay) {
//Remote display has been created.
//Now is a good time to do parsing for spatial data
VideoStreamingManager.this.remoteDisplay = remoteDisplay;
if(hapticManager != null) {
remoteDisplay.getMainView().post(new Runnable() {
@Override
public void run() {
hapticManager.refreshHapticData(remoteDisplay.getMainView());
}
});
}
//Get touch scalars
ImageResolution resolution = null;
if(getWiProVersion()>=5){ //At this point we should already have the capability
VideoStreamingCapability capability = (VideoStreamingCapability)_systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING);
resolution = capability.getPreferredResolution();
}else {
DisplayCapabilities dispCap = (DisplayCapabilities) _systemCapabilityManager.getCapability(SystemCapabilityType.DISPLAY);
if (dispCap != null) {
resolution = (dispCap.getScreenParams().getImageResolution());
}
}
if(resolution != null){
DisplayMetrics displayMetrics = new DisplayMetrics();
disp.getMetrics(displayMetrics);
touchScalar[0] = ((float)displayMetrics.widthPixels) / resolution.getResolutionWidth();
touchScalar[1] = ((float)displayMetrics.heightPixels) / resolution.getResolutionHeight();
}
}
@Override
public void onInvalidated(final SdlRemoteDisplay remoteDisplay) {
//Our view has been invalidated
//A good time to refresh spatial data
if(hapticManager != null) {
remoteDisplay.getMainView().post(new Runnable() {
@Override
public void run() {
hapticManager.refreshHapticData(remoteDisplay.getMainView());
}
});
}
}
} ));
Thread showPresentation = new Thread(fTask);
showPresentation.start();
} catch (Exception ex) {
Log.e(TAG, "Unable to create Virtual Display.");
}
}
@Override
public void onServiceStarted(SdlSession session, SessionType type, boolean isEncrypted) {
}
@Override
public void onServiceEnded(SdlSession session, SessionType type) {
if(SessionType.NAV.equals(type)){
dispose();
}
}
@Override
public void onServiceError(SdlSession session, SessionType type, String reason) {
}
private MotionEvent convertTouchEvent(OnTouchEvent touchEvent){
List<TouchEvent> eventList = touchEvent.getEvent();
if (eventList == null || eventList.size() == 0) return null;
TouchType touchType = touchEvent.getType();
if (touchType == null){ return null;}
float x;
float y;
TouchEvent event = eventList.get(eventList.size() - 1);
List<TouchCoord> coordList = event.getTouchCoordinates();
if (coordList == null || coordList.size() == 0){ return null;}
TouchCoord coord = coordList.get(coordList.size() - 1);
if (coord == null){ return null;}
x = (coord.getX() * touchScalar[0]);
y = (coord.getY() * touchScalar[1]);
if (x == 0 && y == 0){ return null;}
int eventAction = MotionEvent.ACTION_DOWN;
long downTime = 0;
if (touchType == TouchType.BEGIN) {
downTime = SystemClock.uptimeMillis();
eventAction = MotionEvent.ACTION_DOWN;
}
long eventTime = SystemClock.uptimeMillis();
if (downTime == 0){ downTime = eventTime - 100;}
if (touchType == TouchType.MOVE) {
eventAction = MotionEvent.ACTION_MOVE;
}
if (touchType == TouchType.END) {
eventAction = MotionEvent.ACTION_UP;
}
return MotionEvent.obtain(downTime, eventTime, eventAction, x, y, 0);
}
}
} // end-class
|
package com.ionic.keyboard;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
public class IonicKeyboard extends CordovaPlugin{
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
//calculate density-independent pixels (dp)
DisplayMetrics dm = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
final float density = dm.density;
final CordovaWebView appView = webView;
final View rootView = cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content).getRootView();
OnGlobalLayoutListener list = new OnGlobalLayoutListener() {
int previousHeightDiff = 0;
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
rootView.getWindowVisibleDisplayFrame(r);
int heightDiff = rootView.getRootView().getHeight() - (r.bottom);
int pixelHeightDiff = (int)(heightDiff / density);
if (pixelHeightDiff > 100 && pixelHeightDiff != previousHeightDiff) { // if more than 100 pixels, its probably a keyboard...
appView.sendJavascript("cordova.plugins.Keyboard.isVisible = true");
appView.sendJavascript("cordova.fireWindowEvent('native.keyboardshow', { 'keyboardHeight':" + Integer.toString(pixelHeightDiff)+"});");
//deprecated
appView.sendJavascript("cordova.fireWindowEvent('native.showkeyboard', { 'keyboardHeight':" + Integer.toString(pixelHeightDiff)+"});");
}
else if ( pixelHeightDiff != previousHeightDiff && ( previousHeightDiff - pixelHeightDiff ) > 100 ){
appView.sendJavascript("cordova.plugins.Keyboard.isVisible = false");
appView.sendJavascript("cordova.fireWindowEvent('native.keyboardhide')");
//deprecated
appView.sendJavascript("cordova.fireWindowEvent('native.hidekeyboard')");
}
previousHeightDiff = pixelHeightDiff;
}
};
rootView.getViewTreeObserver().addOnGlobalLayoutListener(list);
}
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if ("close".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
InputMethodManager inputManager = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
View v = cordova.getActivity().getCurrentFocus();
if (v == null) {
callbackContext.error("No current focus");
} else {
inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
callbackContext.success(); // Thread-safe.
}
}
});
return true;
}
if ("show".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
callbackContext.success(); // Thread-safe.
}
});
return true;
}
if ("hideTitleBar".equals(action)) {
final String show = args.getString(0);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
if (show == "true" || show == "1") {
cordova.getActivity().getActionBar().show();
}
else {
cordova.getActivity().getActionBar().hide();
}
callbackContext.success(); // Thread-safe.
}
});
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
}
|
package com.jjdltc.cordova.plugin.zip;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class decompressZip {
private String sourceEntry = "";
private String targetPath = "";
private final int BUFFER_SIZE = 2048;
public decompressZip(JSONObject opts) {
this.sourceEntry = opts.optString("sourceEntry");
this.targetPath = opts.optString("targetPath");
}
public boolean unZip(){
boolean result = false;
try {
result = this.doUnZip(this.targetPath);
} catch (IOException e) {
result = false;
}
return result;
}
/**
* Extracts a zip file to a given path
* @param actualTargetPath Path to un-zip
* @throws IOException
*/
public boolean doUnZip(String actualTargetPath) throws IOException{
File target = new File(actualTargetPath);
if (!target.exists()) {
target.mkdirs();
}
ZipInputStream zipFl= new ZipInputStream(new FileInputStream(this.sourceEntry));
ZipEntry entry = zipFl.getNextEntry();
while (entry != null) {
String filePath = actualTargetPath + (actualTargetPath.endsWith("/") ? entry.getName() : File.separator + entry.getName());
if (entry.isDirectory()) {
//This part doesn't seem to be fired
File path = new File(filePath);
path.mkdir();
} else {
//That is why we check here if the target dir exists
File targetDir = new File(filePath.substring(0, filePath.lastIndexOf("/")));
if (!targetDir.exists()) {
targetDir.mkdirs();
}
extractFile(zipFl, filePath);
}
zipFl.closeEntry();
entry = zipFl.getNextEntry();
}
zipFl.close();
return true;
}
/**
* Extracts a file
* @param zipIn
* @param filePath
* @throws IOException
*/
private void extractFile(ZipInputStream zipFl, String filePath) throws IOException {
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[this.BUFFER_SIZE];
int read = 0;
while ((read = zipFl.read(bytesIn)) != -1) {
buffer.write(bytesIn, 0, read);
}
buffer.close();
}
}
|
package be.ibridge.kettle.core;
import java.io.UnsupportedEncodingException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.exception.KettleXMLException;
/**
* This class contains code to help you drag data from one
* part of a GUI to another by using XML as an intermediate step.
*
* @author matt
* @since 2006-04-16
*
*/
public class DragAndDropContainer implements XMLInterface
{
public static final int TYPE_STEP = 1;
public static final int TYPE_BASE_STEP_TYPE = 2;
public static final int TYPE_DATABASE_CONNECTION = 3;
public static final int TYPE_TRANS_HOP = 4;
public static final int TYPE_TEXT = 5;
public static final int TYPE_JOB_ENTRY = 6;
public static final int TYPE_BASE_JOB_ENTRY = 7;
public static final int TYPE_PHYSICAL_TABLE = 8;
public static final int TYPE_PHYSICAL_COLUMN = 9;
public static final int TYPE_BUSINESS_VIEW = 10;
public static final int TYPE_BUSINESS_TABLE = 11;
public static final int TYPE_BUSINESS_COLUMN = 12;
public static final int TYPE_RELATIONSHIP = 13;
private static final String typeCodes[] = {
"",
"Step",
"BaseStep",
"DatabaseConnection",
"TransHop",
"Text",
"Jobentry",
"BaseJobentry",
"PhysicalTable",
"PhysicalColumn",
"BusinessView",
"BusinessTable",
"BusinessColumn",
"Relationship"
};
private int type;
private String data;
/**
* Create a new DragAndDropContainer
*
* @param type The type of drag&drop to perform
* @param data The data in the form of a String
*/
public DragAndDropContainer(int type, String data)
{
this.type = type;
this.data = data;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public String getData()
{
return data;
}
public void setData(String data)
{
this.data = data;
}
public String getTypeCode()
{
if (type<=0 || type>=typeCodes.length) return null;
return typeCodes[type];
}
public static final int getType(String typeCode)
{
for (int i=1;i<typeCodes.length;i++)
{
if (typeCodes[i].equals(typeCode)) return i;
}
return 0;
}
public String getXML()
{
try
{
StringBuffer xml = new StringBuffer();
xml.append(XMLHandler.getXMLHeader()); // UFT-8 XML header
xml.append("<DragAndDrop>").append(Const.CR);
xml.append(" ").append(XMLHandler.addTagValue("DragType", getTypeCode()));
xml.append(" ").append(XMLHandler.addTagValue("Data", Base64.encodeBytes(data.getBytes(Const.XML_ENCODING))));
xml.append("</DragAndDrop>").append(Const.CR);
return xml.toString();
}
catch(UnsupportedEncodingException e)
{
throw new RuntimeException("Unable to encode String in encoding ["+Const.XML_ENCODING+"]", e);
}
}
/**
* Construct a Drag and drop container from an XML String
* @param xml The XML string to convert from
*/
public DragAndDropContainer(String xml) throws KettleXMLException
{
try
{
Document doc = XMLHandler.loadXMLString(xml);
Node dnd = XMLHandler.getSubNode(doc, "DragAndDrop");
type = getType( XMLHandler.getTagValue(dnd, "DragType") );
data = new String( Base64.decode( XMLHandler.getTagValue(dnd, "Data") ), Const.XML_ENCODING );
}
catch(Exception e)
{
throw new KettleXMLException("Unexpected error parsing Drag & Drop XML fragment: "+xml, e);
}
}
}
|
package com.ccnode.codegenerator.view;
import com.ccnode.codegenerator.enums.UrlManager;
import com.ccnode.codegenerator.genCode.GenCodeService;
import com.ccnode.codegenerator.pojo.ChangeInfo;
import com.ccnode.codegenerator.pojo.GenCodeRequest;
import com.ccnode.codegenerator.pojo.GenCodeResponse;
import com.ccnode.codegenerator.pojo.ServerMsg;
import com.ccnode.codegenerator.pojoHelper.GenCodeResponseHelper;
import com.ccnode.codegenerator.storage.SettingService;
import com.ccnode.codegenerator.util.LoggerWrapper;
import com.ccnode.codegenerator.util.PojoUtil;
import com.google.common.collect.Lists;
import com.intellij.ide.browsers.BrowserLauncher;
import com.intellij.ide.browsers.WebBrowserManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class GenCodeAction extends AnAction {
// If you register the action from Java code, this constructor is used to set the menu item name
// (optionally, you can specify the menu description and an icon to display next to the menu item).
// You can omit this constructor when registering the action in the plugin.xml file.
public GenCodeAction() {
// Set the menu item name.
super("Text _Boxes");
// Set the menu item name, description and icon.
// super("Text _Boxes","Item description",IconLoader.getIcon("/Mypackage/icon.png"));
}
public void actionPerformed(AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT);
VirtualFileManager.getInstance().syncRefresh();
ApplicationManager.getApplication().saveAll();
if(project == null){
return;
}
@Nullable String projectPath = project.getBasePath();
if(projectPath == null){
projectPath = StringUtils.EMPTY;
}
GenCodeResponse genCodeResponse = new GenCodeResponse();
GenCodeResponseHelper.setResponse(genCodeResponse);
try{
GenCodeRequest request = new GenCodeRequest(Lists.newArrayList(), projectPath,
System.getProperty("file.separator"));
request.setProject(project);
genCodeResponse = GenCodeService.genCode(request);
VirtualFileManager.getInstance().syncRefresh();
LoggerWrapper.saveAllLogs(genCodeResponse);
if(SettingService.getInstance().canUsePremium()){
Messages.showMessageDialog(project, buildEffectRowMsg(genCodeResponse), genCodeResponse.getStatus(), null);
}else{
int result = Messages.showOkCancelDialog(project, buildEffectRowMsg(genCodeResponse), genCodeResponse.getStatus() ,"OK","Buy Premium", null);
if(result == 2){
BrowserLauncher.getInstance().browse(UrlManager.PREMIUM_URL, WebBrowserManager.getInstance().getFirstActiveBrowser());
}
}
ServerMsg serverMsg = genCodeResponse.getServerMsg();
if(serverMsg != null && serverMsg.getHasServerMsg()){
int result = Messages.showOkCancelDialog(project, serverMsg.getContent(), serverMsg.getTitle(), "OK", serverMsg.getButtonStr(), null);
if(result == 2 && StringUtils.isNotBlank(serverMsg.getButtonUrl())){
BrowserLauncher.getInstance().browse(serverMsg.getButtonUrl(), WebBrowserManager.getInstance().getFirstActiveBrowser());
}
}
}catch(Throwable e){
e.printStackTrace();
genCodeResponse.setThrowable(e);
}
ApplicationManager.getApplication().saveAll();
VirtualFileManager.getInstance().syncRefresh();
}
private static String buildEffectRowMsg(GenCodeResponse response){
List<ChangeInfo> newFiles = response.getNewFiles();
List<ChangeInfo> updateFiles = response.getUpdateFiles();
List<String> msgList = Lists.newArrayList();
if(response.checkSuccess()){
Integer affectRows = getAffectRows(newFiles);
affectRows += getAffectRows(updateFiles);
if(newFiles.isEmpty() && affectRows.equals(0)){
return "No File Generated Or Updated";
}
if(!newFiles.isEmpty()){
msgList.add(" ");
}
for (ChangeInfo newFile : newFiles) {
msgList.add(" new file:"+ "\t\t" + newFile.getFileName());
}
if(!updateFiles.isEmpty()){
msgList.add("");
}
for (ChangeInfo updated : updateFiles) {
if(updated.getAffectRow() > 0){
msgList.add(" updated:"+ "\t\t" + updated.getFileName());
}
}
}else{
msgList.add(response.getMsg());
}
String ret = StringUtils.EMPTY;
for (String msg : msgList) {
ret += msg;
ret += "\n";
}
return ret.trim();
}
private static Integer getAffectRows(List<ChangeInfo> newFiles) {
newFiles = PojoUtil.avoidEmptyList(newFiles);
Integer affectRow = 0;
for (ChangeInfo newFile : newFiles) {
if(newFile.getAffectRow() != null){
affectRow += newFile.getAffectRow();
}
}
return affectRow;
}
}
|
package com.devinhartzell.chess.gui;
import java.awt.Composite;
import javax.annotation.PostConstruct;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import com.devinhartzell.chess.ChessGame;
import com.devinhartzell.chess.board.Board;
import com.devinhartzell.chess.pieces.ChessPiece;
import com.devinhartzell.chess.pieces.Pawn;
import java.io.IOException;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
public class ChessGameWindow extends JFrame {
private JLabel whiteLabel;
private JLabel blackLabel;
private String whiteName;
private String blackName;
private static JLabel moveLabel;
private static final long serialVersionUID = 1109205743042597274L;
private static JScrollPane scrollPane;
private static JTextArea recentMoves;
private static int turn = 1;
private static char[] xrel = {'X', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
private static char[] yrel = {'X', '8', '7', '6', '5', '4', '3', '2', '1'};
public ChessGameWindow(ChessGame game, String white, String black)
throws IOException {
super("Chess Game");
getContentPane().setLayout(null);
setResizable(false);
recentMoves = new JTextArea();
recentMoves.setText("");
recentMoves.setEditable(false);
scrollPane = new JScrollPane(recentMoves);
scrollPane.setBounds(418, 39, 162, 367);
getContentPane().add(scrollPane);
JLabel lblRecentMoves = new JLabel("Recent Moves");
lblRecentMoves.setBounds(418, 11, 86, 16);
getContentPane().add(lblRecentMoves);
this.setSize(621, 475);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
whiteLabel = new JLabel(String.format("White: %s", white));
whiteLabel.setHorizontalAlignment(SwingConstants.CENTER);
whiteLabel.setBounds(6, 418, 150, 16);
getContentPane().add(whiteLabel);
blackLabel = new JLabel(String.format("Black: %s", black));
blackLabel.setHorizontalAlignment(SwingConstants.CENTER);
blackLabel.setBounds(262, 418, 150, 16);
getContentPane().add(blackLabel);
moveLabel = new JLabel("White to move");
moveLabel.setBounds(428, 418, 114, 16);
getContentPane().add(moveLabel);
Board b = new Board(true);
getContentPane().add(b.getBoardPanel());
}
@PostConstruct
public void createControls(Composite parent) {
}
public static void nextMove() {
if (ChessGame.getMainBoard().currentMove)
moveLabel.setText("Black to move");
else
moveLabel.setText("White to move");
}
public static void addMove(ChessPiece p, boolean capture) {
String type = String.valueOf(Character.toUpperCase(p.getType()));
if (p instanceof Pawn) {
if (capture)
type = String.valueOf(xrel[p.getOldX()]) + String.valueOf(yrel[p.getOldY()]);
else
type = "";
}
if (!p.getColor()) {
if (!(turn == 1))
recentMoves.append("\n");
if (capture)
recentMoves.append(String.format("%s. %sx%s%s", turn, type, xrel[p.getX()], yrel[p.getY()]));
else
recentMoves.append(String.format("%s. %s%s%s", turn, type, xrel[p.getX()], yrel[p.getY()]));
} else {
if (capture)
recentMoves.append(String.format(" %sx%s%s", type, xrel[p.getX()], yrel[p.getY()]));
else
recentMoves.append(String.format(" %s%s%s", type, xrel[p.getX()], yrel[p.getY()]));
turn++;
}
}
public static void append(String s) {
recentMoves.append(s);
}
public String getWhite() {
return whiteName;
}
public String getBlack() {
return blackName;
}
}
|
package com.ecyrd.jspwiki.providers;
import java.io.IOException;
import java.util.*;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.parser.MarkupParser;
import com.ecyrd.jspwiki.render.RenderingManager;
import com.ecyrd.jspwiki.util.ClassUtil;
import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.base.events.*;
/**
* Provides a caching page provider. This class rests on top of a
* real provider class and provides a cache to speed things up. Only
* if the cache copy of the page text has expired, we fetch it from
* the provider.
* <p>
* This class also detects if someone has modified the page
* externally, not through JSPWiki routines, and throws the proper
* RepositoryModifiedException.
* <p>
* Heavily based on ideas by Chris Brooking.
* <p>
* Since 2.1.52 uses the OSCache library from OpenSymphony.
*
* @author Janne Jalkanen
* @since 1.6.4
* @see RepositoryModifiedException
*/
// FIXME: Synchronization is a bit inconsistent in places.
// FIXME: A part of the stuff is now redundant, since we could easily use the text cache
// for a lot of things. RefactorMe.
public class CachingProvider
implements WikiPageProvider, VersioningProvider
{
private static final Logger log = Logger.getLogger(CachingProvider.class);
private WikiPageProvider m_provider;
// FIXME: Find another way to the search engine to use instead of from WikiEngine?
private WikiEngine m_engine;
private Cache m_cache;
private Cache m_negCache; // Cache for holding non-existing pages
private Cache m_textCache;
private Cache m_historyCache;
private long m_cacheMisses = 0;
private long m_cacheHits = 0;
private long m_historyCacheMisses = 0;
private long m_historyCacheHits = 0;
private int m_expiryPeriod = 30;
/**
* This can be very long, as normally all modifications are noticed in an earlier
* stage.
*/
private int m_pageContentExpiryPeriod = 24*60*60;
// FIXME: This MUST be cached somehow.
private boolean m_gotall = false;
private CacheItemCollector m_allCollector = new CacheItemCollector();
/**
* Defines, in seconds, the amount of time a text will live in the cache
* at most before requiring a refresh.
*/
public static final String PROP_CACHECHECKINTERVAL = "jspwiki.cachingProvider.cacheCheckInterval";
public static final String PROP_CACHECAPACITY = "jspwiki.cachingProvider.capacity";
private static final int DEFAULT_CACHECAPACITY = 1000; // Good most wikis
private static final String OSCACHE_ALGORITHM = "com.opensymphony.oscache.base.algorithm.LRUCache";
public void initialize( WikiEngine engine, Properties properties )
throws NoRequiredPropertyException,
IOException
{
log.debug("Initing CachingProvider");
// engine is used for getting the search engine
m_engine = engine;
// Cache consistency checks
m_expiryPeriod = TextUtil.getIntegerProperty( properties,
PROP_CACHECHECKINTERVAL,
m_expiryPeriod );
log.debug("Cache expiry period is "+m_expiryPeriod+" s");
// Text cache capacity
int capacity = TextUtil.getIntegerProperty( properties,
PROP_CACHECAPACITY,
DEFAULT_CACHECAPACITY );
log.debug("Cache capacity "+capacity+" pages.");
m_cache = new Cache( true, false, false );
// OSCache documentation sucks big time. The clazz-parameter is completely
// undefined; I had to read the source code to figure out that you need
// to declare what type of a listener you are adding by sending the type
// of the interface.
m_cache.addCacheEventListener( m_allCollector, CacheEntryEventListener.class );
m_negCache = new Cache( true, false, false );
m_textCache = new Cache( true, false, false,
false,
OSCACHE_ALGORITHM,
capacity );
m_historyCache = new Cache( true, false, false, false,
OSCACHE_ALGORITHM,
capacity );
// Find and initialize real provider.
String classname = WikiEngine.getRequiredProperty( properties,
PageManager.PROP_PAGEPROVIDER );
try
{
Class providerclass = ClassUtil.findClass( "com.ecyrd.jspwiki.providers",
classname );
m_provider = (WikiPageProvider)providerclass.newInstance();
log.debug("Initializing real provider class "+m_provider);
m_provider.initialize( engine, properties );
}
catch( ClassNotFoundException e )
{
log.error("Unable to locate provider class "+classname,e);
throw new IllegalArgumentException("no provider class");
}
catch( InstantiationException e )
{
log.error("Unable to create provider class "+classname,e);
throw new IllegalArgumentException("faulty provider class");
}
catch( IllegalAccessException e )
{
log.error("Illegal access to provider class "+classname,e);
throw new IllegalArgumentException("illegal provider class");
}
}
private WikiPage getPageInfoFromCache( String name )
throws ProviderException,
RepositoryModifiedException
{
// Sanity check; seems to occur sometimes
if( name == null ) return null;
try
{
WikiPage item = (WikiPage)m_cache.getFromCache( name, m_expiryPeriod );
if( item != null )
return item;
return null;
}
catch( NeedsRefreshException e )
{
WikiPage cached = (WikiPage)e.getCacheContent();
// int version = (cached != null) ? cached.getVersion() : WikiPageProvider.LATEST_VERSION;
WikiPage refreshed = m_provider.getPageInfo( name, WikiPageProvider.LATEST_VERSION );
if( refreshed == null && cached != null )
{
// Page has been removed evilly by a goon from outer space
log.debug("Page "+name+" has been removed externally.");
m_cache.putInCache( name, null );
m_textCache.putInCache( name, null );
m_historyCache.putInCache( name, null );
// We cache a page miss
m_negCache.putInCache( name, name );
throw new RepositoryModifiedException( "Removed: "+name, name );
}
else if( cached == null )
{
// The page did not exist in the first place
if( refreshed != null )
{
// We must now add it
m_cache.putInCache( name, refreshed );
// Requests for this page are now no longer denied
m_negCache.putInCache( name, null );
throw new RepositoryModifiedException( "Added: "+name, name );
// return refreshed;
}
// Cache page miss
m_negCache.putInCache( name, name );
m_cache.cancelUpdate( name );
}
else if( cached.getVersion() != refreshed.getVersion() )
{
// The newest version has been deleted, but older versions still remain
log.debug("Page "+cached.getName()+" newest version deleted, reloading...");
m_cache.putInCache( name, refreshed );
// Requests for this page are now no longer denied
m_negCache.putInCache( name, null );
m_textCache.flushEntry( name );
m_historyCache.flushEntry( name );
return refreshed;
}
else if( Math.abs(refreshed.getLastModified().getTime()-cached.getLastModified().getTime()) > 1000L )
{
// Yes, the page has been modified externally and nobody told us
log.info("Page "+cached.getName()+" changed, reloading...");
m_cache.putInCache( name, refreshed );
// Requests for this page are now no longer denied
m_negCache.putInCache( name, null );
m_textCache.flushEntry( name );
m_historyCache.flushEntry( name );
throw new RepositoryModifiedException( "Modified: "+name, name );
}
else
{
// Refresh the cache by putting the same object back
m_cache.putInCache( name, cached );
// Requests for this page are now no longer denied
m_negCache.putInCache( name, null );
}
return cached;
}
}
public boolean pageExists( String pageName, int version )
{
if( pageName == null ) return false;
// First, check the negative cache if we've seen it before
try
{
String isNonExistant = (String) m_negCache.getFromCache( pageName, m_expiryPeriod );
if( isNonExistant != null ) return false; // No such page
}
catch( NeedsRefreshException e )
{
m_negCache.cancelUpdate(pageName);
}
WikiPage p = null;
try
{
p = getPageInfoFromCache( pageName );
}
catch( RepositoryModifiedException e )
{
// The repository was modified, we need to check now if the page was removed or
// added.
// TODO: This information would be available in the exception, but we would
// need to subclass.
try
{
p = getPageInfoFromCache( pageName );
}
catch( Exception ex ) { return false; } // This should not happen
}
catch( ProviderException e )
{
log.info("Provider failed while trying to check if page exists: "+pageName);
return false;
}
if( p != null )
{
int latestVersion = p.getVersion();
if( version == latestVersion || version == LATEST_VERSION )
{
return true;
}
if( m_provider instanceof VersioningProvider )
return ((VersioningProvider) m_provider).pageExists( pageName, version );
}
try
{
return getPageInfo( pageName, version ) != null;
}
catch( ProviderException e )
{}
return false;
}
public boolean pageExists( String pageName )
{
if( pageName == null ) return false;
// First, check the negative cache if we've seen it before
try
{
String isNonExistant = (String) m_negCache.getFromCache( pageName, m_expiryPeriod );
if( isNonExistant != null ) return false; // No such page
}
catch( NeedsRefreshException e )
{
m_negCache.cancelUpdate(pageName);
}
WikiPage p = null;
try
{
p = getPageInfoFromCache( pageName );
}
catch( RepositoryModifiedException e )
{
// The repository was modified, we need to check now if the page was removed or
// added.
// TODO: This information would be available in the exception, but we would
// need to subclass.
try
{
p = getPageInfoFromCache( pageName );
}
catch( Exception ex ) { return false; } // This should not happen
}
catch( ProviderException e )
{
log.info("Provider failed while trying to check if page exists: "+pageName);
return false;
}
// A null item means that the page either does not
// exist, or has not yet been cached; a non-null
// means that the page does exist.
if( p != null )
{
return true;
}
// If we have a list of all pages in memory, then any page
// not in the cache must be non-existent.
// FIXME: There's a problem here; if someone modifies the
// repository by adding a page outside JSPWiki,
// we won't notice it.
if( m_gotall )
{
return false;
}
// We could add the page to the cache here as well,
// but in order to understand whether that is a
// good thing or not we would need to analyze
// the JSPWiki calling patterns extensively. Presumably
// it would be a good thing if pageExists() is called
// many times before the first getPageText() is called,
// and the whole page is cached.
return m_provider.pageExists( pageName );
}
/**
* @throws RepositoryModifiedException If the page has been externally modified.
*/
public String getPageText( String pageName, int version )
throws ProviderException,
RepositoryModifiedException
{
String result = null;
if( pageName == null ) return null;
if( version == WikiPageProvider.LATEST_VERSION )
{
result = getTextFromCache( pageName );
}
else
{
WikiPage p = getPageInfoFromCache( pageName );
// Or is this the latest version fetched by version number?
if( p != null && p.getVersion() == version )
{
result = getTextFromCache( pageName );
}
else
{
result = m_provider.getPageText( pageName, version );
}
}
return result;
}
/**
* @throws RepositoryModifiedException If the page has been externally modified.
*/
private String getTextFromCache( String pageName )
throws ProviderException,
RepositoryModifiedException
{
String text;
if( pageName == null ) return null;
WikiPage page = getPageInfoFromCache( pageName );
try
{
text = (String)m_textCache.getFromCache( pageName,
m_pageContentExpiryPeriod );
if( text == null )
{
if( page != null )
{
text = m_provider.getPageText( pageName, WikiPageProvider.LATEST_VERSION );
m_textCache.putInCache( pageName, text );
m_cacheMisses++;
}
else
{
return null;
}
}
else
{
m_cacheHits++;
}
}
catch( NeedsRefreshException e )
{
if( pageExists(pageName) )
{
text = m_provider.getPageText( pageName, WikiPageProvider.LATEST_VERSION );
m_textCache.putInCache( pageName, text );
m_cacheMisses++;
}
else
{
m_textCache.putInCache( pageName, null );
return null; // No page exists
}
}
return text;
}
public void putPageText( WikiPage page, String text )
throws ProviderException
{
synchronized(this)
{
m_provider.putPageText( page, text );
page.setLastModified( new Date() );
// Refresh caches properly
m_cache.flushEntry( page.getName() );
m_textCache.flushEntry( page.getName() );
m_historyCache.flushEntry( page.getName() );
m_negCache.flushEntry( page.getName() );
// Refresh caches
try
{
getPageInfoFromCache( page.getName() );
}
catch(RepositoryModifiedException e) {} // Expected
}
}
public Collection getAllPages()
throws ProviderException
{
Collection all;
if( m_gotall == false )
{
all = m_provider.getAllPages();
// Make sure that all pages are in the cache.
synchronized(this)
{
for( Iterator i = all.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage) i.next();
m_cache.putInCache( p.getName(), p );
// Requests for this page are now no longer denied
m_negCache.putInCache( p.getName(), null );
}
m_gotall = true;
}
}
else
{
all = m_allCollector.getAllItems();
}
return all;
}
public Collection getAllChangedSince( Date date )
{
return m_provider.getAllChangedSince( date );
}
public int getPageCount()
throws ProviderException
{
return m_provider.getPageCount();
}
public Collection findPages( QueryItem[] query )
{
// If the provider is a fast searcher, then
// just pass this request through.
return m_provider.findPages( query );
// FIXME: Does not implement fast searching
}
// FIXME: Kludge: make sure that the page is also parsed and it gets all the
// necessary variables.
private void refreshMetadata( WikiPage page )
{
if( page != null && !page.hasMetadata() )
{
RenderingManager mgr = m_engine.getRenderingManager();
try
{
String data = m_provider.getPageText(page.getName(), page.getVersion());
WikiContext ctx = new WikiContext( m_engine, page );
MarkupParser parser = mgr.getParser( ctx, data );
parser.parse();
}
catch( Exception ex )
{
log.debug("Failed to retrieve variables for wikipage "+page);
}
}
}
public WikiPage getPageInfo( String pageName, int version )
throws ProviderException,
RepositoryModifiedException
{
WikiPage page = null;
WikiPage cached = getPageInfoFromCache( pageName );
int latestcached = (cached != null) ? cached.getVersion() : Integer.MIN_VALUE;
if( version == WikiPageProvider.LATEST_VERSION ||
version == latestcached )
{
if( cached == null )
{
WikiPage data = m_provider.getPageInfo( pageName, version );
if( data != null )
{
m_cache.putInCache( pageName, data );
// Requests for this page are now no longer denied
m_negCache.putInCache( pageName, null );
}
page = data;
}
else
{
page = cached;
}
}
else
{
// We do not cache old versions.
page = m_provider.getPageInfo( pageName, version );
//refreshMetadata( page );
}
refreshMetadata( page );
return page;
}
public List getVersionHistory( String page )
throws ProviderException
{
List history = null;
if( page == null ) return null;
try
{
history = (List)m_historyCache.getFromCache( page,
m_expiryPeriod );
log.debug("History cache hit for page "+page);
m_historyCacheHits++;
}
catch( NeedsRefreshException e )
{
history = m_provider.getVersionHistory( page );
m_historyCache.putInCache( page, history );
log.debug("History cache miss for page "+page);
m_historyCacheMisses++;
}
return history;
}
public synchronized String getProviderInfo()
{
return("Real provider: "+m_provider.getClass().getName()+
"<br />Cache misses: "+m_cacheMisses+
"<br />Cache hits: "+m_cacheHits+
"<br />History cache hits: "+m_historyCacheHits+
"<br />History cache misses: "+m_historyCacheMisses+
"<br />Cache consistency checks: "+m_expiryPeriod+"s");
}
public void deleteVersion( String pageName, int version )
throws ProviderException
{
// Luckily, this is such a rare operation it is okay
// to synchronize against the whole thing.
synchronized( this )
{
WikiPage cached = getPageInfoFromCache( pageName );
int latestcached = (cached != null) ? cached.getVersion() : Integer.MIN_VALUE;
// If we have this version cached, remove from cache.
if( version == WikiPageProvider.LATEST_VERSION ||
version == latestcached )
{
m_cache.flushEntry( pageName );
m_textCache.putInCache( pageName, null );
m_historyCache.putInCache( pageName, null );
}
m_provider.deleteVersion( pageName, version );
}
}
public void deletePage( String pageName )
throws ProviderException
{
// See note in deleteVersion().
synchronized(this)
{
m_cache.putInCache( pageName, null );
m_textCache.putInCache( pageName, null );
m_historyCache.putInCache( pageName, null );
m_negCache.putInCache( pageName, pageName );
m_provider.deletePage( pageName );
}
}
public void movePage( String from,
String to )
throws ProviderException
{
m_provider.movePage( from, to );
synchronized(this)
{
// Clear any cached version of the old page
log.debug("Removing page "+from+" from cache");
m_cache.flushEntry( from );
// Clear the cache for the to page, if that page already exists
//if ( m_cache.get( to ) != null )
log.debug("Removing page "+to+" from cache");
m_cache.flushEntry( to );
}
}
/**
* Returns the actual used provider.
* @since 2.0
*/
public WikiPageProvider getRealProvider()
{
return m_provider;
}
/**
* This is a simple class that keeps a list of all WikiPages that
* we have in memory. Because the OSCache cannot give us a list
* of all pages currently in cache, we'll have to check this.
*
* @author jalkanen
*
* @since
*/
private class CacheItemCollector
implements CacheEntryEventListener
{
private TreeSet m_allItems = new TreeSet();
/**
*
* Returns a clone of the set - you cannot manipulate this.
* @return
*/
public Set getAllItems()
{
return (Set)m_allItems.clone();
}
public void cacheEntryAdded( CacheEntryEvent arg0 )
{
cacheEntryUpdated( arg0 );
}
public void cachePatternFlushed( CachePatternEvent ev )
{
}
public void cacheGroupFlushed( CacheGroupEvent ev )
{
}
public void cacheFlushed( CachewideEvent ev )
{
}
public void cacheEntryFlushed( CacheEntryEvent arg0 )
{
cacheEntryRemoved( arg0 );
}
public void cacheEntryRemoved( CacheEntryEvent arg0 )
{
WikiPage item = (WikiPage) arg0.getEntry().getContent();
if( item != null )
{
m_allItems.remove( item );
}
}
public void cacheEntryUpdated( CacheEntryEvent arg0 )
{
WikiPage item = (WikiPage) arg0.getEntry().getContent();
if( item != null )
{
// Item added or replaced.
m_allItems.add( item );
}
else
{
// Removed item
// FIXME: If the page system is changed during this time, we'll just fail gracefully
try
{
for( Iterator i = m_allItems.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage)i.next();
if( p.getName().equals( arg0.getKey() ) )
{
i.remove();
break;
}
}
}
catch( Exception e )
{}
}
}
}
}
|
package com.example.glasswareXE12.main;
import java.io.File;
import com.google.android.glass.app.Card;
import com.google.android.glass.media.CameraManager;
import com.google.android.glass.touchpad.GestureDetector;
import android.app.Activity;
import android.content.Intent;
import android.gesture.Gesture;
import android.view.KeyEvent;
import android.view.View;
import android.view.Menu;
import android.view.WindowManager;
import android.os.Bundle;
import android.os.FileObserver;
import android.provider.MediaStore;
public class MainActivity extends Activity {
//declare privates
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//keeps the camera on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Card card1 = new Card(this);
card1.setText("Nice Picture!");
card1.setFootnote("Cool! ...");
View card1View = card1.toView();
setContentView(card1View);
takePicture();
}
/**
* Boiler plate google code
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CAMERA) {
// Stop the preview and release the camera.
// Execute your logic as quickly as possible
// so the capture happens quickly.
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onResume() {
super.onResume();
// Re-acquire the camera and start the preview.
}
private static final int TAKE_PICTURE_REQUEST = 1;
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) {
String picturePath = data.getStringExtra(
CameraManager.EXTRA_PICTURE_FILE_PATH);
processPictureWhenReady(picturePath);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void processPictureWhenReady(final String picturePath) {
final File pictureFile = new File(picturePath);
if (pictureFile.exists()) {
// The picture is ready; process it.
} else {
// The file does not exist yet. Before starting the file observer, you
// can update your UI to let the user know that the application is
// waiting for the picture (for example, by displaying the thumbnail
// image and a progress indicator).
final File parentDirectory = pictureFile.getParentFile();
FileObserver observer = new FileObserver(parentDirectory.getPath()) {
// Protect against additional pending events after CLOSE_WRITE is
// handled.
private boolean isFileWritten;
@Override
public void onEvent(int event, String path) {
if (!isFileWritten) {
// For safety, make sure that the file that was created in
// the directory is actually the one that we're expecting.
File affectedFile = new File(parentDirectory, path);
isFileWritten = (event == FileObserver.CLOSE_WRITE
&& affectedFile.equals(pictureFile));
if (isFileWritten) {
stopWatching();
// Now that the file is ready, recursively call
// processPictureWhenReady again (on the UI thread).
runOnUiThread(new Runnable() {
@Override
public void run() {
processPictureWhenReady(picturePath);
}
});
}
}
}
};
observer.startWatching();
}
}
/*
* end of boiler plate
*/
}
|
package com.gmail.harleenssahni.mbr;
import static com.gmail.harleenssahni.mbr.Constants.TAG;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.gmail.harleenssahni.mbr.receivers.MediaButtonReceiver;
/**
* Allows the user to choose which media receiver will handle a media button
* press. Can be navigated via touch screen or media button keys. Provides voice
* feedback.
*
* @author harleenssahni@gmail.com
*/
public class MediaButtonList extends ListActivity implements OnInitListener {
private class SweepBroadcastReceiver extends BroadcastReceiver {
String name;
public SweepBroadcastReceiver(String name) {
this.name = name;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Media Button Selector: After running broadcast receiver " + name + "have resultcode: "
+ getResultCode() + " result Data: " + getResultData());
}
}
/**
* Key used to store and retrieve last selected receiver.
*/
private static final String SELECTION_KEY = "btButtonSelection";
/**
* Key used to store and retrieve last selected receiver that actually was
* forwarded a media button by the user.
*/
private static final String SELECTION_ACTED_KEY = "btButtonSelectionActed";
/**
* Number of seconds to wait before timing out and just cancelling.
*/
private int timeoutTime;
/**
* The media button event that {@link MediaButtonReceiver} captured, and
* that we will be forwarding to a music player's {@code BroadcastReceiver}
* on selection.
*/
private KeyEvent trappedKeyEvent;
/**
* The {@code BroadcastReceiver}'s registered in the system for *
* {@link Intent.ACTION_MEDIA_BUTTON}.
*/
private List<ResolveInfo> receivers;
/** The intent filter for registering our local {@code BroadcastReceiver}. */
private IntentFilter uiIntentFilter;
/** The text to speech engine used to announce navigation to the user. */
private TextToSpeech textToSpeech;
/**
* The receiver currently selected by bluetooth next/prev navigation. We
* track this ourselves because there isn't persisted selection w/ touch
* screen interfaces.
*/
private int btButtonSelection;
/**
* Whether we've done the start up announcement to the user using the text
* to speech. Tracked so we don't repeat ourselves on orientation change.
*/
private boolean announced;
/**
* The power manager used to wake the device with a wake lock so that we can
* handle input. Allows us to have a regular activity life cycle when media
* buttons are pressed when and the screen is off.
*/
private PowerManager powerManager;
/**
* Used to wake up screen so that we can navigate our UI and select an app
* to handle media button presses when display is off.
*/
private WakeLock wakeLock;
/**
* ScheduledExecutorService used to time out and close activity if the user
* doesn't make a selection within certain amount of time. Resets on user
* interaction.
*/
private ScheduledExecutorService timeoutExecutor;
/**
* ScheduledFuture of timeout.
*/
private ScheduledFuture<?> timeoutScheduledFuture;
/** The cancel button. */
private View cancelButton;
private ImageView mediaImage;
/** The header */
private TextView header;
/** The intro dialog. May be null if no dialog is being shown. */
private AlertDialog introDialog;
/**
* Local broadcast receiver that allows us to handle media button events for
* navigation inside the activity.
*/
private BroadcastReceiver uiMediaReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent navigationKeyEvent = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
int keyCode = navigationKeyEvent.getKeyCode();
if (Utils.isMediaButton(keyCode)) {
Log.i(TAG, "Media Button Selector: UI is directly handling key: " + navigationKeyEvent);
if (navigationKeyEvent.getAction() == KeyEvent.ACTION_UP) {
switch (keyCode) {
case KeyEvent.KEYCODE_MEDIA_NEXT:
moveSelection(1);
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
moveSelection(-1);
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
select();
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
// just cancel
finish();
break;
default:
break;
}
}
abortBroadcast();
}
}
}
};
/**
* {@inheritDoc}
*/
@Override
public void onInit(int status) {
// text to speech initialized
// XXX This is where we announce to the user what we're handling. It's
// not clear that this will always get called. I don't know how else to
// query if the text to speech is started though.
// Only annouce if we haven't before
if (!announced && trappedKeyEvent != null) {
String actionText = "";
switch (trappedKeyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
// This is just play even though the keycode is both play/pause,
// the app shouldn't handle
// pause if music is already playing, it should go to whoever is
// playing the music.
actionText = getString(R.string.play_speak_text);
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
actionText = getString(R.string.next_speak_text);
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
actionText = getString(R.string.previous_speak_text);
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
actionText = getString(R.string.stop_speak_text);
break;
}
String textToSpeak = null;
if (btButtonSelection > 0 && btButtonSelection < receivers.size()) {
textToSpeak = String.format(getString(R.string.application_announce_speak_text), actionText,
getAppName(receivers.get(btButtonSelection)));
} else {
textToSpeak = String.format(getString(R.string.announce_speak_text), actionText);
}
textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null);
announced = true;
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Media Button Selector: On Create Called");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
setContentView(R.layout.media_button_list);
uiIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
uiIntentFilter.setPriority(Integer.MAX_VALUE);
// TODO Handle text engine not installed, etc. Documented on android
// developer guide
textToSpeech = new TextToSpeech(this, this);
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
// XXX can't use integer array, argh:
timeoutTime = Integer.valueOf(preferenceManager.getString(Constants.TIMEOUT_KEY, "5"));
// XXX Is mode private right? Will this result in the selection
// being
// stored in different places for this
// and MediaButtonListLocked
// btButtonSelection = savedInstanceState != null ?
// savedInstanceState.getInt(SELECTION_KEY, -1) : -1;
btButtonSelection = getPreferences(MODE_PRIVATE).getInt(SELECTION_KEY, -1);
receivers = Utils.getMediaReceivers(getPackageManager());
Boolean lastAnnounced = (Boolean) getLastNonConfigurationInstance();
if (lastAnnounced != null) {
announced = lastAnnounced;
}
// Remove our app's receiver from the list so users can't select it.
// NOTE: Our local receiver isn't registered at this point so we don't
// have to remove it.
if (receivers != null) {
for (int i = 0; i < receivers.size(); i++) {
if (MediaButtonReceiver.class.getName().equals(receivers.get(i).activityInfo.name)) {
receivers.remove(i);
break;
}
}
}
// TODO MAYBE sort receivers by MRU so user doesn't have to skip as many
// apps,
// right now apps are sorted by priority (not set by the user, set by
// the app authors.. )
setListAdapter(new BaseAdapter() {
@Override
public int getCount() {
return receivers.size();
}
@Override
public Object getItem(int position) {
return receivers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.media_receiver_view, null);
}
ResolveInfo resolveInfo = receivers.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.receiverAppImage);
imageView.setImageDrawable(resolveInfo.loadIcon(getPackageManager()));
TextView textView = (TextView) view.findViewById(R.id.receiverAppName);
textView.setText(getAppName(resolveInfo));
return view;
}
});
header = (TextView) findViewById(R.id.dialogHeader);
cancelButton = findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mediaImage = (ImageView) findViewById(R.id.mediaImage);
Log.i(TAG, "Media Button Selector: created.");
}
/**
* {@inheritDoc}
*/
@Override
protected void onDestroy() {
super.onDestroy();
textToSpeech.shutdown();
Log.d(TAG, "Media Button Selector: destroyed.");
}
/**
* {@inheritDoc}
*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
btButtonSelection = position;
forwardToMediaReceiver(position);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "Media Button Selector: onPause");
Log.d(TAG, "Media Button Selector: unegistered UI receiver");
unregisterReceiver(uiMediaReceiver);
if (wakeLock.isHeld()) {
wakeLock.release();
}
textToSpeech.stop();
timeoutExecutor.shutdownNow();
getPreferences(MODE_PRIVATE).edit().putInt(SELECTION_KEY, btButtonSelection).commit();
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "Media Button Selector: On Start called");
// TODO Originally thought most work should happen onResume and onPause.
// I don't know if the onResume part is
// right since you can't actually ever get back to this view, single
// instance, and not shown in recents. Maybe it's possible if ANOTHER
// dialog opens in front of ours?
}
/**
* {@inheritDoc}
*/
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "Media Button Selector: onResume");
// Check to see if intro has been displayed before
if (introDialog == null || !introDialog.isShowing()) {
introDialog = Utils.showIntroifNeccessary(this);
}
// TODO Clean this up, figure out which things need to be set on the
// list view and which don't.
if (getIntent().getExtras() != null && getIntent().getExtras().get(Intent.EXTRA_KEY_EVENT) != null) {
trappedKeyEvent = (KeyEvent) getIntent().getExtras().get(Intent.EXTRA_KEY_EVENT);
Log.i(TAG, "Media Button Selector: handling event: " + trappedKeyEvent + " from intent:" + getIntent());
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setClickable(true);
getListView().setFocusable(true);
getListView().setFocusableInTouchMode(true);
String action = "";
switch (trappedKeyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
action = getString(R.string.play);
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
action = getString(R.string.next);
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
action = getString(R.string.prev);
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
action = getString(R.string.stop);
break;
}
header.setText(String.format(getString(R.string.dialog_header_with_action), action));
} else {
Log.i(TAG, "Media Button Selector: launched without key event, started with intent: " + getIntent());
trappedKeyEvent = null;
getListView().setClickable(false);
getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
getListView().setFocusable(false);
getListView().setFocusableInTouchMode(false);
}
Log.d(TAG, "Media Button Selector: Registered UI receiver");
registerReceiver(uiMediaReceiver, uiIntentFilter);
// power on device's screen so we can interact with it, otherwise on
// pause gets called immediately.
// alternative would be to change all of the selection logic to happen
// in a service?? don't know if that process life cycle would fit well
// -- look into
// added On after release so screen stays on a little longer instead of
// immediately to try and stop resume pause cycle that sometimes
// happens.
wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, TAG);
wakeLock.setReferenceCounted(false);
wakeLock.acquire();
timeoutExecutor = Executors.newSingleThreadScheduledExecutor();
if (introDialog == null) {
// Don't time out in the middle of showing the dialog, that's rude.
// We could reset timeout here, but this is the first time the user
// is seeing the selection screen, so just let it stay till they
// dismiss.
resetTimeout();
}
}
/**
* {@inheritDoc}
*/
@Override
public Object onRetainNonConfigurationInstance() {
return announced;
}
/**
* {@inheritDoc}
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.selector_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_settings) {
startActivity(new Intent(this, MediaButtonConfigure.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Resets the timeout before the application is automatically dismissed.
*/
private void resetTimeout() {
if (timeoutScheduledFuture != null) {
timeoutScheduledFuture.cancel(false);
}
timeoutScheduledFuture = timeoutExecutor.schedule(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
onTimeout();
}
});
}
}, timeoutTime, TimeUnit.SECONDS);
}
/**
* {@inheritDoc}
*/
@Override
public void onUserInteraction() {
super.onUserInteraction();
// Reset timeout to finish
if (!timeoutExecutor.isShutdown()) {
resetTimeout();
}
}
/**
* Forwards the {@code #trappedKeyEvent} to the receiver at specified
* position.
*
* @param position
* The index of the receiver to select. Must be in bounds.
*/
private void forwardToMediaReceiver(int position) {
ResolveInfo resolveInfo = receivers.get(position);
if (resolveInfo != null) {
if (trappedKeyEvent != null) {
ComponentName selectedReceiver = new ComponentName(resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name);
Utils.forwardKeyCodeToComponent(this, selectedReceiver, true, trappedKeyEvent.getKeyCode(),
new SweepBroadcastReceiver(selectedReceiver.toString()));
// save the last acted on app in case we have no idea who is
// playing music so we can make a guess
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putString(SELECTION_ACTED_KEY, resolveInfo.activityInfo.name).commit();
finish();
}
}
}
/**
* Returns the name of the application of the broadcast receiver specified
* by {@code resolveInfo}.
*
* @param resolveInfo
* The receiver.
* @return The name of the application.
*/
private String getAppName(ResolveInfo resolveInfo) {
return resolveInfo.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();
}
/**
* Moves selection by the amount specified in the list. If we're already at
* the last item and we're moving forward, wraps to the first item. If we're
* already at the first item, and we're moving backwards, wraps to the last
* item.
*
* @param amount
* The amount to move, may be positive or negative.
*/
private void moveSelection(int amount) {
resetTimeout();
btButtonSelection += amount;
if (btButtonSelection >= receivers.size()) {
// wrap
btButtonSelection = 0;
} else if (btButtonSelection < 0) {
// wrap
btButtonSelection = receivers.size() - 1;
}
// May not highlight, but will scroll to item
getListView().setSelection(btButtonSelection);
textToSpeech.speak(getAppName(receivers.get(btButtonSelection)), TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Select the currently selected receiver.
*/
private void select() {
// TODO if there is no selection, we should either forward to whoever
// would have handled if we didn't exist, or to mru
if (btButtonSelection == -1) {
finish();
} else {
forwardToMediaReceiver(btButtonSelection);
}
}
/**
* Takes appropriate action to notify user and dismiss activity on timeout.
*/
private void onTimeout() {
Log.d(TAG, "Media Button Selector: Timed out waiting for user interaction, finishing activity");
final MediaPlayer timeoutPlayer = MediaPlayer.create(this, R.raw.dismiss);
timeoutPlayer.start();
// not having an on error listener results in on completion listener
// being called anyway
timeoutPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
timeoutPlayer.release();
}
});
finish();
}
}
|
package com.isitchristmas.android;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
public class ChristmasActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
isItChristmas(); // set the answer now
setLocalAlarm(); // so it updates this screen while the user is watching on Christmas
// will cancel and re-schedule all alarms when the user opens the app
ChristmasUtils.setAlarms(this);
}
public void isItChristmas() {
((TextView) findViewById(R.id.answer)).setText(Christmas.answer(Christmas.isIt(), Locale.getDefault()));
}
final Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
isItChristmas();
}
};
public void setLocalAlarm() {
Thread alarm = new Thread() {
public void run() {
long untilChristmas = Christmas.time() - System.currentTimeMillis();
try {
sleep(untilChristmas);
} catch(InterruptedException e) {
// well, I never
}
handler.post(updater);
};
};
alarm.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.preferences:
startActivity(new Intent(this, ChristmasPreferences.class));
break;
}
return true;
}
}
|
package com.jayantkrish.jklol.util;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
/**
* Counts (fractional) occurrences of objects of type {@code T}. This
* class is similar to {@link Multimap}, except that occurrence counts
* can be fractional. A common use of this class is to estimate a
* multinomial distribution over an unknown set of objects.
*
* @author jayantk
*/
public class CountAccumulator<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final DefaultHashMap<T, Double> counts;
private double totalCount;
/**
* See {@link #create()}.
*/
private CountAccumulator() {
counts = new DefaultHashMap<T, Double>(0.0);
totalCount = 0.0;
}
/**
* Creates an accumulator with a count of 0 for all T, without
* requiring a type argument.
*
* @return
*/
public static <T> CountAccumulator<T> create() {
return new CountAccumulator<T>();
}
/**
* Increments the occurrence count for {@code item} by
* {@code amount}.
*
* @param item
* @param amount
*/
public void increment(T item, double amount) {
counts.put(item, counts.get(item) + amount);
totalCount += amount;
}
/**
* Increments the occurrence count of each key in {@code amounts} by
* its corresponding value.
*
* @param amounts
*/
public void increment(Map<? extends T, Double> amounts) {
for (Map.Entry<? extends T, Double> entry : amounts.entrySet()) {
increment(entry.getKey(), entry.getValue());
}
}
/**
* Increments the occurrence count (in {@code this}) of each item in
* {@code amounts} by its corresponding count.
*
* @param amounts
*/
public void increment(CountAccumulator<? extends T> amounts) {
increment(amounts.getCountMap());
}
/**
* Increments by 1 the count of each item in {@code items}.
*
* @param items
*/
public void incrementByOne(Collection<? extends T> items) {
for (T item : items) {
increment(item, 1.0);
}
}
public void multiply(T item, double amount) {
double originalCount = counts.get(item);
counts.put(item, originalCount * amount);
totalCount += (originalCount * amount) - originalCount;
}
/**
* Gets the occurrence count associated with {@code item}.
*
* @param item
* @return
*/
public double getCount(T item) {
return counts.get(item);
}
/**
* Gets the empirical probability of {@code item}, that is
* {@code getCount(item) / getTotalCount()}.
*
* @param item
* @return
*/
public double getProbability(T item) {
return getCount(item) / getTotalCount();
}
/**
* Gets the sum of occurrence counts for all items in {@code this}.
*
* @return
*/
public double getTotalCount() {
return totalCount;
}
/**
* Gets all items T which have been observed.
*
* @return
*/
public Set<T> keySet() {
return counts.keySet();
}
/**
* Gets the keys in this sorted order, from
* the highest count to the lowest count.
*
* @return
*/
public List<T> getSortedKeys() {
List<T> l = Lists.newArrayList(counts.keySet());
Collections.sort(l, Ordering.natural().reverse().onResultOf(Functions.forMap(counts.getBaseMap())));
return l;
}
/**
* Returns the set of keys in this whose total count is strictly
* greater than {@code threshold}.
*
* @param threshold
* @return
*/
public Set<T> getKeysAboveCountThreshold(double threshold) {
Set<T> keys = Sets.newHashSet();
for (T key : counts.keySet()) {
if (counts.get(key) > threshold) {
keys.add(key);
}
}
return keys;
}
/**
* Gets the counts in {@code this} as a {@code Map}. Each observed
* item is a key in the returned map, and its occurrence count is
* the corresponding value.
*
* @return
*/
public Map<T, Double> getCountMap() {
return counts.getBaseMap();
}
/**
* Gets the probabilities of the items in {@code this} as a
* {@code Map}. Each observed item is a key in the returned map, and
* its probability is the corresponding value.
*
* @return
*/
public Map<T, Double> getProbabilityMap() {
Map<T, Double> probabilityMap = Maps.newHashMap();
for (T item : counts.keySet()) {
probabilityMap.put(item, getProbability(item));
}
return probabilityMap;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((counts == null) ? 0 : counts.hashCode());
long temp;
temp = Double.doubleToLongBits(totalCount);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CountAccumulator other = (CountAccumulator) obj;
if (counts == null) {
if (other.counts != null)
return false;
} else if (!counts.equals(other.counts))
return false;
if (Double.doubleToLongBits(totalCount) != Double.doubleToLongBits(other.totalCount))
return false;
return true;
}
}
|
package com.kirelcodes.RoboticCraft.robot;
import static com.kirelcodes.RoboticCraft.utils.NMSClassInteracter.getDeclaredField;
import static com.kirelcodes.RoboticCraft.utils.NMSClassInteracter.getField;
import static com.kirelcodes.RoboticCraft.utils.NMSClassInteracter.getNMS;
import static com.kirelcodes.RoboticCraft.utils.NMSClassInteracter.getVersion;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.StringJoiner;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Chicken;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.EulerAngle;
import com.bekvon.bukkit.residence.api.ResidenceApi;
import com.kirelcodes.RoboticCraft.RoboticCraft;
import com.kirelcodes.RoboticCraft.pathFinders.FollowPathfinder;
import com.kirelcodes.RoboticCraft.pathFinders.PathManager;
import com.kirelcodes.RoboticCraft.pathFinders.RandomStrollPathfinder;
import com.kirelcodes.RoboticCraft.robot.animation.AnimationFrame;
import com.kirelcodes.RoboticCraft.robot.animation.AnimationManager;
import com.kirelcodes.RoboticCraft.utils.ItemStackUtils;
import com.kirelcodes.RoboticCraft.utils.NBTRobotId;
import com.massivecraft.factions.entity.BoardColl;
import com.massivecraft.factions.entity.Faction;
import com.massivecraft.factions.entity.FactionColl;
import com.massivecraft.factions.entity.MPlayer;
import com.massivecraft.massivecore.ps.PS;
/**
*
* @author NacOJerk
*
*/
public class RobotBase implements InventoryHolder {
protected AnimationFrame deafult = new AnimationFrame()
.setBody(new EulerAngle(0, 0, 0)).setHead(new EulerAngle(0, 0, 0))
.setLeftHand(new EulerAngle(0, 0, 0))
.setLeftLeg(new EulerAngle(0, 0, 0))
.setRightHand(new EulerAngle(0, 0, 0))
.setRightLeg(new EulerAngle(0, 0, 0));
private Chicken chick;
private ArmorStand armorStand;
private boolean isStuck;
private int ID;
private int fuel;
private boolean isFollowing;
private Entity followTarget;
private RobotTask robotTask;
private Inventory invetory;
private Object nmsHandel;
private UUID owner;
protected PathManager pathManager;
private Location targetLocation, previus;
/**
* Responsible for the armor stand teleportation and target following
*
* @author NacOJerk
*
*/
public class RobotTask implements Runnable {
private int ID;
// private int mark; not needed
// private int stuckCalc;
// private Location previus;
public RobotTask() {
this.ID = Bukkit.getScheduler().scheduleSyncRepeatingTask(
RoboticCraft.getInstance(), this, 0L, 1L);
// mark = 0;
}
@Override
public void run() {
if (!hasFuel()) {
try {
setTargetLocation(getLocation());
} catch (Exception e) {
// Error thrower here
}
}
if (onTargetLocation()) {
AnimationManager.walk.cancelTask(getArmorStand());
deafult.setLocations(getArmorStand());
}
if (previus.distanceSquared(getLocation()) < 1) {
AnimationManager.walk.cancelTask(getArmorStand());
deafult.setLocations(getArmorStand());
}
getArmorStand().teleport(getLocation());
previus = getLocation();
}
public void cancel() {
Bukkit.getScheduler().cancelTask(ID);
}
}
/**
* Spawns the robot
*
* @param loc
* the location where the robot would be spawned
* @param owner
*
*/
public RobotBase(Location loc, UUID owner) {
Chicken chick = null;
if (getVersion().contains("9")) {
try {
chick = getSilentChicken(loc);
} catch (Exception e1) {
e1.printStackTrace();
}
} else
chick = (Chicken) loc.getWorld().spawnEntity(loc,
EntityType.CHICKEN);
this.chick = chick;
this.chick.setMaxHealth(Integer.MAX_VALUE);
this.chick.setHealth(this.chick.getMaxHealth());
final Chicken fchick = chick;
Bukkit.getScheduler().scheduleSyncDelayedTask(
RoboticCraft.getInstance(), new Runnable() {
public void run() {
try {
clearChicken();
} catch (Exception e) {
fchick.remove();
return;
}
}
}, 2L);
this.armorStand = (ArmorStand) getWorld().spawnEntity(getLocation(),
EntityType.ARMOR_STAND);
this.armorStand.setBasePlate(false);
this.armorStand.setArms(true);
try {
this.armorStand
.setHelmet(ItemStackUtils
.getSkullFromURL(
"http://textures.minecraft.net/texture/c510d9b61ca333d2946c61a26cb17e374d4adb573b46afdebaf89f65ba5d4ae2",
"Robot"));
} catch (Exception e) {
e.printStackTrace();
}
this.armorStand.setBoots(new ItemStack(Material.IRON_BOOTS));
this.armorStand.setLeggings(new ItemStack(Material.IRON_LEGGINGS));
this.armorStand.setChestplate(new ItemStack(Material.IRON_CHESTPLATE));
this.armorStand.setMarker(true);
setFuel(100);
this.pathManager = new PathManager(this);
addPaths();
this.invetory = Bukkit.createInventory(this, 9 * 3, ChatColor.RED
+ "Robot's Inventory");
this.robotTask = new RobotTask();
this.ID = RobotCenter.addRobot(this);
getArmorStand().setCustomName(
ChatColor.MAGIC + "NacOJerkGalShaked-" + ID);
getArmorStand().setCustomNameVisible(false);
this.previus = getLocation();
this.owner = owner;
if (!checkAllowed(loc))
remove();
}
/**
* Spawns the robot
*
* @param loc
* the location where the robot would be spawned
* @param owner
*
*/
public RobotBase(Location loc, Player owner) {
this(loc, owner.getUniqueId());
}
/**
* Adds the paths to the code
*/
protected void addPaths() {
pathManager.addPath(new RandomStrollPathfinder(this));
pathManager.addPath(new FollowPathfinder(this));
}
/**
*
* @return the location of the navigator (chicken)
*/
public Location getLocation() {
return chick.getLocation();
}
public World getWorld() {
return getLocation().getWorld();
}
/**
*
* @return an NMS version of the chicken
* @throws Exception
*/
private Object getNMSHandle() throws Exception {
return (nmsHandel == null) ? (nmsHandel = chick.getClass()
.getMethod("getHandle").invoke(chick)) : nmsHandel;
}
/**
* Clears the chicken pathfinders Sets its size to the armor stand one (for
* the navigator) Sets it invisible
*
* @throws Exception
*/
private void clearChicken() throws Exception {
// chick.setCanPickupItems(true);
chick.setCustomName(ChatColor.MAGIC + "" + getID());
chick.setCustomNameVisible(false);
Object goalSelector = getField(getNMSHandle(), "goalSelector");
if (getVersion().contains("9")) {
LinkedHashSet<?> goalSelectorA = (LinkedHashSet<?>) getDeclaredField(
goalSelector, "b");
LinkedHashSet<?> goalSelectorB = (LinkedHashSet<?>) getDeclaredField(
goalSelector, "c");
goalSelectorA.clear();
goalSelectorB.clear();
} else {
List<?> goalSelectorA = (List<?>) getDeclaredField(goalSelector,
"b");
List<?> goalSelectorB = (List<?>) getDeclaredField(goalSelector,
"c");
goalSelectorA.clear();
goalSelectorB.clear();
}
getNMSHandle().getClass().getMethod("setInvisible", boolean.class)
.invoke(getNMSHandle(), true);
}
/**
* Sets the speed of the chicken (Navigator)
*
* @param speed
* chicken's deafult speed is 0.25D
* @throws Exception
*/
public void setSpeed(double speed) throws Exception {
Object MOVEMENT_SPEED = getNMS("GenericAttributes").getField(
"MOVEMENT_SPEED").get(null);
Object genericSpeed = getNMSHandle().getClass()
.getMethod("getAttributeInstance", getNMS("IAttribute"))
.invoke(getNMSHandle(), MOVEMENT_SPEED);
genericSpeed.getClass().getMethod("setValue", double.class)
.invoke(genericSpeed, speed);
}
/**
* Gets the speed of the chicken (Navigator)
*
* @throws Exception
*/
public double getSpeed() throws Exception {
Object MOVEMENT_SPEED = getNMS("GenericAttributes").getField(
"MOVEMENT_SPEED").get(null);
Object genericSpeed = getNMSHandle().getClass()
.getMethod("getAttributeInstance", getNMS("IAttribute"))
.invoke(getNMSHandle(), MOVEMENT_SPEED);
return (double) genericSpeed.getClass().getMethod("getValue")
.invoke(genericSpeed);
}
public boolean onTargetLocation() {
if (targetLocation == null)
return false;
if (targetLocation.distanceSquared(getLocation()) < 1) {
targetLocation = null;
return true;
}
return false;
}
/**
* Sets the location the robot should move to
*
* @param loc
* @return did it start or not
* @throws Exception
*/
public boolean setTargetLocation(Location loc) throws Exception {
Object navagation = getNMSHandle().getClass()
.getMethod("getNavigation").invoke(getNMSHandle());
Object path = navagation.getClass()
.getMethod("a", double.class, double.class, double.class)
.invoke(navagation, loc.getX(), loc.getY(), loc.getZ());
if (path == null) {
return false;
}
navagation.getClass()
.getMethod("a", getNMS("PathEntity"), double.class)
.invoke(navagation, path, getSpeed());
navagation.getClass().getMethod("a", double.class)
.invoke(navagation, 2.0D);
targetLocation = loc;
AnimationManager.walk.runAnimationCycle(getArmorStand(), 15L);
return true;
}
/**
* Get blocks in a nearby radius
*
* @param raduis
* @return
*/
public List<Block> getNearbyBlocks(int raduis) {
List<Block> circle = new ArrayList<>();
circle.add(getLocation().getBlock());
for(int i = 0 ; i < raduis ; i++)
circle.addAll(getCircle(getLocation(), i + 1));
return circle;
}
public List<Block> getCircle(Location loc , int i ){
List<Block> circle = new ArrayList<>();
Location relavtive = loc.clone();
relavtive.add(i, 0, i);
for(int x = 0; x < i * 2; x++){
relavtive.subtract(1, 0, 0);
circle.add(relavtive.getBlock());
}
for(int z = 0; z < i * 2; z++){
relavtive.subtract(0, 0, 1);
circle.add(relavtive.getBlock());
}
for(int x = 0; x < i * 2; x++){
relavtive.add(1, 0, 0);
circle.add(relavtive.getBlock());
}
for(int z = 0; z < i * 2; z++){
relavtive.add(0, 0, 1);
circle.add(relavtive.getBlock());
}
return circle;
}
/**
*
* @return the navigator (Chicken)
*/
public Chicken getNavigator() {
return chick;
}
/**
*
* @return the armor which represents the robot
*/
public ArmorStand getArmorStand() {
return armorStand;
}
/**
*
* @return if the robot haven't moved for 3 seconds a distance bigger than 1
* blocks
*/
public boolean isStuck() {
return isStuck;
}
/**
*
* @return the robot's ID
*/
public int getID() {
return ID;
}
public int getFuel() {
return fuel;
}
/**
* Between 0 to 100
*
* @param fuel
*/
public void setFuel(int fuel) {
if (!(0 <= fuel && fuel <= 100)) {
// Error logger here
return;
}
this.fuel = fuel;
}
public boolean hasFuel() {
return 0 < fuel;
}
/**
*
* @param en
* entity which the robot would follow
*/
public void setFollow(Entity en) {
this.followTarget = en;
this.isFollowing = true;
}
public boolean isFollowing() {
return isFollowing;
}
public Entity getFollowTarget() {
return followTarget;
}
public void cancelFollow() {
this.isFollowing = false;
this.followTarget = null;
}
private void setID(int ID) {
this.ID = ID;
}
/**
* Destroys the robot and drops an armor remove (Robot remove)
*/
public void destroy() {
ArmorStand armor = (ArmorStand) getWorld().spawnEntity(getLocation(),
EntityType.ARMOR_STAND);
StringJoiner string = new StringJoiner(" , ", "{", "}");
string.add("NacOSearilize");
string.add(this.getClass().getName());
string.add(getOwner().toString());
string.add(getID() + "");
armor.setCustomName(ChatColor.MAGIC + string.toString());
armor.setCustomNameVisible(false);
armor.setMarker(true);
armor.setVisible(false);
armor.setGravity(false);
getLocation().getBlock().setType(Material.CHEST);
Chest chesty = (Chest) getLocation().getBlock().getState();
for (int i = 0; i < getInventory().getContents().length; i++)
if (getInventory().getContents()[i] != null)
chesty.getBlockInventory().addItem(
getInventory().getContents()[i]);
remove();
}
@SuppressWarnings("deprecation")
public void guiDestroy(Player p) {
for (ItemStack stack : getInventory().getContents())
if (stack != null)
p.getInventory().addItem(stack);
p.setItemInHand(NBTRobotId.clearNBT(p.getItemInHand()));
remove();
}
public static RobotBase getRobot(ArmorStand armor, Chest chest)
throws Exception {
String[] data = ChatColor.stripColor(
armor.getCustomName().replaceAll("\\{", "")
.replaceAll("\\}", "")).split(" , ");
Inventory inven = chest.getInventory();
String clazz = data[1];
UUID uuid = UUID.fromString(data[2]);
int ID = Integer.parseInt(data[3]);
RobotBase robot = (RobotBase) Class.forName(clazz)
.getConstructor(Location.class, UUID.class)
.newInstance(armor.getLocation(), uuid);
for (int i = 0; i < inven.getContents().length; i++)
if (inven.getContents()[i] != null)
robot.addItem(inven.getContents()[i]);
RobotCenter.removeRobot(robot.getID());
robot.setID(ID);
RobotCenter.addRobotID(robot);
chest.getInventory().clear();
chest.getBlock().setType(Material.AIR);
armor.remove();
return robot;
}
/**
* Completely removes the robot
*/
public void remove() {
this.robotTask.cancel();
this.pathManager.cancel();
this.chick.remove();
this.armorStand.remove();
RobotCenter.removeRobot(getID());
}
public Inventory getInventory() {
return invetory;
}
public HashMap<Integer, ItemStack> addItem(ItemStack... item) {
HashMap<Integer, ItemStack> items = getInventory().addItem(item);
if (getFuel() != 100) {
for (ItemStack itemH : getInventory().getContents()) {
if(itemH == null)
continue;
if (itemH.getType() == Material.COAL_BLOCK) {
if(itemH.getAmount() == 1)
getInventory().remove(itemH);
else
itemH.setAmount(itemH.getAmount() - 1);
setFuel((getFuel() + 1) >= 100 ? 100 : getFuel() + 1);
break;
}
}
}
return items;
}
public static Chicken getSilentChicken(Location loc) throws Exception {
Object nbtTAG = getNMS("NBTTagCompound").getConstructor().newInstance();
nbtTAG.getClass()
.getDeclaredMethod("setString", String.class, String.class)
.invoke(nbtTAG, "id", "Chicken");
nbtTAG.getClass()
.getDeclaredMethod("setBoolean", String.class, boolean.class)
.invoke(nbtTAG, "Silent", true);
Object world = loc.getWorld().getClass().getMethod("getHandle")
.invoke(loc.getWorld());
Object entity = null;
if (getVersion().contains("9")) {
entity = getNMS("ChunkRegionLoader").getMethod("a",
nbtTAG.getClass(), getNMS("World"), double.class,
double.class, double.class, boolean.class).invoke(null,
nbtTAG, world, loc.getX(), loc.getY(), loc.getZ(), true);
entity.getClass()
.getMethod("setPosition", double.class, double.class,
double.class)
.invoke(entity, loc.getX(), loc.getY(), loc.getZ());
Object craftChicken = entity.getClass()
.getMethod("getBukkitEntity").invoke(entity);
return (Chicken) craftChicken;
} else {
return (Chicken) loc.getWorld()
.spawnEntity(loc, EntityType.CHICKEN);
}
}
public void setStuck(boolean stuck) {
this.isStuck = stuck;
}
public UUID getOwner() {
return owner;
}
public boolean checkAllowed(Location loc) {
if (RoboticCraft.usingWorldGuard())
if (!RoboticCraft.getWorldGuard().canBuild(
Bukkit.getPlayer(getOwner()), loc))
return false;
if (RoboticCraft.usingFactions()) {
Faction facL = BoardColl.get().getFactionAt(PS.valueOf(loc));
if (facL.getId().equals(FactionColl.get().getNone().getId())) {
MPlayer mplayer = MPlayer.get(owner);
if (facL.getId() != mplayer.getFactionId())
return false;
}
}
if(RoboticCraft.usingResidence()){
if (ResidenceApi.getResidenceManager().getByLoc(loc) != null)
if (RoboticCraft.usingResidence())
if (!ResidenceApi
.getPlayerManager()
.getResidenceList(
Bukkit.getOfflinePlayer(owner).getName())
.contains(
ResidenceApi.getResidenceManager()
.getNameByLoc(loc)))
return false;
}
return true;
}
}
|
package com.lamfire.chimaera.client;
import com.lamfire.logger.Logger;
import com.lamfire.utils.Threads;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class RebundleMonitor {
private static final Logger LOGGER = Logger.getLogger(RebundleMonitor.class);
private static final ScheduledExecutorService service = Executors.newScheduledThreadPool(1, Threads.makeThreadFactory("RebundleMonitor"));
public static void shutdownMonitorThread(){
service.shutdown();
}
private Map<String, Rebundler> map = new HashMap<String, Rebundler>();
public RebundleMonitor() {
service.scheduleWithFixedDelay(checker, 30, 30, TimeUnit.SECONDS);
}
public void add(Rebundler reBundler) {
String entryKey = entryKey(reBundler.getKey(), reBundler.getClientId());
this.map.put(entryKey, reBundler);
}
private String entryKey(String key, String clientId) {
return key + ":" + clientId;
}
public Rebundler remove(String key, String clientId) {
String entryKey = entryKey(key, clientId);
return this.map.remove(entryKey);
}
Runnable checker = new Runnable() {
@Override
public void run() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[RebundleMonitor]:check bundles [" + map.size() + "]");
}
try{
for (Map.Entry<String, Rebundler> e : map.entrySet()) {
Rebundler rebundler = e.getValue();
if (!rebundler.isAvailable()) {
LOGGER.info("[RebundleMonitor]: the bundle was unavailable :" + rebundler);
rebundler.rebind();
}
}
}catch (Throwable t){
}
}
};
}
|
package com.legit2.Demigods.Listeners;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import com.legit2.Demigods.DUtil;
public class DChatCommands implements Listener
{
@EventHandler
public void onChatCommand(AsyncPlayerChatEvent event)
{
// Define variables
Player player = event.getPlayer();
if(!DUtil.isImmortal(player.getName())) return;
if(event.getMessage().equals("pl")) pl(player,event);
}
private void pl(Player player, AsyncPlayerChatEvent event)
{
HashMap<String, ArrayList<String>> alliances = new HashMap<String, ArrayList<String>>();
for(Player onlinePlayer : DUtil.getPlugin().getServer().getOnlinePlayers())
{
if (DUtil.isImmortal(onlinePlayer.getName()))
{
if (!alliances.containsKey(DUtil.getAlliance(onlinePlayer.getName()).toUpperCase())) alliances.put(DUtil.getAlliance(onlinePlayer.getName()).toUpperCase(), new ArrayList<String>());
alliances.get(DUtil.getAlliance(onlinePlayer.getName()).toUpperCase()).add(onlinePlayer.getName());
}
}
for(String alliance : alliances.keySet())
{
{
String names = "";
for (String name : alliances.get(alliance)) names+=" "+name;
player.sendMessage(ChatColor.YELLOW+alliance+": "+ChatColor.WHITE+names);
}
event.getRecipients().clear();
event.setCancelled(true);
}
}
}
|
package com.pigmal.android.fourbeat.sample;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient.CustomViewCallback;
public class QuizView extends View{
private Handler mHander = new Handler();
private int mCurrentQuizNo = 0;
/**
*
* jpg gif mp3
*/
private String[][] mStage =
{
{
"uma1.jpg",
"uma2.jpg",
"uma3.jpg",
"uma4.jpg",
"uma.mp3",
"uma5.jpg",
},
{
"inu1.jpg",
"inu2.jpg",
"inu3.jpg",
"inu4.jpg",
"inu.mp3",
"inu5.jpg",
},
{
"elephant1.jpg",
"elephant2.jpg",
"elephant3.jpg",
"elephant4.jpg",
"zou.mp3",
"elephant5.jpg",
},
{
"neko1.jpg",
"neko2.jpg",
"neko3.jpg",
"neko4.jpg",
"cat.mp3",
"neko5.jpg",
},
};
private String[] mAnswers = {
"",
"",
"",
"",
};
private String mCurrentAnswer = "";
private Bitmap mCurrentBitmap = null;
private Bitmap mCorrectBitmap = null;
private Bitmap mIncorrectBitmap = null;
private Bitmap mTimeoutBitmap = null;
private Runnable mCurrentTask;
private int mCurrentPanelQuestion = 0;
private QuizViewListener mListener = null;
private boolean mIsCorrect = false;
private boolean mIsMistake = false;
private boolean mIsTimeout = false;
private static final int DELAY_MS = 3000;
public QuizView(Context context, AttributeSet attrs) {
super(context, attrs);
try {
InputStream is = getResources().getAssets().open("correct.png");
mCorrectBitmap = BitmapFactory.decodeStream(is);
is = getResources().getAssets().open("incorrect.png");
mIncorrectBitmap = BitmapFactory.decodeStream(is);
is = getResources().getAssets().open("timeout.png");
mTimeoutBitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.e("Quiz","");
e.printStackTrace();
}
}
/**
* init stage
* asset
* @param stage
*/
public void initStage(String stage) {
mCurrentQuizNo = 0;
}
private void playHint(String filename){
String extension = null;
int point = filename.lastIndexOf(".");
if (point != -1) {
extension = filename.substring(point + 1);
}
if ("gif".equals(extension) || "jpg".equals(extension)){
InputStream is;
try {
is = getResources().getAssets().open(filename);
mCurrentBitmap = BitmapFactory.decodeStream(is);
Log.d("Quiz"," "+filename);
} catch (IOException e) {
Log.e("Quiz", "", e);
e.printStackTrace();
}
}else if ("mp3".equals(extension)){
playSound(filename);
}
}
/**
*
* @param filename
*/
private void playSound(String filename){
try {
Log.d("Quiz"," "+filename);
if (filename.equals("uma.mp3")){
MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.uma);
mp.start();
return;
}else if (filename.equals("zou.mp3")){
MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.zou);
mp.start();
return;
}else if (filename.equals("inu.mp3")){
MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.inu);
mp.start();
return;
}else if (filename.equals("cat.mp3")){
MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.cat);
mp.start();
return;
}
AssetFileDescriptor afd = getContext().getAssets().openFd(filename);
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(afd.getFileDescriptor());
mp.prepare();
mp.start();
} catch (IOException e) {
Log.e("Quiz", "",e);
e.printStackTrace();
}
}
/**
*
*
* ()
*
* @param quizNo
*/
public void start(int quizNo){
if (quizNo >= mStage.length){
Log.d("Quiz","");
}
Log.d("Quiz","QuizView.start");
initStage(null);
mCurrentQuizNo = quizNo;
mCurrentPanelQuestion = 0;
mCurrentAnswer = mAnswers[quizNo];
mIsTimeout = false;
mIsCorrect = false;
playHint(getCurrentFilename());
refreash();
setNextHintTimer();
}
/**
* Stop Quiz
*/
public void stop(){
Log.d("Quiz","QuizView.stop");
if (mCurrentTask != null){
mHander.removeCallbacks(mCurrentTask);
}
}
/**
* Resume Quiz
*/
public void resume(){
Log.d("Quiz","QuizView.resume");
if (mIsMistake){
mIsMistake = false;
invalidateByUIThread();
}
if (mCurrentTask != null){
mHander.postDelayed(mCurrentTask, DELAY_MS);
}
}
private void setNextHintTimer(){
if (mCurrentTask != null){
mHander.removeCallbacks(mCurrentTask);
}
mCurrentTask = new Runnable() {
@Override
public void run() {
mCurrentPanelQuestion++;
if (mCurrentPanelQuestion >= mStage[mCurrentQuizNo].length){
mCurrentPanelQuestion = 0;
if (mListener != null){
mListener.quizFinished();
}
mIsTimeout = true;
invalidateByUIThread();
}else{
refreash();
setNextHintTimer();
}
}
};
mHander.postDelayed(mCurrentTask, DELAY_MS);
}
private void refreash(){
String currentFilename = getCurrentFilename();
playHint(currentFilename);
invalidateByUIThread();
}
private String getCurrentFilename(){
return mStage[mCurrentQuizNo][mCurrentPanelQuestion];
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("Quiz"," start");
if (mCurrentBitmap != null){
int w = mCurrentBitmap.getWidth();
int h = mCurrentBitmap.getHeight();
Rect src = new Rect(0, 0, w, h);
Rect dst = new Rect(0, 0,getWidth(),getHeight());
canvas.drawBitmap(mCurrentBitmap, src, dst, null);
}
if (mIsCorrect){
Log.d("Quiz", "");
Rect src = new Rect(0, 0, mCorrectBitmap.getWidth(), mCorrectBitmap.getHeight());
Rect dst = new Rect(0, 0,getWidth(),getHeight());
canvas.drawBitmap(mCorrectBitmap, src, dst, null);
}
if (mIsMistake){
Log.d("Quiz", "");
Rect src = new Rect(0, 0, mIncorrectBitmap.getWidth(), mIncorrectBitmap.getHeight());
Rect dst = new Rect(0, 0,getWidth(),getHeight());
canvas.drawBitmap(mIncorrectBitmap, src, dst, null);
}
if (mIsTimeout){
Log.d("Quiz", "");
Rect src = new Rect(0, 0, mTimeoutBitmap.getWidth(), mTimeoutBitmap.getHeight());
Rect dst = new Rect(0, 0,getWidth(),getHeight());
canvas.drawBitmap(mTimeoutBitmap, src, dst, null);
}
Log.d("Quiz"," end");
}
public QuizViewListener getListener() {
return mListener;
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
/*
if(visibility == View.INVISIBLE){
if (mCurrentTask != null){
mHander.removeCallbacks(mCurrentTask);
}
}*/
Log.d("Quiz","onVisivilityChanged visivility="+visibility);
}
/**
*
* @param answerList
* @return
*/
public boolean answer(List<String> answerList){
for(String ans:answerList){
if (ans.contains(mCurrentAnswer)){
Log.d("Quiz"," ="+mCurrentAnswer+" ="+ans);
mIsCorrect = true;
invalidateByUIThread();
return true;
}
}
mIsMistake = true;
invalidateByUIThread();
return false;
}
private void invalidateByUIThread(){
mHander.post(new Runnable() {
@Override
public void run() {
invalidate();
}
});
}
public void setListener(QuizViewListener listener) {
this.mListener = listener;
}
/**
*
* @return
*/
public int getQuizSize(){
return mStage.length;
}
}
|
package com.robrua.orianna.type.core.common;
import java.util.HashMap;
import java.util.Map;
public enum GameMap {
BUTCHERS_BRIDGE(14), HOWLING_ABYSS(12), SUMMONERS_RIFT(11), SUMMONERS_RIFT_AUTUMN(2), SUMMONERS_RIFT_SUMMER(1), THE_CRYSTAL_SCAR(8), THE_PROVING_GROUNDS(3), TWISTED_TREELINE(10), TWISTED_TREELINE_ORIGINAL(
4);
private static final Map<Long, GameMap> IDs = new HashMap<>();
static {
for(final GameMap m : GameMap.values()) {
IDs.put(m.ID, m);
}
}
/**
* Gets the map for a specified ID
*
* @param ID
* the map ID
* @return the map type
*/
public static GameMap forID(final long ID) {
return IDs.get(ID);
}
private final Long ID;
/**
* @param ID
*/
private GameMap(final long ID) {
this.ID = ID;
}
/**
* Gets the ID for this map
*
* @return the ID for this map
*/
public long getID() {
return ID;
}
}
|
package com.sibisoft.faizaniftikhartdd;
import static org.junit.Assert.*;
import org.junit.Test;
public class DollarTestV2
{
@Test
public void testMultiplication()
{
Dollar five= new Dollar(5);
assertEquals(new Dollar(10), five.times(2));
assertEquals(new Dollar(15), five.times(3));
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package com.snakybo.sengine.camera;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;
import java.util.HashSet;
import java.util.Set;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import com.snakybo.sengine.object.Transform;
import com.snakybo.sengine.scene.SceneUtilities;
import com.snakybo.sengine.util.Color;
/**
* @author Snakybo
* @since 1.0
*/
public final class StandaloneCamera
{
private static Set<StandaloneCamera> cameras = new HashSet<StandaloneCamera>();
private static StandaloneCamera current;
private CameraClearFlags clearFlags;
private Matrix4f projection;
private Transform transform;
private Color clearColor;
/**
* Create a new camera
* @param projection - The projection of the camera
* @param clearFlags - The {@link CameraClearFlags} to use
*/
public StandaloneCamera(Matrix4f projection, CameraClearFlags clearFlags)
{
this(projection, clearFlags, new Color());
}
/**
* Create a new camera
* @param projection - The projection of the camera
* @param clearFlags - The {@link CameraClearFlags} to use
* @param clearColor - The clear color, only used in {@link CameraClearFlags#SolidColor}
*/
public StandaloneCamera(Matrix4f projection, CameraClearFlags clearFlags, Color clearColor)
{
this.projection = projection;
this.clearFlags = clearFlags;
this.clearColor = clearColor;
transform = new Transform();
cameras.add(this);
}
public void destroy()
{
cameras.remove(this);
}
/**
* Make the camera render now
*/
public final void render()
{
current = this;
switch(clearFlags)
{
case Skybox:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
break;
case SolidColor:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
break;
case DepthOnly:
glClear(GL_DEPTH_BUFFER_BIT);
break;
case NoClear:
break;
}
SceneUtilities.renderCamera();
current = null;
}
/**
* Set the {@link CameraClearFlags} to use
* @param clearFlags - The new clear flags
*/
public final void setClearFlags(CameraClearFlags clearFlags)
{
this.clearFlags = clearFlags;
}
/**
* Set the projection of the camera
* @param projection - The new projection
*/
public final void setProjection(Matrix4f projection)
{
this.projection = projection;
}
/**
* Set the transform of the camera
* @param transform - The new transform
*/
public final void setTransform(Transform transform)
{
this.transform = transform;
}
/**
* Set the clear color of the camera, only used in {@link CameraClearFlags#SolidColor}
* @param clearColor - The new clear color
*/
public final void setClearColor(Color clearColor)
{
this.clearColor = clearColor;
}
/**
* @return The {@link CameraClearFlags} this camera is using
*/
public final CameraClearFlags getClearFlags()
{
return clearFlags;
}
/**
* @return The projection of the camera
*/
public final Matrix4f getProjection()
{
return projection;
}
/**
* @return The view projection of the camera
*/
public final Matrix4f getViewProjection()
{
Vector3f position = transform.getPosition().mul(-1, new Vector3f());
Quaternionf rotation = transform.getRotation().conjugate(new Quaternionf());
Matrix4f viewProjection = new Matrix4f(projection);
viewProjection.translate(position);
viewProjection.rotate(rotation);
return viewProjection;
}
/**
* @return The clear color of the camera
*/
public final Color getClearColor()
{
return clearColor;
}
/**
* @return A collection of all cameras
*/
public static Iterable<StandaloneCamera> getCameras()
{
return cameras;
}
/**
* Get the current camera, use {@link Camera#getCurrentCamera()} unless you have to access internal cameras
* @return The current camera
*/
public static StandaloneCamera getCurrentCamera()
{
return current;
}
}
|
package com.xruby.runtime.builtin;
import com.xruby.runtime.lang.*;
import com.xruby.runtime.value.*;
class Array_length extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
return ObjectFactory.createFixnum(value.size());
}
}
class Array_clear extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
return value.clear();
}
}
class Array_to_s extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
return value.to_s();
}
}
class Array_array_first extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a = (RubyArray) receiver;
if (null == args) {
return a.get(0);
} else {
RubyFixnum n = (RubyFixnum) args.get(0);
return a.subarray(0, n.intValue());
}
}
}
class Array_array_last extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a = (RubyArray) receiver;
if (null == args) {
return a.get(-1);
} else {
RubyFixnum n = (RubyFixnum) args.get(0);
return a.subarray(a.size() - n.intValue(), n.intValue());
}
}
}
class Array_array_access extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
if (1 == args.size()) {
Object argValue = args.get(0);
if (argValue instanceof RubyFixnum) {
RubyFixnum index = (RubyFixnum) argValue;
return value.get(index.intValue());
} else if (args.get(0) instanceof RubyRange) {
int begin = ((RubyFixnum) ((RubyRange) args.get(0)).getLeft()).intValue();
int end = ((RubyFixnum) ((RubyRange) args.get(0)).getRight()).intValue();
if (begin < 0) {
begin = value.size() + begin;
}
if (end < 0) {
end = value.size() + end;
}
if (!((RubyRange) args.get(0)).isExcludeEnd()) {
++end;
}
RubyArray resultValue = value.subarray(begin, end - begin);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
} else if (2 == args.size()) {
Object arg0Value = args.get(0);
Object arg1Value = args.get(1);
if (arg0Value instanceof RubyFixnum && arg1Value instanceof RubyFixnum) {
int begin = ((RubyFixnum) arg0Value).intValue();
int length = ((RubyFixnum) arg1Value).intValue();
RubyArray resultValue = value.subarray(begin, length);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
}
//TODO
throw new RubyException("not implemented");
}
}
class Array_slice_danger extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
if (1 == args.size()) {
Object argValue = args.get(0);
if (argValue instanceof RubyFixnum) {
RubyFixnum index = (RubyFixnum) argValue;
return value.delete_at(index.intValue());
} else if (args.get(0) instanceof RubyRange) {
int begin = ((RubyFixnum) ((RubyRange) args.get(0)).getLeft()).intValue();
int end = ((RubyFixnum) ((RubyRange) args.get(0)).getRight()).intValue();
if (begin < 0) {
begin = value.size() + begin;
}
if (end < 0) {
end = value.size() + end;
}
if (!((RubyRange) args.get(0)).isExcludeEnd()) {
++end;
}
RubyArray resultValue = value.delete_at(begin, end - begin);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
} else if (2 == args.size()) {
Object arg0Value = args.get(0);
Object arg1Value = args.get(1);
if (arg0Value instanceof RubyFixnum && arg1Value instanceof RubyFixnum) {
int begin = ((RubyFixnum) arg0Value).intValue();
int length = ((RubyFixnum) arg1Value).intValue();
RubyArray resultValue = value.delete_at(begin, length);
return (null == resultValue ? ObjectFactory.NIL_VALUE : resultValue);
}
}
//TODO
throw new RubyException("not implemented");
}
}
class Array_array_at extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
RubyFixnum index = (RubyFixnum) arg;
return value.get(index.intValue());
}
}
class Array_array_set extends RubyVarArgMethod {
private int getRealIndex(int size,int i) {
int index = i;
if (index < 0) {
index = size + index;
}
if (index < 0) {
throw new RubyException(RubyRuntime.IndexErrorClass, "index " + i + " out of array");
}
return index;
}
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray value = (RubyArray) receiver;
if (2 == args.size()) {
if (args.get(0) instanceof RubyRange) {
RubyRange range = (RubyRange) args.get(0);
RubyFixnum left = (RubyFixnum)range.getLeft();
RubyFixnum right = (RubyFixnum)range.getRight();
int l_index = getRealIndex(value.size(), left.intValue());
int r_index = getRealIndex(value.size(), right.intValue());
int length = r_index-l_index+1;
return value.replace(l_index, length, args.get(1));
} else {
RubyFixnum index = (RubyFixnum) args.get(0);
return value.set(index.intValue(), args.get(1));
}
} else if (3 == args.size()) {
RubyFixnum index = (RubyFixnum) args.get(0);
RubyFixnum length = (RubyFixnum) args.get(1);
return value.replace(index.intValue(), length.intValue(), args.get(2));
}
throw new RubyException("not implemented");
}
}
class Array_equal extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
Object right = arg;
if (!(right instanceof RubyArray)) {
return ObjectFactory.FALSE_VALUE;
}
return left.equals((RubyArray) right) ? ObjectFactory.TRUE_VALUE : ObjectFactory.FALSE_VALUE;
}
}
class Array_compare extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
Object right = arg;
if (!(right instanceof RubyArray)) {
throw new RubyException(RubyRuntime.TypeErrorClass, "Can't convert " + arg.getRubyClass().getName() + " into Array");
}
return left.compare((RubyArray) right);
}
}
class Array_concat extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
left.concat(arg);
return receiver;
}
}
class Array_left_shift_operator extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
left.add(arg);
return receiver;
}
}
class Array_plus extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
RubyArray right = (RubyArray) arg;
return left.plus(right);
}
}
class Array_minus extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray left = (RubyArray) receiver;
RubyArray right = (RubyArray) arg;
return left.minus(right);
}
}
class Array_times extends RubyOneArgMethod {
private RubyID joinID = StringMap.intern("join");
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (arg instanceof RubyFixnum) {
RubyFixnum times = (RubyFixnum) arg;
return array.times(times.intValue());
} else if (arg instanceof RubyString) {
return RubyAPI.callOneArgMethod(receiver, arg, block, joinID);
}
throw new RubyException(RubyRuntime.TypeErrorClass, "no implicit conversion from " + arg + " to integer");
}
}
class Array_operator_and extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.and((RubyArray) arg);
}
}
class Array_operator_or extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.or((RubyArray) arg);
}
}
class Array_push extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (null != args) {
for (RubyValue v : args) {
array.add(v);
}
}
return array;
}
}
class Array_insert extends RubyTwoArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyFixnum index = (RubyFixnum) arg1;
return array.insert(index.intValue(), arg2);
}
}
class Array_pop extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.delete_at(array.size() - 1);
}
}
//TODO array.delete(obj) { block }
class Array_delete_at extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyFixnum pos = (RubyFixnum) arg;
return array.delete_at(pos.intValue());
}
}
class Array_delete_if extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.delete_if(block);
}
}
class Array_delete extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.delete(arg);
}
}
class Array_include extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (array.include(arg)) {
return ObjectFactory.TRUE_VALUE;
} else {
return ObjectFactory.FALSE_VALUE;
}
}
}
class Array_each extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.each(receiver, block);
}
}
class Array_each_index extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.each_index(receiver, block);
}
}
class Array_reverse_each extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.reverse_each(receiver, block);
}
}
class Array_unshift extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.unshift(args);
}
}
class Array_new extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a;
if (null == args) {
a = new RubyArray();
} else if(null == block) {
if (args.get(0) instanceof RubyArray) {
a = (RubyArray)args.get(0).clone();
} else {
RubyFixnum size = (RubyFixnum) args.get(0);
RubyValue default_value = args.get(1);
a = ObjectFactory.createArray(size.intValue(), default_value);
}
} else {
RubyFixnum size = (RubyFixnum) args.get(0);
a = new RubyArray();
for(int i=0; i<size.intValue(); i++)
{
RubyValue return_value = block.invoke(receiver, new RubyArray(ObjectFactory.createFixnum(i)));
a.add(return_value);
}
}
a.setRubyClass((RubyClass) receiver);
return a;
}
}
class Array_new_with_given_objects extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray a;
if (null == args) {
a = new RubyArray();
} else {
a = args.copy();
}
a.setRubyClass((RubyClass) receiver);
return a;
}
}
class Array_shift extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.delete_at(0);
}
}
class Array_sort_dangers extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
if (null == block) {
array.sort();
} else {
array.sort(block);
}
return array;
}
}
class Array_sort extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
if (null == block) {
array.sort();
} else {
array.sort(block);
}
return array;
}
}
class Array_hash extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return ObjectFactory.createFixnum(array.hash());
}
}
class Array_compact_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.compact() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_compact extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
return array.compact() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_uniq_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
return array.uniq() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_uniq extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
return array.uniq() ? array : ObjectFactory.NIL_VALUE;
}
}
class Array_reverse_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
array.reverse();
return array;
}
}
class Array_reverse extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = ((RubyArray) receiver).copy();
array.reverse();
return array;
}
}
class Array_pack extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
String format = ((RubyString) arg).toString();
return ObjectFactory.createString(ArrayPacker.pack(array, format));
}
}
class Array_index extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
for(int i=0; i<array.size(); i++){
if(array.get(i).equals(arg))
return ObjectFactory.createFixnum(i);
}
return ObjectFactory.NIL_VALUE;
}
}
class Array_rindex extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
for(int i=array.size()-1; i>=0; i
if(array.get(i).equals(arg))
return ObjectFactory.createFixnum(i);
}
return ObjectFactory.NIL_VALUE;
}
}
class Array_replace extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyArray anotherArray = (RubyArray)arg;
if(array == anotherArray)
return array;
array.clear();
for(int i=0;i<anotherArray.size();i++){
array.add(anotherArray.get(i));
}
return array;
}
}
class Array_indexes extends RubyVarArgMethod {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyArray array = (RubyArray)receiver;
RubyArray a = new RubyArray(args.size());
for(int i=0;i<args.size();i++){
RubyFixnum n = (RubyFixnum) args.get(i);
a.add(array.get(n.intValue()));
}
return a;
}
}
class Array_nitems extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
int n = 0;
for(int i=0;i<array.size();i++){
if(array.get(i) != ObjectFactory.NIL_VALUE)
n++;
}
return ObjectFactory.createFixnum(n);
}
}
class Array_flatten extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyArray a = new RubyArray();
recursiveAdd(a,array);
return a;
}
private void recursiveAdd(RubyArray receiver,RubyArray array){
for(int i=0;i<array.size();i++){
RubyValue val = array.get(i);
if(val instanceof RubyArray){
recursiveAdd(receiver,(RubyArray)val);
}else{
receiver.add(val);
}
}
}
}
class Array_flatten_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyArray copy = array.copy();
array.clear();
boolean hasModified = recursiveAdd(array,copy);
if(hasModified){
return array;
}else{
return ObjectFactory.NIL_VALUE;
}
}
private boolean recursiveAdd(RubyArray receiver,RubyArray array){
boolean flag = false;
for(int i=0;i<array.size();i++){
RubyValue val = array.get(i);
if(val instanceof RubyArray){
flag = true;
recursiveAdd(receiver,(RubyArray)val);
}else{
receiver.add(val);
}
}
return flag;
}
}
class Array_collect_danger extends RubyNoArgMethod {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
RubyArray a = (RubyArray)RubyAPI.callPublicMethod(receiver, null, block, StringMap.intern("collect"));
RubyArray array = (RubyArray) receiver;
array.clear();
for(int i=0;i<a.size();i++){
array.add(a.get(i));
}
return array;
}
}
class Array_assoc extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyValue val = null;
for(int i=0;i<array.size();i++){
val = array.get(i);
if(val instanceof RubyArray){
if(((RubyArray)val).size() > 0){
RubyValue tmp = ((RubyArray)val).get(0);
if(arg.equals(tmp)){
return val;
}
}
}
}
return ObjectFactory.NIL_VALUE;
}
}
class Array_rassoc extends RubyOneArgMethod {
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) {
RubyArray array = (RubyArray) receiver;
RubyValue val = null;
for(int i=0;i<array.size();i++){
val = array.get(i);
if(val instanceof RubyArray){
if(((RubyArray)val).size() > 1){
RubyValue tmp = ((RubyArray)val).get(1);
if(arg.equals(tmp)){
return val;
}
}
}
}
return ObjectFactory.NIL_VALUE;
}
}
public class ArrayClassBuilder {
public static void initialize() {
RubyClass c = RubyRuntime.ArrayClass;
c.getSingletonClass().defineMethod("new", new Array_new());
c.getSingletonClass().defineMethod("[]", new Array_new_with_given_objects());
c.defineMethod("length", new Array_length());
c.defineMethod("clear", new Array_clear());
c.defineMethod("to_s", new Array_to_s());
c.defineMethod("[]", new Array_array_access());
c.defineMethod("first", new Array_array_first());
c.defineMethod("last", new Array_array_last());
c.defineMethod("at", new Array_array_at());
c.defineMethod("[]=", new Array_array_set());
c.defineMethod("==", new Array_equal());
c.defineMethod("<=>", new Array_compare());
c.defineMethod("<<", new Array_left_shift_operator());
c.defineMethod("concat", new Array_concat());
c.defineMethod("+", new Array_plus());
c.defineMethod("-", new Array_minus());
c.defineMethod("*", new Array_times());
c.defineMethod("&", new Array_operator_and());
c.defineMethod("|", new Array_operator_or());
c.defineMethod("push", new Array_push());
c.defineMethod("insert", new Array_insert());
c.defineMethod("pop", new Array_pop());
c.defineMethod("delete", new Array_delete());
c.defineMethod("delete_at", new Array_delete_at());
c.defineMethod("delete_if", new Array_delete_if());
c.defineMethod("include?", new Array_include());
c.defineMethod("unshift", new Array_unshift());
c.defineMethod("each", new Array_each());
c.defineMethod("reverse_each", new Array_reverse_each());
c.defineMethod("pack", new Array_pack());
c.defineMethod("shift", new Array_shift());
c.defineMethod("sort!", new Array_sort_dangers());
c.defineMethod("sort", new Array_sort());
c.defineMethod("hash", new Array_hash());
c.defineMethod("compact!", new Array_compact_danger());
c.defineMethod("compact", new Array_compact());
c.defineMethod("uniq!", new Array_uniq_danger());
c.defineMethod("uniq", new Array_uniq());
c.defineMethod("reverse!", new Array_reverse_danger());
c.defineMethod("reverse", new Array_reverse());
c.defineMethod("slice", new Array_array_access());
c.defineMethod("slice!", new Array_slice_danger());
c.defineMethod("index",new Array_index());
c.defineMethod("rindex",new Array_rindex());
c.defineMethod("replace", new Array_replace());
c.defineMethod("eql?", new Array_equal());
c.defineMethod("indexes", new Array_indexes());
c.defineMethod("indices", new Array_indexes());
c.defineMethod("nitems",new Array_nitems());
c.defineMethod("flatten", new Array_flatten());
c.defineMethod("flatten!", new Array_flatten_danger());
c.defineMethod("each_index", new Array_each_index());
c.defineMethod("collect!", new Array_collect_danger());
c.defineMethod("assoc", new Array_assoc());
c.defineMethod("rassoc", new Array_rassoc());
c.includeModule(RubyRuntime.EnumerableModule);
}
}
|
package se.sics.mspsim.chip;
import se.sics.mspsim.core.*;
import se.sics.mspsim.core.EmulationLogger.WarningType;
import se.sics.mspsim.util.ArrayFIFO;
import se.sics.mspsim.util.CCITT_CRC;
import se.sics.mspsim.util.Utils;
public class CC2520 extends Radio802154 implements USARTListener, SPIData {
public static class GPIO {
private IOPort port;
private int pin;
boolean polarity = true;
boolean isActive;
public void setConfig(IOPort port, int pin) {
this.port = port;
this.pin = pin;
port.setPinState(pin, isActive == polarity ? IOPort.PinState.HI : IOPort.PinState.LOW);
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
if (this.isActive != isActive) {
this.isActive = isActive;
if (port != null) {
port.setPinState(pin, isActive == polarity ? IOPort.PinState.HI : IOPort.PinState.LOW);
}
}
}
public void setPolarity(boolean polarity) {
if (this.polarity != polarity) {
this.polarity = polarity;
if (port != null) {
port.setPinState(pin, isActive == polarity ? IOPort.PinState.HI : IOPort.PinState.LOW);
}
}
}
}
// FREG definitions (BSET/BCLR supported)
public final static int REG_FRMFILT0 = 0x000;
public final static int REG_FRMFILT1 = 0x001;
public final static int REG_SRCMATCH = 0x002;
public final static int REG_SRCSHORTEN0 = 0x004;
public final static int REG_SRCSHORTEN1 = 0x005;
public final static int REG_SRCSHORTEN2 = 0x006;
public final static int REG_SRCEXTEN0 = 0x008;
public final static int REG_SRCEXTEN1 = 0x009;
public final static int REG_SRCEXTEN2 = 0x00A;
public final static int REG_FRMCTRL0 = 0x00C;
public final static int REG_FRMCTRL1 = 0x00D;
public final static int REG_RXENABLE0 = 0x00E;
public final static int REG_RXENABLE1 = 0x00F;
public final static int REG_EXCFLAG0 = 0x010;
public final static int REG_EXCFLAG1 = 0x011;
public final static int REG_EXCFLAG2 = 0x012;
public final static int REG_EXCMASKA0 = 0x014;
public final static int REG_EXCMASKA1 = 0x015;
public final static int REG_EXCMASKA2 = 0x016;
public final static int REG_EXCMASKB0 = 0x018;
public final static int REG_EXCMASKB1 = 0x019;
public final static int REG_EXCMASKB2 = 0x01A;
public final static int REG_EXCBINDX0 = 0x01C;
public final static int REG_EXCBINDX1 = 0x01D;
public final static int REG_EXCBINDY0 = 0x01E;
public final static int REG_EXCBINDY1 = 0x01F;
public final static int REG_GPIOCTRL0 = 0x020;
public final static int REG_GPIOCTRL1 = 0x021;
public final static int REG_GPIOCTRL2 = 0x022;
public final static int REG_GPIOCTRL3 = 0x023;
public final static int REG_GPIOCTRL4 = 0x024;
public final static int REG_GPIOCTRL5 = 0x025;
public final static int REG_GPIOPOLARITY = 0x026;
public final static int REG_GPIOCTRL = 0x028;
public final static int REG_DPUCON = 0x02A;
public final static int REG_DPUSTAT = 0x02C;
public final static int REG_FREQCTRL = 0x02E;
public final static int REG_FREQTUNE = 0x02F;
public final static int REG_TXPOWER = 0x030;
public final static int REG_TXCTRL = 0x031;
public final static int REG_FSMSTAT0 = 0x032;
public final static int REG_FSMSTAT1 = 0x033;
public final static int REG_FIFOPCTRL = 0x034;
public final static int REG_FSMCTRL = 0x035;
public final static int REG_CCACTRL0 = 0x036;
public final static int REG_CCACTRL1 = 0x037;
public final static int REG_RSSI = 0x038;
public final static int REG_RSSISTAT = 0x039;
public final static int REG_TXFIFO_BUF = 0x03A;
public final static int REG_RXFIRST = 0x03C;
public final static int REG_RXFIFOCNT = 0x03E;
public final static int REG_TXFIFOCNT = 0x03F;
// SREG definitions (BSET/BCLR unsupported)
public final static int REG_CHIPID = 0x040;
public final static int REG_VERSION = 0x042;
public final static int REG_EXTCLOCK = 0x044;
public final static int REG_MDMCTRL0 = 0x046;
public final static int REG_MDMCTRL1 = 0x047;
public final static int REG_FREQEST = 0x048;
public final static int REG_RXCTRL = 0x04A;
public final static int REG_FSCTRL = 0x04C;
public final static int REG_FSCAL0 = 0x04E;
public final static int REG_FSCAL1 = 0x04F;
public final static int REG_FSCAL2 = 0x050;
public final static int REG_FSCAL3 = 0x051;
public final static int REG_AGCCTRL0 = 0x052;
public final static int REG_AGCCTRL1 = 0x053;
public final static int REG_AGCCTRL2 = 0x054;
public final static int REG_AGCCTRL3 = 0x055;
public final static int REG_ADCTEST0 = 0x056;
public final static int REG_ADCTEST1 = 0x057;
public final static int REG_ADCTEST2 = 0x058;
public final static int REG_MDMTEST0 = 0x05A;
public final static int REG_MDMTEST1 = 0x05B;
public final static int REG_DACTEST0 = 0x05C;
public final static int REG_DACTEST1 = 0x05D;
public final static int REG_ATEST = 0x05E;
public final static int REG_DACTEST2 = 0x05F;
public final static int REG_PTEST0 = 0x060;
public final static int REG_PTEST1 = 0x061;
public final static int REG_RESERVED = 0x062;
public final static int REG_DPUBIST = 0x07A;
public final static int REG_ACTBIST = 0x07C;
public final static int REG_RAMBIST = 0x07E;
// Instructions
public final static int INS_SNOP = 0x00;
public final static int INS_IBUFLD = 0x02;
public final static int INS_SIBUFEX = 0x03;
public final static int INS_SSAMPLECCA = 0x04;
public final static int INS_SRES = 0x0F;
public final static int INS_MEMRD = 0x10;
public final static int INS_MEMWR = 0x20;
public final static int INS_RXBUF = 0x30;
public final static int INS_RXBUFCP = 0x38;
public final static int INS_RXBUFMOV = 0x32;
public final static int INS_TXBUF = 0x3A;
public final static int INS_TXBUFCP = 0x3E;
public final static int INS_RANDOM = 0x3C;
public final static int INS_SXOSCON = 0x40;
public final static int INS_STXCAL = 0x41;
public final static int INS_SRXON = 0x42;
public final static int INS_STXON = 0x43;
public final static int INS_STXONCCA = 0x44;
public final static int INS_SRFOFF = 0x45;
public final static int INS_SXOSCOFF = 0x46;
public final static int INS_SFLUSHRX = 0x47;
public final static int INS_SFLUSHTX = 0x48;
public final static int INS_SACK = 0x49;
public final static int INS_SACKPEND = 0x4A;
public final static int INS_SNACK = 0x4B;
public final static int INS_SRXMASKBITSET = 0x4C;
public final static int INS_SRXMASKBITCLR = 0x4D;
public final static int INS_RXMASKAND = 0x4E;
public final static int INS_RXMASKOR = 0x4F;
public final static int INS_MEMCP = 0x50;
public final static int INS_MEMCPR = 0x52;
public final static int INS_MEMXCP = 0x54;
public final static int INS_MEMXWR = 0x56;
public final static int INS_BCLR = 0x58;
public final static int INS_BSET = 0x59;
public final static int INS_CTR = 0x60;
public final static int INS_CBCMAC = 0x64;
public final static int INS_UCBCMAC = 0x66;
public final static int INS_CCM = 0x68;
public final static int INS_UCCM = 0x6A;
public final static int INS_ECB = 0x70;
public final static int INS_ECBO = 0x72;
public final static int INS_ECBX = 0x74;
public final static int INS_ECBXO = 0x76;
public final static int INS_INC = 0x78;
public final static int INS_ABORT = 0x7F;
public final static int INS_REGRD = 0x80;
public final static int INS_REGWR = 0xC0;
// Status register flags
public static final int STATUS_XOSC16M_STABLE = 1 << 7;
public static final int STATUS_RSSI_VALID = 1 << 6;
public static final int STATUS_EXCEPTION_CHA = 1 << 5;
public static final int STATUS_EXCEPTION_CHB = 1 << 4;
public static final int STATUS_DPU_H = 1 << 3;
public static final int STATUS_DPU_L = 1 << 2;
public static final int STATUS_TX_ACTIVE = 1 << 1;
public static final int STATUS_RX_ACTIVE = 1 << 0;
// Exceptions (bits in the EXCFLAGx memory)
public final static int EXC_RF_IDLE = 1 << 0;
public final static int EXC_TX_FRM_DONE = 1 << 1;
public final static int EXC_RX_FRM_ABORTED = 0x20;
public final static int EXC_RX_FRM_UNDERFLOW = 0x20;
// RAM Addresses
public static final int RAM_TXFIFO = 0x100;
public static final int RAM_RXFIFO = 0x180;
public static final int RAM_IEEEADDR = 0x3EA;
public static final int RAM_PANID = 0x3F2;
public static final int RAM_SHORTADDR = 0x3F4;
// public static final int RAM_KEY0 = 0x100;
// public static final int RAM_RXNONCE = 0x110;
// public static final int RAM_SABUF = 0x120;
// public static final int RAM_KEY1 = 0x130;
// public static final int RAM_TXNONCE = 0x140;
// public static final int RAM_CBCSTATE = 0x150;
/* one single byte instruction can be stored in the IBUF */
int instructionBuffer = 0;
// IOCFG0 memory Bit masks
public static final int BCN_ACCEPT = (1<<11);
public static final int FIFOP_THR = 0x7F;
// IOCFG1 memory Bit Masks
// public static final int SFDMUX = 0x3E0;
// public static final int CCAMUX = 0x1F;
// CCAMUX values
// public static final int CCAMUX_CCA = 0;
// public static final int CCAMUX_XOSC16M_STABLE = 24;
// FRMFILT0/FRMCTRL0 values
public static final int FRAME_FILTER = (1 << 0);
public static final int AUTOCRC = (1 << 6);
public static final int AUTOACK = (1 << 5);
// FRMFILT1
public static final int ACCEPT_FT_4TO7_RESERVED = (1 << 7);
public static final int ACCEPT_FT_3_MAC_CMD = (1 << 6);
public static final int ACCEPT_FT_2_ACK = (1 << 5);
public static final int ACCEPT_FT_1_DATA = (1 << 4);
public static final int ACCEPT_FT_0_BEACON = (1 << 3);
public static final int SHORT_ADDRESS = 2;
public static final int LONG_ADDRESS = 3;
// The Operation modes of the CC2520
public static final int MODE_TXRX_OFF = 0x00;
public static final int MODE_RX_ON = 0x01;
public static final int MODE_TXRX_ON = 0x02;
public static final int MODE_POWER_OFF = 0x03;
public static final int MODE_MAX = MODE_POWER_OFF;
private static final String[] MODE_NAMES = new String[] {
"off", "listen", "transmit", "power_off"
};
// State Machine - Datasheet Figure 30 page 85
public enum RadioState {
VREG_OFF(-2),
POWER_DOWN(-1),
IDLE(0),
RX_CALIBRATE(2),
RX_SFD_SEARCH(3),
RX_WAIT(14),
RX_FRAME(15),
RX_OVERFLOW(17),
TX_CALIBRATE(32),
TX_PREAMBLE(34),
TX_FRAME(37),
TX_ACK_CALIBRATE(48),
TX_ACK_PREAMBLE(49),
TX_ACK(52),
TX_UNDERFLOW(56);
private final int state;
RadioState(int stateNo) {
state = stateNo;
}
public int getFSMState() {
return state;
}
};
// FCF High
public static final int FRAME_TYPE = 0x07;
public static final int SECURITY_ENABLED = (1 << 3);
public static final int FRAME_PENDING = (1 << 4);
public static final int ACK_REQUEST = (1 << 5);
public static final int INTRA_PAN = (1 << 6);
public static final int TYPE_BEACON_FRAME = 0x00;
public static final int TYPE_DATA_FRAME = 0x01;
public static final int TYPE_ACK_FRAME = 0x02;
// FCF Low
public static final int DESTINATION_ADDRESS_MODE = 0x30;
public static final int SOURCE_ADDRESS_MODE = 0x3;
// Position of SEQ-NO in ACK packet...
public static final int ACK_SEQPOS = 3;
private RadioState stateMachine = RadioState.VREG_OFF;
// 802.15.4 symbol period in ms
public static final double SYMBOL_PERIOD = 0.016; // 16 us
private static final int[] BC_ADDRESS = new int[] {0xff, 0xff};
private int shrPos;
private int txfifoPos;
private boolean txfifoFlush; // TXFIFO is automatically flushed on next write
private int rxfifoReadLeft; // number of bytes left to read from current packet
private int rxlen;
private int rxread;
private int zeroSymbols;
/* RSSI is an externally set value of the RSSI for this CC2520 */
/* low RSSI => CCA = true in normal mode */
private int rssi = -100;
private static int RSSI_OFFSET = -45; /* cc2520 datasheet */
/* This is the magical LQI */
private int corrval = 37;
/* FIFOP Threshold */
private int fifopThr = 0x40;
/* Configuration for frame filtering and auto acknowledgments */
private boolean frameFilter = false;
private boolean autoAck = false;
private boolean shouldAck = false;
private boolean ackRequest = false;
private boolean autoCRC = false;
// Data from last received packet
private int dsn = 0;
private int fcf0 = 0;
private int fcf1 = 0;
private int frameType = 0;
private boolean crcOk = false;
private int activeFrequency = 0;
private int activeChannel = 0;
//private int status = STATUS_XOSC16M_STABLE | STATUS_RSSI_VALID;
private int status = 0;
private final int[] memory = new int[0x400]; /* total memory */
private CC2520SPI cc2520SPI = new CC2520SPI(this);
private SPICommand command;
private int[] spiData = new int[20]; /* SPI data buffer */
private int spiLen;
// Buffer to hold 5 byte Synchronization header, as it is not written to the TXFIFO
private final byte[] SHR = new byte[5];
/* the data that should be SPI response */
private int outputSPI;
private boolean chipSelect;
private final GPIO[] gpio = new GPIO[6];
private GPIO ccaGPIO;
private GPIO fifopGPIO;
private GPIO fifoGPIO;
private GPIO sfdGPIO;
private boolean currentFIFO;
private boolean currentFIFOP;
/* current CCA value */
private boolean currentCCA = false;
private int txCursor;
private boolean isRadioOn;
private TimeEvent oscillatorEvent = new TimeEvent(0, "CC2520 OSC") {
public void execute(long t) {
status |= STATUS_XOSC16M_STABLE;
if(DEBUG) log("Oscillator Stable Event.");
setState(RadioState.IDLE);
updateCCA();
}
};
private TimeEvent vregEvent = new TimeEvent(0, "CC2520 VREG") {
public void execute(long t) {
if(DEBUG) log("VREG Started at: " + t + " cyc: " +
cpu.cycles + " " + getTime());
isRadioOn = true;
setState(RadioState.POWER_DOWN);
updateCCA();
}
};
private TimeEvent sendEvent = new TimeEvent(0, "CC2520 Send") {
public void execute(long t) {
txNext();
}
};
private TimeEvent ackEvent = new TimeEvent(0, "CC2520 Ack") {
public void execute(long t) {
ackNext();
}
};
private TimeEvent shrEvent = new TimeEvent(0, "CC2520 SHR") {
public void execute(long t) {
shrNext();
}
};
private TimeEvent symbolEvent = new TimeEvent(0, "CC2520 Symbol") {
public void execute(long t) {
switch(stateMachine) {
case RX_CALIBRATE:
setState(RadioState.RX_SFD_SEARCH);
break;
/* this will be called 8 symbols after first SFD_SEARCH */
case RX_SFD_SEARCH:
status |= STATUS_RSSI_VALID;
memory[REG_RSSISTAT] = 1;
updateCCA();
break;
case TX_CALIBRATE:
setState(RadioState.TX_PREAMBLE);
break;
case RX_WAIT:
setState(RadioState.RX_SFD_SEARCH);
break;
case TX_ACK_CALIBRATE:
setState(RadioState.TX_ACK_PREAMBLE);
break;
default:
// Ignore other states
break;
}
}
};
private boolean overflow = false;
private boolean frameRejected = false;
private int ackPos;
/* type = 2 (ACK), third byte needs to be sequence number... */
private int[] ackBuf = {0x05, 0x02, 0x00, 0x00, 0x00, 0x00};
private boolean ackFramePending = false;
private CCITT_CRC rxCrc = new CCITT_CRC();
private CCITT_CRC txCrc = new CCITT_CRC();
private final ArrayFIFO rxFIFO = new ArrayFIFO("RXFIFO", memory, 128, 128);
public CC2520(MSP430Core cpu) {
super("CC2520", "Radio", cpu);
for (int i = 0; i < gpio.length; i++) {
gpio[i] = new GPIO();
}
setModeNames(MODE_NAMES);
setMode(MODE_POWER_OFF);
rxFIFO.reset();
overflow = false;
reset();
}
public RadioState getState() {
return stateMachine;
}
private int getFCFReservedMask() {
return (memory[REG_FRMFILT0] >> 4) & 7;
}
private int getFCFMaxFrameVersion() {
return (memory[REG_FRMFILT0] >> 2) & 3;
}
private void updateGPIOConfig() {
int bit = 1;
for (GPIO io : gpio) {
io.setPolarity((memory[REG_GPIOPOLARITY] & bit) > 0);
bit = bit << 1;
}
}
public int getFooterLength() {
if (autoCRC) {
return 2;
}
return 0;
}
private void reset() {
// FCF max fram version = 3 and frame filtering enabled
memory[REG_FRMFILT0] = 0x0d;
frameFilter = true;
memory[REG_FRMFILT1] = 0x78;
// autocrc enabled, autoack disabled
memory[REG_FRMCTRL0] = 0x40;
autoCRC = true;
autoAck = false;
memory[REG_MDMCTRL0] = 0x45;
memory[REG_MDMCTRL1] = 0x3e;
memory[REG_FSMSTAT0] = 0;
memory[REG_FSMSTAT1] = 0;
memory[REG_RSSISTAT] = 0;
memory[REG_TXPOWER] = 0x06;
memory[REG_FIFOPCTRL] = fifopThr = 0x40;
memory[REG_FREQCTRL] = 0x0b;
/* back to default configuration of GPIOs */
memory[REG_GPIOPOLARITY] = 0x3f;
updateGPIOConfig();
fifoGPIO = gpio[1];
fifopGPIO = gpio[2];
ccaGPIO = gpio[3];
sfdGPIO = gpio[4];
setFIFO(false);
setFIFOP(false);
setSFD(false);
updateCCA();
}
private boolean setState(RadioState state) {
if(DEBUG) log("State transition from " + stateMachine + " to " + state);
stateMachine = state;
/* write to FSM state register */
memory[REG_FSMSTAT0] = (memory[REG_FSMSTAT0] & 0x3f);//state.getFSMState();
switch(stateMachine) {
case VREG_OFF:
if (DEBUG) log("VREG Off.");
flushRX();
flushTX();
status &= ~(STATUS_RSSI_VALID | STATUS_XOSC16M_STABLE);
memory[REG_RSSISTAT] = 0;
crcOk = false;
reset();
setMode(MODE_POWER_OFF);
updateCCA();
break;
case POWER_DOWN:
rxFIFO.reset();
status &= ~(STATUS_RSSI_VALID | STATUS_XOSC16M_STABLE);
memory[REG_RSSISTAT] = 0;
crcOk = false;
reset();
setMode(MODE_POWER_OFF);
updateCCA();
break;
case RX_CALIBRATE:
/* should be 12 according to specification */
setSymbolEvent(12);
setMode(MODE_RX_ON);
break;
case RX_SFD_SEARCH:
zeroSymbols = 0;
/* eight symbols after first SFD search RSSI will be valid */
if ((status & STATUS_RSSI_VALID) == 0) {
setSymbolEvent(8);
}
// status |= STATUS_RSSI_VALID;
updateCCA();
setMode(MODE_RX_ON);
break;
case TX_CALIBRATE:
/* 12 symbols calibration, and one byte's wait since we deliver immediately
* to listener when after calibration?
*/
setSymbolEvent(12 + 2);
setMode(MODE_TXRX_ON);
break;
case TX_PREAMBLE:
shrPos = 0;
SHR[0] = 0;
SHR[1] = 0;
SHR[2] = 0;
SHR[3] = 0;
SHR[4] = 0x7A;
shrNext();
break;
case TX_FRAME:
txfifoPos = 0;
// Reset CRC ok flag to disable software acknowledgments until next received packet
crcOk = false;
txNext();
break;
case RX_WAIT:
setSymbolEvent(8);
setMode(MODE_RX_ON);
break;
case IDLE:
status &= ~STATUS_RSSI_VALID;
memory[REG_RSSISTAT] = 0;
setMode(MODE_TXRX_OFF);
updateCCA();
break;
case TX_ACK_CALIBRATE:
/* TX active during ACK + NOTE: we ignore the SFD when receiving full packets so
* we need to add another extra 2 symbols here to get a correct timing */
status |= STATUS_TX_ACTIVE;
memory[REG_FSMSTAT1] |= (1 << 1);
setSymbolEvent(12 + 2 + 2);
setMode(MODE_TXRX_ON);
break;
case TX_ACK_PREAMBLE:
/* same as normal preamble ?? */
shrPos = 0;
SHR[0] = 0;
SHR[1] = 0;
SHR[2] = 0;
SHR[3] = 0;
SHR[4] = 0x7A;
shrNext();
break;
case TX_ACK:
ackPos = 0;
// Reset CRC ok flag to disable software acknowledgments until next received packet
crcOk = false;
ackNext();
break;
case RX_FRAME:
/* mark position of frame start - for rejecting when address is wrong */
rxFIFO.mark();
rxread = 0;
frameRejected = false;
shouldAck = false;
crcOk = false;
break;
case RX_OVERFLOW:
break;
case TX_UNDERFLOW:
// TODO handle TX underflow
break;
}
/* Notify state listener */
stateChanged(stateMachine.state);
return true;
}
private void rejectFrame() {
// Immediately jump to SFD Search again... something more???
/* reset state */
rxFIFO.restore();
setSFD(false);
setFIFO(rxFIFO.length() > 0);
frameRejected = true;
}
/* variables for the address recognition */
int destinationAddressMode = 0;
boolean decodeAddress = false;
/* Receive a byte from the radio medium
* @see se.sics.mspsim.chip.RFListener#receivedByte(byte)
*/
public void receivedByte(byte data) {
// Received a byte from the "air"
if (DEBUG)
log("RF Byte received: " + Utils.hex8(data) + " state: " + stateMachine + " noZeroes: " + zeroSymbols +
((stateMachine == RadioState.RX_SFD_SEARCH || stateMachine == RadioState.RX_FRAME) ? "" : " *** Ignored"));
if(stateMachine == RadioState.RX_SFD_SEARCH) {
// Look for the preamble (4 zero bytes) followed by the SFD byte 0x7A
if(data == 0) {
// Count zero bytes
zeroSymbols++;
} else if(zeroSymbols >= 4 && data == 0x7A) {
// If the received byte is !zero, we have counted 4 zero bytes prior to this one,
// and the current received byte == 0x7A (SFD), we're in sync.
// In RX mode, SFD goes high when the SFD is received
setSFD(true);
if (DEBUG) log("RX: Preamble/SFD Synchronized.");
setState(RadioState.RX_FRAME);
} else {
/* if not four zeros and 0x7A then no zeroes... */
zeroSymbols = 0;
}
} else if(stateMachine == RadioState.RX_FRAME) {
if (overflow) {
/* if the CC2520 RX FIFO is in overflow - it needs a flush before receiving again */
} else if(rxFIFO.isFull()) {
setRxOverflow();
} else {
if (!frameRejected) {
rxFIFO.write(data);
if (rxread == 0) {
rxCrc.setCRC(0);
rxlen = data & 0xff;
//System.out.println("Starting to get packet at: " + rxfifoWritePos + " len = " + rxlen);
decodeAddress = frameFilter;
if (DEBUG) log("RX: Start frame length " + rxlen);
// FIFO pin goes high after length byte is written to RXFIFO
setFIFO(true);
} else if (rxread < rxlen - 1) {
/* As long as we are not in the length or FCF (CRC) we count CRC */
rxCrc.addBitrev(data & 0xff);
if (rxread == 1) {
fcf0 = data & 0xff;
frameType = fcf0 & FRAME_TYPE;
} else if (rxread == 2) {
fcf1 = data & 0xff;
if (frameFilter
&& (((getFCFReservedMask() & (((fcf0 & 3) << 1) | (fcf1 & 1))) != 0)
|| (getFCFMaxFrameVersion() < ((fcf0 >> 2) & 3)))) {
rejectFrame();
} else if (frameType == TYPE_DATA_FRAME) {
ackRequest = (fcf0 & ACK_REQUEST) > 0;
destinationAddressMode = (fcf1 >> 2) & 3;
/* check this !!! */
if (frameFilter) {
if ((destinationAddressMode != LONG_ADDRESS
&& destinationAddressMode != SHORT_ADDRESS)
|| (memory[REG_FRMFILT1] & ACCEPT_FT_1_DATA) == 0) {
rejectFrame();
}
}
} else if (frameType == TYPE_ACK_FRAME) {
decodeAddress = false;
ackRequest = false;
if (frameFilter) {
if (rxlen != 5
|| (memory[REG_FRMFILT1] & ACCEPT_FT_2_ACK) == 0) {
rejectFrame();
}
}
} else if (frameType == TYPE_BEACON_FRAME) {
decodeAddress = false;
ackRequest = false;
destinationAddressMode = (fcf1 >> 2) & 3;
if (frameFilter) {
if (rxlen < 9
|| (memory[REG_FRMFILT1] & ACCEPT_FT_0_BEACON) == 0
|| destinationAddressMode != 0) {
rejectFrame();
}
}
} else if (frameFilter) {
rejectFrame();
}
} else if (rxread == 3) {
// save data sequence number
dsn = data & 0xff;
} else if (decodeAddress) {
boolean flushPacket = false;
/* here we decode the address !!! */
if (destinationAddressMode == LONG_ADDRESS && rxread == 8 + 5) {
/* here we need to check that this address is correct compared to the stored address */
flushPacket = !rxFIFO.tailEquals(memory, RAM_IEEEADDR, 8);
flushPacket |= !rxFIFO.tailEquals(memory, RAM_PANID, 2, 8)
&& !rxFIFO.tailEquals(BC_ADDRESS, 0, 2, 8);
decodeAddress = false;
} else if (destinationAddressMode == SHORT_ADDRESS && rxread == 2 + 5){
/* should check short address */
flushPacket = !rxFIFO.tailEquals(BC_ADDRESS, 0, 2)
&& !rxFIFO.tailEquals(memory, RAM_SHORTADDR, 2);
flushPacket |= !rxFIFO.tailEquals(memory, RAM_PANID, 2, 2)
&& !rxFIFO.tailEquals(BC_ADDRESS, 0, 2, 2);
decodeAddress = false;
}
if (flushPacket) {
rejectFrame();
}
}
}
/* In RX mode, FIFOP goes high when the size of the first enqueued packet exceeds
* the programmable threshold and address recognition isn't ongoing */
if (currentFIFOP == false
&& rxFIFO.length() <= rxlen + 1
&& !decodeAddress && !frameRejected
&& rxFIFO.length() > fifopThr) {
setFIFOP(true);
if (DEBUG) log("RX: FIFOP Threshold reached - setting FIFOP");
}
}
if (rxread++ == rxlen) {
if (frameRejected) {
if (DEBUG) log("Frame rejected - setting SFD to false and RXWAIT\n");
setSFD(false);
setState(RadioState.RX_WAIT);
return;
}
// In RX mode, FIFOP goes high, if threshold is higher than frame length....
// Here we check the CRC of the packet!
//System.out.println("Reading from " + ((rxfifoWritePos + 128 - 2) & 127));
if (autoCRC) {
int crc = rxFIFO.get(-2) << 8;
crc += rxFIFO.get(-1); //memory[RAM_RXFIFO + ((rxfifoWritePos + 128 - 1) & 127)];
crcOk = crc == rxCrc.getCRCBitrev();
if (DEBUG && !crcOk) {
log("CRC not OK: recv:" + Utils.hex16(crc) + " calc: " + Utils.hex16(rxCrc.getCRCBitrev()));
}
// Should take a RSSI value as input or use a set-RSSI value...
rxFIFO.set(-2, memory[REG_RSSI] & 0xff);
rxFIFO.set(-1, (corrval & 0x7F) | (crcOk ? 0x80 : 0));
// memory[RAM_RXFIFO + ((rxfifoWritePos + 128 - 2) & 127)] = ;
// // Set CRC ok and add a correlation - TODO: fix better correlation value!!!
// memory[RAM_RXFIFO + ((rxfifoWritePos + 128 - 1) & 127)] = 37 |
// (crcOk ? 0x80 : 0);
} else {
crcOk = true;
}
/* set FIFOP only if this is the first received packet - e.g. if rxfifoLen is at most rxlen + 1
* TODO: check what happens when rxfifoLen < rxlen - e.g we have been reading before FIFOP */
if (rxFIFO.length() <= rxlen + 1) {
setFIFOP(true);
} else {
if (DEBUG) log("Did not set FIFOP rxfifoLen: " + rxFIFO.length() + " rxlen: " + rxlen);
}
setSFD(false);
if (DEBUG) log("RX: Complete: packetStart: " + rxFIFO.stateToString());
/* if either manual ack request (shouldAck) or autoack + ACK_REQ on package do ack! */
/* Autoack-mode + good CRC => autoack */
if (((autoAck && ackRequest) || shouldAck) && crcOk) {
setState(RadioState.TX_ACK_CALIBRATE);
} else {
setState(RadioState.RX_WAIT);
}
}
}
}
}
/* API used in CC2520 SPI for both memory and registers */
void writeMemory(int address, int data) {
// System.out.printf("CC2520: writing to %x => %x\n", address, data);
int oldValue = memory[address];
memory[address] = data;
switch(address) {
case REG_FRMFILT0:
frameFilter = (data & FRAME_FILTER) != 0;
break;
case REG_FRMCTRL0:
autoCRC = (data & AUTOCRC) != 0;
autoAck = (data & AUTOACK) != 0;
break;
case REG_TXPOWER:
if (!isDefinedTxPower(data)) {
logw(WarningType.EXECUTION, "*** Warning - writing an undefined TXPOWER value (0x"
+ Utils.hex8(data) + ") to CC2520!!!");
}
break;
case REG_FIFOPCTRL:
fifopThr = data & FIFOP_THR;
if (DEBUG) log("FIFOPCTRL: 0x" + Utils.hex16(oldValue) + " => 0x" + Utils.hex16(data));
break;
case REG_GPIOPOLARITY:
if (DEBUG) log("GIOPOLARITY: 0x" + Utils.hex16(oldValue) + " => 0x" + Utils.hex16(data));
if (oldValue != data) {
updateGPIOConfig();
}
break;
// case REG_IOCFG1:
// if (DEBUG)
// log("IOCFG1: SFDMUX "
// + ((memory[address] & SFDMUX) >> SFDMUX)
// + " CCAMUX: " + (memory[address] & CCAMUX));
// updateCCA();
// break;
case REG_GPIOCTRL0:
/*
* XXX TODO Implement support for GPIO control. Below example code
* demonstrates how GPIO0 is set to fifop functionality (0x28).
*/
if (data == 0x28) {
fifopGPIO = gpio[0];
}
break;
case REG_FSCTRL: {
ChannelListener listener = this.channelListener;
if (listener != null) {
int oldChannel = activeChannel;
updateActiveFrequency();
if (oldChannel != activeChannel) {
listener.channelChanged(activeChannel);
}
}
break;
}
}
configurationChanged(address, oldValue, data);
}
int readMemory(int address) {
switch(address) {
case REG_RXFIFOCNT:
return rxFIFO.length();
}
return memory[address];
}
@Override
public void dataReceived(USARTSource source, int data) {
outputSPI = status; /* if nothing replace the outputSPI it will be output */
if (DEBUG) {
log("byte received: " + Utils.hex8(data) +
" (" + ((data >= ' ' && data <= 'Z') ? (char) data : '.') + ')' +
" CS: " + chipSelect + " SPI(" + spiLen + "): " + (command == null ? "<waiting>" : command.name)
+ " State: " + stateMachine);
}
if (!chipSelect) {
// Chip is not selected
return;
}
if (stateMachine == RadioState.VREG_OFF) {
/* No VREG but chip select */
source.byteReceived(0);
logw(WarningType.EXECUTION, "**** Warning - writing to CC2520 when VREG is off!!!");
return;
}
if (command == null) {
command = cc2520SPI.getCommand(data);
if (command == null) {
logw(WarningType.EMULATION_ERROR, "**** Warning - not implemented command on SPI: " + data);
} else if (DEBUG) {
if (!"SNOP".equals(command.name)) {
log("SPI command: " + command.name);
}
}
}
/* command handling */
spiData[spiLen] = data;
/* ensure that we do not store too many SPI data items */
if (spiLen < (spiData.length - 1)) {
spiLen++;
}
if (command != null) {
command.dataReceived(data);
if (spiLen == command.commandLen) {
// System.out.println("CC2520 Executing command: " + command.name);
command.executeSPICommand();
command = null;
spiLen = 0;
}
}
source.byteReceived(outputSPI);
}
void rxon() {
if(stateMachine == RadioState.IDLE) {
setState(RadioState.RX_CALIBRATE);
//updateActiveFrequency();
if (DEBUG) {
log("Strobe RX-ON!!!");
}
} else {
if (DEBUG) log("WARNING: SRXON when not IDLE");
}
}
void rxtxoff() {
if (DEBUG) {
log("Strobe RXTX-OFF!!! at " + cpu.cycles);
if (stateMachine == RadioState.TX_ACK ||
stateMachine == RadioState.TX_FRAME ||
stateMachine == RadioState.RX_FRAME) {
log("WARNING: turning off RXTX during " + stateMachine);
}
}
setState(RadioState.IDLE);
}
void stxon() {
// State transition valid from IDLE state or all RX states
if( (stateMachine == RadioState.IDLE) ||
(stateMachine == RadioState.RX_CALIBRATE) ||
(stateMachine == RadioState.RX_SFD_SEARCH) ||
(stateMachine == RadioState.RX_FRAME) ||
(stateMachine == RadioState.RX_OVERFLOW) ||
(stateMachine == RadioState.RX_WAIT)) {
status |= STATUS_TX_ACTIVE;
memory[REG_FSMSTAT1] |= (1 << 1);
setState(RadioState.TX_CALIBRATE);
if (sendEvents) {
sendEvent("STXON", null);
}
// Starting up TX subsystem - indicate that we are in TX mode!
if (DEBUG) log("Strobe STXON - transmit on! at " + cpu.cycles);
}
}
void stxoncca() {
// Only valid from all RX states,
// since CCA requires ??(look this up) receive symbol periods to be valid
if( (stateMachine == RadioState.RX_CALIBRATE) ||
(stateMachine == RadioState.RX_SFD_SEARCH) ||
(stateMachine == RadioState.RX_FRAME) ||
(stateMachine == RadioState.RX_OVERFLOW) ||
(stateMachine == RadioState.RX_WAIT)) {
if (sendEvents) {
sendEvent("STXON_CCA", null);
}
if(currentCCA) {
status |= STATUS_TX_ACTIVE;
memory[REG_FSMSTAT1] |= (1 << 1);
setState(RadioState.TX_CALIBRATE);
if (DEBUG) log("Strobe STXONCCA - transmit on! at " + cpu.cycles);
}else{
if (DEBUG) log("STXONCCA Ignored, CCA false");
}
}
}
void sack(boolean pend) {
// Set the frame pending flag for all future autoack based on SACK/SACKPEND
ackFramePending = pend;
if (stateMachine == RadioState.RX_FRAME) {
shouldAck = true;
} else if (crcOk) {
setState(RadioState.TX_ACK_CALIBRATE);
}
}
private void shrNext() {
if(shrPos == 5) {
// Set SFD high
setSFD(true);
if (stateMachine == RadioState.TX_PREAMBLE) {
setState(RadioState.TX_FRAME);
} else if (stateMachine == RadioState.TX_ACK_PREAMBLE) {
setState(RadioState.TX_ACK);
} else {
log("Can not move to TX_FRAME or TX_ACK after preamble since radio is in wrong mode: " +
stateMachine);
}
} else {
if (rfListener != null) {
if (DEBUG) log("transmitting byte: " + Utils.hex8(SHR[shrPos]));
rfListener.receivedByte(SHR[shrPos]);
}
shrPos++;
cpu.scheduleTimeEventMillis(shrEvent, SYMBOL_PERIOD * 2);
}
}
private void txNext() {
if(txfifoPos <= memory[RAM_TXFIFO]) {
int len = memory[RAM_TXFIFO] & 0xff;
if (autoCRC) {
if (txfifoPos == len - 1) {
txCrc.setCRC(0);
for (int i = 1; i < len - 1; i++) {
txCrc.addBitrev(memory[RAM_TXFIFO + i] & 0xff);
}
memory[RAM_TXFIFO + len - 1] = txCrc.getCRCHi();
memory[RAM_TXFIFO + len] = txCrc.getCRCLow();
}
}
if (txfifoPos > 0x7f) {
logw(WarningType.EXECUTION, "**** Warning - packet size too large - repeating packet bytes txfifoPos: " + txfifoPos);
}
if (rfListener != null) {
if (DEBUG) log("transmitting byte: " + Utils.hex8(memory[RAM_TXFIFO + (txfifoPos & 0x7f)] & 0xFF));
rfListener.receivedByte((byte)(memory[RAM_TXFIFO + (txfifoPos & 0x7f)] & 0xFF));
}
txfifoPos++;
// Two symbol periods to send a byte...
cpu.scheduleTimeEventMillis(sendEvent, SYMBOL_PERIOD * 2);
} else {
if (DEBUG) log("Completed Transmission.");
status &= ~STATUS_TX_ACTIVE;
memory[REG_FSMSTAT1] &= ~(1 << 1);
setSFD(false);
if (overflow) {
/* TODO: is it going back to overflow here ?=? */
setState(RadioState.RX_OVERFLOW);
} else {
setState(RadioState.RX_CALIBRATE);
}
/* Back to RX ON */
setMode(MODE_RX_ON);
txfifoFlush = true;
}
}
private void ackNext() {
if (ackPos < ackBuf.length) {
if(ackPos == 0) {
txCrc.setCRC(0);
if (ackFramePending) {
ackBuf[1] |= FRAME_PENDING;
} else {
ackBuf[1] &= ~FRAME_PENDING;
}
// set dsn
ackBuf[3] = dsn;
int len = 4;
for (int i = 1; i < len; i++) {
txCrc.addBitrev(ackBuf[i] & 0xff);
}
ackBuf[4] = txCrc.getCRCHi();
ackBuf[5] = txCrc.getCRCLow();
}
if (rfListener != null) {
if (DEBUG) log("transmitting byte: " + Utils.hex8(memory[RAM_TXFIFO + (txfifoPos & 0x7f)] & 0xFF));
rfListener.receivedByte((byte)(ackBuf[ackPos] & 0xFF));
}
ackPos++;
// Two symbol periods to send a byte...
cpu.scheduleTimeEventMillis(ackEvent, SYMBOL_PERIOD * 2);
} else {
if (DEBUG) log("Completed Transmission of ACK.");
status &= ~STATUS_TX_ACTIVE;
memory[REG_FSMSTAT1] &= ~(1 << 1);
setSFD(false);
setState(RadioState.RX_CALIBRATE);
/* Back to RX ON */
setMode(MODE_RX_ON);
}
}
private void setSymbolEvent(int symbols) {
double period = SYMBOL_PERIOD * symbols;
cpu.scheduleTimeEventMillis(symbolEvent, period);
//log("Set Symbol event: " + period);
}
void startOscillator() {
// 1ms crystal startup from datasheet pg12
cpu.scheduleTimeEventMillis(oscillatorEvent, 1);
}
void stopOscillator() {
status &= ~STATUS_XOSC16M_STABLE;
setState(RadioState.POWER_DOWN);
if (DEBUG) log("Oscillator Off.");
// Reset state
setFIFOP(false);
}
void flushRX() {
if (DEBUG) {
log("Flushing RX len = " + rxFIFO.length());
}
rxFIFO.reset();
setSFD(false);
setFIFOP(false);
setFIFO(false);
overflow = false;
/* goto RX Calibrate */
if( (stateMachine == RadioState.RX_CALIBRATE) ||
(stateMachine == RadioState.RX_SFD_SEARCH) ||
(stateMachine == RadioState.RX_FRAME) ||
(stateMachine == RadioState.RX_OVERFLOW) ||
(stateMachine == RadioState.RX_WAIT)) {
setState(RadioState.RX_SFD_SEARCH);
}
}
void writeTXFIFO(int data) {
if(txfifoFlush) {
txCursor = 0;
txfifoFlush = false;
}
if (DEBUG) log("Writing data: " + data + " to tx: " + txCursor);
if(txCursor == 0) {
if ((data & 0xff) > 127) {
logger.logw(this, WarningType.EXECUTION, "CC2520: Warning - packet size too large: " + (data & 0xff));
}
} else if (txCursor > 127) {
logger.logw(this, WarningType.EXECUTION, "CC2520: Warning - TX Cursor wrapped");
txCursor = 0;
}
memory[RAM_TXFIFO + txCursor] = data & 0xff;
txCursor++;
if (sendEvents) {
sendEvent("WRITE_TXFIFO", null);
}
}
// TODO: update any pins here?
void flushTX() {
txCursor = 0;
}
private void updateCCA() {
boolean oldCCA = currentCCA;
currentCCA = (status & STATUS_RSSI_VALID) > 0 && rssi < -95;
if (currentCCA != oldCCA) {
ccaGPIO.setActive(currentCCA);
if (currentCCA) {
memory[REG_FSMSTAT1] |= 1 << 4;
} else {
memory[REG_FSMSTAT1] &= ~(1 << 4);
}
if (DEBUG) log("Setting CCA to: " + currentCCA);
}
}
private void setSFD(boolean sfd) {
sfdGPIO.setActive(sfd);
if (sfd) {
memory[REG_FSMSTAT1] |= 1 << 5;
} else {
memory[REG_FSMSTAT1] &= ~(1 << 5);
}
if (DEBUG) log("SFD: " + sfd + " " + cpu.cycles);
}
private void setFIFOP(boolean fifop) {
currentFIFOP = fifop;
fifopGPIO.setActive(fifop);
if (fifop) {
memory[REG_FSMSTAT1] |= 1 << 6;
} else {
memory[REG_FSMSTAT1] &= ~(1 << 6);
}
if (DEBUG) log("Setting FIFOP to " + fifop);
}
private void setFIFO(boolean fifo) {
currentFIFO = fifo;
fifoGPIO.setActive(fifo);
if (fifo) {
memory[REG_FSMSTAT1] |= 1 << 7;
} else {
memory[REG_FSMSTAT1] &= ~(1 << 7);
}
if (DEBUG) log("Setting FIFO to " + fifo);
}
private void setRxOverflow() {
if (DEBUG) log("RXFIFO Overflow! Read Pos: " + rxFIFO.stateToString());
setFIFOP(true);
setFIFO(false);
setSFD(false);
overflow = true;
shouldAck = false;
setState(RadioState.RX_OVERFLOW);
}
@Override
public boolean isReadyToReceive() {
return getState() == RadioState.RX_SFD_SEARCH;
}
private void updateActiveFrequency() {
/* INVERTED: f = 5 * (c - 11) + 357 + 0x4000 */
int freg = memory[REG_FREQCTRL] & 0x7f;
activeFrequency = freg + 2394;
activeChannel = 11 + (freg - 11) / 5;
}
@Override
public int getActiveFrequency() {
updateActiveFrequency();
return activeFrequency;
}
@Override
public int getActiveChannel() {
updateActiveFrequency();
return activeChannel;
}
/**
* This is actually the "CORR" value.
* @param lqi The Corr-val
* @sa CC2520 Datasheet
*/
@Override
public void setLQI(int lqi){
if(lqi < 0) {
lqi = 0;
} else if(lqi > 0x7f ) {
lqi = 0x7f;
}
corrval = lqi;
}
@Override
public int getLQI() {
return corrval;
}
@Override
public void setRSSI(int power) {
final int minp = -128 + RSSI_OFFSET;
final int maxp = 128 + RSSI_OFFSET;
if (power < minp) {
power = -minp;
}
if(power > maxp){
power = maxp;
}
if (DEBUG) log("external setRSSI to: " + power);
rssi = power;
memory[REG_RSSI] = power - RSSI_OFFSET;
updateCCA();
}
@Override
public int getRSSI() {
return rssi;
}
private boolean isDefinedTxPower(int txpower) {
switch (txpower) {
case 0xf7:
case 0xf2:
case 0xab:
case 0x88:
case 0x81:
case 0x32:
case 0x2c:
case 0x13:
case 0x03:
return true;
default:
return false;
}
}
@Override
public int getOutputPowerIndicator() {
// Higher TXPOWER value does not always mean higher transmission power.
// Instead of using the TXPOWER value, the output power is mapped into 9 classes.
int txpower = memory[REG_TXPOWER];
if (txpower >= 0xf7) {
return 9;
}
if (txpower >= 0xf2) {
return 8;
}
if (txpower >= 0xab) {
return 7;
}
if (txpower >= 0x88) {
return 3;
}
if (txpower >= 0x81) {
return 4;
}
if (txpower >= 0x32) {
return 5;
}
if (txpower >= 0x2c) {
return 2;
}
if (txpower >= 0x13) {
return 6;
}
if (txpower >= 0x03) {
return 1;
}
/* Unknown */
return 0;
// return memory[REG_TXPOWER];
}
@Override
public int getOutputPowerIndicatorMax() {
return 9;
// return 255;
}
@Override
public int getOutputPower() {
/* From CC2520 datasheet, table 17 */
int txpower = memory[REG_TXPOWER];
if (txpower >= 0xf7) {
return 5;
}
if (txpower >= 0xf2) {
return 3;
}
if (txpower >= 0xab) {
return 2;
}
if (txpower >= 0x88) {
return -4;
}
if (txpower >= 0x81) {
return -2;
}
if (txpower >= 0x32) {
return 0;
}
if (txpower >= 0x2c) {
return -7;
}
if (txpower >= 0x13) {
return 1;
}
if (txpower >= 0x03) {
return -18;
}
/* Unknown */
return -100;
}
@Override
public int getOutputPowerMax() {
return 5;
}
@Override
public void notifyReset() {
super.notifyReset();
setChipSelect(false);
status &= ~STATUS_TX_ACTIVE;
memory[REG_FSMSTAT1] &= ~(1 << 1);
setVRegOn(false);
reset();
}
public void setVRegOn(boolean newOn) {
if(isRadioOn == newOn) return;
if(newOn) {
// 0.6ms maximum vreg startup from datasheet pg 13
// but Z1 platform does not work with 0.1 so trying with lower...
cpu.scheduleTimeEventMillis(vregEvent, 0.05);
if (DEBUG) log("Scheduling vregEvent at: cyc = " + cpu.cycles +
" target: " + vregEvent.getTime() + " current: " + cpu.getTime());
} else {
isRadioOn = false;
setState(RadioState.VREG_OFF);
}
}
public void setChipSelect(boolean select) {
chipSelect = select;
if (!chipSelect) {
spiLen = 0;
if (command != null) {
command.executeSPICommand();
}
command = null;
}
if (DEBUG) {
log("ChipSelect: " + chipSelect);
}
}
public boolean getChipSelect() {
return chipSelect;
}
public void setGPIO(int index, IOPort port, int pin) {
gpio[index].setConfig(port, pin);
}
@Override
public int getModeMax() {
return MODE_MAX;
}
private String getLongAddress() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8; i++) {
if ((i % 2 == 0) && i > 0) {
sb.append(':');
}
sb.append(Utils.hex8(memory[RAM_IEEEADDR + 7 - i]));
}
return sb.toString();
}
@Override
public String info() {
updateActiveFrequency();
String commandStr = command == null ? "<waiting>" : command.name;
return " VREG_ON: " + isRadioOn + " Chip Select: " + chipSelect +
" OSC Stable: " + ((status & STATUS_XOSC16M_STABLE) > 0) +
" GPIO Polarity: 0x" + Utils.hex8(memory[REG_GPIOPOLARITY]) +
"\n RSSI Valid: " + ((status & STATUS_RSSI_VALID) > 0) + " CCA: " + currentCCA +
"\n FIFOP: " + currentFIFOP + " threshold: " + fifopThr + " FIFO: " + currentFIFO + " SFD: " + sfdGPIO.isActive() +
"\n " + rxFIFO.stateToString() + " expPacketLen: " + rxlen +
"\n Radio State: " + stateMachine + " SPI State: " + commandStr +
"\n AutoACK: " + autoAck + " AddrDecode: " + frameFilter + " AutoCRC: " + autoCRC +
"\n PanID: 0x" + Utils.hex8(memory[RAM_PANID + 1]) + Utils.hex8(memory[RAM_PANID]) +
" ShortAddr: 0x" + Utils.hex8(memory[RAM_SHORTADDR + 1]) + Utils.hex8(memory[RAM_SHORTADDR]) +
" LongAddr: 0x" + getLongAddress() +
"\n Channel: " + activeChannel +
" Output Power: " + getOutputPower() + "dB (" + getOutputPowerIndicator() + '/' + getOutputPowerIndicatorMax() +
") txpower: 0x" + Utils.hex8(memory[REG_TXPOWER]) +
"\n";
}
@Override
public void stateChanged(int state) {
}
/* return data in register at the correct position */
@Override
public int getConfiguration(int parameter) {
return memory[parameter];
}
/* For SPI Commands */
@Override
public int getSPIData(int offset) {
return spiData[offset];
}
@Override
public int getSPIDataLen() {
return spiLen;
}
@Override
public void outputSPI(int data) {
outputSPI = data;
}
/* reads one byte from RX fifo */
void readRXFifo() {
int fifoData = rxFIFO.read();
if (DEBUG) log("RXFIFO READ: " + rxFIFO.stateToString());
outputSPI = fifoData;
/* first check and clear FIFOP - since we now have read a byte! */
if (currentFIFOP && !overflow) {
/* FIFOP is lowered when rxFIFO is lower than or equal to fifopThr */
if(rxFIFO.length() <= fifopThr) {
if (DEBUG) log("*** FIFOP cleared at: " + rxFIFO.stateToString());
setFIFOP(false);
}
}
/* initiate read of another packet - update some variables to keep track of packet reading... */
if (rxfifoReadLeft == 0) {
rxfifoReadLeft = fifoData;
if (DEBUG) log("Init read of packet - len: " + rxfifoReadLeft +
" fifo: " + rxFIFO.stateToString());
} else if (--rxfifoReadLeft == 0) {
/* check if we have another packet in buffer */
if (rxFIFO.length() > 0) {
/* check if the packet is complete or longer than fifopThr */
if (rxFIFO.length() > rxFIFO.peek(0) ||
(rxFIFO.length() > fifopThr && !decodeAddress && !frameRejected)) {
if (DEBUG) log("More in FIFO - FIFOP = 1! plen: " + rxFIFO.stateToString());
if (!overflow) setFIFOP(true);
}
}
}
// Set the FIFO pin low if there are no more bytes available in the RXFIFO.
if (rxFIFO.length() == 0) {
if (DEBUG) log("Setting FIFO to low (buffer empty)");
setFIFO(false);
}
}
} // CC2520
|
package se.sics.mspsim.core;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import se.sics.mspsim.util.MapEntry;
import se.sics.mspsim.util.MapTable;
import se.sics.mspsim.util.Utils;
public class DisAsm implements MSP430Constants {
private boolean step = true; //false;
private MapTable map;
// Idiots solution to single stepping...
private BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
public void setMap(MapTable m) {
map = m;
}
public MapTable getMap() {
return map;
}
public DbgInstruction disassemble(int pc, int[] memory, int[] reg) {
return disassemble(pc, memory, reg, 0);
}
public DbgInstruction disassemble(int pc, int[] memory, int[] reg,
int interrupt) {
DbgInstruction dbg = disassemble(pc, memory, reg, new DbgInstruction(),
interrupt);
String fkn;
if ((fkn = dbg.getFunction()) != null) {
System.out.println("//// " + fkn);
}
System.out.println(dbg.getASMLine());
/* Hack for printing the instruction after the ext word... */
if (dbg.isExtensionWord()) {
pc = pc + 2;
dbg = disassemble(pc, memory, reg, new DbgInstruction(),
interrupt);
System.out.println(dbg.getASMLine());
}
return dbg;
}
public DbgInstruction getDbgInstruction(int pc, MSP430 cpu) {
return disassemble(pc, cpu.memory, cpu.reg, new DbgInstruction(),
cpu.servicedInterrupt);
}
public DbgInstruction disassemble(int pc, int[] memory, int[] reg,
DbgInstruction dbg, int interrupt) {
int startPC = pc;
int size = 0;
int instruction = memory[pc] + (memory[pc + 1] << 8);
int op = instruction >> 12;
boolean word = (instruction & 0x40) == 0;
String output = " ";
if (interrupt > 0) {
output = "I:" + Integer.toString(interrupt) + ' ';
}
String regs = "";
if (pc < 0x0010) {
output += "000" + Integer.toString(pc, 16);
} else if (pc < 0x0100) {
output += "00" + Integer.toString(pc, 16);
} else if (pc < 0x1000) {
output += "0" + Integer.toString(pc, 16);
} else {
output += Integer.toString(pc, 16);
}
output += ":\t";
pc += 2;
size += 2;
switch (op) {
case 0: // MSP430X instructions
{
// MSP430X - additional instructions
String opstr = "";
op = instruction & 0xf0f0;
int srcdata = (instruction & 0x0f00) >> 8;
int dst = instruction & 0x000f;
int nextData = memory[pc] + (memory[pc + 1] << 8);
boolean rrword = true;
switch(op) {
case MOVA_IND:
opstr = "MOVA @R" + srcdata + ",R" + dst;
break;
case MOVA_IND_AUTOINC:
opstr = "MOVA @R" + srcdata + "+,R" + dst;
break;
case MOVA_ABS2REG:
opstr = "MOVA &$" + Utils.hex20(((srcdata << 16) | nextData)) + ",R" + dst;
size += 2;
break;
case MOVA_INDX2REG:
opstr = "MOVA $" + Utils.hex16(nextData) + "(R" + srcdata + "),R" + dst;
size += 2;
break;
case MOVA_REG2ABS:
opstr = "MOVA R" + srcdata + ",&$" + Utils.hex20(((dst << 16) | nextData));
size += 2;
break;
case MOVA_REG2INDX:
opstr = "MOVA R" + srcdata + ",$" + Utils.hex16(nextData) + "(R" + dst + ")";
size += 2;
break;
case MOVA_IMM2REG:
opstr = "MOVA #$" + Utils.hex20(((srcdata << 16) | nextData)) + ",R" + dst;
size += 2;
break;
case CMPA_IMM:
opstr = "CMPA #$" + Utils.hex20(((srcdata << 16) | nextData)) + ",R" + dst;
size += 2;
break;
case ADDA_IMM:
opstr = "ADDA #$" + Utils.hex20(((srcdata << 16) | nextData)) + ",R" + dst;
size += 2;
break;
case SUBA_IMM:
opstr = "SUBA #$" + Utils.hex20(((srcdata << 16) | nextData)) + ",R" + dst;
size += 2;
break;
case MOVA_REG:
opstr = "MOVA R" + srcdata + ",R" + dst;
break;
case CMPA_REG:
opstr = "CMPA R" + srcdata + ",R" + dst;
break;
case ADDA_REG:
opstr = "ADDA R" + srcdata + ",R" + dst;
break;
case SUBA_REG:
opstr = "SUBA R" + srcdata + ",R" + dst;
break;
case RRXX_ADDR:
rrword = false;
case RRXX_WORD:
String rrwordStr = rrword ? ".W" : ".A";
int count = ((instruction >> 10) & 0x03) + 1; // shift amount
switch (instruction & RRMASK) {
case RRCM:
opstr = "RRCM" + rrwordStr + " #" + count + ",R" + dst;
break;
case RRAM:
opstr = "RRAM" + rrwordStr + " #" + count + ",R" + dst;
break;
case RLAM:
opstr = "RLAM" + rrwordStr + " #" + count + ",R" + dst;
break;
case RRUM:
opstr = "RRUM" + rrwordStr + " #" + count + ",R" + dst;
break;
}
break;
}
output += dumpMem(startPC, size, memory);
output += opstr + " ";
regs = "R" + srcdata + "=" + Utils.hex16(reg[srcdata]);
regs += " SP=" + Utils.hex16(reg[SP]);
}
break;
case 1: // Single operand instructions
{
/* check CALLA first */
int dst = instruction & 0x000f;
int nextData = memory[pc] + (memory[pc + 1] << 8);
String opstr = null;
switch(instruction & 0xfff0) {
case CALLA_REG:
opstr = "CALLA R" + dst;
break;
case CALLA_IND:
opstr = "CALLA @R" + dst;
break;
case CALLA_IND_AUTOINC:
opstr = "CALLA @R" + dst + "+";
break;
case CALLA_ABS:
opstr = "CALLA &" + Utils.hex20(((dst << 16) | nextData));
size += 2;
break;
case CALLA_EDE:
opstr = "CALLA " + Utils.hex20(((dst << 16) | nextData)) + "(PC)";
size += 2;
break;
case CALLA_IMM:
opstr = "CALLA #" + Utils.hex20(((dst << 16) | nextData));
size += 2;
break;
default:
switch (instruction & 0xff00) {
case PUSHM_A:
opstr = "PUSHM.A #" + (1 + ((instruction >> 4) & 0x0f)) + ", R" + (instruction & 0x0f);
break;
case PUSHM_W:
opstr = "PUSHM.W #" + (1 + ((instruction >> 4) & 0x0f)) + ", R" + (instruction & 0x0f);
break;
case POPM_A:
opstr = "POPM.A #" + (1 + ((instruction >> 4) & 0x0f)) + ", R" + (instruction & 0x0f);
break;
case POPM_W:
opstr = "POPM.W #" + (1 + ((instruction >> 4) & 0x0f)) + ", R" + (instruction & 0x0f);
break;
}
}
if (opstr != null) {
output += dumpMem(startPC, size, memory);
output += opstr + " ";
regs = "R" + dst + "=" + Utils.hex16(reg[dst]);
regs += " SP=" + Utils.hex16(reg[SP]);
} else {
// Register
int register = instruction & 0xf;
// Adress mode of destination...
int ad = (instruction >> 4) & 3;
// Pick up the destination address based on ad more and regs...
int dstAddress = 0;
String adr = "";
switch(ad) {
// Operand in register!
case AM_REG:
adr = "R" + register;
break;
case AM_INDEX:
dstAddress = memory[pc] + (memory[pc + 1] << 8);
adr = "R" + register + "(" + dstAddress + ")";
dstAddress = (register == CG1 ? 0 : reg[register]) + dstAddress;
pc += 2;
size += 2;
break;
// Indirect register
case AM_IND_REG:
adr = "@(R" + register + ")";
dstAddress = reg[register];
break;
case AM_IND_AUTOINC:
if (register == 0) {
// Can this be PC and be incremented only one byte?
int tmp = memory[pc] + (memory[pc + 1] << 8);
MapEntry me;
if (map != null && (me = map.getEntry(tmp)) != null) {
adr = me.getName(); // + " = $" + Utils.hex16(tmp);
} else {
adr = "#$" + Utils.hex16(tmp);
}
size += 2;
} else {
adr = "@(R" + register + "+)";
dstAddress = reg[register];
}
break;
}
switch(instruction & 0xff80) {
case RRC:
opstr = "RRC" + (word ? ".W" : ".B");
break;
case SWPB:
opstr = "SWPB" + (word ? ".W" : ".B");
break;
case RRA:
opstr = "RRA" + (word ? ".W" : ".B");
break;
case SXT:
opstr = "RRA" + (word ? ".W" : ".B");
break;
case PUSH:
opstr = "PUSH" + (word ? ".W" : ".B");
break;
case CALL:
opstr = "CALL";
break;
case RETI:
opstr = "RETI";
break;
default:
if ((instruction & 0xf800) == 0x1800) {
int zc = (instruction & EXTWORD_ZC) > 0 ? 1 : 0;
int al = (instruction & EXTWORD_AL) > 0 ? 1 : 0;
int rp = (instruction & EXTWORD_REPEAT) > 0 ? 1 : 0;
int shi = (instruction & EXTWORD_SRC) >> 7;
int dhi = (instruction & EXTWORD_DST);
opstr = "ExtWord " + Utils.hex16(instruction) + ":ZC:" + zc + "
" A/L:" + al + " src:" + shi + " dst:" + dhi;
dbg.setExtWord(true);
} else {
System.out.println("Not implemented instruction: $" + Utils.hex16(instruction) +
" at " + Utils.hex16(startPC));
opstr = "<Unkown>";
}
}
output += dumpMem(startPC, size, memory);
output += opstr + " " + adr;
regs = "R" + register + "=" + Utils.hex16(reg[register]);
regs += " SP=" + Utils.hex16(reg[SP]);
}
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
String opstr = "";
switch(instruction & 0xfc00) {
case JNE:
opstr = "JNE";
break;
case JEQ:
opstr = "JEQ";
break;
case JNC:
opstr = "JNC";
break;
case JC:
opstr = "JC";
break;
case JN:
opstr = "JN";
break;
case JGE:
opstr = "JGE";
break;
case JL:
opstr = "JL";
break;
case JMP:
opstr = "JMP";
break;
default:
System.out.println("Not implemented instruction: " +
Utils.binary16(instruction));
}
output += dumpMem(startPC, size, memory);
output += opstr + " $" + Utils.hex16(jmpOffset);
regs = "\tSR=" + dumpSR(reg[SR]);
break;
default:
// Double operand instructions!
int dstRegister = (instruction & 0xf);
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
boolean dstRegMode = ((instruction >> 7) & 1) == 0;
int dstAddress = 0;
int srcAddress = 0;
int src = 0;
int dst = 0;
boolean write = false;
boolean updateStatus = true;
String srcadr = "";
String dstadr = "";
switch(as) {
// Operand in register!
case AM_REG:
if (srcRegister == CG2) {
srcadr = "
} else if (srcRegister == CG1) {
srcadr = "
} else {
srcadr = getRegName(srcRegister);
}
break;
case AM_INDEX:
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
if (srcRegister == CG1) {
srcAddress = memory[pc] + (memory[pc + 1] << 8);
MapEntry me;
if (map != null && (me = map.getEntry(srcAddress)) != null) {
srcadr = "&" + me.getName(); // + " = $" + Utils.hex16(srcAddress);
} else {
srcadr = "&$" + Utils.hex16(srcAddress);
}
size += 2;
} else if (srcRegister == CG2) {
srcadr = "
} else {
srcAddress = reg[srcRegister] + memory[pc] + (memory[pc + 1] << 8);
srcadr = "$" + Utils.hex16(memory[pc] + (memory[pc + 1] << 8)) + "(R" + srcRegister + ")";
size += 2;
}
pc += 2;
break;
// Indirect register
case AM_IND_REG:
if (srcRegister == CG2) {
srcadr = "
} else if (srcRegister == CG1) {
srcadr = "
} else {
srcadr = "@" + getRegName(srcRegister);
}
break;
case AM_IND_AUTOINC:
if (srcRegister == CG2) {
srcadr = "#$ffff";
} else if (srcRegister == CG1) {
srcadr = "
} else if (srcRegister == PC) {
srcadr = "#$" + Utils.hex16(memory[pc] + (memory[pc + 1] << 8));
pc += 2;
size += 2;
} else if (srcRegister == CG2) {
srcadr = "#$ffff";
} else {
srcadr = "@" + getRegName(srcRegister) + "+";
srcAddress = reg[srcRegister];
}
break;
}
if (dstRegMode) {
dstadr = getRegName(dstRegister);
} else {
dstAddress = memory[pc] + (memory[pc + 1] << 8);
MapEntry me = map != null ? map.getEntry(dstAddress) : null;
if (dstRegister == 2) {
if (me != null) {
dstadr = "&" + me.getName(); // + " = $" + Utils.hex16(srcAddress);
} else {
dstadr = "&$" + Utils.hex16(dstAddress);
}
} else {
if (me != null) {
dstadr = me.getName() + "(R" + dstRegister + ")";
} else {
dstadr = "$" + Utils.hex16(dstAddress) + "(R" + dstRegister + ")";
}
}
pc += 2;
size += 2;
}
// If byte mode the source will not contain the full word...
if (!word) {
src = src & 0xff;
dst = dst & 0xff;
}
opstr = "";
switch (op) {
case MOV: // MOV
if (instruction == 0x3041) {
opstr = "RET /emulated: MOV.W ";
} else {
opstr = "MOV" + (word ? ".W" : ".B");
}
break;
case ADD: // ADD
opstr = "ADD" + (word ? ".W" : ".B");
break;
case ADDC: // ADDC
opstr = "ADDC" + (word ? ".W" : ".B");
break;
case SUBC: // SUBC
opstr = "SUBC" + (word ? ".W" : ".B");
break;
case SUB: // SUB
opstr = "SUB" + (word ? ".W" : ".B");
break;
case CMP: // CMP
opstr = "CMP" + (word ? ".W" : ".B");
break;
case DADD: // DADD
opstr = "DADD" + (word ? ".W" : ".B");
break;
case BIT: // BIT
opstr = "BIT" + (word ? ".W" : ".B");
break;
case BIC: // BIC
opstr = "BIC" + (word ? ".W" : ".B");
break;
case BIS: // BIS
opstr = "BIS" + (word ? ".W" : ".B");
break;
case XOR: // XOR
opstr = "XOR" + (word ? ".W" : ".B");
break;
case AND: // AND
opstr = "AND" + (word ? ".W" : ".B");
break;
default:
if (startPC > 0x200)
System.out.println(output + " DoubleOperand not implemented: " +
op + " instruction: " +
Utils.binary16(instruction) + " = " +
Utils.hex16(instruction));
}
output += dumpMem(startPC, size, memory);
output += opstr + " " + srcadr + ", " + dstadr;
regs = "R" + dstRegister + "=" + Utils.hex16(reg[dstRegister]) +
" R" + srcRegister + "=" + Utils.hex16(reg[srcRegister]);
regs += " SR=" + dumpSR(reg[SR]);
regs += " SP=" + Utils.hex16(reg[SP]);
regs += "; as = " + as;
srcAddress &= 0xffff;
if (srcAddress != -1) {
srcAddress &= 0xffff;
regs += " sMem:" + Utils.hex16(memory[srcAddress] +
(memory[(srcAddress + 1) % 0xffff]
<< 8));
}
}
dbg.setASMLine(output);
dbg.setRegs(regs);
dbg.setInstruction(instruction, size);
if (map != null) {
dbg.setFunction(map.getFunctionName(startPC));
}
if (!step) {
String line = "";
try {line = input.readLine();}catch(Exception e){}
if (line != null && line.length() > 0 && line.charAt(0) == 'r') {
System.out.println("Registers:");
for (int i = 0, n = 16; i < n; i++) {
System.out.print("R" + i + "=" + Utils.hex16(reg[i]) + " ");
if (i % 7 == 0 && i != 0) System.out.println();
}
System.out.println();
}
}
return dbg;
}
private String getRegName(int index) {
if (index == 0) return "PC";
if (index == 1) return "SP";
if (index == 2) return "SR";
return "R" + index;
}
public static String getSingleOPStr(int instruction) {
boolean word = (instruction & 0x40) == 0;
switch(instruction & 0xff80) {
case RRC:
return "RRC" + (word ? ".W" : ".B");
case SWPB:
return "SWPB" + (word ? ".W" : ".B");
case RRA:
return "RRA" + (word ? ".W" : ".B");
case SXT:
return "RRA" + (word ? ".W" : ".B");
case PUSH:
return "PUSH" + (word ? ".W" : ".B");
case CALL:
return "CALL";
case RETI:
return "RETI";
default:
return "-";
}
}
private static String dumpSR(int sr) {
return "" +
(((sr & OVERFLOW) != 0) ? 'V' : '-') +
(((sr & NEGATIVE) != 0) ? 'N' : '-') +
(((sr & ZERO) != 0) ? 'Z' : '-') +
(((sr & CARRY) != 0) ? 'C' : '-');
}
private static String dumpMem(int pc, int size, int[] memory) {
String output = "";
for (int i = 0, n = size; i < n; i++) {
if (size > i) {
output += Utils.hex8(memory[pc + i]) + " ";
} else {
output += " ";
}
}
return output;
}
}
|
// $Header: /share/content/gforge/sentinel/sentinel/src/gov/nih/nci/cadsr/sentinel/audits/AuditConceptToEVS.java,v 1.3 2006-09-22 14:56:46 hebell Exp $
// $Name: not supported by cvs2svn $
package gov.nih.nci.cadsr.sentinel.audits;
import gov.nih.nci.cadsr.sentinel.database.DBProperty;
import gov.nih.nci.cadsr.sentinel.tool.ConceptItem;
import gov.nih.nci.evs.domain.Definition;
import gov.nih.nci.evs.domain.Property;
import gov.nih.nci.evs.domain.DescLogicConcept;
import gov.nih.nci.evs.domain.MetaThesaurusConcept;
import gov.nih.nci.evs.domain.Source;
import gov.nih.nci.evs.query.EVSQuery;
import gov.nih.nci.evs.query.EVSQueryImpl;
import gov.nih.nci.system.applicationservice.ApplicationException;
import gov.nih.nci.system.applicationservice.ApplicationService;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.apache.log4j.Logger;
/**
* This class compares the caDSR Concepts table to the referenced EVS Concepts. If the concept code or name is not
* valid an appropriate message is returned. Concepts which match EVS are not reported.
*
* @author lhebel
*
*/
public class AuditConceptToEVS extends AuditReport
{
/* (non-Javadoc)
* @see gov.nih.nci.cadsr.sentinel.tool.AuditReport#getTitle()
*/
@Override
public String getTitle()
{
return "caDSR / EVS Concept Inconsistencies";
}
/* (non-Javadoc)
* @see gov.nih.nci.cadsr.sentinel.tool.AuditReport#getReportRows()
*/
@Override
public String[] getReportRows()
{
Vector<String> msgs = validate();
String[] rows = new String[msgs.size()];
for (int i = 0; i < rows.length; ++i)
{
rows[i] = msgs.get(i);
}
return rows;
}
/* (non-Javadoc)
* @see gov.nih.nci.cadsr.sentinel.tool.AuditReport#okToDisplayCount()
*/
@Override
public boolean okToDisplayCount()
{
return true;
}
/* (non-Javadoc)
* @see gov.nih.nci.cadsr.sentinel.tool.AuditReport#rightJustifyLastColumn()
*/
@Override
public boolean rightJustifyLastColumn()
{
return false;
}
/**
* Parse the DBProperties and create appropriate EVSVocab objects.
*
* @param props_ the property (key/value pairs)
* @return the equivalent vocab objects
*/
private EVSVocab[] parseProperties(DBProperty[] props_)
{
Vector<EVSVocab> vocabs = new Vector<EVSVocab>();
String defProp = "";
// Get defaults
for (int i = 0; i < props_.length; ++i)
{
String[] text = props_[i]._key.split("[.]");
if (text[2].equals("ALL"))
{
if (text[3].equals("PROPERTY") && text[4].equals("DEFINITION"))
defProp = props_[i]._value;
break;
}
}
// Process vocab data
EVSVocab vocab = null;
vocab = new EVSVocab();
vocab._display = "MetaThesaurus";
vocab._vocab = "MetaThesaurus";
vocab._source = "NCI_META_CUI";
vocab._source2 = "UMLS_CUI";
vocab._ed = new MetaTh(vocab);
vocabs.add(vocab);
String vDisplay = null;
String vName = null;
String vDefProp = null;
String vSearch = null;
String vSource = null;
String last = null;
for (int i = 0; i < props_.length; ++i)
{
String[] text = props_[i]._key.split("[.]");
if (!text[2].equals("ALL"))
{
if (last == null)
last = text[2];
if (!last.equals(text[2]))
{
vocab = new EVSVocab();
vocab._display = vDisplay;
vocab._vocab = vName;
vocab._preferredDefinitionProp = (vDefProp == null) ? defProp : vDefProp;
vocab._preferredNameProp = vSearch;
vocab._ed = new NonMetaTh(vocab);
vocab._source = vSource;
vocabs.add(vocab);
vDisplay = null;
vName = null;
vDefProp = null;
vSearch = null;
vSource = null;
last = text[2];
}
if (text.length == 4)
{
if (text[3].equals("DISPLAY"))
vDisplay = props_[i]._value;
else if (text[3].equals("EVSNAME"))
{
vName = props_[i]._value;
if (vName.equals("NCI_Thesaurus"))
vSource = "NCI_CONCEPT_CODE";
else if (vName.equals("LOINC"))
vSource = "LOINC_CODE";
else if (vName.equals("GO"))
vSource = "GO_CODE";
else if (vName.equals("MedDRA"))
vSource = "MEDDRA_CODE";
else if (vName.equals("SNOMED_CT"))
vSource = "SNOMED_CODE";
else if (vName.equals("VA_NDFRT"))
vSource = "VA_NDF_CODE";
else if (vName.equals("MGED_Ontology"))
vSource = "NCI_MO_CODE";
}
}
else if (text.length == 5)
{
if (text[3].equals("PROPERTY"))
{
if (text[4].equals("DEFINITION"))
{
vDefProp = props_[i]._value;
}
else if (text[4].equals("NAMESEARCH"))
{
vSearch = props_[i]._value;
}
}
}
}
}
vocab = new EVSVocab();
vocab._display = vDisplay;
vocab._vocab = vName;
vocab._preferredDefinitionProp = (vDefProp == null) ? defProp : vDefProp;
vocab._preferredNameProp = vSearch;
vocab._ed = new NonMetaTh(vocab);
vocab._source = vSource;
vocabs.add(vocab);
EVSVocab[] rs = new EVSVocab[vocabs.size()];
for (int i = 0; i < rs.length; ++i)
{
rs[i] = vocabs.get(i);
}
return rs;
}
private class EVSVocab
{
/**
* Constructor
*/
public EVSVocab()
{
}
public String _vocab;
public String _display;
public String _preferredNameProp;
public String _preferredDefinitionProp;
public String _source;
public String _source2;
public EVSData _ed;
}
private abstract class EVSData
{
/**
* Constructor
*
* @param vocab_ the vocabulary description
*/
public EVSData(EVSVocab vocab_)
{
reset();
_vocab = vocab_;
}
/**
* Reset the data elements to empty.
*
*/
public void reset()
{
_msg = "";
_flag = true;
}
/**
* Determine the recommended concept name when it is missing.
*
* @return the recommended concept name
*/
abstract public String recommendName();
/**
* Search EVS for the Concept Code.
*
* @param query_ the EVSQuery defined by the caCORE API
*/
abstract public void search(EVSQuery query_);
/**
* Validate the Concept Code, Concept Name and Concept Definition.
*/
abstract public void validate();
/**
* The messages from the validate() method.
*/
public String _msg;
/**
* The recommended name for a Concept.
*/
public String _name;
/**
* The caDSR Concept record to validate.
*/
public ConceptItem _rec;
/**
* The validation flag, true indicates the Name does not match.
*/
public boolean _flag;
/**
* The concept list returned by the caCORE API EVS Query.
*/
public List _cons;
/**
* The name property list use to validate the concept name.
*/
public EVSVocab _vocab;
}
private class MetaTh extends EVSData
{
/**
* Constructor
*
* @param vocab_ the EVS vocab description
*/
public MetaTh(EVSVocab vocab_)
{
super(vocab_);
}
@Override
public void search(EVSQuery query_)
{
query_.searchMetaThesaurus(_rec._preferredName);
}
@Override
public String recommendName()
{
MetaThesaurusConcept obj = (MetaThesaurusConcept) _cons.get(0);
return obj.getName();
}
@Override
public void validate()
{
try
{
// The search returns a list of results so process all.
for (int i = 0; i < _cons.size(); ++i)
{
// The objects are Meta Thesaurus
MetaThesaurusConcept temp = (MetaThesaurusConcept) _cons.get(i);
// Check the default name.
if (_rec._longName.compareToIgnoreCase(temp.getName()) == 0)
{
_flag = false;
break;
}
// Check the synonyms if the default name didn't match.
ArrayList value = temp.getSynonymCollection();
if (value.indexOf(_rec._longName) > -1)
{
_flag = false;
break;
}
}
// We didn't find a name so recommend one.
if (_flag)
_name = recommendName();
}
catch (ClassCastException ex)
{
// Mislabeled as a MetaThesaurus Concept
_msg += formatMsg(_MSG001);
_flag = false;
_logger.warn(ex.toString());
// Can't check anything else when this exception happens.
return;
}
// Must have a definition source to proceed.
if (_rec._definitionSource == null || _rec._definitionSource.length() == 0)
{
boolean defFlag = false;
for (int i = 0; i < _cons.size(); ++i)
{
// Need definitions.
MetaThesaurusConcept temp = (MetaThesaurusConcept) _cons.get(i);
@SuppressWarnings("unchecked")
ArrayList<Definition> defs = temp.getDefinitionCollection();
if (defs != null && defs.size() > 0)
{
defFlag = true;
break;
}
}
// The caDSR definition source is missing and EVS has possible definitions
if (defFlag)
_msg += formatMsg(_MSG002);
// EVS has no definitions for this term and the caDSR contains definition text
else if (_rec._preferredDefinition.length() > 0)
_msg += formatMsg(_MSG003);
}
else
{
// Process the search results again only this time for the definition.
boolean srcFlag = true;
boolean defFlag = true;
boolean defCol = true;
String defSource = null;
int full = 0;
for (int i = 0; i < _cons.size() && full < 3 && srcFlag && defFlag; ++i)
{
// Need definitions.
MetaThesaurusConcept temp = (MetaThesaurusConcept) _cons.get(i);
@SuppressWarnings("unchecked")
ArrayList<Definition> defs = temp.getDefinitionCollection();
if (defs != null && defs.size() > 0)
{
defCol = false;
// Check the definition source and definition text.
for (Definition def : defs)
{
full = 0;
Source defsor = def.getSource();
if (defsor != null && defsor.getAbbreviation().equals(_rec._definitionSource))
{
srcFlag = false;
full += 1;
}
if (def.getDefinition().equals(_rec._preferredDefinition))
{
if (defsor != null)
defSource = defsor.getAbbreviation();
defFlag = false;
full += 2;
}
if (full == 3)
break;
}
}
}
// Did we find everything?
if (full == 3)
return;
if (defCol)
{
// No definitions exist in EVS and the caDSR contains a definition source [{0}]
_msg += formatMsg(_MSG004, _rec._definitionSource);
return;
}
if (srcFlag)
{
// Definition Source [{0}] does not exist for this Concept
if (defFlag)
_msg += formatMsg(_MSG005, _rec._definitionSource);
// Definition matches source [{0}] but was expecting source to be [{1}]
else if (defSource != null)
_msg += formatMsg(_MSG006, defSource, _rec._definitionSource);
// Definition matches unnamed source but was expecting source to be [{0}]
else
_msg += formatMsg(_MSG007, _rec._definitionSource);
}
// Definition does not match EVS. [{0}]
else if (defFlag)
_msg += formatMsg(_MSG008, _rec._definitionSource);
// Definition and Source found for concept but Definition matches source [{0}] and expecting source [{1}]
else
_msg += formatMsg(_MSG009, defSource, _rec._definitionSource);
}
}
}
private class NonMetaTh extends EVSData
{
/**
* Constructor
*
* @param vocab_ the EVS vocab description
*/
public NonMetaTh(EVSVocab vocab_)
{
super(vocab_);
}
@Override
public void search(EVSQuery query_)
{
query_.getDescLogicConcept(_vocab._vocab, _rec._preferredName, true);
}
@Override
public String recommendName()
{
DescLogicConcept obj = (DescLogicConcept) _cons.get(0);
if (_vocab._preferredNameProp == null)
return obj.getName();
String name = "no recommendations available";
@SuppressWarnings ("unchecked")
Vector<Property> collection = obj.getPropertyCollection();
if (collection == null || collection.size() == 0)
{
String temp = obj.getName();
if (temp != null && temp.length() > 0)
name = temp;
}
else
{
for (Property prop : collection)
{
if (prop.getName().equals(_vocab._preferredNameProp))
{
name = prop.getValue();
break;
}
}
}
return name;
}
@Override
public void validate()
{
try
{
for (int i = 0; i < _cons.size(); ++i)
{
Vector collection = null;
Property prop = null;
DescLogicConcept temp = (DescLogicConcept) _cons.get(i);
if (_vocab._preferredNameProp == null)
{
if (temp.getName().compareToIgnoreCase(_rec._longName) == 0)
{
_flag = false;
break;
}
collection = temp.getPropertyCollection();
}
else
{
collection = temp.getPropertyCollection();
// Searching a Vector class is best using the Vector.contains() method. Depending
// on the vocabulary different attribute names must be used to match the name. This
// information is also stored in the tool_options table for the Curation Tool.
prop = new Property();
prop.setName(_vocab._preferredNameProp);
prop.setValue(_rec._longName);
if (collection.contains(prop))
{
_flag = false;
break;
}
}
// In the off chance none of the current defined attributes contain the name, perhaps
// an attribute was removed from the Curation Tool options after a concept was
// copied from EVS.
for (int n = 0; n < collection.size(); ++n)
{
prop = (Property) collection.get(n);
if (_rec._longName.compareToIgnoreCase(prop.getValue()) == 0)
{
// Name matches on property {0} but expected to match on property {1}
_msg += formatMsg(_MSG010, prop.getName(), ((_vocab._preferredNameProp == null) ? "(default)" : _vocab._preferredNameProp));
_flag = false;
break;
}
}
}
if (_flag)
_name = recommendName();
}
catch (ClassCastException ex)
{
// Mislabeled, should be a MetaThesaurus Concept
_msg += formatMsg(_MSG011);
_flag = false;
_logger.warn(ex.toString());
// Can't continue if this exception occurs.
return;
}
boolean srcFlag = true;
boolean defFlag = true;
for (int i = 0; i < _cons.size() && srcFlag && defFlag; ++i)
{
DescLogicConcept temp = (DescLogicConcept) _cons.get(i);
@SuppressWarnings("unchecked")
Vector<Property> props = temp.getPropertyCollection();
for (Property prop : props)
{
if (prop.getName().equals(_vocab._preferredDefinitionProp))
{
srcFlag = false;
int pDefSrc;
int tDefSrc;
pDefSrc = prop.getValue().indexOf("<def-source>");
if (pDefSrc >= 0)
{
pDefSrc += "<def-source>".length();
String text = prop.getValue().substring(pDefSrc);
tDefSrc = text.indexOf("</def-source>");
text = text.substring(0, tDefSrc);
if (text.length() == 0)
{
// The EVS definition source is missing, caDSR is [{0}]
if (_rec._definitionSource != null && _rec._definitionSource.length() > 0)
_msg += formatMsg(_MSG012, _rec._definitionSource);
}
else
{
// The caDSR definition source is missing, EVS is [{0}]
if (_rec._definitionSource == null || _rec._definitionSource.length() == 0)
_msg += formatMsg(_MSG013, text);
else
{
// The caDSR definition source [{0}] does not match EVS. [{1}]
if (!text.equals(_rec._definitionSource))
_msg += formatMsg(_MSG014, _rec._definitionSource, text);
}
}
}
pDefSrc = prop.getValue().indexOf("<def-definition>");
if (pDefSrc < 0)
{
if (prop.getValue().equals(_rec._preferredDefinition))
{
defFlag = false;
}
}
else
{
pDefSrc += "<def-definition>".length();
String text = prop.getValue().substring(pDefSrc);
tDefSrc = text.indexOf("</def-definition>");
if (text.substring(0, tDefSrc).equals(_rec._preferredDefinition))
{
defFlag = false;
}
}
break;
}
}
}
if (srcFlag)
{
// No definitions exist in EVS for property [{0}] can not compare definitions
if (_rec._preferredDefinition.length() > 0)
_msg += formatMsg(_MSG015, _vocab._preferredDefinitionProp);
}
else if (defFlag)
{
// Definition does not match EVS
if (_rec._definitionSource == null)
_msg += formatMsg(_MSG016);
// Definition does not match EVS [{0}]
else
_msg += formatMsg(_MSG017, _rec._definitionSource);
}
}
}
/**
* Validate the caDSR Concepts against EVS
*
* @return exception, error and information messages
*/
private Vector<String> validate()
{
// Seed message list with column headings.
Vector<String> msgs = new Vector<String>();
msgs.add(formatTitleMsg());
// Get all the Concepts from the caDSR.
Vector<ConceptItem> concepts = _db.selectConcepts();
EVSVocab[] vocabs = parseProperties(_db.selectEVSVocabs());
// Get the EVS URL and establish the application service.
String evsURL = _db.selectEvsUrl();
ApplicationService coreapi = ApplicationService.getRemoteInstance(evsURL);
// Check each concept with EVS.
String msg = null;
String name = null;
int count = 0;
for (ConceptItem rec : concepts)
{
// Reset loop variables.
msg = "";
if (rec._preferredDefinition.toLowerCase().startsWith("no value exists"))
rec._preferredDefinition = "";
// Show status messages when debugging.
if ((count % 100) == 0)
{
_logger.debug("Completed " + count + " out of " + concepts.size() + " (" + (count * 100 / concepts.size()) + "%) . Message/Failure count " + msgs.size() + " (" + String.valueOf(msgs.size() * 100 / concepts.size()) + "%)");
}
++count;
EVSVocab vocab = null;;
while (true)
{
// Missing EVS Source
if (rec._evsSource == null || rec._evsSource.length() == 0)
{
msg += formatMsg(_MSG020);
break;
}
// Determine the desired vocabulary using the EVS source value in caDSR.
// This translation should be in the tool options table or the data content of the EVS
// source column should use the standard vocabulary abbreviation.
for (int i = 0; i < vocabs.length; ++i)
{
if (rec._evsSource.equals(vocabs[i]._source))
{
vocab = vocabs[i];
break;
}
}
if (vocab == null)
{
if (rec._evsSource.equals(vocabs[0]._source2))
vocab = vocabs[0];
}
// Unknown EVS Source {0}
if (vocab == null)
{
msg += formatMsg(_MSG021, rec._evsSource);
break;
}
// Missing Concept Code
if (rec._preferredName== null || rec._preferredName.length() == 0)
{
msg += formatMsg(_MSG022);
break;
}
EVSData ed = vocab._ed;
ed.reset();
ed._rec = rec;
EVSQuery query = new EVSQueryImpl();
ed.search(query);
try
{
// Get the attributes for the concept code.
ed._cons = coreapi.evsSearch(query);
}
catch (ApplicationException ex)
{
// Invalid concept code
if (ex.toString().indexOf("Invalid concept code") > -1)
{
msg += formatMsg(_MSG023);
_logger.warn(ex.toString());
break;
}
// Invalid concept ID
else if (ex.toString().indexOf("Invalid conceptID") > -1)
{
msg += formatMsg(_MSG024);
_logger.warn(ex.toString());
break;
}
// An unexpected exception occurred so record it and terminate the validation.
else
{
msg += "\n" + ex.toString();
msg = formatMsg(rec, vocab, msg);
msgs.add(msg);
_logger.error(ex.toString());
return msgs;
}
}
// Failed to retrieve EVS concept
if (ed._cons.size() == 0)
{
msg += formatMsg(_MSG025);
break;
}
// Missing Concept Long Name, recommend using [{0}]
if (rec._longName == null || rec._longName.length() == 0)
{
msg += formatMsg(_MSG026, ed.recommendName());
break;
}
// Assume we will not match the concept name.
boolean flag = true;
name = null;
// Validate data.
ed.validate();
flag = ed._flag;
name = ed._name;
msg += ed._msg;
// The name of the concept in the caDSR doesn't match anything in EVS for this concept code.
if (flag)
{
// Concept name does not match EVS
if (name == null)
msg += formatMsg(_MSG018);
// Concept name does not match EVS, expected [{0}]
else
msg += formatMsg(_MSG019, name);
}
break;
}
// If something happened during the validation, record the message and continue with the next concept.
if (msg.length() > 0)
{
msg = formatMsg(rec, vocab, msg);
msgs.add(msg);
if (msgs.size() >= _maxMsgs)
{
msgs.add(formatMaxMsg());
break;
}
}
}
// Return all the messages, the validation processing is complete.
return msgs;
}
private static String formatMsg(String msg_, String ... subs_)
{
String text = msg_;
for (int i = 0; i < subs_.length; ++i)
{
String temp = "{" + i + "}";
text = text.replace(temp, subs_[i]);
}
return "\n" + text;
}
private String formatMsg(ConceptItem rec_, EVSVocab vocab_, String msg_)
{
return rec_._longName + "::" + rec_._publicID + "::" + rec_._version + "::" + ((vocab_ == null) ? "" : vocab_._display) + "::" + rec_._preferredName + "::"
+ ((msg_.charAt(0) == '\n') ? msg_.substring(1) : msg_);
}
private String formatMaxMsg()
{
return "*** Maximum Messages ***::***::***::***::***::The Error Message maximum limit [" + _maxMsgs + "] has been reached, report truncated.";
}
private String formatTitleMsg()
{
return "Concept::Public ID::Version::Vocabulary::Concept Code::Message";
}
private static final String _MSG001 = "Mislabeled as a MetaThesaurus Concept.";
private static final String _MSG002 = "The caDSR definition source is missing and EVS has possible definitions.";
private static final String _MSG003 = "EVS has no definitions for this term and the caDSR contains definition text.";
private static final String _MSG004 = "No definitions exist in EVS and the caDSR contains a definition source [{0}].";
private static final String _MSG005 = "Definition Source [{0}] does not exist for this Concept.";
private static final String _MSG006 = "Definition matches source [{0}] but was expecting source to be [{1}]";
private static final String _MSG007 = "Definition matches unnamed source but was expecting source to be [{0}]";
private static final String _MSG008 = "Definition does not match EVS. [{0}]";
private static final String _MSG009 = "Definition and Source found for concept but Definition matches source [{0}] and expecting source [{1}]";
private static final String _MSG010 = "Name matches on property [{0}] but expected to match on property [{1}]";
private static final String _MSG011 = "Mislabeled, should be a MetaThesaurus Concept.";
private static final String _MSG012 = "The EVS definition source is missing, caDSR is [{0}].";
private static final String _MSG013 = "The caDSR definition source is missing, EVS is [{0}].";
private static final String _MSG014 = "The caDSR definition source [{0}] does not match EVS [{1}]";
private static final String _MSG015 = "No definitions exist in EVS for property [{0}] can not compare definitions.";
private static final String _MSG016 = "Definition does not match EVS.";
private static final String _MSG017 = "Definition does not match EVS [{0}].";
private static final String _MSG018 = "Concept name does not match EVS";
private static final String _MSG019 = "Concept name does not match EVS, expected [{0}].";
private static final String _MSG020 = "Missing EVS Source";
private static final String _MSG021 = "Unknown EVS Source [{0}]";
private static final String _MSG022 = "Missing Concept Code";
private static final String _MSG023 = "Invalid concept code.";
private static final String _MSG024 = "Invalid concept ID.";
private static final String _MSG025 = "Failed to retrieve EVS concept";
private static final String _MSG026 = "Missing Concept Long Name, recommend using [{0}]";
private static final int _maxMsgs = 200;
private static final Logger _logger = Logger.getLogger(AuditConceptToEVS.class.getName());
}
|
package io.druid.server;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.repackaged.com.google.common.base.Throwables;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.metamx.emitter.EmittingLogger;
import com.metamx.emitter.service.ServiceEmitter;
import com.metamx.emitter.service.ServiceMetricEvent;
import com.metamx.http.client.response.ClientResponse;
import com.metamx.http.client.response.HttpResponseHandler;
import io.druid.client.RoutingDruidClient;
import io.druid.guice.annotations.Json;
import io.druid.guice.annotations.Smile;
import io.druid.query.Query;
import io.druid.server.log.RequestLogger;
import io.druid.server.router.QueryHostFinder;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.joda.time.DateTime;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.UUID;
/**
* This class does async query processing and should be merged with QueryResource at some point
*/
@WebServlet(asyncSupported = true)
public class AsyncQueryForwardingServlet extends HttpServlet
{
private static final EmittingLogger log = new EmittingLogger(AsyncQueryForwardingServlet.class);
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final String DISPATCHED = "dispatched";
private static final Joiner COMMA_JOIN = Joiner.on(",");
private final ObjectMapper jsonMapper;
private final ObjectMapper smileMapper;
private final QueryHostFinder hostFinder;
private final RoutingDruidClient routingDruidClient;
private final ServiceEmitter emitter;
private final RequestLogger requestLogger;
public AsyncQueryForwardingServlet(
@Json ObjectMapper jsonMapper,
@Smile ObjectMapper smileMapper,
QueryHostFinder hostFinder,
RoutingDruidClient routingDruidClient,
ServiceEmitter emitter,
RequestLogger requestLogger
)
{
this.jsonMapper = jsonMapper;
this.smileMapper = smileMapper;
this.hostFinder = hostFinder;
this.routingDruidClient = routingDruidClient;
this.emitter = emitter;
this.requestLogger = requestLogger;
}
@Override
protected void doPost(
final HttpServletRequest req, final HttpServletResponse resp
) throws ServletException, IOException
{
final long start = System.currentTimeMillis();
Query query = null;
String queryId;
final boolean isSmile = "application/smile".equals(req.getContentType());
final ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;
OutputStream out = null;
try {
final AsyncContext ctx = req.startAsync(req, resp);
if (req.getAttribute(DISPATCHED) != null) {
return;
}
req.setAttribute(DISPATCHED, true);
query = objectMapper.readValue(req.getInputStream(), Query.class);
queryId = query.getId();
if (queryId == null) {
queryId = UUID.randomUUID().toString();
query = query.withId(queryId);
}
if (log.isDebugEnabled()) {
log.debug("Got query [%s]", query);
}
out = resp.getOutputStream();
final OutputStream outputStream = out;
final String host = hostFinder.getHost(query);
final Query theQuery = query;
final String theQueryId = queryId;
final HttpResponseHandler<OutputStream, OutputStream> responseHandler = new HttpResponseHandler<OutputStream, OutputStream>()
{
@Override
public ClientResponse<OutputStream> handleResponse(HttpResponse response)
{
resp.setStatus(response.getStatus().getCode());
resp.setContentType("application/x-javascript");
byte[] bytes = getContentBytes(response.getContent());
if (bytes.length > 0) {
try {
outputStream.write(bytes);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
return ClientResponse.finished(outputStream);
}
@Override
public ClientResponse<OutputStream> handleChunk(
ClientResponse<OutputStream> clientResponse, HttpChunk chunk
)
{
byte[] bytes = getContentBytes(chunk.getContent());
if (bytes.length > 0) {
try {
clientResponse.getObj().write(bytes);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
return clientResponse;
}
@Override
public ClientResponse<OutputStream> done(ClientResponse<OutputStream> clientResponse)
{
final long requestTime = System.currentTimeMillis() - start;
log.debug("Request time: %d", requestTime);
emitter.emit(
new ServiceMetricEvent.Builder()
.setUser2(theQuery.getDataSource().getName())
.setUser4(theQuery.getType())
.setUser5(COMMA_JOIN.join(theQuery.getIntervals()))
.setUser6(String.valueOf(theQuery.hasFilters()))
.setUser7(req.getRemoteAddr())
.setUser8(theQueryId)
.setUser9(theQuery.getDuration().toPeriod().toStandardMinutes().toString())
.build("request/time", requestTime)
);
final OutputStream obj = clientResponse.getObj();
try {
requestLogger.log(
new RequestLogLine(
new DateTime(),
req.getRemoteAddr(),
theQuery,
new QueryStats(ImmutableMap.<String, Object>of("request/time", requestTime, "success", true))
)
);
resp.flushBuffer();
outputStream.close();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
finally {
ctx.dispatch();
}
return ClientResponse.finished(obj);
}
private byte[] getContentBytes(ChannelBuffer content)
{
byte[] contentBytes = new byte[content.readableBytes()];
content.readBytes(contentBytes);
return contentBytes;
}
};
ctx.start(
new Runnable()
{
@Override
public void run()
{
routingDruidClient.run(makeUrl(host, req), theQuery, responseHandler);
}
}
);
}
catch (Exception e) {
if (!resp.isCommitted()) {
resp.setStatus(500);
resp.resetBuffer();
if (out == null) {
out = resp.getOutputStream();
}
out.write((e.getMessage() == null) ? "Exception null".getBytes(UTF8) : e.getMessage().getBytes(UTF8));
out.write("\n".getBytes(UTF8));
}
resp.flushBuffer();
try {
requestLogger.log(
new RequestLogLine(
new DateTime(),
req.getRemoteAddr(),
query,
new QueryStats(ImmutableMap.<String, Object>of("success", false, "exception", e.toString()))
)
);
}
catch (Exception e2) {
log.error(e2, "Unable to log query [%s]!", query);
}
log.makeAlert(e, "Exception handling request")
.addData("query", query)
.addData("peer", req.getRemoteAddr())
.emit();
}
}
private String makeUrl(String host, HttpServletRequest req)
{
String queryString = req.getQueryString();
if (queryString == null) {
return String.format("http://%s%s", host, req.getRequestURI());
}
return String.format("http://%s%s?%s", host, req.getRequestURI(), req.getQueryString());
}
}
|
package de.andreasgiemza.ubicomproject;
import java.util.Map.Entry;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.ui.IconGenerator;
import de.andreasgiemza.ubicomproject.gcm.GcmIntentService;
import de.andreasgiemza.ubicomproject.helpers.PositionsStorage;
import de.andreasgiemza.ubicomproject.helpers.PositionsStorage.Position;
import de.andreasgiemza.ubicomproject.helpers.Preferences;
import de.andreasgiemza.ubicomproject.location.LocationService;
public class MainActivity extends Activity {
private Preferences preferences;
private GoogleMap googleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
preferences = new Preferences(getApplicationContext());
if (!preferences.isRegistered()) {
startActivity(new Intent(getApplicationContext(),
RegisterActivity.class));
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create GoogleMap
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// show own position
googleMap.setMyLocationEnabled(true);
// start Service
startService(new Intent(getBaseContext(), LocationService.class));
// BroadcastReceiver
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(mMessageReceiver,
new IntentFilter(GcmIntentService.BROADCAST_ACTION));
drawFriends();
}
@Override
protected void onResume() {
super.onResume();
drawFriends();
}
private void drawFriends() {
googleMap.clear();
IconGenerator iconFactory = new IconGenerator(getApplicationContext());
for (Entry<String, Position> entry : PositionsStorage.INSTANCE.positions
.entrySet()) {
int elapsedSeconds = (int) ((System.currentTimeMillis() - entry
.getValue().time) / 1000);
if (elapsedSeconds < 60 * 60) {
MarkerOptions markerOptions = new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(iconFactory
.makeIcon(entry.getKey() + "\n"
+ elapsedSeconds + " seconds ago")))
.position(entry.getValue().latLng)
.anchor(iconFactory.getAnchorU(),
iconFactory.getAnchorV());
googleMap.addMarker(markerOptions);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(getApplicationContext())
.unregisterReceiver(mMessageReceiver);
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(android.content.Context context, Intent intent) {
drawFriends();
};
};
}
|
package de.danoeh.antennapod.activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.actionbarsherlock.app.SherlockActivity;
import de.danoeh.antennapod.R;
/** Displays the 'about' screen */
public class AboutActivity extends SherlockActivity {
private WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.about);
webview = (WebView) findViewById(R.id.webvAbout);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
webview.loadUrl("file:///android_asset/about.html");
}
}
|
package de.electricdynamite.pasty;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.ClipboardManager;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.webkit.URLUtil;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import de.electricdynamite.pasty.PastyLoader.PastyResponse;
public class ClipboardFragment extends SherlockListFragment implements LoaderCallbacks<PastyLoader.PastyResponse> {
private static final String TAG = ClipboardFragment.class.toString();
private LayoutInflater mInflater;
private Resources mRes;
private ClipboardItemListAdapter mAdapter;
private ArrayList<ClipboardItem> mItems;
private boolean mFirstRun = true;
private final Handler mHandler = new Handler();
private PastyClipboardFragmentListener activity;
public interface PastyClipboardFragmentListener {
void onPastyClipboardFragmentSignal(int signal);
void onPastyClipboardFragmentSignal(int signal, int dialogId);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// this is really important in order to save the state across screen
// configuration changes for example
setRetainInstance(true);
//LoaderManager.enableDebugLogging(true);
mRes = getResources();
mInflater = LayoutInflater.from(getSherlockActivity());
activity = (PastyClipboardFragmentListener) getSherlockActivity();
// you only need to instantiate these the first time your fragment is
// created; then, the method above will do the rest
if (mAdapter == null) {
mItems = new ArrayList<ClipboardItem>();
mAdapter = new ClipboardItemListAdapter(getSherlockActivity(), mItems);
}
getListView().setAdapter(mAdapter);
// call this to re-connect with an existing
// loader (after screen configuration changes for e.g!)
LoaderManager lm = getLoaderManager();
if (lm.getLoader(PastyLoader.TASK_CLIPBOARD_FETCH) != null) {
//Log.d(TAG, "onActivityCreated(): Loader already exists, reconnecting");
lm.initLoader(PastyLoader.TASK_CLIPBOARD_FETCH, null, this);
} else {
//Log.d(TAG, "onActivityCreated(): No PastyLoader found");
startLoading();
}
if(mFirstRun) {
startLoading();
mFirstRun = false;
}
}
protected void startLoading() {
//Log.d(TAG,"startLoading()");
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(Boolean.TRUE);
TextView mHelpTextBig = (TextView) getSherlockActivity().findViewById(R.id.tvHelpTextBig);
ProgressBar pbLoading = (ProgressBar) getSherlockActivity().findViewById(R.id.progressbar_downloading);
mHelpTextBig.setText(R.string.helptext_PastyActivity_loading);
pbLoading.setVisibility(View.VISIBLE);
mHelpTextBig = null;
pbLoading = null;
Bundle b = new Bundle();
// first time we call this loader, so we need to create a new one
getLoaderManager().initLoader(PastyLoader.TASK_CLIPBOARD_FETCH, b, this);
b = null;
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(Boolean.TRUE);
}
protected void restartLoading() {
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(Boolean.TRUE);
// call restart because we want the background work to be executed
// again
// Log.d(TAG, "restartLoading(): re-starting loader");
Bundle b = new Bundle();
// TODO Make sure this does not get called before startLoading was called, or NULL PE
getLoaderManager().restartLoader(PastyLoader.TASK_CLIPBOARD_FETCH, b, this);
b = null;
}
@Override
public Loader<PastyLoader.PastyResponse> onCreateLoader(int id, Bundle args) {
// Log.d(TAG, "onCreateLoader(): New PastyLoader created");
return new PastyLoader(getSherlockActivity(), id);
}
@Override
public void onLoadFinished(Loader<PastyLoader.PastyResponse> loader, PastyLoader.PastyResponse response) {
ProgressBar pbLoading = (ProgressBar) getSherlockActivity().findViewById(R.id.progressbar_downloading);
pbLoading.setVisibility(View.GONE);
pbLoading = null;
TextView mHelpTextBig = (TextView) getSherlockActivity().findViewById(R.id.tvHelpTextBig);
TextView mHelpTextSmall = (TextView) getSherlockActivity().findViewById(R.id.tvHelpTextSmall);
mHelpTextBig.setTextColor(getResources().getColor(R.color.abs__primary_text_holo_light));
mHelpTextBig.setBackgroundColor(getResources().getColor(R.color.abs__background_holo_light));
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(Boolean.FALSE);
if(response.hasException) {
// Log.d(TAG, "onLoadFinished(): Loader delivered exception; calling handleException()");
// an error occured
PastyException mException = response.getException();
handleException(mException);
} else {
switch(loader.getId()) {
case PastyLoader.TASK_CLIPBOARD_FETCH:
// Log.d(TAG, "Loader delivered TASK_CLIPBOARD_FETCH without exception");
JSONArray Clipboard = response.getClipboard();
mItems.clear();
mAdapter.notifyDataSetChanged();
getListView().invalidateViews();
try {
if(Clipboard.length() == 0) {
//Clipboard is empty
mHelpTextBig.setText(R.string.helptext_PastyActivity_clipboard_empty);
mHelpTextBig = null;
mHelpTextSmall.setText(R.string.helptext_PastyActivity_how_to_add);
mHelpTextSmall = null;
} else {
if(Clipboard.length() > 15) {
throw new Exception();
}
for (int i = 0; i < Clipboard.length(); i++) {
JSONObject Item = Clipboard.getJSONObject(i);
ClipboardItem cbItem = new ClipboardItem(Item.getString("_id"), Item.getString("item"));
this.mItems.add(cbItem);
}
mHelpTextBig.setText(R.string.helptext_PastyActivity_copy);
mHelpTextSmall.setText(R.string.helptext_PastyActivity_options);
mHelpTextBig = null;
mHelpTextSmall = null;
//Assign adapter to ListView
ListView listView = (ListView) getSherlockActivity().findViewById(R.id.listItems);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ClipboardItem Item = mItems.get(position); // get a ClipboardItem from the clicked position
if(Item.isLinkified()) {
String url = Item.getText();
if(!URLUtil.isValidUrl(url)) url = "http://"+url;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else {
/* Else we copy the item to the systems clipboard,
* show a Toast and finish() the activity
*/
ClipboardManager sysClipboard = (ClipboardManager) getSherlockActivity().getSystemService(Context.CLIPBOARD_SERVICE);
Item.copyToClipboard(sysClipboard);
Context context = getSherlockActivity().getApplicationContext();
CharSequence text = getString(R.string.item_copied);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
toast = null;
context = null;
sysClipboard = null;
text = null;
getSherlockActivity().finish();
}
}
});
registerForContextMenu(listView);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
}
@Override
public void onLoaderReset(Loader<PastyResponse> arg0) {
// TODO Auto-generated method stub
}
public class ClipboardItemListAdapter extends BaseAdapter {
// List of stored ClipboardItems
private List<ClipboardItem> itemList;
private Context context;
public ClipboardItemListAdapter(Context context, List<ClipboardItem> itemList) {
this.itemList = itemList;
this.context = context;
}
public int getCount() {
return itemList.size();
}
public ClipboardItem getItem(int position) {
return itemList.get(position);
}
public long getItemId(int position) {
return position;
}
public String getClipboardItemId(int position) {
return itemList.get(position).getId();
}
public void linkified(int position) {
this.itemList.get(position).linkfied();
}
public Boolean isLinkified(int position) {
return this.itemList.get(position).isLinkified();
}
public void remove(int position) {
this.itemList.remove(position);
this.notifyDataSetChanged();
}
public void removeAll() {
this.itemList.clear();
}
public void delete(int position) {
ClipboardItem mItem = getItem(position);
new ItemDeleteTask().execute(mItem);
remove(position); // TODO Implement some kind of callback to remove only upon successful deletion.
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Wrapper wrapper;
if (view == null) {
view = mInflater.inflate(R.layout.listitem, parent, false);
wrapper = new Wrapper(view);
view.setTag(wrapper);
} else {
wrapper = (Wrapper) view.getTag();
}
// get the item associated with this position
ClipboardItem Item = itemList.get(position);
// Select our text view from our view row
TextView tvListItem = (TextView) view.findViewById(R.id.myListitem);
tvListItem.setText(Item.getText());
/* Linkify/ListView / JB problem work around:
* 1. Linkify the item
* 2. If the item was linkified, write it into the ClipboardItem
* 3. Delete the MovementMethod
* 4. (in the onClick callback) check if the clicked ClipboardItem was linkified
* 5. (in the onClick callback) if it was, fire a manual ACTIEN_VIEW intent
* 6. ????
* 7. PROFIT!!!11 (and dirty, dirty code!)
* (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN)
*/
Boolean linkified = Linkify.addLinks(tvListItem, Linkify.WEB_URLS);
if(linkified) {
linkified(position); // Tell the ClipboardItem that it was linkified.
}
/* Delete the MovementMethod to prevent linkified items from firing an intent
* at onItemClick() or onItemLongClick()
*/
tvListItem.setMovementMethod(null);
linkified = null;
return view;
}
}
private class ItemDeleteTask extends AsyncTask<ClipboardItem, Void, PastyResponse > {
private Context context;
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
@Override
protected PastyResponse doInBackground(ClipboardItem... item) {
if(context == null) {
context = getSherlockActivity().getBaseContext();
}
PastyPreferencesProvider prefs = new PastyPreferencesProvider(context);
PastyClient client = new PastyClient(prefs.getRESTBaseURL(), true);
client.setUsername(prefs.getUsername());
client.setPassword(prefs.getPassword());
PastyResponse result;
try {
client.deleteItem(item[0]);
result = new PastyResponse();
} catch (PastyException e) {
result = new PastyResponse(e);
}
return result;
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(PastyResponse result) {
if(result.hasException) {
handleException(result.getException());
} else {
int duration = Toast.LENGTH_LONG;
CharSequence text = getString(R.string.item_deleted);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
toast = null;
context = null;
}
}
}
// use an wrapper (or view holder) object to limit calling the
// findViewById() method, which parses the entire structure of your
// XML in search for the ID of your view
private static class Wrapper {
private final View mRoot;
private TextView tvHelpTextBig;
private TextView tvHelpTextSmall;
private ProgressBar pbLoading;
public static final int VIEW_HELPTEXT_BIG = 0x1;
public static final int VIEW_HELPTEXT_SMALL = 0x2;
public static final int VIEW_PROGRESS_LOADING = 0x3;
public Wrapper(View root) {
mRoot = root;
}
public TextView getTextView(int tv) {
switch (tv) {
case VIEW_HELPTEXT_BIG:
if (tvHelpTextBig == null) {
tvHelpTextBig = (TextView) mRoot.findViewById(R.id.tvHelpTextBig);
}
return tvHelpTextBig;
case VIEW_HELPTEXT_SMALL:
if (tvHelpTextSmall == null) {
tvHelpTextSmall = (TextView) mRoot.findViewById(R.id.tvHelpTextSmall);
}
return tvHelpTextBig;
default:
return null;
}
}
public View getBar() {
if (pbLoading == null) {
pbLoading = (ProgressBar) mRoot.findViewById(R.id.progressbar_downloading);
}
return pbLoading;
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.listItems || v.getId() == R.id.myListimage) {
menu.setHeaderTitle(getString(R.string.itemContextMenuTitle));
String[] menuItems = getResources().getStringArray(R.array.itemContextMenu);
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
ClipboardItem Item = mItems.get(info.position);
switch (menuItemIndex) {
case PastySharedStatics.ITEM_CONTEXTMENU_COPY_ID:
// Copy without exit selected
ClipboardManager clipboard = (ClipboardManager) getSherlockActivity().getSystemService(Context.CLIPBOARD_SERVICE);
Item.copyToClipboard(clipboard);
Context context = getSherlockActivity().getApplicationContext();
CharSequence text = getString(R.string.item_copied);
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
toast = null;
context = null;
clipboard = null;
text = null;
break;
case PastySharedStatics.ITEM_CONTEXTMENU_SHARE_ID:
// Share to another app
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, Item.getText());
startActivity(Intent.createChooser(shareIntent, getString(R.string.app_share_from_pasty)));
break;
case PastySharedStatics.ITEM_CONTEXTMENU_DELETE_ID:
// Delete selected
mAdapter.delete(info.position);
break;
}
return true;
}
/** handles PastyExceptions within this Fragment
*/
protected void handleException(PastyException mException) {
TextView mHelpTextBig = (TextView) getSherlockActivity().findViewById(R.id.tvHelpTextBig);
TextView mHelpTextSmall = (TextView) getSherlockActivity().findViewById(R.id.tvHelpTextSmall);
switch(mException.errorId) {
case PastyException.ERROR_AUTHORIZATION_FAILED:
// Log.i(TAG, "ERROR_AUTHORIZATION_FAILED EXCEPTION");
mHelpTextBig.setTextColor(getResources().getColor(R.color.white));
mHelpTextBig.setBackgroundColor(getResources().getColor(R.color.red));
mHelpTextBig.setText(R.string.error_login_failed_title);
mHelpTextSmall.setText(R.string.error_login_failed);
return;
case PastyException.ERROR_IO_EXCEPTION:
// Log.i(TAG, "ERROR_IO_EXCEPTION");
mHelpTextBig.setTextColor(getResources().getColor(R.color.white));
mHelpTextBig.setBackgroundColor(getResources().getColor(R.color.red));
mHelpTextBig.setText(R.string.error_io_title);
mHelpTextSmall.setText(R.string.error_io);
case PastyException.ERROR_ILLEGAL_RESPONSE:
mHelpTextBig.setTextColor(getResources().getColor(R.color.white));
mHelpTextBig.setBackgroundColor(getResources().getColor(R.color.red));
mHelpTextBig.setText(R.string.error_badanswer_title);
mHelpTextSmall.setText(R.string.error_badanswer);
return;
case PastyException.ERROR_UNKNOWN:
mHelpTextBig.setTextColor(getResources().getColor(R.color.white));
mHelpTextBig.setBackgroundColor(getResources().getColor(R.color.red));
mHelpTextBig.setText(R.string.error_unknown_title);
mHelpTextSmall.setText(R.string.error_unknown);
Log.e(TAG,mException.getMessage());
return;
default:
break;
}
mHelpTextBig = null;
mHelpTextSmall = null;
}
/* public class LinkTextView extends TextView {
public LinkTextView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
TextView widget = (TextView) this;
Object text = widget.getText();
if (text instanceof Spanned) {
Spannable buffer = (Spannable) text;
int action = event.getAction();
if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off,
ClickableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget);
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
return true;
}
}
}
return false;
}
}*/
}
|
package edu.wustl.common.query.impl;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import edu.common.dynamicextensions.domaininterface.AssociationInterface;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.BooleanTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.DateTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.DoubleTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.domaininterface.IntegerTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.StringTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.databaseproperties.ConstraintKeyPropertiesInterface;
import edu.common.dynamicextensions.domaininterface.databaseproperties.ConstraintPropertiesInterface;
import edu.common.dynamicextensions.entitymanager.EntityManager;
import edu.common.dynamicextensions.util.global.Constants.InheritanceStrategy;
import edu.wustl.cab2b.server.category.CategoryOperations;
import edu.wustl.cab2b.server.queryengine.querybuilders.CategoryPreprocessor;
import edu.wustl.common.query.queryobject.impl.OutputTreeDataNode;
import edu.wustl.common.query.queryobject.util.InheritanceUtils;
import edu.wustl.common.query.queryobject.util.QueryObjectProcessor;
import edu.wustl.common.querysuite.exceptions.MultipleRootsException;
import edu.wustl.common.querysuite.exceptions.SqlException;
import edu.wustl.common.querysuite.factory.QueryObjectFactory;
import edu.wustl.common.querysuite.metadata.associations.IAssociation;
import edu.wustl.common.querysuite.metadata.associations.IIntraModelAssociation;
import edu.wustl.common.querysuite.metadata.category.Category;
import edu.wustl.common.querysuite.queryobject.ICondition;
import edu.wustl.common.querysuite.queryobject.IConnector;
import edu.wustl.common.querysuite.queryobject.IExpression;
import edu.wustl.common.querysuite.queryobject.IOutputTerm;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.querysuite.queryobject.IQueryEntity;
import edu.wustl.common.querysuite.queryobject.IRule;
import edu.wustl.common.querysuite.queryobject.LogicalOperator;
import edu.wustl.common.querysuite.queryobject.RelationalOperator;
import edu.wustl.common.querysuite.queryobject.TimeInterval;
import edu.wustl.common.querysuite.queryobject.impl.Expression;
import edu.wustl.common.querysuite.queryobject.impl.JoinGraph;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.global.Variables;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.metadata.util.DyExtnObjectCloner;
import edu.wustl.query.util.global.Constants;
import edu.wustl.query.util.global.Utility;
/**
* To generate SQL from the given Query Object.
*
* @author prafull_kadam
*
*/
public class SqlGenerator extends QueryGenerator
{
/**
* Default Constructor to instantiate SQL generator object.
*/
public SqlGenerator()
{
}
/**
* Generates SQL for the given Query Object.
*
* @param query The Reference to Query Object.
* @return the String representing SQL for the given Query object.
* @throws MultipleRootsException When there are multpile roots present in a
* graph.
* @throws SqlException When there is error in the passed IQuery object.
* @see edu.wustl.common.querysuite.queryengine.ISqlGenerator#generateSQL(edu.wustl.common.querysuite.queryobject.IQuery)
*/
public String generateQuery(IQuery query) throws MultipleRootsException, SqlException,
RuntimeException
{
Logger.out.debug("Srarted SqlGenerator.generateSQL().....");
String sql = buildQuery(query);
Logger.out.debug("Finished SqlGenerator.generateSQL()...SQL:" + sql);
return sql;
}
/**
* Changes made for adding new rule in expression which do not have rule
* provided that expression contains Activity status attribute.
*
* @param expressionId Root Expression Id
*/
private void addactivityStatusToEmptExpr(int expressionId)
{
Expression expression = (Expression) constraints.getExpression(expressionId);
List<IExpression> operandList = joinGraph.getChildrenList(expression);
for (IExpression subExpression : operandList)
{
// TODO check this code.
// if (subExpression.isSubExpressionOperand()) {
addactivityStatusToEmptExpr(subExpression.getExpressionId());
}
if (!expression.containsRule())
{
if (getActivityStatusAttribute(expression.getQueryEntity().getDynamicExtensionsEntity()) != null)
{
IRule rule = QueryObjectFactory.createRule();
IConnector<LogicalOperator> logicalConnector = QueryObjectFactory
.createLogicalConnector(LogicalOperator.And);
expression.addOperand(0, rule, logicalConnector);
}
}
}
/**
* To initialize map the variables. & build the SQL for the Given Query
* Object.
*
* @param query the IQuery reference.
* @return The Root Expetssion of the IQuery.
* @throws MultipleRootsException When there exists multiple roots in
* joingraph.
* @throws SqlException When there is error in the passed IQuery object.
*/
String buildQuery(IQuery query) throws MultipleRootsException, SqlException, RuntimeException
{
IQuery queryClone = new DyExtnObjectCloner().clone(query);
// IQuery queryClone = query;
constraints = queryClone.getConstraints();
QueryObjectProcessor.replaceMultipleParents(constraints);
processExpressionsWithCategories(queryClone);
this.joinGraph = (JoinGraph) constraints.getJoinGraph();
IExpression rootExpression = constraints.getRootExpression();
// Initializin map variables.
aliasNameMap = new HashMap<String, String>();
createAliasAppenderMap();
addactivityStatusToEmptExpr(rootExpression.getExpressionId());
// Identifying empty Expressions.
checkForEmptyExpression(rootExpression.getExpressionId());
//pAndExpressions = new HashSet<IExpression>();
// Generating output tree.
createTree();
// Creating SQL.
String wherePart = getCompleteWherePart(rootExpression);
String fromPart = getFromPartSQL(rootExpression, null, new HashSet<Integer>());
StringBuilder selectPart = new StringBuilder(getSelectPart());
// SRINATH
if (selectPart.length() > 0)
{
selectPart.append(Constants.QUERY_COMMA);
}
selectPart.append(getSelectForOutputTerms(queryClone.getOutputTerms()));
Utility.removeLastComma(selectPart);
String sql = selectPart + " " + fromPart + " " + wherePart;
log(sql);
return sql;
}
private void log(String sql)
{
// TODO format.
try
{
new SQLLogger().log(sql);
}
catch (IOException e)
{
Logger.out.error("Error while logging sql.\n" + e);
}
}
/**
* Returns complete where part //including PAND conditions.
*
* @param rootExpression
* @return
* @throws SqlException
*/
private String getCompleteWherePart(IExpression rootExpression) throws SqlException,
RuntimeException
{
String wherePart = buildWherePart(rootExpression, null);
// Adding extra where condition for PAND to check activity status value
// as disabled or null
StringBuffer extraWherePAnd = new StringBuffer();
//Set<Integer> expressionIDs = new HashSet<Integer>(); // set to hold
// values of
// aliasAppender,
// so that
// duplicate
// condition
// should not
// get added in
// Query.
/*for (IExpression expression : pAndExpressions)
{
if (expressionIDs.add(aliasAppenderMap.get(expression)))
{
AttributeInterface attributeObj = getActivityStatusAttribute(expression
.getQueryEntity().getDynamicExtensionsEntity());
if (attributeObj != null)
{
// creating activityStatus is null condition, this is
// required in case of Pseudo-Anded expressions.
ICondition condition = QueryObjectFactory.createCondition(attributeObj,
RelationalOperator.IsNull, null);
extraWherePAnd.append('(').append(processOperator(condition, expression)).append(" OR ");
// creating activityStatus != disabled condition.
condition = createActivityStatusCondition(attributeObj);
extraWherePAnd.append(processOperator(condition, expression));
extraWherePAnd.append(')').append(LogicalOperator.And).append(' ');
}
}
// expression.getQueryEntity()
}*/
wherePart = Constants.WHERE + extraWherePAnd.toString() + wherePart;
return wherePart;
}
/**
* Creates condition ActivitiStatus!='disabled'
*
* @param attributeObj
* @return
*/
private ICondition createActivityStatusCondition(AttributeInterface attributeObj)
{
List<String> values = new ArrayList<String>();
values.add(Constants.ACTIVITY_STATUS_DISABLED);
ICondition condition = QueryObjectFactory.createCondition(attributeObj,
RelationalOperator.NotEquals, values);
return condition;
}
/**
* To handle Expressions constrained on Categories. If Query contains an
* Expression having Constraint Entity as Category, then that Expression is
* expanded in such a way that it will look as if it is constrained on
* Classes without changing Query criteria.
*
* @throws SqlException if there is any error in processing category.
*/
private void processExpressionsWithCategories(IQuery query) throws SqlException
{
if (containsCategrory())
{
Connection connection = null;
try
{
EntityInterface rootEntity = null;
EntityInterface rootDEEntity = constraints.getRootExpression().getQueryEntity()
.getDynamicExtensionsEntity();
boolean isCategory = edu.wustl.cab2b.common.util.Utility.isCategory(rootDEEntity);
// This is temporary work around, This connection parameter will
// be reomoved in future.
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:/catissuecore");
connection = dataSource.getConnection();
/**
* if the root entity itself is category, then get the root
* entity of the category & pass it to the processCategory()
* method.
*/
if (isCategory)
{
Category category = new CategoryOperations().getCategoryByEntityId(rootDEEntity
.getId(), connection);
rootEntity = EntityManager.getInstance().getEntityByIdentifier(
category.getRootClass().getDeEntityId());
}
else
{
rootEntity = rootDEEntity;
}
new CategoryPreprocessor().processCategories(query);
}
catch (Exception e)
{
Logger.out.error(e.getMessage(), e);
throw new SqlException("Error in preprocessing category!!!!", e);
}
finally
{
if (connection != null) // Closing connection.
{
try
{
connection.close();
}
catch (SQLException e)
{
Logger.out.error(e.getMessage(), e);
throw new SqlException(
"Error in closing connection while preprocessing category!!!!", e);
}
}
}
}
}
/**
* To check whether there is any Expression having Constraint Entity as
* category or not.
*
* @return true if there is any constraint put on category.
*/
private boolean containsCategrory()
{
Set<IQueryEntity> constraintEntities = constraints.getQueryEntities();
for (IQueryEntity entity : constraintEntities)
{
boolean isCategory = edu.wustl.cab2b.common.util.Utility.isCategory(entity
.getDynamicExtensionsEntity());
if (isCategory)
{
return true;
}
}
return false;
}
/**
* To get the select part of the SQL.
*
* @return The SQL for the select part of the query.
*/
private String getSelectPart()
{
// columnMapList = new
// ArrayList<Map<Long,Map<AttributeInterface,String>>>();
StringBuilder selectAttribute = new StringBuilder();
for (OutputTreeDataNode rootOutputTreeNode : rootOutputTreeNodeList)
{
selectAttribute.append(getSelectAttributes(rootOutputTreeNode));
}
//Deepti : added quick fix for bug 6950. Add distinct only when columns do not include CLOB type.
if (containsCLOBTypeColumn)
{
selectAttribute.insert(0, Constants.SELECT);
}
else
{
selectAttribute.insert(0, Constants.SELECT_DISTINCT);
}
Utility.removeLastComma(selectAttribute);
return selectAttribute.toString();
}
/**
* To get the From clause of the Query.
*
* @param expression The Root Expression.
* @param leftAlias the String representing alias of left table. This will
* be alias of table represented by Parent Expression. Will be
* null for the Root Expression.
* @param processedAlias The set of aliases processed.
* @return the From clause of the SQL.
* @throws SqlException When there is problem in creating from part. problem
* can be like: no primary key found in entity for join.
*/
private String getFromPartSQL(IExpression expression, String leftAlias, Set<Integer> processedAlias)
throws SqlException
{
StringBuffer buffer = new StringBuffer();
if (processedAlias.isEmpty()) // this will be true only for root node.
{
EntityInterface leftEntity = expression.getQueryEntity().getDynamicExtensionsEntity();
leftAlias = getAliasName(expression);
buffer.append(Constants.FROM);
buffer.append(leftEntity.getTableProperties().getName());
buffer.append(Constants.SPACE).append(leftAlias);
createFromPartForDerivedEntity(expression, buffer);
}
Integer parentExpressionAliasAppender = aliasAppenderMap.get(expression);
processedAlias.add(parentExpressionAliasAppender);
// Processing children
buffer.append(processChildExpressions(leftAlias, processedAlias, expression));
return buffer.toString();
}
/**
* To create From path for the deirved entity.
*
* @param expression the reference to expression.
* @param buffer The buffer to which the Output will be appended.
* @throws SqlException
*/
private void createFromPartForDerivedEntity(IExpression expression, StringBuffer buffer)
throws SqlException
{
EntityInterface leftEntity = expression.getQueryEntity().getDynamicExtensionsEntity();
EntityInterface superClassEntity = leftEntity.getParentEntity();
// processing Parent class heirarchy.
if (superClassEntity != null)
{
EntityInterface theLeftEntity = leftEntity;
while (superClassEntity != null)
{
InheritanceStrategy inheritanceType = theLeftEntity.getInheritanceStrategy();
if (InheritanceStrategy.TABLE_PER_SUB_CLASS.equals(inheritanceType)) // only
// need
// handle
// this
// type
// inheritance
// here.
{
AttributeInterface primaryKey = getPrimaryKey(theLeftEntity);
String primaryKeyColumnName = primaryKey.getColumnProperties().getName();
String subClassAlias = getAliasFor(expression, theLeftEntity);
String superClassAlias = getAliasFor(expression, superClassEntity);
buffer.append(Constants.LEFT_JOIN);
buffer.append(superClassEntity.getTableProperties().getName());
buffer.append(' ').append(superClassAlias).append(Constants.ON);
String leftAttribute = subClassAlias + Constants.QUERY_DOT + primaryKeyColumnName;
String rightAttribute = superClassAlias + Constants.QUERY_DOT + primaryKeyColumnName;
buffer.append(Constants.QUERY_DOT).append(leftAttribute).append(Constants.QUERY_EQUALS).
append(rightAttribute).append(Constants.QUERY_CLOSING_PARENTHESIS);
}
theLeftEntity = superClassEntity;
superClassEntity = superClassEntity.getParentEntity();
}
}
}
/**
* To process all child expression of the given Expression & get their SQL
* representation for where part.
*
* @param leftAlias left table alias in join.
* @param processedAlias The list of precessed alias.
* @param parentExpressionId The reference to expression whose children to
* be processed.
* @return the left join sql for children expression.
* @throws SqlException when there is error in the passed IQuery object.
*/
private String processChildExpressions(String leftAlias, Set<Integer> processedAlias,
IExpression parentExpression) throws SqlException
{
StringBuffer buffer = new StringBuffer();
List<IExpression> children = joinGraph.getChildrenList(parentExpression);
if (!children.isEmpty())
{
// processing all outgoing edges/nodes from the current node in the
// joingraph.
for (IExpression childExpression : children)
{
// IExpression childExpression =
// constraints.getExpression(childExpressionId);
IAssociation association = joinGraph.getAssociation(parentExpression,
childExpression);
AssociationInterface actualEavAssociation = ((IIntraModelAssociation) association)
.getDynamicExtensionsAssociation();
AssociationInterface eavAssociation = actualEavAssociation;
EntityInterface rightEntity = eavAssociation.getTargetEntity();
String actualRightAlias = getAliasFor(childExpression, rightEntity);
String rightAlias = actualRightAlias;
if (!processedAlias.contains(aliasAppenderMap.get(childExpression)))
{
if (InheritanceUtils.getInstance().isInherited(eavAssociation))
{
eavAssociation = InheritanceUtils.getInstance().getActualAassociation(
eavAssociation);
rightEntity = eavAssociation.getTargetEntity();
leftAlias = getAliasFor(parentExpression, eavAssociation.getEntity());
rightAlias = getAliasFor(childExpression, eavAssociation.getTargetEntity());
}
else
{
leftAlias = getAliasFor(parentExpression, eavAssociation.getEntity());
}
EntityInterface childEntity = childExpression.getQueryEntity()
.getDynamicExtensionsEntity();
//EntityInterface leftEntity = eavAssociation.getEntity();
ConstraintPropertiesInterface constraintProperties = eavAssociation
.getConstraintProperties();
Collection<ConstraintKeyPropertiesInterface> srcCnstrKeyPropColl=constraintProperties.getSrcEntityConstraintKeyPropertiesCollection();
Collection<ConstraintKeyPropertiesInterface> tgtCnstrKeyPropColl=constraintProperties.getTgtEntityConstraintKeyPropertiesCollection();
AttributeInterface primaryKey;
String leftAttribute = null;
String rightAttribute = null;
if (!srcCnstrKeyPropColl.isEmpty() && !tgtCnstrKeyPropColl.isEmpty())// Many
// Many
// Case
{
String middleTableName = constraintProperties.getName();
String middleTableAlias = getAliasForMiddleTable(childExpression,
middleTableName);
for(ConstraintKeyPropertiesInterface cnstrKeyProp : srcCnstrKeyPropColl)
{
primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute();//getPrimaryKey(leftEntity);
leftAttribute = leftAlias + Constants.QUERY_DOT
+ primaryKey.getColumnProperties().getName();
rightAttribute = middleTableAlias + Constants.QUERY_DOT
+ cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName();
// Forming joing with middle table.
buffer.append(Constants.LEFT_JOIN).append(middleTableName).append(Constants.SPACE).append(middleTableAlias)
.append(Constants.ON);
buffer.append(Constants.QUERY_OPENING_PARENTHESIS).append(leftAttribute)
.append(Constants.QUERY_EQUALS).append(rightAttribute);
/*
* Adding descriminator column condition for the 1st
* parent node while forming FROM part left joins. This
* will be executed only once i.e. when only one node is
* processed.
*/
if (processedAlias.size() == 1)
{
buffer.append(getDescriminatorCondition(actualEavAssociation
.getEntity(), leftAlias));
}
buffer.append(Constants.QUERY_CLOSING_PARENTHESIS);
}
for(ConstraintKeyPropertiesInterface cnstrKeyProp : tgtCnstrKeyPropColl)
{
// Forming join with child table.
leftAttribute = middleTableAlias + Constants.QUERY_DOT
+ cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName();
primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute();//getPrimaryKey(rightEntity);
rightAttribute = rightAlias + Constants.QUERY_DOT
+ primaryKey.getColumnProperties().getName();
buffer.append(Constants.LEFT_JOIN).append(rightEntity.getTableProperties().getName())
.append(Constants.SPACE).append(rightAlias).append(Constants.ON);
buffer.append(Constants.QUERY_OPENING_PARENTHESIS).append(leftAttribute)
.append(Constants.QUERY_EQUALS).append(rightAttribute);
/*
* Adding descriminator column condition for the child
* node while forming FROM part left joins.
*/
buffer.append(getDescriminatorCondition(actualEavAssociation
.getTargetEntity(), rightAlias))
.append(Constants.QUERY_CLOSING_PARENTHESIS);
}
}
else
{
if (srcCnstrKeyPropColl.isEmpty())// Many
// Side
{
for(ConstraintKeyPropertiesInterface cnstrKeyProp : srcCnstrKeyPropColl)
{
leftAttribute = leftAlias + Constants.QUERY_DOT
+ cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName();
primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute();
rightAttribute = rightAlias + Constants.QUERY_DOT
+ primaryKey.getColumnProperties().getName();
}
}
else
// One Side
{
for(ConstraintKeyPropertiesInterface cnstrKeyProp : tgtCnstrKeyPropColl)
{
primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute();
leftAttribute = leftAlias + Constants.QUERY_DOT
+ primaryKey.getColumnProperties().getName();
rightAttribute = rightAlias + Constants.QUERY_DOT
+ cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName();
}
}
buffer.append(Constants.LEFT_JOIN).append(rightEntity.getTableProperties().getName())
.append(Constants.SPACE).append(rightAlias).append(Constants.ON);
buffer.append(Constants.QUERY_OPENING_PARENTHESIS).append(leftAttribute)
.append(Constants.QUERY_EQUALS).append(rightAttribute);
/*
* Adding descriminator column condition for the 1st
* parent node while forming FROM part left joins. This
* will be executed only once i.e. when only one node is
* processed.
*/
if (processedAlias.size() == 1)
{
buffer.append(getDescriminatorCondition(actualEavAssociation
.getEntity(), leftAlias));
}
/*
* Adding descriminator column condition for the child
* node while forming FROM part left joins.
*/
buffer.append(getDescriminatorCondition(actualEavAssociation
.getTargetEntity(), rightAlias))
.append(Constants.QUERY_CLOSING_PARENTHESIS);
}
buffer.append(getParentHeirarchy(childExpression, childEntity, rightEntity));
}
// append from part SQL for the next Expressions.
buffer.append(getFromPartSQL(childExpression, actualRightAlias, processedAlias));
}
}
return buffer.toString();
}
/**
* To get the SQL for the descriminator column condition for the given
* entity. It will return SQL for condition in format: " AND
* <DescriminatorColumnName> = '<DescriminatorColumnValue>'"
*
* @param entity The reference to the entity.
* @param aliasName The alias Name assigned to that entity table in the SQL.
* @return The String representing SQL for the descriminator column
* condition for the given entity, if inheritance strategy is
* TABLE_PER_HEIRARCHY. Returns empty String if there is no
* Descriminator column condition present for the Entity. i.e. when
* either of following is true: 1. when entity is not derived
* entity.(Parent entity is null) 2. Inheritance strategy is not
* TABLE_PER_HEIRARCHY.
*/
protected String getDescriminatorCondition(EntityInterface entity, String aliasName)
{
String sql = null;
EntityInterface parentEntity = entity.getParentEntity();
// Checking whether the entity is derived or not.
if (parentEntity != null)
{
InheritanceStrategy inheritanceType = entity.getInheritanceStrategy();
if (inheritanceType.equals(InheritanceStrategy.TABLE_PER_HEIRARCHY))
{
String columnName = entity.getDiscriminatorColumn();
String columnValue = entity.getDiscriminatorValue();
// Assuming Discrimanator is of type String.
String condition = aliasName + Constants.QUERY_DOT + columnName + Constants.QUERY_EQUALS + "'" + columnValue + "'";
sql = " " + LogicalOperator.And + " " + condition;
}
}
return sql;
}
/**
* To get the alias name for the Many to Many table.
*
* @param childExpression The child Expression of the association.
* @param middleTableName The Many to Mant table name.
* @return The String representing aliasName for the Many to Many table.
*/
private String getAliasForMiddleTable(IExpression childExpression, String middleTableName)
{
return getAliasForClassName(Constants.QUERY_DOT + middleTableName) + Constants.QUERY_UNDERSCORE
+ aliasAppenderMap.get(childExpression);
}
/**
* To add the Parent Heirarchy to the join part.
*
* @param childExpression The Expression to which the entity belongs.
* @param childEntity The entity whose parent heirarchy to be joined.
* @param alreadyAddedEntity The entity already added in join part.
* @return left join sql for childEntity.
* @throws SqlException when there is error in the passed IQuery object.
*/
private String getParentHeirarchy(IExpression childExpression, EntityInterface childEntity,
EntityInterface alreadyAddedEntity) throws SqlException
{
StringBuffer combinedJoinPart = new StringBuffer();
if (childEntity.getParentEntity() != null) // Joining Parent & child
// classes of the entity.
{
EntityInterface entity = childEntity;
EntityInterface parent = childEntity.getParentEntity();
boolean isReverse = false;
List<String> joinSqlList = new ArrayList<String>();
while (parent != null)
{
if (entity.equals(alreadyAddedEntity))
{
isReverse = true;
}
if (entity.getInheritanceStrategy().equals(InheritanceStrategy.TABLE_PER_SUB_CLASS))
{
String leftEntityalias = getAliasFor(childExpression, entity);
String rightEntityalias = getAliasFor(childExpression, parent);
AttributeInterface primaryKey = getPrimaryKey(entity);
String primaryKeyColumnName = primaryKey.getColumnProperties().getName();
String leftAttributeColumn = leftEntityalias + Constants.QUERY_DOT + primaryKeyColumnName;
String rightAttributeColumn = rightEntityalias + Constants.QUERY_DOT + primaryKeyColumnName;
String sql = null;
if (isReverse)
{
sql = Constants.INNER_JOIN + parent.getTableProperties().getName() + " "
+ rightEntityalias + Constants.ON;
sql += Constants.QUERY_OPENING_PARENTHESIS + leftAttributeColumn + Constants.QUERY_EQUALS + rightAttributeColumn + Constants.QUERY_CLOSING_PARENTHESIS;
}
else
{
sql = Constants.INNER_JOIN + entity.getTableProperties().getName() + " "
+ leftEntityalias + Constants.ON;
sql += Constants.QUERY_OPENING_PARENTHESIS + rightAttributeColumn + Constants.QUERY_EQUALS + leftAttributeColumn + Constants.QUERY_CLOSING_PARENTHESIS;
}
// joinSqlList.add(0, sql);
joinSqlList.add(sql);
}
entity = parent;
parent = parent.getParentEntity();
}
if (isReverse)
{
for (String joinSql : joinSqlList)
{
combinedJoinPart.append(joinSql);
}
}
else
{
for (String joinSql : joinSqlList)
{
combinedJoinPart.insert(0, joinSql);
}
}
}
return combinedJoinPart.toString();
}
/**
* To form the Pseudo-And condition for the expression.
*
* @param expression The child Expression reference.
* @param parentExpression The parent Expression.
* @param eavAssociation The association between parent & child expression.
* @return The Pseudo-And SQL condition.
* @throws SqlException When there is problem in creating from part. problem
* can be like: no primary key found in entity for join.
*/
protected String createPseudoAndCondition(IExpression expression, IExpression parentExpression,
AssociationInterface eavAssociation) throws SqlException
{
String pseudoAndSQL;
EntityInterface entity = expression.getQueryEntity().getDynamicExtensionsEntity();
String tableName = entity.getTableProperties().getName() + ' ';
String leftAlias = getAliasName(expression);
String selectAttribute = leftAlias + '.';
ConstraintPropertiesInterface constraintProperties = eavAssociation
.getConstraintProperties();
Collection<ConstraintKeyPropertiesInterface> srcCnstrKeyPopColl=constraintProperties.getSrcEntityConstraintKeyPropertiesCollection();
Collection<ConstraintKeyPropertiesInterface> tgtCnstrKeyPopColl=constraintProperties.getTgtEntityConstraintKeyPropertiesCollection();
if (!srcCnstrKeyPopColl.isEmpty() && !tgtCnstrKeyPopColl.isEmpty())// Many
// many
// case.
{
// This will start FROM part of SQL from the parent table.
selectAttribute = getAliasName(parentExpression)
+ '.'
+ getPrimaryKey(parentExpression.getQueryEntity().getDynamicExtensionsEntity())
.getColumnProperties().getName();
pseudoAndSQL = Constants.SELECT + selectAttribute;
Set<Integer> processedAlias = new HashSet<Integer>();
String fromPart = getFromPartSQL(parentExpression, leftAlias, processedAlias);
pseudoAndSQL += ' ' + fromPart + Constants.WHERE;
}
else
{
if (tgtCnstrKeyPopColl.isEmpty())
{
selectAttribute += getPrimaryKey(entity).getColumnProperties().getName();
}
else
{
selectAttribute += constraintProperties.getTgtEntityConstraintKeyProperties().getTgtForiegnKeyColumnProperties().getName();
}
pseudoAndSQL = Constants.SELECT + selectAttribute;
Set<Integer> processedAlias = new HashSet<Integer>();
processedAlias.add(aliasAppenderMap.get(expression));
String fromPart = getFromPartSQL(expression, leftAlias, processedAlias);
StringBuffer buffer = new StringBuffer();
buffer.append(Constants.FROM).append(tableName).append(' ').append(leftAlias);
createFromPartForDerivedEntity(expression, buffer);
buffer.append(fromPart).append(Constants.WHERE);
pseudoAndSQL += buffer.toString();
}
return pseudoAndSQL;
}
public void addActivityStatusCondition(IRule rule)
{
IExpression expression = rule.getContainingExpression();
AttributeInterface attributeObj = getActivityStatusAttribute(expression.getQueryEntity()
.getDynamicExtensionsEntity());
if (attributeObj != null)
{
ICondition condition = createActivityStatusCondition(attributeObj);
rule.addCondition(condition);
}
}
/**
* Check for activity status present in entity.
*
* @param entityInterfaceObj The Entity for which we required to check if
* activity status present.
* @return Reference to the AttributeInterface if activityStatus attribute
* present in the entity, else null.
*/
private AttributeInterface getActivityStatusAttribute(EntityInterface entityInterfaceObj)
{
Collection<AttributeInterface> attributes = entityInterfaceObj
.getEntityAttributesForQuery();
for (AttributeInterface attribute : attributes)
{
if (attribute.getName().equals(Constants.ACTIVITY_STATUS))
{
return attribute;
}
}
return null;
}
/**
* Get the query specific representation for Attribute ie the LHS of a condition.
*
* @param attribute The reference to AttributeInterface
* @param expression The reference to Expression to which this attribute
* belongs.
* @return The query specific representation for Attribute.
*/
protected String getConditionAttributeName(AttributeInterface attribute, IExpression expression)
{
AttributeInterface actualAttribute = attribute;
if (InheritanceUtils.getInstance().isInherited(attribute))
{
actualAttribute = InheritanceUtils.getInstance().getActualAttribute(attribute);
}
EntityInterface attributeEntity = actualAttribute.getEntity();
String aliasName = getAliasFor(expression, attributeEntity);
String attributeName = aliasName + Constants.QUERY_DOT
+ actualAttribute.getColumnProperties().getName();
return attributeName;
}
/**
* To Modify value as per the Data type. 1. In case of String datatype,
* replace occurence of single quote by singlequote twice. 2. Enclose the
* Given values by single Quotes for String & Date Data type. 3. For Boolean
* DataType it will change value to 1 if its TRUE, else 0.
*
* @param value the Modified value.
* @param dataType The DataType of the passed value.
* @return The String representing encoded value for the given value &
* datatype.
* @throws SqlException when there is problem with the values, for Ex.
* unable to parse date/integer/double etc.
*/
protected String modifyValueForDataType(String value, AttributeTypeInformationInterface dataType)
throws SqlException
{
if (dataType instanceof StringTypeInformationInterface)// for data type
// String it will be enclosed in single quote.
{
value = value.replaceAll("'", "''");
value = "'" + value + "'";
}
else if (dataType instanceof DateTypeInformationInterface) // for
// data type date it will be enclosed in single quote.
{
try
{
Date date = new Date();
date = Utility.parseDate(value);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
value = (calendar.get(Calendar.MONTH) + 1) + "-"
+ calendar.get(Calendar.DAY_OF_MONTH) + "-" + calendar.get(Calendar.YEAR);
String strToDateFunction = Variables.strTodateFunction;
if (strToDateFunction == null || strToDateFunction.trim().equals(""))
{
strToDateFunction = Constants.STR_TO_DATE; // using MySQL function
// if the Value is not
// defined.
}
String datePattern = Variables.datePattern;
if (datePattern == null || datePattern.trim().equals(""))
{
datePattern = "%m-%d-%Y"; // using MySQL function if the
// Value is not defined.
}
value = strToDateFunction + "('" + value + "','" + datePattern + "')";
}
catch (ParseException parseExp)
{
Logger.out.error(parseExp.getMessage(), parseExp);
throw new SqlException(parseExp.getMessage(), parseExp);
}
}
else if (dataType instanceof BooleanTypeInformationInterface) // defining
// value
// for
// boolean
// datatype.
{
if (value == null
|| !(value.equalsIgnoreCase(Constants.TRUE) || value
.equalsIgnoreCase(Constants.FALSE)))
{
throw new SqlException(
"Incorrect value found in value part for boolean operator!!!");
}
if (value.equalsIgnoreCase(Constants.TRUE))
{
value = "1";
}
else
{
value = "0";
}
}
else if (dataType instanceof IntegerTypeInformationInterface)
{
if (!new Validator().isNumeric(value))
{
throw new SqlException("Non numeric value found in value part!!!");
}
}
else if (dataType instanceof DoubleTypeInformationInterface)
{
if (!new Validator().isDouble(value))
{
throw new SqlException("Non numeric value found in value part!!!");
}
}
return value;
}
private String getSelectForOutputTerms(List<IOutputTerm> terms)
{
outputTermsColumns = new HashMap<String, IOutputTerm>();
StringBuilder s = new StringBuilder();
for (IOutputTerm term : terms)
{
String termString = Constants.QUERY_OPENING_PARENTHESIS + getTermString(term.getTerm()) + Constants.QUERY_CLOSING_PARENTHESIS;
termString = modifyForTimeInterval(termString, term.getTimeInterval());
String columnName = Constants.COLUMN_NAME + selectIndex++;
s.append(termString + " " + columnName + Constants.QUERY_COMMA);
outputTermsColumns.put(columnName, term);
}
Utility.removeLastComma(s);
return s.toString();
}
private String modifyForTimeInterval(String termString, TimeInterval<?> timeInterval)
{
if (timeInterval == null)
{
return termString;
}
termString = termString + "/" + timeInterval.numSeconds();
termString = "ROUND" + Constants.QUERY_OPENING_PARENTHESIS + termString + Constants.QUERY_CLOSING_PARENTHESIS;
return termString;
}
protected String getTemporalCondition(String operandquery)
{
return operandquery;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.