text:
package com.htc.dotbreaker;

import java.io.IOException;
import java.util.List;

import com.htc.dotbreaker.ui.CustomizedImage;
import com.htc.dotbreaker.utils.DotBreakerUtils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

public class GameActivity extends Activity implements SensorEventListener {
    final String LOG_TAG = "HtcDotBreaker";
    final String LOG_PREFIX = "[GameActivity] ";

    private static final String ANIMATION_LEVEL = "level_animation";
    private static final String ANIMATION_WIN = "win_animation";
    private static final String ANIMATION_LOSE = "lose_animation";
    private static final String ANIMATION_FINAL_WIN = "open_cover_animation";
    private static final String DOTMATRIX_PACKAGENAME = "com.htc.dotmatrix";
    private static final String DOTMATRIX_PACKAGENAME_ODM = "com.htc.dotmatrix_odm";

    private Resources mRes = null;
    float SLIDE_MIN_DISTANCE;

    RelativeLayout mLayout;
    View mView;

    View mTipsView;
    CustomizedImage mAnimationLevel = null;
    CustomizedImage mAnimationWin = null;
    CustomizedImage mAnimationLose = null;
    CustomizedImage mAnimationFinalWin = null;
    GameStartsLevelView mGameStartsLevelView;
    BrickView mBrickView;
    GameWinView mGameWinView;
    GameOverView mGameOverView;

    CountDownTimer mToGamePageTimer;

    static private SharedPreferences mSharedprefs = null;
    static private SharedPreferences.Editor mSharedprefs_editor = null;

    static float gravity_sensor[] = new float[3];
    static final int x = 0, y = 1, z = 2;
    static private SensorManager sSensorManager;
    static private Sensor sSensor;

    MediaPlayer mMediaPlayer;

    private static final String GAME_ID = "activityName";
    final static String ACTION_COVEROPEN = "com.htc.cover.closed";
    // true: cover open, false: cover close
    public static final String KEY_STATE = "state";
    // N pole for flip case, S pole for DotMatrix
    public static final String KEY_POLE_N = "north";

    BroadcastReceiver mCoverStateReceiver = new BroadcastReceiver() {
        boolean mFirstNear = false;

        @Override
        public void onReceive(Context context, Intent intent) {
            String szAction = intent.getAction();
            // false: Full HW cover, true: special HW, there is no UI
            boolean HWFullType = !(intent.getBooleanExtra(KEY_POLE_N, false));
            // false: cover is open true: cover is close
            boolean close = intent.getBooleanExtra(KEY_STATE, false);

            Log.i(LOG_TAG, "onReceive:" + szAction + " HWFULLTYPE:" + HWFullType + " close=" + close);

            if (HWFullType && close) {
                setMaxBright();
            } else {
                restoreBright();
            }

            if (ACTION_COVEROPEN == szAction) {
                if (close) {
                    mFirstNear = true;
                    // start game in full screen mode
                    getWindow().getDecorView().setSystemUiVisibility(getWindow().getDecorView().getSystemUiVisibility()
                                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
                    checkViewStatus();
                } else {
                    if (mFirstNear) {
                        stop_timer();
                        onBackPressed();
                        GameActivity.this.finish();
                        String toast_pause = mRes.getString(R.string.toast_pause);
                        Toast.makeText(GameActivity.this, toast_pause, Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    };

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && hasFocus && mTipsView == null) {
            getWindow().getDecorView().setSystemUiVisibility(
                    getWindow().getDecorView().getSystemUiVisibility()
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    void setMaxBright() {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL;
        getWindow().setAttributes(layoutParams);
    }

    void restoreBright() {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        getWindow().setAttributes(layoutParams);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mBrickView != null) {
            mBrickView.onBackPressed();
        } else if (mGameWinView != null) {
            hint_animation_stop();
            BrickView.hint_animation = false;
        } else if (mGameOverView != null) {
            hint_animation_stop();
            BrickView.hint_animation = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityList.getInstance().addActivity(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.brickbreakergame);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // keep screen on.

        WindowManager.LayoutParams window = getWindow().getAttributes(); // get window attributes
        window.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL; // set bright to Max
        getWindow().setAttributes(window); // set window attributes

        mRes = getResources();
        SLIDE_MIN_DISTANCE = mRes.getDimension(R.dimen.slide_min_distance);

        sSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sSensor = sSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sSensorManager.registerListener(this, sSensor, SensorManager.SENSOR_DELAY_NORMAL);

        mLayout = (RelativeLayout) findViewById(R.id.brickgame_view);
        mTipsView = getLayoutInflater().inflate(R.layout.tips, null);
        LayoutParams param = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        mLayout.addView(mTipsView, param);

        // start the tip animation
        ImageView iv = (ImageView) findViewById(R.id.animation);
        AnimationDrawable tipsAnimation = (AnimationDrawable) iv.getDrawable();
        tipsAnimation.start();

        mSharedprefs = getSharedPreferences("PREFS_MyStatus", 0);
        mSharedprefs_editor = mSharedprefs.edit();

        mDetector = new GestureDetector(getApplicationContext(), mGestureListener);

        mDotViewCommunity.bindDotViewService();

        IntentFilter intentFilter = new IntentFilter(ACTION_COVEROPEN);
        if (mCoverStateReceiver != null) {
            registerReceiver(mCoverStateReceiver, intentFilter);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        Window win = getWindow();
        WindowManager.LayoutParams params = win.getAttributes();
        params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;

        mDotViewCommunity.resume();
    }

    public boolean isTopActivity(String szAPKName) {
        String szTopActivity = null;
        boolean bRes = false;
        ActivityManager actManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> runningTasks = actManager.getRunningTasks(1);
        if (runningTasks != null && runningTasks.size() > 0) {
            ComponentName topActivity = runningTasks.get(0).topActivity;
            if (topActivity != null)
                szTopActivity = topActivity.getPackageName();
            else
                Log.e(LOG_TAG, "TopActivity is null");
        } else {
            Log.e(LOG_TAG, "TopActivity is 0 task");
        }

        if ((szAPKName != null) && (szTopActivity != null)) {
            bRes = (0 == szAPKName.compareTo(szTopActivity));
        }

        Log.d(LOG_TAG, "isTopActivity send: " + szAPKName + ", top: " + szTopActivity + ", match: " + bRes);
        return bRes;
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(LOG_TAG, "onPause, top: " + isTopActivity(getPackageName()));
        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            if (mMediaPlayer != null) {
                mMediaPlayer.release();
            }
        }
        mDotViewCommunity.pause();
    }

    @Override
    protected void onDestroy() {

        unregisterReceiver(mCoverStateReceiver);

        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            if (mMediaPlayer != null)
                mMediaPlayer.release();
        }
        mDotViewCommunity.doUnbindDotViewService();
        super.onDestroy();
    }

    static protected boolean preferencesGet(String key, boolean value) {
        return mSharedprefs.getBoolean(key, value);
    }

    static protected int preferencesGet(String key, int value) {
        return mSharedprefs.getInt(key, value);
    }

    static protected float preferencesGet(String key, float value) {
        return mSharedprefs.getFloat(key, value);
    }

    static protected void preferencesEditor(String key, boolean value) {
        mSharedprefs_editor.putBoolean(key, value);
    }

    static protected void preferencesEditor(String key, int value) {
        mSharedprefs_editor.putInt(key, value);
    }

    static protected void preferencesEditorApply() {
        mSharedprefs_editor.apply();
    }

    static protected void preferencesEditorCommit() {
        mSharedprefs_editor.commit();
    }

    private void stop_timer() {
        mToGamePageTimer.cancel();
        check_game_complete_timer.cancel();
        hint_animation_timer.cancel();
    }

    private void check_game_complete() {
        check_game_complete_timer.cancel();
        check_game_complete_timer.start();
    }

    CountDownTimer check_game_complete_timer = new CountDownTimer(1000, BrickView.ball_speed) {
        public void onTick(long millisUntilFinished) {
            if (BrickView.game_level_complete) {
                toGameWinPage();
            } else if (BrickView.game_over) {
                toGameOverPage();
            }
        }

        public void onFinish() {
            check_game_complete();
        }
    };

    private void checkViewStatus() {
        if (mTipsView != null) {
            toGameStartPage();
        } else if (mGameStartsLevelView != null) {
            toGameStartPage();
        } else if (mBrickView != null) {
            toGamePage();
        } else if (mGameWinView != null) {
            toGameWinPage();
        } else if (mGameOverView != null) {
            toGameOverPage();
        } else if (mAnimationFinalWin != null) {
            toGameWin_FinalWin();
        }
    }

    private void setGameLevelPreferencesStatus() {
        for (int level = 0; level < BrickView.MAX_GAME_LEVEL; ++level) {
            int gameStatus = mSharedprefs.getInt("GameStatus[" + level + "]", GameLevel.locked);
            if (gameStatus != GameLevel.locked) {
                GameActivity.preferencesEditor("GameStatus[" + level + "]", GameLevel.passed);
            } else {
                break;
            }
        }
        GameActivity.preferencesEditor("GameStatus[" + BrickView.brick_game_level + "]", GameLevel.ongoing);
        GameActivity.preferencesEditorApply();
    }

    private void toGameStartPage() {
        mLayout.removeAllViews();
        mTipsView = null;
        mGameStartsLevelView = new GameStartsLevelView(GameActivity.this);
        mBrickView = null;
        mAnimationWin = null;
        mGameWinView = null;
        mAnimationLose = null;
        mGameOverView = null;

        mAnimationLevel = new CustomizedImage(this);
        if (mAnimationLevel != null && mRes != null) {
            mAnimationLevel.setLayoutParams(getRelativeLayoutParams());
            try {
                mAnimationLevel.setDotMatrixList(DotBreakerUtils.readPNGtoAnimation(this, true, ANIMATION_LEVEL, 66, 48, 27), false, 1500);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mGameStartsLevelView = new GameStartsLevelView(GameActivity.this);
        mLayout.addView(mAnimationLevel);
        mLayout.addView(mGameStartsLevelView);

        new CountDownTimer(1000, 1000) {
            public void onTick(long millisUntilFinished) {}

            public void onFinish() {
                if (mGameStartsLevelView != null) {
                    mGameStartsLevelView.updateLevelNum(false);
                }
            }
        }.start();

        mToGamePageTimer = new CountDownTimer(3000, 3000) {
            public void onTick(long millisUntilFinished) {}

            public void onFinish() {
                toGamePage();
            }
        }.start();

        setGameLevelPreferencesStatus();
    }

    private void toGamePage() {
        mLayout.removeAllViews();
        mAnimationLevel = null;
        mTipsView = null;
        mGameStartsLevelView = null;
        mAnimationWin = null;
        mGameWinView = null;
        mAnimationLose = null;
        mGameOverView = null;

        if (mBrickView == null)
        	mBrickView = new BrickView(GameActivity.this);
        mLayout.addView(mBrickView);
        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            if (BrickView.brick_game_level <= 5)
                mMediaPlayer = MediaPlayer.create(this, R.raw.gameplay_loop_1_5);
            else if (BrickView.brick_game_level <= 10)
                mMediaPlayer = MediaPlayer.create(this, R.raw.gameplay_loop_6_10);
            else if (BrickView.brick_game_level <= 16)
                mMediaPlayer = MediaPlayer.create(this, R.raw.gameplay_loop_11_16);
            else if (BrickView.brick_game_level <= 19)
                mMediaPlayer = MediaPlayer.create(this, R.raw.gameplay_loop_17_19);
            else
                mMediaPlayer = MediaPlayer.create(this, R.raw.gameplay_loop_20);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
        check_game_complete();
    }

    private void toGameWin_FinalWin() {
        mLayout.removeAllViews();
        mTipsView = null;
        mGameStartsLevelView = null;
        mBrickView = null;
        mAnimationWin = null;
        mGameWinView = null;
        mAnimationLose = null;
        mGameOverView = null;
        mAnimationFinalWin = new CustomizedImage(this);
        if (mAnimationFinalWin != null && mRes != null) {
            mAnimationFinalWin.setLayoutParams(getRelativeLayoutParams());
            try {
                mAnimationFinalWin.setDotMatrixList(DotBreakerUtils.readPNGtoAnimation(this, true, ANIMATION_FINAL_WIN, 31, 48, 27), true, 2000);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mLayout.addView(mAnimationFinalWin);
        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            mMediaPlayer.release();
            mMediaPlayer = MediaPlayer.create(this, R.raw.gamewin_loop);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
    }

    private void toGameWinPage() {
        if (mBrickView != null) {
            GameActivity.preferencesEditor("Current_GameState", false);
            GameActivity.preferencesEditor("BricksHit", GameActivity.preferencesGet("BricksHit", 0) + mBrickView.mBricksHit);
            GameActivity.preferencesEditor("PlayTime", GameActivity.preferencesGet("PlayTime", 0) + mBrickView.tmp_playTime);
            GameActivity.preferencesEditor("LevelPass", GameActivity.preferencesGet("LevelPass", 0) + 1);
            GameActivity.preferencesEditor("BallTravelled", GameActivity.preferencesGet("BallTravelled", 0) + mBrickView.ball_travelled);
            GameActivity.preferencesEditorApply();
        }

        mLayout.removeAllViews();
        mTipsView = null;
        mGameStartsLevelView = null;
        check_game_complete_timer.cancel();
        mBrickView = null;
        mAnimationLose = null;
        mGameOverView = null;

        mAnimationWin = new CustomizedImage(this);
        if (mAnimationWin != null && mRes != null) {
            mAnimationWin.setLayoutParams(getRelativeLayoutParams());
            try {
                mAnimationWin.setDotMatrixList(DotBreakerUtils.readPNGtoAnimation(this, true, ANIMATION_WIN, 30, 48, 27), true, 5000);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mGameWinView = new GameWinView(GameActivity.this);
        mLayout.addView(mAnimationWin);
        mLayout.addView(mGameWinView);
        BrickView.game_level_complete = false;
        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            mMediaPlayer.release();
            mMediaPlayer = MediaPlayer.create(this, R.raw.gamewin_loop);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
	}

	private void toGameOverPage() {
        if (mBrickView != null) {
            GameActivity.preferencesEditor("Current_GameState", false);
            if (mBrickView.score != null)
                preferencesEditor("BestScore", Math.max(mBrickView.score.mNumeric, preferencesGet("BestScore", 0)));
            GameActivity.preferencesEditor("BricksHit", GameActivity.preferencesGet("BricksHit", 0) + mBrickView.mBricksHit);
            GameActivity.preferencesEditor("PlayTime", GameActivity.preferencesGet("PlayTime", 0) + mBrickView.tmp_playTime);
            GameActivity.preferencesEditor("Deaths", GameActivity.preferencesGet("Deaths", 0) + 1);
            GameActivity.preferencesEditor("BallTravelled", GameActivity.preferencesGet("BallTravelled", 0) + mBrickView.ball_travelled);
            GameActivity.preferencesEditorApply();
        }

        BrickView.keep_score = BrickView.KEEP_SCORE_INIT;
        mLayout.removeAllViews();
        mTipsView = null;
        mGameStartsLevelView = null;
        check_game_complete_timer.cancel();
        mBrickView = null;
        mGameWinView = null;
        mAnimationWin = null;

        mAnimationLose = new CustomizedImage(this);
        if (mAnimationLose != null && mRes != null) {
            mAnimationLose.setLayoutParams(getRelativeLayoutParams());
            try {
                mAnimationLose.setDotMatrixList(DotBreakerUtils.readPNGtoAnimation(this, true, ANIMATION_LOSE, 30, 48, 27), true, 5000);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mGameOverView = new GameOverView(GameActivity.this);
        mLayout.addView(mAnimationLose);
        mLayout.addView(mGameOverView);
        BrickView.game_over = false;
        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            mMediaPlayer.release();
            mMediaPlayer = MediaPlayer.create(this, R.raw.gameover_loop);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
    }

    private void nextLevel() {
        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            mMediaPlayer.release();
        }
        toGameStartPage();
    }

    private void restartLevel() {
        if (mSharedprefs.getBoolean(Settings.sMUSIC, true)) {
            mMediaPlayer.release();
        }
        toGameStartPage();
    }

    private GestureDetector mDetector;

    private SimpleOnGestureListener mGestureListener = new SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            float X = e.getX();
            float Y = e.getY();
            Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onSingleTapUp, e.x = " + X + ", e.y = " + Y);

            if (mTipsView != null) {
                Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onSingleTapUp  in View: drawView");
            } else if (mGameStartsLevelView != null) {
                Log.d(GameLevel.LOG_TAG, LOG_PREFIX
                        + "mGestureListener.onSingleTapUp  in View: gameStartsLevelView");
            } else if (mBrickView != null) {
                Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onSingleTapUp  in View: brickView");
                if (!mBrickView.mBall_alive) {
                    mBrickView.toStartGame();
                } else if (mBrickView.game_pause && X > BrickView.MARK_PAUSE_LOC_X
                        && X < BrickView.MARK_PAUSE_LOC_X + 5 * BrickView.BLOCK_WIDTH
                        && Y > BrickView.MARK_PAUSE_LOC_Y
                        && Y < BrickView.MARK_PAUSE_LOC_Y + 5 * BrickView.BLOCK_WIDTH
                        && BrickView.hint_animation == false) {
                    hint_animation_show(mBrickView);
                }
            } else if (mGameWinView != null) {
                Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onSingleTapUp  in View: gameWinView");
                if (X > mGameWinView.WORD_NEXT_LOC_X
                        && X < mGameWinView.WORD_NEXT_LOC_X + 15 * BrickView.BLOCK_WIDTH
                        && Y > mGameWinView.WORD_NEXT_LOC_Y
                        && Y < mGameWinView.WORD_NEXT_LOC_Y + 5 * BrickView.BLOCK_WIDTH
                        && BrickView.hint_animation == false) {
                    if (preferencesGet("CongratulationMessage", false)) { // Final Win
                        // Show open case animation
                        toGameWin_FinalWin();
                    } else {
                        hint_animation_show(mGameWinView);
                    }
                }
            } else if (mGameOverView != null) {
                Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onSingleTapUp  in View: gameOverView");
                if (X > mGameOverView.WORD_RESTART_LOC_X
                        && X < mGameOverView.WORD_RESTART_LOC_X + 27 * BrickView.BLOCK_WIDTH
                        && Y > mGameOverView.WORD_RESTART_LOC_Y
                        && Y < mGameOverView.WORD_RESTART_LOC_Y + 5 * BrickView.BLOCK_WIDTH
                        && BrickView.hint_animation == false) {
                    hint_animation_show(mGameOverView);
                }
            }
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float Y1 = e1.getY();
            float Y2 = e2.getY();
            if (Y2 >= Y1 && (Y2 - Y1) > SLIDE_MIN_DISTANCE) { // swipe_down
                if (mTipsView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_down  in View: drawView");
                } else if (mGameStartsLevelView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_down  in View: gameStartsLevelView");
                } else if (mBrickView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_down  in View: brickView");
                    if (mBrickView.game_pause) {
                        mBrickView.toExitBrick();
                    } else
                        mBrickView.toGamePause();
                } else if (mGameWinView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_down  in View: gameWinView");
                    if (preferencesGet("CongratulationMessage", false)) { // Final Win
                        preferencesEditor("CongratulationMessage", false);
                        preferencesEditorApply();
                    }
                    hint_animation_stop();
                    BrickView.hint_animation = false;
                    ActivityList.getInstance().exit(); // Exit APP, delete all Activity.
                } else if (mGameOverView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_down  in View: gameOverView");
                    hint_animation_stop();
                    BrickView.hint_animation = false;
                    ActivityList.getInstance().exit(); // Exit APP, delete all Activity.
                }
            } else if (Y2 < Y1 && (Y1 - Y2) > SLIDE_MIN_DISTANCE) { // swipe_up
                if (mTipsView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_up  in View: drawView");
                } else if (mGameStartsLevelView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_up  in View: gameStartsLevelView");
                } else if (mBrickView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_up  in View: brickView");
                    if (mBrickView.game_pause) {
                        mBrickView.toGameResume();
                    } else {
                        mBrickView.toStartGame();
                    }
                } else if (mGameWinView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_up  in View: gameWinView");
                    if (preferencesGet("CongratulationMessage", false)) { // Final Win
                        // Show open case animation
                        toGameWin_FinalWin();
                    } else {
                        hint_animation_stop();
                        BrickView.hint_animation = false;
                        nextLevel();
                    }
                } else if (mGameOverView != null) {
                    Log.d(LOG_TAG, LOG_PREFIX + "mGestureListener.onFling.swipe_up  in View: gameOverView");
                    hint_animation_stop();
                    BrickView.hint_animation = false;
                    mGameOverView.invalidate();
                    restartLevel();
                }
            }
			return true;
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    private void hint_animation_show(View view) {
        BrickView.hint_animation = true;
        BrickView.hint_animation_number = BrickView.HINT_ANIMATION.length - 1;
        hint_animation_stop();
        mView = view;
        hint_animation_timer.start();
    }

    private void hint_animation_stop() {
        mView = null;
        hint_animation_timer.cancel();
    }

    CountDownTimer hint_animation_timer = new CountDownTimer(2100, 200) {
        public void onTick(long millisUntilFinished) {
            ++BrickView.hint_animation_number;
            BrickView.hint_animation_number %= 10;
            mView.invalidate();
        }

        public void onFinish() {
            BrickView.hint_animation = false;
            mView.invalidate();
        }
    };

    final static String DOTVIEWACTION_STRING = "com.htc.intent.action.dotviewgameservice";
    static final String PERMISSION_DOTVIEW_GAME = "com.htc.permission.dotviewgame";

    static final int MSG_DOTVIEW_CLIENT_REGISTER = 1;
    static final int MSG_DOTVIEW_CLIENT_UNREGISTER = 2;
    static final int MSG_DOTVIEW_CLIENT_RESUME = 3;
    static final int MSG_DOTVIEW_CLIENT_PAUSE = 4;

    static final int MSG_DOTVIEW_SERVCER_REGISTER_SUCCESS = 101;
    static final int MSG_DOTVIEW_SERVER_REGISTER_FAIL = 102;
    static final int MSG_DOTVIEW_SERVER_REMOVECURRENTGAME = 105;
	static final int MSG_DOTVIEW_SERVER_RESUME_SUCCESSS = 106;
    static final int MSG_DOTVIEW_SERVER_RESUME_FAIL = 107;
    static final int MSG_DOTVIEW_SERVER_PAUSE_SUCCESSS = 108;
    static final int MSG_DOTVIEW_SERVER_PAUSE_FAIL = 109;
    static final int MSG_DOTVIEW_SERVER_DOTVIEW_LEAVE_GAME_MODE = 110;
    static final int MSG_DOTVIEW_SERVER_DOTVIEWVERSION = 111;

    DotViewCommunity mDotViewCommunity = new DotViewCommunity();
    int mDotViewVersion;

    public class DotViewCommunity {
        static final int MSG_SET_VALUE = 3;

        static final int MSG_INNER_RETRY_RESUME = 1;

        Messenger mService = null;
        boolean mIsBound = false;

        Messenger mMessenger = new Messenger(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.i(LOG_TAG, "handleMessage: " + msg.what);
                String szText;
                Bundle data;

                switch (msg.what) {
                    case MSG_DOTVIEW_SERVER_DOTVIEWVERSION:
                        mDotViewVersion = msg.arg1;
                        Log.i(LOG_TAG, "DotView ver:" + mDotViewVersion);
                        break;

                    case MSG_DOTVIEW_SERVER_RESUME_SUCCESSS:
                        Log.i(LOG_TAG, " resume succeed");
                        break;
                    case MSG_DOTVIEW_SERVER_RESUME_FAIL:
                    case MSG_DOTVIEW_SERVER_PAUSE_FAIL:
                    case MSG_DOTVIEW_SERVER_REGISTER_FAIL:
                        // Do retry?
                        szText = "DotView error:";
                        data = msg.getData();
                        if (data != null)
                            szText += data.getString("reason");

                        Log.i(LOG_TAG, "DotView Game Fail:" +szText);

                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        });

        Handler mInnerHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.i(LOG_TAG, "mInnerMessenger, msg.what: " + msg.what);
                switch (msg.what) {
                    case MSG_INNER_RETRY_RESUME:
                        if (mService != null) {
                            resume();
                        } else {
                            int retry = msg.arg1;
                            int delay = msg.arg2;
                            if (retry < 5) {
                                retry++;
                                delay += 100;

                                if (mInnerHandler.hasMessages(MSG_INNER_RETRY_RESUME)) {
                                    mInnerHandler.removeMessages(MSG_INNER_RETRY_RESUME);
                                }
                                mInnerHandler.sendMessageDelayed(Message.obtain(null, MSG_INNER_RETRY_RESUME, retry, delay), (long) delay);
                            }
                        }
                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        };

        DotViewSericeConnection mServiceConnect = new DotViewSericeConnection();

        class DotViewSericeConnection implements ServiceConnection {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.i(LOG_TAG, "onServiceConnected: " + name);
                mService = new Messenger(service);

                try {
                    Message msg = Message.obtain(null, MSG_DOTVIEW_CLIENT_REGISTER);
                    msg.replyTo = mMessenger;

                    Bundle data = new Bundle();
                    // data.putString(GAME_ID, getPackageName());
                    data.putString(GAME_ID, GameActivity.class.getName());

					Window win = getWindow();
                    WindowManager.LayoutParams params = win.getAttributes();
                    msg.arg1 = params.flags;

                    msg.setData(data);
                    mService.send(msg);

                    // msg = Message.obtain(null,MSG_DOTVIEWSERVER_SET_VALUE,
                    // this.hashCode(), 0);
                    // mService.send(msg);
                } catch (RemoteException e) {
                    Log.i(LOG_TAG, "send server fail:" + e, e);
                }

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i(LOG_TAG, "onServiceDisconnected:" + name);
                mService = null;
            }
        }

        public boolean resume() {
            boolean bRes = false;
            Log.i(LOG_TAG, "resume");

            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MSG_DOTVIEW_CLIENT_RESUME);
                    Bundle data = new Bundle();
                    // data.putString(GAME_ID, getPackageName());
                    data.putString(GAME_ID, GameActivity.class.getName());
                    msg.setData(data);
                    mService.send(msg);

                    bRes = true;
                } catch (RemoteException e) {
                    Log.i(LOG_TAG, "send server fail:" + e, e);
                }
            } else {
                if (mInnerHandler.hasMessages(MSG_INNER_RETRY_RESUME)) {
                    mInnerHandler.removeMessages(MSG_INNER_RETRY_RESUME);
                }
                int retry = 0;
                int delay = 100;
                mInnerHandler.sendMessageDelayed(Message.obtain(null, MSG_INNER_RETRY_RESUME, retry, delay), (long) delay);
            }
            return bRes;
        }

        public boolean pause() {
            boolean bRes = false;
            Log.i(LOG_TAG, "pause");

            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MSG_DOTVIEW_CLIENT_PAUSE);
                    Bundle data = new Bundle();
                    // data.putString(GAME_ID, getPackageName());
                    data.putString(GAME_ID, GameActivity.class.getName());
                    msg.setData(data);

                    mService.send(msg);
                    bRes = true;

                    if (mInnerHandler.hasMessages(MSG_INNER_RETRY_RESUME)) {
                        mInnerHandler.removeMessages(MSG_INNER_RETRY_RESUME);
                    }
                } catch (RemoteException e) {
                    Log.i(LOG_TAG, "send server fail:" + e, e);
                }
            }
            return bRes;
        }

        public boolean bindDotViewService() {
            boolean bRes = false;
            Log.i(LOG_TAG, "bindDotService: " + !mIsBound);

            if (!mIsBound) {
                mIsBound = true;
                Intent intent = new Intent(DOTVIEWACTION_STRING);
                if (DotBreakerUtils.isPackageExisted(DOTMATRIX_PACKAGENAME, GameActivity.this)) {
                    intent.setPackage(DOTMATRIX_PACKAGENAME);
                }
                else if(DotBreakerUtils.isPackageExisted(DOTMATRIX_PACKAGENAME_ODM, GameActivity.this)) {
                    intent.setPackage(DOTMATRIX_PACKAGENAME_ODM);
                }
                else {
                    Log.v(LOG_TAG, "DotView don't exist");
                    return bRes;
                }
                bRes = bindService(intent, mServiceConnect, BIND_AUTO_CREATE);
            }
            return bRes;
        }

        public void doUnbindDotViewService() {
            Log.i(LOG_TAG, "doUnbindDotViewService:" + mIsBound);
            if (mIsBound) {
                if (mService != null) {
                    try {
                        Message msg = Message.obtain(null, MSG_DOTVIEW_CLIENT_UNREGISTER);
                        Bundle data = new Bundle();
                        // data.putString(GAME_ID, getPackageName());
                        data.putString(GAME_ID, GameActivity.class.getName());
                        msg.setData(data);
                        // msg.replyTo = mMessenger;
                        mService.send(msg);
                    } catch (RemoteException e) {
                        Log.i(LOG_TAG, "send server2 fail:" + e, e);
                        // There is nothing special we need to do if the service
                        // has crashed.
                    }
                }

                // Detach our existing connection.
                unbindService(mServiceConnect);
                mIsBound = false;
            }
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        gravity_sensor[x] = event.values[0];
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
    }

    private RelativeLayout.LayoutParams getRelativeLayoutParams() {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                DotBreakerUtils.getDotViewInnerFrameWidth(mRes),
                DotBreakerUtils.getDotViewInnerFrameHeight(mRes));
        params.leftMargin = DotBreakerUtils.getDotViewInnerFrameMarginLeft(mRes);
        params.topMargin = DotBreakerUtils.getDotViewInnerFrameMarginTop(mRes);
        return params;
    }
}


text:
class ScriptsController < ApplicationController
  include Scripts::Filters

  before_action :authorize, :not_guest, :not_owner, :not_manager, :not_security
  before_action :set_title, except: [:destroy]
  before_action :set_script, only: [:show, :edit, :update, :destroy]
  before_action :set_server, only: [:show]
  before_action :check_if_can_edit, only: [:edit, :update, :destroy]

  def index
    @scripts = scripts.order(:id).page params[:page]
  end

  def show
    respond_to do |format|
      format.pdf { render_pdf @script }
      format.any :html, :json
    end
  end

  def new
    @script = Script.new language: params[:lang]
  end

  def edit
  end

  def create
    @script = Script.new script_params

    if @script.save
      redirect_to @script
    else
      render 'new', status: :unprocessable_entity
    end
  end

  def update
    if @script.update script_params
      redirect_to @script
    else
      render 'edit', status: :unprocessable_entity
    end
  end

  def destroy
    @script.destroy

    redirect_to scripts_url
  end

  private

    def set_script
      @script = Script.find params[:id]
    end

    def set_server
      @server = Server.default.take
    end

    def script_params
      params.require(:script).permit :name, :core, :attachment, :text, :change,
        :language, :database_id, :lock_version,
        libraries_attributes: [:id, :name, :options, :_destroy],
        maintainers_attributes: [:id, :user_id, :_destroy],
        descriptions_attributes: [:id, :name, :value, :_destroy],
        parameters_attributes: [:id, :name, :value, :_destroy],
        requires_attributes: [:id, :script_id, :_destroy],
        taggings_attributes: [:id, :tag_id, :_destroy]
    end

    def check_if_can_edit
      unless @script.can_be_edited_by? current_user
        redirect_to scripts_url, alert: t('messages.not_allowed')
      end
    end
end

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.4.4.18-5-6
description: Array.prototype.forEach - thisArg is function
includes: [runTestCase.js]
---*/

function testcase() {
  var res = false;
  var result;
  function callbackfn(val, idx, obj)
  {
    result = this.res;
  }

  function foo(){}
  foo.res = true;

  var arr = [1];
  arr.forEach(callbackfn,foo)
  if( result === true)
    return true;

 }
runTestCase(testcase);


text:
package utilities;
/****************************************************************************************************
* Project: ClubHub
* Author(s): A. Dicks-Stephen, B. Lamaa, J. Thiessen
* Student Number: 100563954, 100911472, 100898311
* Date: Feb 03, 2016
* Description: PostDao - prepares a database access object for the Post model
****************************************************************************************************/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Post;
import model.User;
import utilities.DatabaseAccess;

public class PostDao {
	private Connection connect = null;
	private Statement statement = null;
	private PreparedStatement preparedStatement = null;
	private ResultSet resultSet = null;

	public PostDao() {
		try {
			connect = DatabaseAccess.connectDataBase();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean isInDatabase(HttpServletRequest request, HttpServletResponse response) throws Exception {
	    try {
			String id = request.getParameter("id");
			statement = connect.createStatement();
			resultSet = statement.executeQuery("select * from ch_post where id = \"" + id + "\"");
			// if there result set is before the first item, there are entries
			// if it is not, there are not
			if (!resultSet.isBeforeFirst() ) {
				return false;
			} else {
				return true;
			}
	    } catch (Exception e) {
	    	throw e;
	    }
	}

	public void addToDatabase(HttpServletRequest request, HttpServletResponse response) throws Exception {
	    try {
			HttpSession session = request.getSession();

			statement = connect.createStatement();
			preparedStatement = connect.prepareStatement("insert into ch_post values (default, ?, ?, ?, ?, ?, ?, ?)");
			// columns are title, content, Userid, Posttypeid, Accessid, Categoryid
			// Parameters start with 1 because we are sending 'default' to the auto incrementing id
		    preparedStatement.setString(1, request.getParameter("blogTitle"));	// title
		    preparedStatement.setString(2, request.getParameter("blogContent")); // content
		    preparedStatement.setString(3, (String)session.getAttribute("loggedInUserID"));	// Userid
		    preparedStatement.setString(4, request.getParameter("pageType")); // Posttypeid
		    preparedStatement.setString(5, request.getParameter("accessLevel")); // Accessid
		    preparedStatement.setString(6, (request.getParameter("pageCategory") != null) ? request.getParameter("pageCategory"): "1"); // Categoryid)
		    preparedStatement.setString(7,  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		    preparedStatement.executeUpdate();
		    } catch (Exception e) {
		      throw e;
		    }
	}

	public void listAll(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		List<Post> posts = new ArrayList<Post>();
		  	try{
		  		statement = connect.createStatement();
			    resultSet = statement.executeQuery("SELECT post.title, post.content, post.Userid, post.id, post.Postdate, user.username, user.firstName, user.lastName, posttype.type, access.type, category.type "
				+ "FROM clubhub.ch_post post "
				+ "JOIN clubhub.ch_posttype posttype "
				+ "ON post.Posttypeid = posttype.id "
				+ "JOIN clubhub.ch_user user "
				+ "ON post.Userid = user.id "
				+ "JOIN clubhub.ch_access access "
				+ "ON post.Accessid = access.id "
				+ "JOIN clubhub.ch_category category "
				+ "ON post.Categoryid = category.id ");

			    while (resultSet.next()) {
			    	  Post post = new Post();
			    	  post.setTitle(resultSet.getString("title"));
			    	  post.setContent(resultSet.getString("content"));
			    	  post.setId(resultSet.getString("id"));
			    	  post.setUserid(resultSet.getString("Userid"));
			    	  post.setUserFirstName(resultSet.getString("user.firstName"));
			    	  post.setUserLastName(resultSet.getString("user.lastName"));
			    	  post.setPostType(resultSet.getString("posttype.type"));
			    	  post.setAccessLevel(resultSet.getString("access.type"));
			    	  post.setCategory(resultSet.getString("category.type"));
			    	  post.setPostDate(resultSet.getString("Postdate"));
			    	  post.setPostMatchUser(post.getUserid().equals((String)session.getAttribute("loggedInUserID")));

			    	  if(!(post.getAccessLevel().equals("Private") && post.isPostMatchUser() == false)) {
			    		  posts.add(post);
			    	  }
			    }
		    } catch (SQLException e) {
			      throw e;
			}
		  	request.setAttribute("posts", posts);
	}

	public void listAllBlogs(HttpServletRequest request) throws Exception {
		  List<Post> posts = new ArrayList<Post>();
		  boolean isLoggedIn = false;
		  HttpSession session = request.getSession();

		  if (session.getAttribute("isLoggedIn") != null) {
			  isLoggedIn = (((Boolean) session.getAttribute("isLoggedIn")).booleanValue());
		  }

		  	try{
		  		statement = connect.createStatement();
			    resultSet = statement.executeQuery("SELECT post.title, post.content, post.Userid, post.id, post.Postdate, user.username, user.firstName, user.lastName, posttype.type, access.type, category.type "
				+ "FROM clubhub.ch_post post "
				+ "JOIN clubhub.ch_posttype posttype "
				+ "ON post.Posttypeid = posttype.id "
				+ "JOIN clubhub.ch_user user "
				+ "ON post.Userid = user.id "
				+ "JOIN clubhub.ch_access access "
				+ "ON post.Accessid = access.id "
				+ "JOIN clubhub.ch_category category "
				+ "ON post.Categoryid = category.id "
				+ "WHERE posttype.id = 1 ORDER BY Postdate");			// Where post is blog

			    while (resultSet.next()) {
			    	  Post post = new Post();
			    	  post.setTitle(resultSet.getString("title"));
			    	  post.setContent(resultSet.getString("content"));
			    	  post.setId(resultSet.getString("id"));
			    	  post.setUserid(resultSet.getString("Userid"));
			    	  post.setUserFirstName(resultSet.getString("user.firstName"));
			    	  post.setUserLastName(resultSet.getString("user.lastName"));
			    	  post.setPostType(resultSet.getString("posttype.type"));
			    	  post.setAccessLevel(resultSet.getString("access.type"));
			    	  post.setCategory(resultSet.getString("category.type"));
			    	  post.setPostDate(resultSet.getString("Postdate"));
			    	  post.setPostMatchUser(post.getUserid().equals((String)session.getAttribute("loggedInUserID")));

			    	  if (post.getAccessLevel().equals("Public")) {
			    		  posts.add(post);
			    	  } else if (post.getAccessLevel().equals("Members") && ((isLoggedIn == true))){
			    		  posts.add(post);
			    	  } else if (post.getAccessLevel().equals("Private") && post.isPostMatchUser() == true) {
			    		  posts.add(post);
			    	  }

			    }
		    } catch (SQLException e) {
			      throw e;
			}
		  	request.setAttribute("blogs", posts);
	}

	public void listStatic(HttpServletRequest request) throws Exception {
		  List<Post> posts = new ArrayList<Post>();
		  boolean isLoggedIn = false;
		  HttpSession session = request.getSession();

		  if (session.getAttribute("isLoggedIn") != null) {
			  isLoggedIn = (((Boolean) session.getAttribute("isLoggedIn")).booleanValue());
		  }

		  	try{
		  		statement = connect.createStatement();
			    resultSet = statement.executeQuery("SELECT post.title, post.content, post.Userid, post.id, user.username, user.firstName, user.lastName, posttype.type, access.type, category.type "
				+ "FROM clubhub.ch_post post "
				+ "JOIN clubhub.ch_posttype posttype "
				+ "ON post.Posttypeid = posttype.id "
				+ "JOIN clubhub.ch_user user "
				+ "ON post.Userid = user.id "
				+ "JOIN clubhub.ch_access access "
				+ "ON post.Accessid = access.id "
				+ "JOIN clubhub.ch_category category "
				+ "ON post.Categoryid = category.id "
				+ "WHERE posttype.id = 2 AND NOT access.id = 3");			// Where post is Static Content, and not private

			    while (resultSet.next()) {
			    	  Post post = new Post();
			    	  post.setTitle(resultSet.getString("title"));
			    	  post.setContent(resultSet.getString("content"));
			    	  post.setId(resultSet.getString("id"));
			    	  post.setUserid(resultSet.getString("Userid"));
			    	  post.setUserFirstName(resultSet.getString("user.firstName"));
			    	  post.setUserLastName(resultSet.getString("user.lastName"));
			    	  post.setPostType(resultSet.getString("posttype.type"));
			    	  post.setAccessLevel(resultSet.getString("access.type"));
			    	  post.setCategory(resultSet.getString("category.type"));
			    	  post.setPostMatchUser(post.getUserid().equals((String)session.getAttribute("loggedInUserID")));

			    	  if (post.getAccessLevel().equals("Public")) {
			    		  posts.add(post);
			    	  } else if(post.getAccessLevel().equals("Members") && ((isLoggedIn == true))){
			    		  posts.add(post);
			    	  } else if(post.getAccessLevel().equals("Private") && post.isPostMatchUser() == true) {
			    			posts.add(post);
			    	  }

			    }
		    } catch (SQLException e) {
			      throw e;
			}
		  	request.setAttribute("posts", posts);
	}

	public void deletePost(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// if coming from batchDelte, attribute will be set. otherwise, parameter will be set
		String postID = (request.getAttribute("postID")) == null ? request.getParameter("postID") : (String) request.getAttribute("postID");

		  try {
			  statement = connect.createStatement();
			  statement.executeUpdate("delete from ch_post where id =" + postID);
			  System.out.println("delte postID = " + postID);
		  } catch (SQLException e) {
		      throw e;
		  }
	}

	public void batchDelete(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String [] markedForDeletion = request.getParameterValues("postSelected");
		for (String postID : markedForDeletion) {
			request.setAttribute("postID", postID);
			System.out.println("batchDelete postID: " + request.getAttribute("postID"));
			deletePost(request, response);
		}
	}

	public void findPost(HttpServletRequest request, String postID) throws Exception {
		  Post post = new Post();

		  	try{
			    statement = connect.createStatement();
			    resultSet = statement.executeQuery("SELECT post.title, post.content, post.id, post.Postdate, user.username, user.firstName, user.lastName, posttype.type, access.type, category.type "
				+ "FROM clubhub.ch_post post "
				+ "JOIN clubhub.ch_posttype posttype "
				+ "ON post.Posttypeid = posttype.id "
				+ "JOIN clubhub.ch_user user "
				+ "ON post.Userid = user.id "
				+ "JOIN clubhub.ch_access access "
				+ "ON post.Accessid = access.id "
				+ "JOIN clubhub.ch_category category "
				+ "ON post.Categoryid = category.id "
				+ "WHERE post.id = " + postID);

			    while (resultSet.next()) {
			    	  post.setTitle(resultSet.getString("title"));
			    	  post.setContent(resultSet.getString("content"));
			    	  post.setId(resultSet.getString("id"));
			    	  post.setUserFirstName(resultSet.getString("user.firstName"));
			    	  post.setUserLastName(resultSet.getString("user.lastName"));
			    	  post.setPostType(resultSet.getString("posttype.type"));
			    	  post.setAccessLevel(resultSet.getString("access.type"));
			    	  post.setCategory(resultSet.getString("category.type"));
			    	  post.setPostDate(resultSet.getString("Postdate"));

			    	  System.out.println("PostDate = " + post.getPostDate());
			    }
			} catch (SQLException e) {
			      throw e;
			}
		  	request.setAttribute("post", post);
		  	request.setAttribute("postTitle", post.getTitle());
	}

	public void editPost(HttpServletRequest request, HttpServletResponse response) throws Exception {

		try {
			String postID = request.getParameter("postID");
		    String title = request.getParameter("blogTitle");	// title
		    String content = request.getParameter("blogContent"); // content
		    String pageType = request.getParameter("pageType"); // Posttypeid
		    String accessLevel = (request.getParameter("accessLevel")!= null) ? request.getParameter("accessLevel"): "1"; // Accessid
		    String category = (request.getParameter("pageCategory") != null) ? request.getParameter("pageCategory"): "1"; // Categoryid

		    statement = connect.createStatement();
		    preparedStatement = connect.prepareStatement("UPDATE ch_post SET title = ?, content = ?, Posttypeid = ?, "
		    		+ "Accessid= ?, Categoryid= ?, Postdate= ? WHERE id='" + postID + "'");

		    preparedStatement.setString(1, title);
		    preparedStatement.setString(2, content);
		    preparedStatement.setString(3, pageType);
		    preparedStatement.setString(4, accessLevel);
		    preparedStatement.setString(5, category);
		    preparedStatement.setString(6,  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

		    preparedStatement.executeUpdate();

	    } catch (Exception e) {
	      throw e;
	    }
	}

	public void batchEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// this method edits the postType, accessLevel, and/or category in ch_post

		String [] markedForEdit = request.getParameterValues("postSelected");
		String postID, pageType, accessLevel, category, executeString = "";

		pageType = request.getParameter("pageType"); // Posttypeid
	    accessLevel = request.getParameter("accessLevel"); // Accessid
	    category = request.getParameter("pageCategory"); // Categoryid

	    if (!pageType.equals("0")) {
	    	executeString = "Posttypeid='" + pageType;
	    }
	    if (!accessLevel.equals("0") && !pageType.equals("0")) {
	    	executeString += "', Accessid='" + accessLevel;
	    } else if(!accessLevel.equals("0"))
	    {
	    	executeString = "Accessid='" + accessLevel;
	    }
	    if (!category.equals("0") && (!accessLevel.equals("0") || !pageType.equals("0"))) {
	    	executeString += "', Categoryid='" + category;
	    } else if(!category.equals("0"))
	    {
	    	executeString = "Categoryid='" + category;
	    }

	    if (!executeString.equals(""))
	    {
	    	System.out.println("executeString is not null. Here's pageType, accessLevel, pageCategory values: " + pageType + accessLevel + category);
	    	System.out.println("And here's executeString: " + executeString);
			for (String x : markedForEdit)
			{
				postID = x;
			    statement = connect.createStatement();
				statement.executeUpdate("UPDATE ch_post SET " + executeString + "' WHERE id='" + postID + "'");
			}
		}
	}

	public void getLastBlogs(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// this method returns the latest 3 blog posts (Posttypeid = 1) in ch_post
		// we do all the pagination coding here. first off, we pull in all viable blog posts and then reverse it to sort by newest.
		// we count the number of entries and how many 'pages' will be needed to display all entries.

		HttpSession session = request.getSession();
		listAllBlogs(request);

		int pageCnt = (session.getAttribute("pageCnt") == null) ? 0 : Integer.parseInt(session.getAttribute("pageCnt").toString());  // Page count, 0 if null
		int numOfPages = 0, ppp = 3;   // Posts Per Page. this can be changed, maybe in preferences even?
		double numOfRows = 0;
		String pageNav = (request.getAttribute("pageNav") == null ? "first" : request.getAttribute("pageNav").toString()) ;
		System.out.println(pageNav);
		List<Post> posts = new ArrayList<Post>();
		@SuppressWarnings("unchecked")
		List<Post> allBlogs = (List<Post>) request.getAttribute("blogs");
		Collections.reverse(allBlogs);  // after this line, we have all our blogs in reverse order as list items

		numOfRows = allBlogs.size();
		numOfPages = (int)Math.ceil(numOfRows/ppp); // number of pages needed is rounded up to the nearest whole number

		switch (pageNav) {
		case "first":
			posts = allBlogs.subList(0, ppp > (int)numOfRows ? (int)numOfRows : ppp); // select the first ppp(3) items, unless the ppp is smaller than the number of rows
			pageCnt = 1;
			break;
		case "previous":
			if (pageCnt > 1) {
				pageCnt--;
				posts = allBlogs.subList(pageCnt*ppp-ppp, pageCnt*ppp);
			} else {
				posts = allBlogs.subList(0, ppp > (int)numOfRows ? (int)numOfRows : ppp);
				pageCnt = 1;
			}
			break;
		case "next":
			if (pageCnt >= numOfPages-1) {
				pageCnt = numOfPages;
				posts = allBlogs.subList(((int)numOfRows - ppp) < 0 ? 0:(int)numOfRows - ppp, (int)numOfRows);
			} else {
				posts = allBlogs.subList(pageCnt*ppp, (pageCnt*ppp+ppp) > (int)numOfRows ? (int)numOfRows : pageCnt*ppp+ppp);
				pageCnt++;
			}
			break;
		case "last":
			pageCnt = numOfPages;
			posts = allBlogs.subList(((int)numOfRows - ppp) < 0 ? 0:(int)numOfRows - ppp, (int)numOfRows);
			break;
		}

		session.setAttribute("pageCnt", pageCnt);
		request.setAttribute("blogs", posts);
		request.removeAttribute("pageNav");

	}

	public void searchPosts(HttpServletRequest request, HttpServletResponse response) throws SQLException {

		List<Post> posts = new ArrayList<Post>();
		boolean isLoggedIn = false;
		String searchTerm = request.getParameter("searchTerm");
		System.out.println("searchTerm = " + searchTerm);

		HttpSession session = request.getSession();

		if (session.getAttribute("isLoggedIn") != null) {
			isLoggedIn = (((Boolean) session.getAttribute("isLoggedIn")).booleanValue());
		}

	  		try{
	  			statement = connect.createStatement();
			    resultSet = statement.executeQuery("SELECT post.title, post.content, post.Userid, post.id, post.Postdate, user.username, user.firstName, user.lastName, posttype.type, access.type, category.type "
				+ "FROM clubhub.ch_post post "
				+ "JOIN clubhub.ch_posttype posttype "
				+ "ON post.Posttypeid = posttype.id "
				+ "JOIN clubhub.ch_user user "
				+ "ON post.Userid = user.id "
				+ "JOIN clubhub.ch_access access "
				+ "ON post.Accessid = access.id "
				+ "JOIN clubhub.ch_category category "
				+ "ON post.Categoryid = category.id "
				+ "WHERE posttype.id = 1 AND content LIKE '%" + searchTerm + "%'");			// Where post is blog

			    while (resultSet.next()) {
			    	  Post post = new Post();
			    	  post.setTitle(resultSet.getString("title"));
			    	  post.setContent(resultSet.getString("content"));
			    	  post.setId(resultSet.getString("id"));
			    	  post.setUserid(resultSet.getString("Userid"));
			    	  post.setUserFirstName(resultSet.getString("user.firstName"));
			    	  post.setUserLastName(resultSet.getString("user.lastName"));
			    	  post.setPostType(resultSet.getString("posttype.type"));
			    	  post.setAccessLevel(resultSet.getString("access.type"));
			    	  post.setCategory(resultSet.getString("category.type"));
			    	  post.setPostDate(resultSet.getString("Postdate"));
			    	  post.setPostMatchUser(post.getUserid().equals((String)session.getAttribute("loggedInUserID")));

			    	  if (post.getAccessLevel().equals("Public")) {
			    		  posts.add(post);
			    	  } else if(post.getAccessLevel().equals("Members") && ((isLoggedIn == true))){
			    		  posts.add(post);
			    	  } else if(post.getAccessLevel().equals("Private") && post.isPostMatchUser() == true) {
			    			posts.add(post);
			    	  }

			    }
		    } catch (SQLException e) {
			      throw e;
			}
		  	request.setAttribute("blogs", posts);

	}
}


text:
package org.bds.lang;

import org.antlr.v4.runtime.tree.ParseTree;

/**
 * Expression '/='
 *
 * @author pcingola
 */
public class ExpressionAssignmentDiv extends ExpressionAssignmentBinary {

	public ExpressionAssignmentDiv(BdsNode parent, ParseTree tree) {
		super(parent, tree);
	}

	@Override
	protected ExpressionBinary createSubExpression() {
		return new ExpressionDivide(this, null);
	}

	@Override
	protected String op() {
		return "/=";
	}

}


text:
namespace Schemin.Tokenize
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	public class Tokenizer
	{
		public List<Token> Tokenize(string input)
		{
			List<Token> tokenList = new List<Token>();
			int currentPosition = 0;
			char[] chars = input.ToCharArray();

			// We use KeyValuePair as a simple tuple type here, containing the next token
			// as well as what position we should resume retrieving tokens from.

			KeyValuePair<Token, int> currentToken;
			while ((currentToken = GetNextToken(chars, currentPosition)).Key != null)
			{
				currentPosition = currentToken.Value;
				tokenList.Add(currentToken.Key);
			}

			return tokenList;
		}

		private KeyValuePair<Token, int> GetNextToken(char[] input, int position)
		{
			int i = position;

			// Skip whitespace
			while (i < input.Length && Whitespace(input[i])) i++;

			// Skip comments and whitespace again, since we can have whitespace after comments etc.
			if (i < input.Length)
			{
				while (i < input.Length && input[i] == ';')
				{
					while (i < input.Length && !Newline(input[i])) i++;
					i++;
					while (i < input.Length && Whitespace(input[i])) i++;
				}
			}

			// get the next token
			if (i < input.Length)
			{
				if (Numerical(input[i]))
					return NumberLiteral(input, i);

				switch(input[i])
				{
					case '#':
						return VectorOrBooleanOrChar(input, i);
					case '"':
						return StringLiteral(input, i);
					case '-':
					case '+':

						// only a number literal if the starting char is numerical, or if the starting char is a - or +
						// AND the next char is part of a number.
						if(i + 1 < input.Length && (Numerical(input[i + 1]) || input[i + 1] == '.'))
							return NumberLiteral(input, i);
						else
							return Symbol(input, i);
					case '\'':
					case '`':
					case ',':
						return QuoteSugar(input, i);
					case '(':
						return MakeTokenPair(TokenType.OpenParen, new String(input, i, 1), input, i, i + 1);
					case ')':
						return MakeTokenPair(TokenType.CloseParen, new String(input, i, 1), input, i, i + 1);
					case '.':
						return MakeTokenPair(TokenType.Dot, new String(input, i, 1), input, i, i + 1);
					default:
						return Symbol(input, i);
				}
			}
			else
			{
				// no more characters, return an empty KVP
				return new KeyValuePair<Token,int>(null, 0);
			}
		}

		// retrieve a string literal token and advance our position
		private KeyValuePair<Token, int> StringLiteral(char[] input, int position)
		{
			int originalPosition = position;
			position++;
			TokenType type = TokenType.StringLiteral;
			StringBuilder sb = new StringBuilder();
			int newPosition = position;
			bool matchingQuotes = false;
			while (newPosition < input.Length)
			{
				// if we get an escape, increment the position some more and map the escaped character to what it should be
				if (input[newPosition] == '\\')
				{
					newPosition++;
					sb.Append(MapEscaped(input[newPosition]));
					newPosition++;
					continue;
				}

				// unescaped quote? We're done with this string.
				if (input[newPosition] == '"')
				{
					newPosition++;
					matchingQuotes = true;
					break;
				}

				sb.Append(input[newPosition]);
				newPosition++;
			}

			// we didn't get opening and closing quotes :(
			if (!matchingQuotes)
			{
				throw new Exception("Tokenizing error: Unmatched quotes in string literal");
			}

			return MakeTokenPair(type, sb.ToString(), input, originalPosition, newPosition);
		}

		// retrieve a symbol token and advance our position
		private KeyValuePair<Token, int> Symbol(char[] input, int position)
		{
			int originalPosition = position;
			TokenType type = TokenType.Symbol;

			int newPosition = position;
			// as long as we don't hit whitespace or something that a symbol shouldn't have, assume it's a symbol
			while (newPosition < input.Length && !Whitespace(input[newPosition]) && SymbolPart(input[newPosition]))
			{
				newPosition++;
			}

			return MakeTokenPair(type, new String(input, position, newPosition - position), input, originalPosition, newPosition);
		}

		// retrieve a quoted sugar token (' ` , ,@) and advance our position
		private KeyValuePair<Token, int> QuoteSugar(char[] input, int position)
		{
			int originalPosition = position;
			TokenType type;

			switch (input[position])
			{
				case '\'':
					type = TokenType.Quote;
					break;
				case '`':
					type = TokenType.BackQuote;
					break;
				case ',':
					type = TokenType.Comma;
					break;
				default:
					throw new Exception("Parse error!");
			}
			int positionOffset = 1;
			if ((position + 1) < input.Length && input[position + 1] == '@')
			{
				type = TokenType.AtComma;
				positionOffset = 2;
			}

			return MakeTokenPair(type, new String(input, position, positionOffset), input, originalPosition, position + positionOffset);
		}

		// retrieve a number literal token (int or decimal) and advance our position
		private KeyValuePair<Token, int> NumberLiteral(char[] input, int position)
		{
			int originalPosition = position;
			TokenType type = TokenType.IntegerLiteral;

			int newPosition = position;
			while (newPosition < input.Length && !Whitespace(input[newPosition]) && NumericalPart(input[newPosition]))
			{
				// if we get a decimal we're no longer working with an integer
				if (input[newPosition] == '.')
					type = TokenType.DecimalLiteral;

				newPosition++;
			}

			return MakeTokenPair(type, new String(input, position, newPosition - position), input, originalPosition, newPosition);
		}

		// retrieve a vector literal marker, boolean token, or character literal token and advance our position
		private KeyValuePair<Token, int> VectorOrBooleanOrChar(char[] input, int position)
		{
			int originalPosition = position;
			List<char> boolLiterals = new List<char> { 'F', 'f', 't', 'T' };
			if (boolLiterals.Contains(input[position + 1]))
			{
				// boolean literal!
				return MakeTokenPair(TokenType.BoolLiteral, new String(input, position, 2), input, originalPosition, position + 2);
			}
			else if (input[position + 1] == '(')
			{
				// vector literal!
				return MakeTokenPair(TokenType.VectorLiteral, new String(input, position, 1), input, originalPosition, position + 1);
			}
			else if (input[position + 1] == '\\')
			{
				// char literal!
				StringBuilder sb = new StringBuilder();
				int newPosition = position;

				while (newPosition < input.Length && !Whitespace(input[newPosition]))
				{
					if (newPosition < position + 3)
					{
						sb.Append(input[newPosition]);
						newPosition++;
					}
					else
					{
						if (SymbolPart(input[newPosition]))
						{
							sb.Append(input[newPosition]);
							newPosition++;
						}
						else
						{
							break;
						}
					}
				}

				return MakeTokenPair(TokenType.CharLiteral, new String(input, position, newPosition - position), input, originalPosition, newPosition);
			}
			else
			{
				throw new Exception("Tokenizing error: Inside '#' but no matching characters to construct a token");
			}
		}

		private bool Numerical(char candidate)
		{
			return Char.IsNumber(candidate);
		}

		private bool NumericalPart(char candidate)
		{
			char[] signs = { '-', '+' };
			return candidate == '.' || Numerical(candidate) || signs.Contains(candidate);
		}

		private bool SymbolPart(char candidate)
		{
			char[] notAllowed = { '(', ')', '"', '\'', ',', '`' };
			return !notAllowed.Contains(candidate);
		}

		private bool Newline(char candidate)
		{
			return candidate == '\r' || candidate == '\n';
		}

		private bool Whitespace(char candidate)
		{
			if (Newline(candidate))
			{
				return true;
			}

			switch (candidate)
			{
				case '\t':
				case ' ':
					return true;
			}

			return false;
		}

		private char MapEscaped(char escaped)
		{
			switch (escaped)
			{
				case 't':
					return '\t';
				case 'n':
					return '\n';
				case 'r':
					return '\r';
			}

			return escaped;
		}

		private KeyValuePair<Token, int> MakeTokenPair(TokenType type, String tokenName, char[] input, int beginPosition, int endPosition)
		{
			Token currentToken = new Token(type, tokenName);
			currentToken.LineNumber = GetLineNumber(input, beginPosition);
			currentToken.ColNumber = GetColNumber(input, beginPosition);
			return new KeyValuePair<Token, int>(currentToken, endPosition);
		}

		private int GetColNumber(char[] input, int position)
		{
			int colNumber = 0;
			for (int i = 0; i < position; i++)
			{
				if (input[i] == '\n')
				{
					colNumber = 0;
				}

				colNumber++;
			}

			return colNumber;
		}

		private int GetLineNumber(char[] input, int position)
		{
			int line = 1;
			for (int i = 0; i < position; i++)
			{
				if (input[i] == '\n')
				{
					line++;
				}
			}

			return line;
		}
	}
}


text:
package com.adobe.acs.commons.twitter.impl;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jcr.Session;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.URLEntity;
import twitter4j.json.DataObjectFactory;

import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.Replicator;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.SearchResult;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;

@Component(immediate = true, label = "ACS AEM Commons - Twitter Feed Update Service",
    metatype = true, description = "Service to update Twitter Feed components.")
@Service
public final class TwitterFeedUpdaterImpl implements TwitterFeedUpdater {

    private static final Logger log = LoggerFactory.getLogger(TwitterFeedUpdaterImpl.class);

    @Reference
    private Replicator replicator;

    @Property(value = "acs-commons/components/content/twitter-feed", unbounded = PropertyUnbounded.ARRAY,
            label = "Twitter Feed component paths", description = "Component paths for Twitter Feed components.")
    private static final String TWITTER_COMPONENT_PATHS = "twitter.component.paths";

    private String[] twitterComponentPaths = null;

    protected void activate(ComponentContext ctx) {
        final Dictionary<?, ?> props = ctx.getProperties();

        twitterComponentPaths = PropertiesUtil.toStringArray(props.get(TWITTER_COMPONENT_PATHS));

    }

    @Override
    public void updateTwitterFeedComponents(ResourceResolver resourceResolver) {
        PageManager pageManager = resourceResolver.adaptTo(PageManager.class);

        List<Resource> twitterResources = findTwitterResources(resourceResolver);

        for (Resource twitterResource : twitterResources) {
            Page page = pageManager.getContainingPage(twitterResource);
            if (page != null) {
                Twitter client = page.adaptTo(Twitter.class);
                if (client != null) {
                    try {
                        ValueMap properties = twitterResource.getValueMap();
                        String username = properties.get("username", String.class);

                        if (!StringUtils.isEmpty(username)) {

                            log.info("Loading Twitter timeline for user {} for component {}.", username,
                                    twitterResource.getPath());

                            List<Status> statuses = client.getUserTimeline(username);

                            if (statuses != null) {
                                List<String> tweetsList = new ArrayList<String>(statuses.size());
                                List<String> jsonList = new ArrayList<String>(statuses.size());

                                for (Status status : statuses) {
                                    tweetsList.add(processTweet(status));
                                    jsonList.add(DataObjectFactory.getRawJSON(status));
                                }

                                if (tweetsList.size() > 0) {
                                    ModifiableValueMap map = twitterResource.adaptTo(ModifiableValueMap.class);
                                    map.put("tweets", tweetsList.toArray(new String[tweetsList.size()]));
                                    map.put("tweetsJson", jsonList.toArray(new String[jsonList.size()]));
                                    twitterResource.getResourceResolver().commit();

                                    handleReplication(pageManager, twitterResource);
                                }
                            }

                        }
                    } catch (PersistenceException e) {
                        log.error("Exception while updating twitter feed on resource:" + twitterResource.getPath(), e);
                    } catch (ReplicationException e) {
                        log.error("Exception while replicating twitter feed on resource:" + twitterResource.getPath(),
                                e);
                    } catch (TwitterException e) {
                        log.error("Exception while loading twitter feed on resource:" + twitterResource.getPath(),
                                e);
                    }
                }
            }

        }

    }

    private List<Resource> findTwitterResources(ResourceResolver resourceResolver) {
        List<Resource> twitterResources = new ArrayList<Resource>();

        Map<String, String> predicateMap = new HashMap<String, String>();
        predicateMap.put("path", "/content");
        predicateMap.put("property", "sling:resourceType");

        int i = 1;
        for (String path : twitterComponentPaths) {
            predicateMap.put("property." + (i++) + "_value", path.toString());

        }

        predicateMap.put("p.limit", "-1");

        QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class);
        Session session = resourceResolver.adaptTo(Session.class);
        Query query = queryBuilder.createQuery(PredicateGroup.create(predicateMap), session);

        SearchResult result = query.getResult();
        Iterator<Resource> resources = result.getResources();
        while (resources.hasNext()) {
            twitterResources.add(resources.next());
        }
        return twitterResources;
    }

    private String processTweet(Status status) {
        String tweet = status.getText();

        for (URLEntity entity : status.getURLEntities()) {
            String url = String.format("%s", entity.getURL(), entity.getURL());
            tweet = tweet.replace(entity.getURL(), url);
        }

        return tweet;

    }

    private void handleReplication(PageManager pageManager, Resource twitterResource) throws ReplicationException {
        if (isReplicationEnabled(twitterResource)) {
            Session session = twitterResource.getResourceResolver().adaptTo(Session.class);
            replicator.replicate(session, ReplicationActionType.ACTIVATE, twitterResource.getPath());
        }

    }

    private boolean isReplicationEnabled(Resource twitterResource) {
        ValueMap properties = twitterResource.getValueMap();
        return properties.get("replicate", false);
    }

}


text:
@interface BSDemoViewController : UIViewController

@end