answer stringlengths 17 10.2M |
|---|
package org.haxe.lime;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import dalvik.system.DexClassLoader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.Math;
import java.lang.Runnable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.List;
import org.haxe.extension.Extension;
import org.haxe.HXCPP;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.google.ads.*;
public class GameActivity extends Activity implements SensorEventListener {
private static final int DEVICE_ORIENTATION_UNKNOWN = 0;
private static final int DEVICE_ORIENTATION_PORTRAIT = 1;
private static final int DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 2;
private static final int DEVICE_ORIENTATION_LANDSCAPE_RIGHT = 3;
private static final int DEVICE_ORIENTATION_LANDSCAPE_LEFT = 4;
private static final int DEVICE_ORIENTATION_FACE_UP = 5;
private static final int DEVICE_ORIENTATION_FACE_DOWN = 6;
private static final int DEVICE_ROTATION_0 = 0;
private static final int DEVICE_ROTATION_90 = 1;
private static final int DEVICE_ROTATION_180 = 2;
private static final int DEVICE_ROTATION_270 = 3;
private static final String GLOBAL_PREF_FILE = "nmeAppPrefs";
private static float[] accelData = new float[3];
private static GameActivity activity;
private static AssetManager mAssets;
private static int bufferedDisplayOrientation = -1;
private static int bufferedNormalOrientation = -1;
private static Context mContext;
private static List<Extension> extensions;
private static float[] inclinationMatrix = new float[16];
private static HashMap<String, Class> mLoadedClasses = new HashMap<String, Class>();
private static float[] magnetData = new float[3];
private static DisplayMetrics metrics;
private static float[] orientData = new float[3];
private static float[] rotationMatrix = new float[16];
private static SensorManager sensorManager;
public Handler mHandler;
static RelativeLayout adLayout;
static RelativeLayout.LayoutParams adMobLayoutParams;
static AdView adView;
static Boolean adVisible = false, adInitialized = false, adTestMode = false;
private static MainView mMainView;
private MainView mView;
private Sound _sound;
protected void onCreate (Bundle state) {
super.onCreate (state);
activity = this;
mContext = this;
mHandler = new Handler ();
mAssets = getAssets ();
Extension.assetManager = mAssets;
Extension.callbackHandler = mHandler;
Extension.mainActivity = this;
Extension.mainContext = this;
_sound = new Sound (getApplication ());
//getResources().getAssets();
requestWindowFeature (Window.FEATURE_NO_TITLE);
::if WIN_FULLSCREEN::
getWindow ().addFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
::end::
metrics = new DisplayMetrics ();
getWindowManager ().getDefaultDisplay ().getMetrics (metrics);
// Pre-load these, so the C++ knows where to find them
//if (mMainView == null) {
Log.d ("lime", "mMainView is NULL");
::foreach ndlls::
System.loadLibrary ("::name::");::end::
HXCPP.run ("ApplicationMain");
//mMainView = new MainView (getApplication (), this);
/*} else {
ViewGroup parent = (ViewGroup)mMainView.getParent ();
if (parent != null) {
parent.removeView (mMainView);
}
mMainView.onResume ();
}
mView = mMainView;*/
FrameLayout rootLayout = new FrameLayout(this);
mView = new MainView(getApplication(), this);
adLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams adMobLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
rootLayout.addView(mView);
rootLayout.addView(adLayout, adMobLayoutParams);
setContentView(rootLayout);
sensorManager = (SensorManager)activity.getSystemService (Context.SENSOR_SERVICE);
if (sensorManager != null) {
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
}
if (extensions == null) {
extensions = new ArrayList<Extension>();
::if (ANDROID_EXTENSIONS != null)::::foreach ANDROID_EXTENSIONS::
extensions.add (new ::__current__:: ());::end::::end::
}
for (Extension extension : extensions) {
extension.onCreate (state);
}
}
static public void loadAd() {
AdRequest req = new AdRequest();
if(adTestMode) req.setTesting(true);
adView.loadAd(req);
}
static public void initAd(final String id, final int x, final int y, final int size, final boolean testMode) {
activity.runOnUiThread(new Runnable() {
public void run() {
String adID = id;
adTestMode = testMode;
if(size == 0) {
adView = new AdView(activity, AdSize.BANNER, adID);
}
else if(size == 1) {
adView = new AdView(activity, AdSize.SMART_BANNER, adID);
}
loadAd();
adMobLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if(x == 0) {
adMobLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
}
else if(x == -1) {
adMobLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
if(y == 0) {
adMobLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
}
else if(y == -1) {
adMobLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
}
adInitialized = true;
}
});
}
static public void showAd() {
activity.runOnUiThread(new Runnable() {
public void run() {
if (adInitialized && !adVisible) {
adLayout.removeAllViews();
adLayout.addView(adView, adMobLayoutParams);
adVisible = true;
}
}
});
}
static public void hideAd() {
activity.runOnUiThread(new Runnable() {
public void run() {
if (adInitialized && adVisible) {
adLayout.removeAllViews();
loadAd();
adVisible = false;
}
}
});
}
public static double CapabilitiesGetPixelAspectRatio () {
return metrics.xdpi / metrics.ydpi;
}
public static double CapabilitiesGetScreenDPI () {
return metrics.xdpi;
}
public static double CapabilitiesGetScreenResolutionX () {
return metrics.widthPixels;
}
public static double CapabilitiesGetScreenResolutionY () {
return metrics.heightPixels;
}
public static String CapabilitiesGetLanguage () {
return Locale.getDefault ().getLanguage ();
}
public static void clearUserPreference (String inId) {
SharedPreferences prefs = activity.getSharedPreferences (GLOBAL_PREF_FILE, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = prefs.edit ();
prefEditor.putString (inId, "");
prefEditor.commit ();
}
public void doPause () {
_sound.doPause ();
mView.sendActivity (Lime.DEACTIVATE);
mView.onPause ();
if (sensorManager != null) {
sensorManager.unregisterListener (this);
}
}
public void doResume () {
mView.onResume ();
_sound.doResume ();
mView.sendActivity (Lime.ACTIVATE);
if (sensorManager != null) {
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
}
}
public static AssetManager getAssetManager () {
return mAssets;
}
public static Context getContext () {
return mContext;
}
public static GameActivity getInstance () {
return activity;
}
public static MainView getMainView () {
return activity.mView;
}
public static byte[] getResource (String inResource) {
try {
InputStream inputStream = mAssets.open (inResource, AssetManager.ACCESS_BUFFER);
long length = inputStream.available ();
byte[] result = new byte[(int)length];
inputStream.read (result);
inputStream.close ();
return result;
} catch (IOException e) {
Log.e ("GameActivity", "getResource" + ":" + e.toString ());
}
return null;
}
public static int getResourceID (String inFilename) {
return -1;
}
static public String getSpecialDir (int inWhich) {
Log.v ("GameActivity", "Get special Dir " + inWhich);
File path = null;
switch (inWhich) {
case 0: // App
return mContext.getPackageCodePath ();
case 1: // Storage
path = mContext.getFilesDir ();
break;
case 2: // Desktop
path = Environment.getDataDirectory ();
break;
case 3: // Docs
path = Environment.getExternalStorageDirectory ();
break;
case 4: // User
path = mContext.getExternalFilesDir (Environment.DIRECTORY_DOWNLOADS);
break;
}
return path == null ? "" : path.getAbsolutePath ();
}
public static String getUserPreference (String inId) {
SharedPreferences prefs = activity.getSharedPreferences (GLOBAL_PREF_FILE, MODE_PRIVATE);
return prefs.getString (inId, "");
}
public static void launchBrowser (String inURL) {
Intent browserIntent = new Intent (Intent.ACTION_VIEW).setData (Uri.parse (inURL));
try {
activity.startActivity (browserIntent);
} catch (Exception e) {
Log.e ("GameActivity", e.toString ());
return;
}
}
private void loadNewSensorData (SensorEvent event) {
final int type = event.sensor.getType ();
if (type == Sensor.TYPE_ACCELEROMETER) {
accelData = event.values.clone ();
Lime.onAccelerate (-accelData[0], -accelData[1], accelData[2]);
}
if (type == Sensor.TYPE_MAGNETIC_FIELD) {
magnetData = event.values.clone ();
//Log.d("GameActivity","new mag: " + magnetData[0] + ", " + magnetData[1] + ", " + magnetData[2]);
}
}
@Override public void onAccuracyChanged (Sensor sensor, int accuracy) {
}
@Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {
for (Extension extension : extensions) {
if (!extension.onActivityResult (requestCode, resultCode, data)) {
return;
}
}
super.onActivityResult (requestCode, resultCode, data);
}
@Override protected void onDestroy () {
for (Extension extension : extensions) {
extension.onDestroy ();
}
// TODO: Wait for result?
mView.sendActivity (Lime.DESTROY);
activity = null;
super.onDestroy ();
}
@Override protected void onPause () {
doPause ();
super.onPause ();
for (Extension extension : extensions) {
extension.onPause ();
}
}
@Override protected void onRestart () {
super.onRestart ();
for (Extension extension : extensions) {
extension.onRestart ();
}
}
@Override protected void onResume () {
super.onResume();
doResume();
for (Extension extension : extensions) {
extension.onResume ();
}
}
@Override public void onSensorChanged (SensorEvent event) {
loadNewSensorData (event);
if (accelData != null && magnetData != null) {
boolean foundRotationMatrix = SensorManager.getRotationMatrix (rotationMatrix, inclinationMatrix, accelData, magnetData);
if (foundRotationMatrix) {
SensorManager.getOrientation (rotationMatrix, orientData);
Lime.onOrientationUpdate (orientData[0], orientData[1], orientData[2]);
}
}
Lime.onDeviceOrientationUpdate (prepareDeviceOrientation ());
Lime.onNormalOrientationFound (bufferedNormalOrientation);
}
@Override protected void onStart () {
super.onStart();
::if WIN_FULLSCREEN::::if (ANDROID_TARGET_SDK_VERSION >= 16)::
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
::end::::end::
for (Extension extension : extensions) {
extension.onStart ();
}
}
@Override protected void onStop () {
super.onStop ();
for (Extension extension : extensions) {
extension.onStop ();
}
}
public static void popView () {
activity.setContentView (activity.mView);
activity.doResume ();
}
public static void postUICallback (final long inHandle) {
activity.mHandler.post (new Runnable () {
@Override public void run () {
Lime.onCallback (inHandle);
}
});
}
private int prepareDeviceOrientation () {
int rawOrientation = getWindow ().getWindowManager ().getDefaultDisplay ().getOrientation ();
if (rawOrientation != bufferedDisplayOrientation) {
bufferedDisplayOrientation = rawOrientation;
}
int screenOrientation = getResources ().getConfiguration ().orientation;
int deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
if (bufferedNormalOrientation < 0) {
switch (screenOrientation) {
case Configuration.ORIENTATION_LANDSCAPE:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_180:
bufferedNormalOrientation = DEVICE_ORIENTATION_LANDSCAPE_LEFT;
break;
case DEVICE_ROTATION_90:
case DEVICE_ROTATION_270:
bufferedNormalOrientation = DEVICE_ORIENTATION_PORTRAIT;
break;
default:
bufferedNormalOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
case Configuration.ORIENTATION_PORTRAIT:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_180:
bufferedNormalOrientation = DEVICE_ORIENTATION_PORTRAIT;
break;
case DEVICE_ROTATION_90:
case DEVICE_ROTATION_270:
bufferedNormalOrientation = DEVICE_ORIENTATION_LANDSCAPE_LEFT;
break;
default:
bufferedNormalOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
default: // ORIENTATION_SQUARE OR ORIENTATION_UNDEFINED
bufferedNormalOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
}
switch (screenOrientation) {
case Configuration.ORIENTATION_LANDSCAPE:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_270:
deviceOrientation = DEVICE_ORIENTATION_LANDSCAPE_LEFT;
break;
case DEVICE_ROTATION_90:
case DEVICE_ROTATION_180:
deviceOrientation = DEVICE_ORIENTATION_LANDSCAPE_RIGHT;
break;
default: // impossible!
deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
case Configuration.ORIENTATION_PORTRAIT:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_90:
deviceOrientation = DEVICE_ORIENTATION_PORTRAIT;
break;
case DEVICE_ROTATION_180:
case DEVICE_ROTATION_270:
deviceOrientation = DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN;
break;
default: // impossible!
deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
default: // ORIENTATION_SQUARE OR ORIENTATION_UNDEFINED
deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
return deviceOrientation;
}
public static void pushView (View inView) {
activity.doPause ();
activity.setContentView (inView);
}
public void queueRunnable (Runnable runnable) {
Log.e ("GameActivity", "queueing...");
}
public static void registerExtension (Extension extension) {
if (extensions.indexOf (extension) == -1) {
extensions.add (extension);
}
}
public static void showKeyboard (boolean show) {
if (activity == null) {
return;
}
InputMethodManager mgr = (InputMethodManager)activity.getSystemService (Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow (activity.mView.getWindowToken (), 0);
if (show) {
mgr.toggleSoftInput (InputMethodManager.SHOW_FORCED, 0);
// On the Nexus One, SHOW_FORCED makes it impossible
// to manually dismiss the keyboard.
// On the Droid SHOW_IMPLICIT doesn't bring up the keyboard.
}
}
public static void setUserPreference (String inId, String inPreference) {
SharedPreferences prefs = activity.getSharedPreferences (GLOBAL_PREF_FILE, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = prefs.edit ();
prefEditor.putString (inId, inPreference);
prefEditor.commit ();
}
public static void vibrate (int period, int duration) {
Vibrator v = (Vibrator)activity.getSystemService (Context.VIBRATOR_SERVICE);
if (period == 0) {
v.vibrate (duration);
} else {
int periodMS = (int)Math.ceil (period / 2);
int count = (int)Math.ceil ((duration / period) * 2);
long[] pattern = new long[count];
for (int i = 0; i < count; i++) {
pattern[i] = periodMS;
}
v.vibrate (pattern, -1);
}
}
} |
package com.peel.react;
import android.support.annotation.Nullable;
import android.util.Base64;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.GuardedAsyncTask;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;
/**
* The NativeModule acting as an api layer for {@link TcpSocketManager}
*/
public final class TcpSockets extends ReactContextBaseJavaModule implements TcpSocketListener {
private static final String TAG = "TcpSockets";
private boolean mShuttingDown = false;
private TcpSocketManager socketManager;
private ReactContext mReactContext;
public TcpSockets(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
try {
socketManager = new TcpSocketManager(this);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String getName() {
return TAG;
}
@Override
public void initialize() {
mShuttingDown = false;
}
@Override
public void onCatalystInstanceDestroy() {
mShuttingDown = true;
try {
new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
socketManager.closeAllSockets();
}
}.execute().get();
} catch (InterruptedException ioe) {
FLog.e(TAG, "onCatalystInstanceDestroy", ioe);
} catch (ExecutionException ee) {
FLog.e(TAG, "onCatalystInstanceDestroy", ee);
}
}
private void sendEvent(String eventName, WritableMap params) {
mReactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
@ReactMethod
public void listen(final Integer cId, final String host, final Integer port) {
new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
try {
socketManager.listen(cId, host, port);
} catch (UnknownHostException uhe) {
FLog.e(TAG, "listen", uhe);
onError(cId, uhe.getMessage());
} catch (IOException ioe) {
FLog.e(TAG, "listen", ioe);
onError(cId, ioe.getMessage());
}
}
}.execute();
}
@ReactMethod
public void connect(final Integer cId, final @Nullable String host, final Integer port, final ReadableMap options) {
new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
// NOTE : ignoring options for now, just use the available interface.
try {
socketManager.connect(cId, host, port);
} catch (UnknownHostException uhe) {
FLog.e(TAG, "connect", uhe);
onError(cId, uhe.getMessage());
} catch (IOException ioe) {
FLog.e(TAG, "connect", ioe);
onError(cId, ioe.getMessage());
}
}
}.execute();
}
@ReactMethod
public void write(final Integer cId, final String base64String, final Callback callback) {
new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
socketManager.write(cId, Base64.decode(base64String, Base64.NO_WRAP));
if (callback != null) {
callback.invoke();
}
}
}.execute();
}
@ReactMethod
public void end(final Integer cId) {
new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
socketManager.close(cId);
}
}.execute();
}
@ReactMethod
public void destroy(final Integer cId) {
end(cId);
}
/** TcpSocketListener */
@Override
public void onConnection(Integer serverId, Integer clientId, InetSocketAddress socketAddress) {
if (mShuttingDown) {
return;
}
WritableMap eventParams = Arguments.createMap();
eventParams.putInt("id", serverId);
WritableMap infoParams = Arguments.createMap();
infoParams.putInt("id", clientId);
final InetAddress address = socketAddress.getAddress();
WritableMap addressParams = Arguments.createMap();
addressParams.putString("address", address.getHostAddress());
addressParams.putInt("port", socketAddress.getPort());
addressParams.putString("family", address instanceof Inet6Address ? "IPv6" : "IPv4");
infoParams.putMap("address", addressParams);
eventParams.putMap("info", infoParams);
sendEvent("connection", eventParams);
}
@Override
public void onConnect(Integer id, InetSocketAddress socketAddress) {
if (mShuttingDown) {
return;
}
WritableMap eventParams = Arguments.createMap();
eventParams.putInt("id", id);
final InetAddress address = socketAddress.getAddress();
WritableMap addressParams = Arguments.createMap();
addressParams.putString("address", address.getHostAddress());
addressParams.putInt("port", socketAddress.getPort());
addressParams.putString("family", address instanceof Inet6Address ? "IPv6" : "IPv4");
eventParams.putMap("address", addressParams);
sendEvent("connect", eventParams);
}
@Override
public void onData(Integer id, byte[] data) {
if (mShuttingDown) {
return;
}
WritableMap eventParams = Arguments.createMap();
eventParams.putInt("id", id);
eventParams.putString("data", Base64.encodeToString(data, Base64.NO_WRAP));
sendEvent("data", eventParams);
}
@Override
public void onClose(Integer id, String error) {
if (mShuttingDown) {
return;
}
if (error != null) {
onError(id, error);
}
WritableMap eventParams = Arguments.createMap();
eventParams.putInt("id", id);
eventParams.putBoolean("hadError", error != null);
sendEvent("close", eventParams);
}
@Override
public void onError(Integer id, String error) {
if (mShuttingDown) {
return;
}
WritableMap eventParams = Arguments.createMap();
eventParams.putInt("id", id);
eventParams.putString("error", error);
sendEvent("error", eventParams);
}
} |
/**
*
* @author Ted Pyne, Hyun Choi, Patrick Forelli
* @version (a version number or a date)
*/
public class Board
{
private Piece[][] board; //Board state, represented by a 2D array of Piece objects
private boolean whiteTurn; //Current player turn is tracked in board to enable double-move logic
private boolean lastMoveDouble; //If the last move allowed a double move, store persistently across turn
private int lastX, lastY; //During the second phase of a double move, the player must select the piece they moved in the first phase
public Board(){
board = new Piece[8][8];
whiteTurn = true; //Start with white
addPieces();
}
private void addPieces(){
for(int i = 0; i < 3; i++) //Correct white rows
for(int j = i%2; j < board[0].length; j += 2)
board[i][j] = new Piece(true); //Initialise White pieces
for(int i = 7; i > 4; i--) //Correct black rows
for(int j = i%2; j < board[0].length; j += 2)
board[i][j] = new Piece(false); //Initialise black pieces
}
public boolean isValidSelection(int xpos, int ypos){ //If the selected piece is owned by the current player's turn
if(board[xpos][ypos]==null) return false;
return board[xpos][ypos].getIsWhite()==whiteTurn; //Compare piece color to current turn
}
public boolean isEmpty(int xpos, int ypos){ //return if a selection is empty
System.out.println("IN ISEMPTY");
return board[xpos][ypos]==null;
}
public boolean isWhiteTurn(){ return whiteTurn;}
public Piece getPiece (int xpos, int ypos)
{
return board[xpos][ypos];
}
/**
* makeMove does NOT perform array bounds checking; all input params are assumed to be 0<=i<=7
*/
public boolean makeMove(int xpos, int ypos, int newXPos, int newYPos){
TurnProcessor turnProc = new TurnProcessor(xpos, ypos, newXPos, newYPos, this); //Create new turnProcessor
if(lastMoveDouble){ //If this move is the second phase of a double move
if(xpos!=lastX && ypos !=lastY) return false; //If the player selects a different piece, return false
turnProc.isValidTurn(); //Process coordinates
if(!turnProc.wasMoveCapture()) return false; //If the move was not a capture move, return false
}
else if(!isValidSelection(xpos, ypos)) return false; //If the move selection is invalid, return false
if(!isEmpty(newXPos,newYPos)) return false; //If the move target is not empty, return false
if(turnProc.isValidTurn()){ //If a valid move
lastMoveDouble = false;
doMove(xpos, ypos, newXPos, newYPos); //Actually perform the moving of the piece
kingPromoter(newXPos, newYPos); //If the piece has reached the end, promote to king
if(turnProc.wasMoveCapture()) makeCapture(turnProc); //If the move involved a capture, make that capture
if(turnProc.wasMoveCapture() && doubleMove(newXPos, newYPos)){ //If a double move is possible
lastMoveDouble = true;
lastX = newXPos; //Store the Piece's coordinates
lastY = newYPos;
}
else nextPlayer(); //Else change player turn
return true;
}
return false;
}
private void doMove(int xpos, int ypos, int newXPos, int newYPos){
board[newXPos][newYPos] = board[xpos][ypos];
board[xpos][ypos] = null;
}
private boolean doubleMove(int xpos, int ypos){ //Return if another capture is possible
int[] newXP = {xpos + 2, xpos - 2};
int[] newYP = {ypos + 2, ypos - 2};
for(int x: newXP)
for(int y: newYP)
if(x > -1 && y > -1 && x < board.length && y < board.length && isEmpty(x,y)){
TurnProcessor turnProc = new TurnProcessor(xpos, ypos, x, y, this); //Check if the move is valid
if(turnProc.isValidTurn() && turnProc.wasMoveCapture()) return true; //If a move is a valid capture move, return true
}
return false;
}
private void kingPromoter(int xpos, int ypos){
if(board[xpos][ypos].getIsWhite() && xpos == board.length -1) board[xpos][ypos].makeKing();
else if(!board[xpos][ypos].getIsWhite() && xpos == 0) board[xpos][ypos].makeKing();
}
private void nextPlayer(){
whiteTurn = !whiteTurn;
}
private void makeCapture(TurnProcessor turnProc){
int[] middle = turnProc.getCaptureTarget();
board[middle[0]][middle[1]]=null;
}
public Piece gameIsWon(){ //If white has won, return a white piece, if black has won, return black, else return null
boolean blackAlive = false, whiteAlive = false;
for(Piece[] row: board){
for(Piece space: row){
if(space!=null){
if(space.getIsWhite()) whiteAlive = true;
else blackAlive = true;
}
}
}
if(blackAlive && whiteAlive) return null;
if(blackAlive) return new Piece(false);
return new Piece(true);
}
/**
* Degugging method: Print board to console
*/
public void printArr(){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j]==null)
System.out.print("| ");
else
System.out.print("|" + board[i][j]);
}
System.out.println("|");
}
}
} |
// OMETiffReader.java
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.IFormatReader;
import loci.formats.MetadataTools;
import loci.formats.MissingLibraryException;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataStore;
import loci.formats.ome.OMEXMLMetadata;
import loci.formats.services.OMEXMLService;
import loci.formats.services.OMEXMLServiceImpl;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffParser;
public class OMETiffReader extends FormatReader {
// -- Fields --
/** Mapping from series and plane numbers to files and IFD entries. */
protected OMETiffPlane[][] info; // dimensioned [numSeries][numPlanes]
/** List of used files. */
protected String[] used;
private int lastPlane;
private boolean hasSPW;
private int[] tileWidth;
private int[] tileHeight;
private OMEXMLService service;
// -- Constructor --
/** Constructs a new OME-TIFF reader. */
public OMETiffReader() {
super("OME-TIFF", new String[] {"ome.tif", "ome.tiff"});
suffixNecessary = false;
suffixSufficient = false;
domains = FormatTools.NON_GRAPHICS_DOMAINS;
hasCompanionFiles = true;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
// parse and populate OME-XML metadata
String fileName = new Location(id).getAbsoluteFile().getAbsolutePath();
RandomAccessInputStream ras = new RandomAccessInputStream(fileName);
TiffParser tp = new TiffParser(ras);
IFD ifd = tp.getFirstIFD();
long[] ifdOffsets = tp.getIFDOffsets();
ras.close();
String xml = ifd.getComment();
if (service == null) setupService();
OMEXMLMetadata meta;
try {
meta = service.createOMEXMLMetadata(xml);
}
catch (ServiceException se) {
throw new FormatException(se);
}
if (meta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
int nImages = 0;
for (int i=0; i<meta.getImageCount(); i++) {
int nChannels = meta.getChannelCount(i);
if (nChannels == 0) nChannels = 1;
int z = meta.getPixelsSizeZ(i).getValue().intValue();
int t = meta.getPixelsSizeT(i).getValue().intValue();
nImages += z * t * nChannels;
}
return nImages <= ifdOffsets.length;
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
boolean validHeader = tp.isValidHeader();
if (!validHeader) return false;
// look for OME-XML in first IFD's comment
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
String comment = ifd.getComment();
if (comment == null || comment.trim().length() == 0) return false;
try {
if (service == null) setupService();
IMetadata meta = service.createOMEXMLMetadata(comment.trim());
for (int i=0; i<meta.getImageCount(); i++) {
meta.setPixelsBinDataBigEndian(Boolean.TRUE, i, 0);
MetadataTools.verifyMinimumPopulated(meta, i);
}
return true;
}
catch (ServiceException se) { }
catch (NullPointerException e) { }
catch (FormatException e) { }
catch (IndexOutOfBoundsException e) { }
return false;
}
/* @see loci.formats.IFormatReader#getDomains() */
public String[] getDomains() {
FormatTools.assertId(currentId, true, 1);
return hasSPW ? new String[] {FormatTools.HCS_DOMAIN} :
FormatTools.NON_SPECIAL_DOMAINS;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
if (info[series][lastPlane] == null ||
info[series][lastPlane].reader == null ||
info[series][lastPlane].id == null)
{
return null;
}
info[series][lastPlane].reader.setId(info[series][lastPlane].id);
return info[series][lastPlane].reader.get8BitLookupTable();
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
if (info[series][lastPlane] == null ||
info[series][lastPlane].reader == null ||
info[series][lastPlane].id == null)
{
return null;
}
info[series][lastPlane].reader.setId(info[series][lastPlane].id);
return info[series][lastPlane].reader.get16BitLookupTable();
}
/*
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
lastPlane = no;
int i = info[series][no].ifd;
MinimalTiffReader r = (MinimalTiffReader) info[series][no].reader;
if (r.getCurrentFile() == null) {
r.setId(info[series][no].id);
}
IFDList ifdList = r.getIFDs();
if (i >= ifdList.size()) {
LOGGER.warn("Error untangling IFDs; the OME-TIFF file may be malformed.");
return buf;
}
IFD ifd = ifdList.get(i);
RandomAccessInputStream s =
new RandomAccessInputStream(info[series][no].id);
TiffParser p = new TiffParser(s);
p.getSamples(ifd, buf, x, y, w, h);
s.close();
return buf;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (noPixels) return null;
Vector<String> usedFiles = new Vector<String>();
for (int i=0; i<info[series].length; i++) {
if (!usedFiles.contains(info[series][i].id)) {
usedFiles.add(info[series][i].id);
}
}
return usedFiles.toArray(new String[usedFiles.size()]);
}
/* @see loci.formats.IFormatReader#fileGroupOption() */
public int fileGroupOption(String id) {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (info != null) {
for (OMETiffPlane[] dimension : info) {
for (OMETiffPlane plane : dimension) {
if (plane.reader != null) {
try {
plane.reader.close();
}
catch (Exception e) {
LOGGER.error("Plane closure failure!", e);
}
}
}
}
}
if (!fileOnly) {
info = null;
used = null;
lastPlane = 0;
tileWidth = null;
tileHeight = null;
}
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
return tileWidth[getSeries()];
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return tileHeight[getSeries()];
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
// normalize file name
super.initFile(normalizeFilename(null, id));
id = currentId;
String dir = new File(id).getParent();
// parse and populate OME-XML metadata
String fileName = new Location(id).getAbsoluteFile().getAbsolutePath();
RandomAccessInputStream ras = new RandomAccessInputStream(fileName);
String xml;
IFD firstIFD;
try {
TiffParser tp = new TiffParser(ras);
firstIFD = tp.getFirstIFD();
xml = firstIFD.getComment();
}
finally {
ras.close();
}
if (service == null) setupService();
OMEXMLMetadata meta;
try {
meta = service.createOMEXMLMetadata(xml);
}
catch (ServiceException se) {
throw new FormatException(se);
}
hasSPW = meta.getPlateCount() > 0;
for (int i=0; i<meta.getImageCount(); i++) {
int sizeC = meta.getPixelsSizeC(i).getValue().intValue();
service.removeChannels(meta, i, sizeC);
}
// TODO
//Hashtable originalMetadata = meta.getOriginalMetadata();
//if (originalMetadata != null) metadata = originalMetadata;
LOGGER.trace(xml);
if (meta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
String currentUUID = meta.getUUID();
service.convertMetadata(meta, metadataStore);
// determine series count from Image and Pixels elements
int seriesCount = meta.getImageCount();
core = new CoreMetadata[seriesCount];
for (int i=0; i<seriesCount; i++) {
core[i] = new CoreMetadata();
}
info = new OMETiffPlane[seriesCount][];
tileWidth = new int[seriesCount];
tileHeight = new int[seriesCount];
// compile list of file/UUID mappings
Hashtable<String, String> files = new Hashtable<String, String>();
boolean needSearch = false;
for (int i=0; i<seriesCount; i++) {
int tiffDataCount = meta.getTiffDataCount(i);
for (int td=0; td<tiffDataCount; td++) {
String uuid = null;
try {
uuid = meta.getUUIDValue(i, td);
}
catch (NullPointerException e) { }
String filename = null;
if (uuid == null) {
// no UUID means that TiffData element refers to this file
uuid = "";
filename = id;
}
else {
filename = meta.getUUIDFileName(i, td);
if (!new Location(dir, filename).exists()) filename = null;
if (filename == null) {
if (uuid.equals(currentUUID) || currentUUID == null) {
// UUID references this file
filename = id;
}
else {
// will need to search for this UUID
filename = "";
needSearch = true;
}
}
else filename = normalizeFilename(dir, filename);
}
String existing = files.get(uuid);
if (existing == null) files.put(uuid, filename);
else if (!existing.equals(filename)) {
throw new FormatException("Inconsistent UUID filenames");
}
}
}
// search for missing filenames
if (needSearch) {
Enumeration en = files.keys();
while (en.hasMoreElements()) {
String uuid = (String) en.nextElement();
String filename = files.get(uuid);
if (filename.equals("")) {
// TODO search...
// should scan only other .ome.tif files
// to make this work with OME server may be a little tricky?
throw new FormatException("Unmatched UUID: " + uuid);
}
}
}
// build list of used files
Enumeration en = files.keys();
int numUUIDs = files.size();
HashSet fileSet = new HashSet(); // ensure no duplicate filenames
for (int i=0; i<numUUIDs; i++) {
String uuid = (String) en.nextElement();
String filename = files.get(uuid);
fileSet.add(filename);
}
used = new String[fileSet.size()];
Iterator iter = fileSet.iterator();
for (int i=0; i<used.length; i++) used[i] = (String) iter.next();
// process TiffData elements
Hashtable<String, IFormatReader> readers =
new Hashtable<String, IFormatReader>();
for (int i=0; i<seriesCount; i++) {
int s = i;
LOGGER.debug("Image[{}] {", i);
LOGGER.debug(" id = {}", meta.getImageID(i));
String order = meta.getPixelsDimensionOrder(i).toString();
PositiveInteger samplesPerPixel = null;
if (meta.getChannelCount(i) > 0) {
samplesPerPixel = meta.getChannelSamplesPerPixel(i, 0);
}
int samples = samplesPerPixel == null ? -1 : samplesPerPixel.getValue();
int tiffSamples = firstIFD.getSamplesPerPixel();
if (samples != tiffSamples) {
LOGGER.warn("SamplesPerPixel mismatch: OME={}, TIFF={}",
samples, tiffSamples);
samples = tiffSamples;
}
int effSizeC = meta.getPixelsSizeC(i).getValue().intValue() / samples;
if (effSizeC == 0) effSizeC = 1;
if (effSizeC * samples != meta.getPixelsSizeC(i).getValue().intValue()) {
effSizeC = meta.getPixelsSizeC(i).getValue().intValue();
}
int sizeT = meta.getPixelsSizeT(i).getValue().intValue();
int sizeZ = meta.getPixelsSizeZ(i).getValue().intValue();
int num = effSizeC * sizeT * sizeZ;
OMETiffPlane[] planes = new OMETiffPlane[num];
for (int no=0; no<num; no++) planes[no] = new OMETiffPlane();
int tiffDataCount = meta.getTiffDataCount(i);
boolean zOneIndexed = false;
boolean cOneIndexed = false;
boolean tOneIndexed = false;
// pre-scan TiffData indices to see if any of them are indexed from 1
for (int td=0; td<tiffDataCount; td++) {
NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td);
NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td);
NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td);
int c = firstC == null ? 0 : firstC.getValue();
int t = firstT == null ? 0 : firstT.getValue();
int z = firstZ == null ? 0 : firstZ.getValue();
if (c >= effSizeC) cOneIndexed = true;
if (z >= sizeZ) zOneIndexed = true;
if (t >= sizeT) tOneIndexed = true;
}
for (int td=0; td<tiffDataCount; td++) {
LOGGER.debug(" TiffData[{}] {", td);
// extract TiffData parameters
String filename = null;
String uuid = null;
try {
filename = meta.getUUIDFileName(i, td);
} catch (NullPointerException e) {
LOGGER.debug("Ignoring null UUID object when retrieving filename.");
}
try {
uuid = meta.getUUIDValue(i, td);
} catch (NullPointerException e) {
LOGGER.debug("Ignoring null UUID object when retrieving value.");
}
NonNegativeInteger tdIFD = meta.getTiffDataIFD(i, td);
int ifd = tdIFD == null ? 0 : tdIFD.getValue();
NonNegativeInteger numPlanes = meta.getTiffDataPlaneCount(i, td);
NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td);
NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td);
NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td);
int c = firstC == null ? 0 : firstC.getValue();
int t = firstT == null ? 0 : firstT.getValue();
int z = firstZ == null ? 0 : firstZ.getValue();
// NB: some writers index FirstC, FirstZ and FirstT from 1
if (cOneIndexed) c
if (zOneIndexed) z
if (tOneIndexed) t
int index = FormatTools.getIndex(order,
sizeZ, effSizeC, sizeT, num, z, c, t);
int count = numPlanes == null ? 1 : numPlanes.getValue();
if (count == 0) {
core[s] = null;
break;
}
// get reader object for this filename
if (filename == null) {
if (uuid == null) filename = id;
else filename = files.get(uuid);
}
else filename = normalizeFilename(dir, filename);
IFormatReader r = readers.get(filename);
if (r == null) {
r = new MinimalTiffReader();
readers.put(filename, r);
}
Location file = new Location(filename);
if (!file.exists()) {
// if this is an absolute file name, try using a relative name
// old versions of OMETiffWriter wrote an absolute path to
// UUID.FileName, which causes problems if the file is moved to
// a different directory
filename =
filename.substring(filename.lastIndexOf(File.separator) + 1);
filename = dir + File.separator + filename;
if (!new Location(filename).exists()) {
filename = currentId;
}
}
// populate plane index -> IFD mapping
for (int q=0; q<count; q++) {
int no = index + q;
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = ifd + q;
planes[no].certain = true;
LOGGER.debug(" Plane[{}]: file={}, IFD={}",
new Object[] {no, planes[no].id, planes[no].ifd});
}
if (numPlanes == null) {
// unknown number of planes; fill down
for (int no=index+1; no<num; no++) {
if (planes[no].certain) break;
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = planes[no - 1].ifd + 1;
LOGGER.debug(" Plane[{}]: FILLED", no);
}
}
else {
// known number of planes; clear anything subsequently filled
for (int no=index+count; no<num; no++) {
if (planes[no].certain) break;
planes[no].reader = null;
planes[no].id = null;
planes[no].ifd = -1;
LOGGER.debug(" Plane[{}]: CLEARED", no);
}
}
LOGGER.debug(" }");
}
if (core[s] == null) continue;
// verify that all planes are available
LOGGER.debug("
for (int no=0; no<num; no++) {
LOGGER.debug(" Plane[{}]: file={}, IFD={}",
new Object[] {no, planes[no].id, planes[no].ifd});
if (planes[no].reader == null) {
LOGGER.warn("Image ID '{}': missing plane
"Using TiffReader to determine the number of planes.",
meta.getImageID(i), no);
TiffReader r = new TiffReader();
r.setId(currentId);
try {
planes = new OMETiffPlane[r.getImageCount()];
for (int plane=0; plane<planes.length; plane++) {
planes[plane] = new OMETiffPlane();
planes[plane].id = currentId;
planes[plane].reader = r;
planes[plane].ifd = plane;
}
num = planes.length;
}
finally {
r.close();
}
}
}
LOGGER.debug(" }");
// populate core metadata
info[s] = planes;
try {
info[s][0].reader.setId(info[s][0].id);
tileWidth[s] = info[s][0].reader.getOptimalTileWidth();
tileHeight[s] = info[s][0].reader.getOptimalTileHeight();
core[s].sizeX = meta.getPixelsSizeX(i).getValue().intValue();
int tiffWidth = (int) firstIFD.getImageWidth();
if (core[s].sizeX != tiffWidth) {
LOGGER.warn("SizeX mismatch: OME={}, TIFF={}",
core[s].sizeX, tiffWidth);
}
core[s].sizeY = meta.getPixelsSizeY(i).getValue().intValue();
int tiffHeight = (int) firstIFD.getImageLength();
if (core[s].sizeY != tiffHeight) {
LOGGER.warn("SizeY mismatch: OME={}, TIFF={}",
core[s].sizeY, tiffHeight);
}
core[s].sizeZ = meta.getPixelsSizeZ(i).getValue().intValue();
core[s].sizeC = meta.getPixelsSizeC(i).getValue().intValue();
core[s].sizeT = meta.getPixelsSizeT(i).getValue().intValue();
core[s].pixelType = FormatTools.pixelTypeFromString(
meta.getPixelsType(i).toString());
int tiffPixelType = firstIFD.getPixelType();
if (core[s].pixelType != tiffPixelType) {
LOGGER.warn("PixelType mismatch: OME={}, TIFF={}",
core[s].pixelType, tiffPixelType);
core[s].pixelType = tiffPixelType;
}
core[s].imageCount = num;
core[s].dimensionOrder = meta.getPixelsDimensionOrder(i).toString();
// hackish workaround for files exported by OMERO that have an
// incorrect dimension order
String uuidFileName = "";
try {
uuidFileName = meta.getUUIDFileName(i, 0);
}
catch (NullPointerException e) { }
if (meta.getChannelCount(i) > 0 && meta.getChannelName(i, 0) == null &&
meta.getTiffDataCount(i) > 0 &&
uuidFileName.indexOf("__omero_export") != -1)
{
core[s].dimensionOrder = "XYZCT";
}
core[s].orderCertain = true;
PhotoInterp photo = firstIFD.getPhotometricInterpretation();
core[s].rgb = samples > 1 || photo == PhotoInterp.RGB;
if ((samples != core[s].sizeC && (samples % core[s].sizeC) != 0 &&
(core[s].sizeC % samples) != 0) || core[s].sizeC == 1)
{
core[s].sizeC *= samples;
}
if (core[s].sizeZ * core[s].sizeT * core[s].sizeC >
core[s].imageCount && !core[s].rgb)
{
if (core[s].sizeZ == core[s].imageCount) {
core[s].sizeT = 1;
core[s].sizeC = 1;
}
else if (core[s].sizeT == core[s].imageCount) {
core[s].sizeZ = 1;
core[s].sizeC = 1;
}
else if (core[s].sizeC == core[s].imageCount) {
core[s].sizeT = 1;
core[s].sizeZ = 1;
}
}
if (meta.getPixelsBinDataCount(i) > 1) {
LOGGER.warn("OME-TIFF Pixels element contains BinData elements! " +
"Ignoring.");
}
core[s].littleEndian = firstIFD.isLittleEndian();
core[s].interleaved = false;
core[s].indexed = photo == PhotoInterp.RGB_PALETTE &&
firstIFD.getIFDValue(IFD.COLOR_MAP) != null;
if (core[s].indexed) {
core[s].rgb = false;
}
core[s].falseColor = true;
core[s].metadataComplete = true;
}
catch (NullPointerException exc) {
throw new FormatException("Incomplete Pixels metadata", exc);
}
}
// remove null CoreMetadata entries
Vector<CoreMetadata> series = new Vector<CoreMetadata>();
Vector<OMETiffPlane[]> planeInfo = new Vector<OMETiffPlane[]>();
for (int i=0; i<core.length; i++) {
if (core[i] != null) {
series.add(core[i]);
planeInfo.add(info[i]);
}
}
core = series.toArray(new CoreMetadata[series.size()]);
info = planeInfo.toArray(new OMETiffPlane[0][0]);
MetadataTools.populatePixels(metadataStore, this, false, false);
metadataStore = getMetadataStoreForConversion();
}
// -- OMETiffReader API methods --
/**
* Returns a MetadataStore that is populated in such a way as to
* produce valid OME-XML. The returned MetadataStore cannot be used
* by an IFormatWriter, as it will not contain the required
* BinData.BigEndian attributes.
*/
public MetadataStore getMetadataStoreForDisplay() {
MetadataStore store = getMetadataStore();
if (service.isOMEXMLMetadata(store)) {
service.removeBinData((OMEXMLMetadata) store);
for (int i=0; i<getSeriesCount(); i++) {
if (((OMEXMLMetadata) store).getTiffDataCount(i) == 0) {
service.addMetadataOnly((OMEXMLMetadata) store, i);
}
}
}
return store;
}
/**
* Returns a MetadataStore that is populated in such a way as to be
* usable by an IFormatWriter. Any OME-XML generated from this
* MetadataStore is <em>very unlikely</em> to be valid, as more than
* likely both BinData and TiffData element will be present.
*/
public MetadataStore getMetadataStoreForConversion() {
MetadataStore store = getMetadataStore();
int realSeries = getSeries();
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
store.setPixelsBinDataBigEndian(new Boolean(!isLittleEndian()), i, 0);
}
setSeries(realSeries);
return store;
}
// -- Helper methods --
private String normalizeFilename(String dir, String name) {
File file = new File(dir, name);
if (file.exists()) return file.getAbsolutePath();
return new Location(name).getAbsolutePath();
}
private void setupService() throws FormatException {
try {
ServiceFactory factory = new ServiceFactory();
service = factory.getInstance(OMEXMLService.class);
}
catch (DependencyException de) {
throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
}
}
// -- Helper classes --
/** Structure containing details on where to find a particular image plane. */
private class OMETiffPlane {
/** Reader to use for accessing this plane. */
public IFormatReader reader;
/** File containing this plane. */
public String id;
/** IFD number of this plane. */
public int ifd = -1;
/** Certainty flag, for dealing with unspecified NumPlanes. */
public boolean certain = false;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sibtra.predictivo;
import org.omg.CORBA.portable.IndirectionException;
import sibtra.util.UtilCalculos;
import Jama.Matrix;
/**
* Esta clase implementa el algoritmo de control predictivo DMC
* @author Jesus
*/
public class ControlPredictivo {
int horPrediccion;
/**
* Indica cuantos comandos de control futuros se quieren calcular
*/
int horControl;
double[][] ruta;
static boolean rutaCerrada;
double landa;
double pesoError;
Coche carroOriginal;
Coche carroSim;
/**
* Periodo de muestreo del controlador
*/
double Ts;
Matrix G;
private Matrix landaEye;
/** Almacena las orientaciones de la prediccion*/
double[] predicOrientacion;
/** Almacena las posiciones x e y de la prediccion*/
double[][] prediccionPosicion;
double comandoCalculado;
double distanciaLateral;
private double[] vectorError;
private double[] orientacionesDeseadas;
private double[] respuestaEscalon;
private Coche carroEscalon;
private int indMinAnt;
public ControlPredictivo(Coche carroOri,double[][] ruta,int horPrediccion,int horControl,double landa,double Ts){
carroOriginal = carroOri;
carroSim = (Coche)carroOri.clone();
carroEscalon=(Coche)carroOriginal.clone();
this.horPrediccion = horPrediccion;
this.horControl = horControl;
this.landa = landa;
this.ruta = ruta;
this.Ts = Ts;
this.indMinAnt = -1;
// creamos todas las matrices que se usan en las iteracioner para evitar tener que
//pedir memoria cada vez
G = new Matrix(horPrediccion,horControl);
this.landaEye = Matrix.identity(horControl,horControl).times(landa);
prediccionPosicion = new double[horPrediccion][2];
predicOrientacion = new double[horPrediccion];
vectorError = new double[horPrediccion];
orientacionesDeseadas = new double[horPrediccion];
respuestaEscalon = new double[horPrediccion];
}
public ControlPredictivo(Coche carroOri,double[][] ruta,int horPrediccion,int horControl,double landa,double Ts,boolean rutaCerrada){
carroOriginal = carroOri;
carroSim = (Coche)carroOri.clone();
carroEscalon=(Coche)carroOriginal.clone();
this.horPrediccion = horPrediccion;
this.horControl = horControl;
this.landa = landa;
this.ruta = ruta;
this.Ts = Ts;
this.rutaCerrada = rutaCerrada;
this.indMinAnt = -1;
// creamos todas las matrices que se usan en las iteracioner para evitar tener que
//pedir memoria cada vez
G = new Matrix(horPrediccion,horControl);
this.landaEye = Matrix.identity(horControl,horControl).times(landa);
prediccionPosicion = new double[horPrediccion][2];
predicOrientacion = new double[horPrediccion];
vectorError = new double[horPrediccion];
orientacionesDeseadas = new double[horPrediccion];
respuestaEscalon = new double[horPrediccion];
}
/**
*
* @return Devuelve el primer componente del vector {@link #orientacionesDeseadas}
*/
public double getOrientacionDeseada() {
return orientacionesDeseadas[0];
}
public int getHorControl() {
return horControl;
}
public void setHorControl(int horControl) {
if (horControl==this.horControl)
return;
this.horControl = horControl;
G = new Matrix(horPrediccion,horControl);
this.landaEye = Matrix.identity(horControl,horControl).times(landa);
}
public int getHorPrediccion() {
return horPrediccion;
}
public void setHorPrediccion(int horPrediccion) {
if(horPrediccion==this.horPrediccion)
return;
this.horPrediccion = horPrediccion;
prediccionPosicion = new double[horPrediccion][2];
G = new Matrix(horPrediccion,horControl);
predicOrientacion = new double[horPrediccion];
vectorError = new double[horPrediccion];
orientacionesDeseadas = new double[horPrediccion];
respuestaEscalon = new double[horPrediccion];
}
public double getLanda() {
return landa;
}
public void setLanda(double landa) {
if(landa==this.landa)
return;
this.landa = landa;
this.landaEye = Matrix.identity(horControl,horControl).times(landa);
}
public void setRuta(double[][] nuevaRuta){
this.ruta = nuevaRuta;
}
private double[] calculaPrediccion(double comando,double velocidad){
carroSim.copy(carroOriginal);
// vec_deseado(1,:) = k_dist*(pos_ref(mod(ind_min(k)+cerca,length(pos_ref))+1,:) - [carro.x,carro.y])
//+ k_ang*[cos(tita_ref(mod(ind_min(k)+cerca,length(tita_ref))+1)),sin(tita_ref(mod(ind_min(k)+cerca,length(tita_ref))+1))];
// int indMin = calculaDistMin(ruta,carroSim.getX(),carroSim.getY());
indMinAnt = calculaDistMinOptimizado(ruta,carroSim.getX(),carroSim.getY(),indMinAnt);
double dx=ruta[indMinAnt][0]-carroSim.getX();
double dy=ruta[indMinAnt][1]-carroSim.getY();
distanciaLateral=Math.sqrt(dx*dx+dy*dy);
double vectorDeseadoX = ruta[indMinAnt][0] - carroSim.getX() + Math.cos(ruta[indMinAnt][2]);
double vectorDeseadoY = ruta[indMinAnt][1] - carroSim.getY() + Math.sin(ruta[indMinAnt][2]);
orientacionesDeseadas[0] = Math.atan2(vectorDeseadoX,vectorDeseadoY);
predicOrientacion[0] = carroSim.getTita();
vectorError[0] = orientacionesDeseadas[0] - predicOrientacion[0];
prediccionPosicion[0][0] = carroSim.getX();
prediccionPosicion[0][1] = carroSim.getY();
int indMin = indMinAnt;
for (int i=1; i<horPrediccion;i++ ){
carroSim.calculaEvolucion(comando,velocidad,Ts);
predicOrientacion[i] = carroSim.getTita();
indMin = calculaDistMinOptimizado(ruta,carroSim.getX(),carroSim.getY(),indMin);
// indMin = calculaDistMin(ruta,carroSim.getX(),carroSim.getY());
vectorDeseadoX = ruta[indMin][0] - carroSim.getX() + Math.cos(ruta[indMin][2]);
vectorDeseadoY = ruta[indMin][1] - carroSim.getY() + Math.sin(ruta[indMin][2]);
orientacionesDeseadas[i] = Math.atan2(vectorDeseadoY,vectorDeseadoX);
// System.out.println("Indice minimo " + indMin);
// System.out.println("Vector x "+vectorDeseadoX+" "+ "Vector y "+vectorDeseadoY+"\n");
// System.out.println("Orientacion deseada " + orientacionesDeseadas[i] + " "
// +"prediccion de orientacion " + predicOrientacion[i]+"\n");
vectorError[i] = UtilCalculos.normalizaAngulo(orientacionesDeseadas[i] - predicOrientacion[i]);
prediccionPosicion[i][0] = carroSim.getX();
prediccionPosicion[i][1] = carroSim.getY();
}
return vectorError;
}
public static int calculaDistMin(double[][] ruta,double posX,double posY){
double distMin=Double.POSITIVE_INFINITY;
int indMin=0;
double dx;
double dy;
for(int i=0; i<ruta.length; i++) {
dx=posX-ruta[i][0];
dy=posY-ruta[i][1];
double dist=Math.sqrt(dx*dx+dy*dy);
if(dist<distMin) {
indMin=i;
distMin=dist;
}
}
return indMin;
}
public static int calculaDistMinOptimizado(double[][] ruta,double posX,double posY,int indMinAnt){
double dx;
double dy;
double distMin=Double.POSITIVE_INFINITY;
int indMin=0;
int indiceInicial = indMinAnt - 10;
if(indMinAnt<0){
return calculaDistMin(ruta, posX, posY);
}
if (rutaCerrada){
indiceInicial = (indMinAnt + ruta.length - 10)%ruta.length;
}else{
if (indiceInicial <= 0)
indiceInicial = 0;
}
boolean encontrado=false;
for(int i=indiceInicial;encontrado!=true; i=(i+1)%ruta.length) {
dx=posX-ruta[i][0];
dy=posY-ruta[i][1];
double dist=Math.sqrt(dx*dx+dy*dy);
if(dist<=distMin) {
indMin=i;
distMin=dist;
}else{
encontrado=true;
}
}
return indMin;
}
public double calculaComando(){
// vector_error = tita_deseado - ftita;
// vector_error = vector_error + (vector_error > pi)*(-2*pi) + (vector_error < -pi)*2*pi;
double[] vectorError = calculaPrediccion(carroOriginal.getConsignaVolante()
,carroOriginal.getVelocidad());
// M = diag(peso_tita'*vector_error);
Matrix M = new Matrix(vectorError,horPrediccion).transpose();
//M.print(1,6);
// u = inv(G'*G + landa*eye(hor_control))*G'*M;
// u_actual = u(1) + u_anterior;
calculaG();
//G.print(1,6);
Matrix Gt = G.transpose();
// Matrix GtporM = Gt.times(M.transpose());
// Matrix GtporG = Gt.times(G);
// Matrix masLandaEye = GtporG.plus(landaEye);
Matrix vectorU = Gt.times(G).plus(landaEye).inverse().times(Gt).times(M.transpose());
//vectorU.print(1,6);
comandoCalculado = vectorU.get(0,0) + carroOriginal.getConsignaVolante();
return comandoCalculado;
}
private Matrix calculaG(){
double[] escalon = calculaEscalon(carroOriginal.getVelocidad());
// for j=1:hor_control,
// cont=1;
// for i=j:hor_predic
// Gtita(i,j)=escalon_tita(cont);
// cont=cont+1;
// end
//end
for (int j=0;j<horControl;j++){
int cont = 0;
for (int i=j;i<horPrediccion;i++){
G.set(i,j,escalon[cont]);
cont++;
}
}
return G;
}
private double[] calculaEscalon(double velocidad){
// carroEscalon.copy(carroOriginal);
carroEscalon.setPostura(0,0,0,0);
carroEscalon.setEstadoA0();
for (int i=0;i<horPrediccion;i++){
carroEscalon.calculaEvolucion(Math.PI/6,velocidad, Ts);
respuestaEscalon[i] = carroEscalon.getTita();
}
return respuestaEscalon;
}
static double[][] generaRuta(int numPuntos,double intervalo){
double[][] rutaAux = new double[numPuntos][3];
rutaAux[0][0] = 0;
rutaAux[0][1] = 0;
rutaAux[0][2] = 0;
for (int i=1;i<numPuntos;i++){
rutaAux[i][0] = i*intervalo;
rutaAux[i][1] = rutaAux[i][0]*2;
rutaAux[i][2] = Math.atan2((rutaAux[i][1]-rutaAux[i-1][1]),
(rutaAux[i][0]-rutaAux[i-1][0]));
}
return rutaAux;
}
public static void main(String[] args){
Coche carroOri = new Coche();
double vel = 2;
double consVolante = 0;
carroOri.setVelocidad(vel);
carroOri.setConsignaVolante(consVolante);
int horPredic = 12;
int horCont = 3;
double paramLanda = 1;
double paramTs = 0.2;
double[][] rutaPrueba = generaRuta(200,0.25);
carroOri.setPostura(rutaPrueba[2][0],rutaPrueba[2][1],rutaPrueba[2][2]+0.1,0);
// for(int i=0;i<20;i++){
// System.out.println(rutaPrueba[i][0] + " / " + rutaPrueba[i][1] +
// "/" + rutaPrueba[i][2]);
ControlPredictivo controlador = new ControlPredictivo(carroOri,rutaPrueba,
horPredic,horCont,paramLanda,paramTs);
controlador.calculaComando();
System.exit(0);
for (int i = 0; i < rutaPrueba.length; i++) {
double comandoVolante = controlador.calculaComando();
if (comandoVolante > Math.PI/4)
comandoVolante = Math.PI/4;
if (comandoVolante < -Math.PI/4)
comandoVolante = -Math.PI/4;
System.out.println("Comando " + comandoVolante);
carroOri.setConsignaVolante(comandoVolante);
carroOri.calculaEvolucion(comandoVolante,2,0.2);
int indice = ControlPredictivo.calculaDistMin(rutaPrueba,carroOri.getX(),carroOri.getY());
double error = rutaPrueba[indice][2] - carroOri.getTita();
System.out.println("Error " + error);
}
// double[] prediccion = controlador.calculaPrediccion(consVolante, vel);
// for(int i=0;i<controlador.horPrediccion;i++){
// System.out.println(prediccion[i]);
// System.out.println("Angulo normalizado " +normalizaAngulo(0));
// System.exit(0);
}
} |
package org.vaadin.alump.openfile;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.MimeTypeMap;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
/**
* This class starts an activity for an intent to view files
*/
public class OpenFile extends CordovaPlugin {
private static final String OPEN_COMMAND = "open";
private static final String TAG = OpenFile.class.getSimpleName();
@Override
public boolean execute(String command, JSONArray jsonArgs, CallbackContext callback) throws JSONException {
if(OPEN_COMMAND.equals(command)) {
final String uri = jsonArgs.getString(0);
findIntent(uri, callback);
} else {
Log.w(TAG, "Unknown command '" + command + "' ignored.");
return false;
}
return true;
}
private void findIntent(String uri, CallbackContext callback) {
if(uri == null || uri.isEmpty()) {
final String error = "Invalid path " + (uri == null ? "null" : ("'" + uri + "'")) + " received.";
Log.e(TAG, error);
callback.error(error);
return;
}
try {
Uri realUri = Uri.parse(uri);
String mime = getMimeTypeFromExtension(uri);
Intent fileIntent = new Intent(Intent.ACTION_VIEW);
if(Build.VERSION.SDK_INT >= 16) {
fileIntent.setDataAndTypeAndNormalize(realUri, mime);
} else {
fileIntent.setDataAndType(realUri, mime);
}
Log.d(TAG, "Starting activity for '" + uri + "'...");
cordova.getActivity().startActivity(fileIntent);
} catch (ActivityNotFoundException e) {
final String error = "Failed to find activity for '" + uri + "'";
Log.e(TAG, error, e);
callback.error(error + ": " + e.getMessage());
}
callback.success();
}
private String getMimeTypeFromExtension(String uri) {
String mimeType = null;
final String extension = MimeTypeMap.getFileExtensionFromUrl(uri);
if(extension != null) {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
Log.d(TAG, "Mime type resolved as " + mimeType);
} else {
Log.w(TAG, "Failed to resolve extension from " + uri);
}
return mimeType;
}
} |
package edu.umd.cs.findbugs;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import edu.umd.cs.findbugs.io.IO;
import edu.umd.cs.findbugs.visitclass.Constants2;
import org.apache.bcel.classfile.*;
import org.apache.bcel.Repository;
import org.apache.bcel.util.ClassPath;
import org.apache.bcel.util.SyntheticRepository;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.ClassObserver;
import edu.umd.cs.findbugs.ba.InnerClassAccessMap;
/**
* An instance of this class is used to apply the selected set of
* analyses on some collection of Java classes. It also implements the
* comand line interface.
*
* @author Bill Pugh
* @author David Hovemeyer
*/
public class FindBugs implements Constants2, ExitCodes
{
/**
* Interface for an object representing a source of class files to analyze.
*/
private interface ClassProducer {
/**
* Get the next class to analyze.
* @return the class, or null of there are no more classes for this ClassProducer
* @throws IOException if an IOException occurs
* @throws InterruptedException if the thread is interrupted
*/
public JavaClass getNextClass() throws IOException, InterruptedException;
/**
* Did this class producer scan any Java source files?
*/
public boolean containsSourceFiles();
}
/**
* ClassProducer for single class files.
*/
private static class SingleClassProducer implements ClassProducer {
private String fileName;
/**
* Constructor.
* @param fileName the single class file to be analyzed
*/
public SingleClassProducer(String fileName) {
this.fileName = fileName;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
if (fileName == null)
return null;
if (Thread.interrupted())
throw new InterruptedException();
String fileNameToParse = fileName;
fileName = null; // don't return it next time
try {
return parseClass(fileNameToParse);
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileNameToParse + ": " + e.getMessage());
}
}
public boolean containsSourceFiles() {
return false;
}
}
/**
* ClassProducer for .zip and .jar files.
* Nested jar and zip files are also scanned for classes;
* this is needed for .ear and .war files associated with EJBs.
*/
private static class ZipClassProducer implements ClassProducer {
private String fileName;
private String nestedFileName;
private ZipFile zipFile;
private Enumeration entries;
private ZipInputStream zipStream;
private boolean containsSourceFiles;
// a DataInputStream wrapper that cannot be closed
private static class DupDataStream extends DataInputStream {
public DupDataStream( InputStream in ) {
super( in );
}
public void close() { };
}
/**
* Constructor.
* @param fileName the name of the zip or jar file
*/
public ZipClassProducer(String fileName) throws IOException {
this.fileName = fileName;
this.zipFile = new ZipFile(fileName);
this.entries = zipFile.entries();
this.zipStream = null;
this.nestedFileName = null;
this.containsSourceFiles = false;
}
private void setZipStream( ZipInputStream in, String fileName ) {
zipStream = in;
nestedFileName = fileName;
}
private void closeZipStream() throws IOException {
zipStream.close();
zipStream = null;
nestedFileName = null;
}
private JavaClass getNextNestedClass() throws IOException, InterruptedException {
JavaClass parsedClass = null;
if ( zipStream != null ) {
ZipEntry entry = zipStream.getNextEntry();
while ( entry != null ) {
if (Thread.interrupted()) throw new InterruptedException();
if ( entry.getName().endsWith( ".class" ) ) {
try {
parsedClass = parseClass(nestedFileName, new DupDataStream(zipStream), entry.getName());
break;
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileName + ":" + nestedFileName + ":" +
entry.getName() + ": " + e.getMessage());
}
}
entry = zipStream.getNextEntry();
}
if ( parsedClass == null ) {
closeZipStream();
}
}
return parsedClass;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
JavaClass parsedClass = getNextNestedClass();
if ( parsedClass != null )
return parsedClass;
while (entries.hasMoreElements()) {
if (Thread.interrupted()) throw new InterruptedException();
ZipEntry entry = (ZipEntry) entries.nextElement();
String name = entry.getName();
if (name.endsWith(".class")) {
try {
parsedClass = parseClass(fileName, zipFile.getInputStream(entry), name);
break;
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileName + ":" + name + ": " + e.getMessage());
}
} else if ( name.endsWith(".jar") || name.endsWith( ".zip" ) ) {
setZipStream(new ZipInputStream(zipFile.getInputStream(entry)), name );
parsedClass = getNextNestedClass();
if ( parsedClass != null ) {
break;
}
} else if (name.endsWith(".java"))
containsSourceFiles = true;
}
return parsedClass;
}
public boolean containsSourceFiles() {
return containsSourceFiles;
}
}
/**
* ClassProducer for directories.
* The directory is scanned recursively for class files.
*/
private static class DirectoryClassProducer implements ClassProducer {
private Iterator<String> rfsIter;
private boolean containsSourceFiles;
public DirectoryClassProducer(String dirName) throws InterruptedException {
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
String fileName = file.getName();
if (file.isDirectory() || fileName.endsWith(".class"))
return true;
if (fileName.endsWith(".java"))
containsSourceFiles = true;
return false;
}
};
// This will throw InterruptedException if the thread is
// interrupted.
RecursiveFileSearch rfs = new RecursiveFileSearch(dirName, filter).search();
this.rfsIter = rfs.fileNameIterator();
this.containsSourceFiles = false;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
if (!rfsIter.hasNext())
return null;
String fileName = rfsIter.next();
try {
return parseClass(fileName);
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileName + ": " + e.getMessage());
}
}
public boolean containsSourceFiles() {
return containsSourceFiles;
}
}
/**
* A delegating bug reporter which counts reported bug instances,
* missing classes, and serious analysis errors.
*/
private static class ErrorCountingBugReporter extends DelegatingBugReporter {
private int bugCount;
private int missingClassCount;
private int errorCount;
private Set<String> missingClassSet = new HashSet<String>();
public ErrorCountingBugReporter(BugReporter realBugReporter) {
super(realBugReporter);
this.bugCount = 0;
this.missingClassCount = 0;
this.errorCount = 0;
// Add an observer to record when bugs make it through
// all priority and filter criteria, so our bug count is
// accurate.
realBugReporter.addObserver(new BugReporterObserver() {
public void reportBug(BugInstance bugInstance) {
++bugCount;
}
});
}
public int getBugCount() {
return bugCount;
}
public int getMissingClassCount() {
return missingClassCount;
}
public int getErrorCount() {
return errorCount;
}
public void logError(String message) {
++errorCount;
super.logError(message);
}
public void reportMissingClass(ClassNotFoundException ex) {
String missing = AbstractBugReporter.getMissingClassName(ex);
if (missingClassSet.add(missing))
++missingClassCount;
super.reportMissingClass(ex);
}
}
private static final int PRINTING_REPORTER = 0;
private static final int SORTING_REPORTER = 1;
private static final int XML_REPORTER = 2;
private static final int EMACS_REPORTER = 3;
private static final int HTML_REPORTER = 4;
private static final int XDOCS_REPORTER = 5;
/**
* Helper class to parse the command line and create
* the FindBugs engine object.
*/
private static class FindBugsCommandLine extends CommandLine {
private int bugReporterType = PRINTING_REPORTER;
private String stylesheet = null;
private Project project = new Project();
private boolean quiet = false;
private String filterFile = null;
private boolean include = false;
private boolean setExitCode = false;
private int priorityThreshold = Detector.NORMAL_PRIORITY;
private PrintStream outputStream = null;
public FindBugsCommandLine() {
addOption("-home", "home directory", "specify FindBugs home directory");
addOption("-pluginList", "jar1["+File.pathSeparator+"jar2...]",
"specify list of plugin Jar files to load");
addOption("-quiet", "suppress error messages");
addOption("-low", "report all warnings");
addOption("-medium", "report only medium and high priority warnings [default]");
addOption("-high", "report only high priority warnings");
addOption("-sortByClass", "sort warnings by class");
addOption("-xml", "XML output");
addOption("-xdocs", "xdoc XML output to use with Apache Maven");
addOption("-html", "HTML output using given XSL stylesheet");
addOption("-emacs", "Use emacs reporting format");
addOption("-outputFile", "filename", "Save output in named file");
addOption("-visitors", "v1[,v2...]", "run only named visitors");
addOption("-omitVisitors", "v1[,v2...]", "omit named visitors");
addOption("-bugCategories", "cat1[,cat2...]", "run only detectors that report given categories");
addOption("-exclude", "filter file", "exclude bugs matching given filter");
addOption("-include", "filter file", "include only bugs matching given filter");
addOption("-auxclasspath", "classpath", "set aux classpath for analysis");
addOption("-sourcepath", "source path", "set source path for analyzed classes");
addOption("-project", "project", "analyze given project");
addOption("-exitcode", "set exit code of process");
}
public Project getProject() {
return project;
}
public boolean setExitCode() { return setExitCode; }
public boolean quiet() { return quiet; }
protected void handleOption(String option) {
if (option.equals("-low"))
priorityThreshold = Detector.LOW_PRIORITY;
else if (option.equals("-medium"))
priorityThreshold = Detector.NORMAL_PRIORITY;
else if (option.equals("-high"))
priorityThreshold = Detector.HIGH_PRIORITY;
else if (option.equals("-sortByClass"))
bugReporterType = SORTING_REPORTER;
else if (option.equals("-xml"))
bugReporterType = XML_REPORTER;
else if (option.equals("-emacs"))
bugReporterType = EMACS_REPORTER;
else if (option.equals("-xdocs"))
bugReporterType = XDOCS_REPORTER;
else if (option.equals("-quiet"))
quiet = true;
else if (option.equals("-exitcode"))
setExitCode = true;
else
throw new IllegalStateException();
}
protected void handleOptionWithArgument(String option, String argument) throws IOException {
if (option.equals("-home")) {
FindBugs.setHome(argument);
} else if (option.equals("-pluginList")) {
String pluginListStr = argument;
ArrayList<File> pluginList = new ArrayList<File>();
StringTokenizer tok = new StringTokenizer(pluginListStr, File.pathSeparator);
while (tok.hasMoreTokens()) {
pluginList.add(new File(tok.nextToken()));
}
DetectorFactoryCollection.setPluginList((File[]) pluginList.toArray(new File[0]));
} else if (option.equals("-html")) {
bugReporterType = HTML_REPORTER;
stylesheet = argument;
} else if (option.equals("-outputFile")) {
String outputFile = argument;
try {
outputStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
} catch (IOException e) {
System.err.println("Couldn't open " + outputFile + " for output: " + e.toString());
System.exit(1);
}
} else if (option.equals("-visitors") || option.equals("-omitVisitors")) {
boolean omit = option.equals("-omitVisitors");
if (!omit) {
// Selecting detectors explicitly, so start out by
// disabling all of them. The selected ones will
// be re-enabled.
DetectorFactoryCollection.instance().disableAll();
}
// Explicitly enable or disable the selected detectors.
StringTokenizer tok = new StringTokenizer(argument, ",");
while (tok.hasMoreTokens()) {
String visitorName = tok.nextToken();
DetectorFactory factory = DetectorFactoryCollection.instance().getFactory(visitorName);
if (factory == null)
throw new IllegalArgumentException("Unknown detector: " + visitorName);
factory.setEnabled(!omit);
}
} else if (option.equals("-bugCategories")) {
handleBugCategories(argument);
} else if (option.equals("-exclude") || option.equals("-include")) {
filterFile = argument;
include = option.equals("-include");
} else if (option.equals("-auxclasspath")) {
StringTokenizer tok = new StringTokenizer(argument, File.pathSeparator);
while (tok.hasMoreTokens())
project.addAuxClasspathEntry(tok.nextToken());
} else if (option.equals("-sourcepath")) {
StringTokenizer tok = new StringTokenizer(argument, File.pathSeparator);
while (tok.hasMoreTokens())
project.addSourceDir(new File(tok.nextToken()).getAbsolutePath());
} else if (option.equals("-project")) {
String projectFile = argument;
// Convert project file to be an absolute path
projectFile = new File(projectFile).getAbsolutePath();
try {
project = new Project();
project.read(projectFile);
} catch (IOException e) {
System.err.println("Error opening " + projectFile);
e.printStackTrace(System.err);
throw e;
}
}
}
public FindBugs createEngine() throws IOException, FilterException {
TextUIBugReporter bugReporter = null;
switch (bugReporterType) {
case PRINTING_REPORTER:
bugReporter = new PrintingBugReporter(); break;
case SORTING_REPORTER:
bugReporter = new SortingBugReporter(); break;
case XML_REPORTER:
bugReporter = new XMLBugReporter(project); break;
case EMACS_REPORTER:
bugReporter = new EmacsBugReporter(); break;
case HTML_REPORTER:
bugReporter = new HTMLBugReporter(project, stylesheet); break;
case XDOCS_REPORTER:
bugReporter = new XDocsBugReporter(project); break;
default:
throw new IllegalStateException();
}
if (quiet)
bugReporter.setErrorVerbosity(BugReporter.SILENT);
bugReporter.setPriorityThreshold(priorityThreshold);
if (outputStream != null)
bugReporter.setOutputStream(outputStream);
FindBugs findBugs = new FindBugs(bugReporter, project);
if (filterFile != null)
findBugs.setFilter(filterFile, include);
return findBugs;
}
}
private static final boolean DEBUG = Boolean.getBoolean("findbugs.debug");
/** FindBugs home directory. */
private static String home;
private ErrorCountingBugReporter bugReporter;
private Project project;
private List<ClassObserver> classObserverList;
private Detector detectors [];
private FindBugsProgress progressCallback;
/**
* Constructor.
* @param bugReporter the BugReporter object that will be used to report
* BugInstance objects, analysis errors, class to source mapping, etc.
* @param project the Project indicating which files to analyze and
* the auxiliary classpath to use
*/
public FindBugs(BugReporter bugReporter, Project project) {
if (bugReporter == null)
throw new IllegalArgumentException("null bugReporter");
if (project == null)
throw new IllegalArgumentException("null project");
this.bugReporter = new ErrorCountingBugReporter(bugReporter);
this.project = project;
this.classObserverList = new LinkedList<ClassObserver>();
// Create a no-op progress callback.
this.progressCallback = new FindBugsProgress() {
public void reportNumberOfArchives(int numArchives) { }
public void finishArchive() { }
public void startAnalysis(int numClasses) { }
public void finishClass() { }
public void finishPerClassAnalysis() { }
};
addClassObserver(bugReporter);
}
/**
* Set the progress callback that will be used to keep track
* of the progress of the analysis.
* @param progressCallback the progress callback
*/
public void setProgressCallback(FindBugsProgress progressCallback) {
this.progressCallback = progressCallback;
}
/**
* Set filter of bug instances to include or exclude.
* @param filterFileName the name of the filter file
* @param include true if the filter specifies bug instances to include,
* false if it specifies bug instances to exclude
*/
public void setFilter(String filterFileName, boolean include) throws IOException, FilterException {
Filter filter = new Filter(filterFileName);
BugReporter origBugReporter = bugReporter.getRealBugReporter();
BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, filter, include);
bugReporter.setRealBugReporter(filterBugReporter);
}
/**
* Add a ClassObserver.
* @param classObserver the ClassObserver
*/
public void addClassObserver(ClassObserver classObserver) {
classObserverList.add(classObserver);
}
/**
* Execute FindBugs on the Project.
* All bugs found are reported to the BugReporter object which was set
* when this object was constructed.
* @throws java.io.IOException if an I/O exception occurs analyzing one of the files
* @throws InterruptedException if the thread is interrupted while conducting the analysis
*/
public void execute() throws java.io.IOException, InterruptedException {
// Configure the analysis context
AnalysisContext analysisContext = AnalysisContext.instance();
analysisContext.setLookupFailureCallback(bugReporter);
analysisContext.setSourcePath(project.getSourceDirList());
// Create detectors, if required
if (detectors == null)
createDetectors();
// Clear the repository of classes
clearRepository();
// Get list of files to analyze.
// Note that despite the name getJarFileArray(),
// they can also be zip files, directories,
// and single class files.
String[] argv = project.getJarFileArray();
// Report how many archives/directories/files will be analyzed,
// for progress dialog in GUI
progressCallback.reportNumberOfArchives(argv.length);
// Keep track of the names of all classes to be analyzed
List<String> repositoryClassList = new LinkedList<String>();
// Add all classes in analyzed archives/directories/files
for (int i = 0; i < argv.length; i++) {
addFileToRepository(argv[i], repositoryClassList);
}
// Callback for progress dialog: analysis is starting
progressCallback.startAnalysis(repositoryClassList.size());
// Examine all classes for bugs.
// Don't examine the same class more than once.
// (The user might specify two jar files that contain
// the same class.)
Set<String> examinedClassSet = new HashSet<String>();
for (Iterator<String> i = repositoryClassList.iterator(); i.hasNext(); ) {
String className = i.next();
if (examinedClassSet.add(className))
examineClass(className);
}
// Callback for progress dialog: analysis finished
progressCallback.finishPerClassAnalysis();
// Force any detectors which defer work until all classes have
// been seen to do that work.
this.reportFinal();
// Flush any queued bug reports
bugReporter.finish();
// Flush any queued error reports
bugReporter.reportQueuedErrors();
}
/**
* Get the number of bug instances that were reported during analysis.
*/
public int getBugCount() {
return bugReporter.getBugCount();
}
/**
* Get the number of errors that occurred during analysis.
*/
public int getErrorCount() {
return bugReporter.getErrorCount();
}
/**
* Get the number of time missing classes were reported during analysis.
*/
public int getMissingClassCount() {
return bugReporter.getMissingClassCount();
}
/**
* Set the FindBugs home directory.
*/
public static void setHome(String home) {
FindBugs.home = home;
}
/**
* Get the FindBugs home directory.
*/
public static String getHome() {
if (home == null) {
home = System.getProperty("findbugs.home");
if (home == null) {
System.err.println("Error: The findbugs.home property is not set!");
}
}
return home;
}
/**
* Create Detectors for each DetectorFactory which is enabled.
* This will populate the detectors array.
*/
private void createDetectors() {
ArrayList<Detector> result = new ArrayList<Detector>();
Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator();
int count = 0;
while (i.hasNext()) {
DetectorFactory factory = i.next();
if (factory.isEnabled())
result.add(factory.create(bugReporter));
}
detectors = result.toArray(new Detector[0]);
}
/**
* Clear the Repository and update it to reflect the classpath
* specified by the current project.
*/
private void clearRepository() {
// Purge repository of previous contents
Repository.clearCache();
// Clear the cache in the AnalysisContext.
AnalysisContext.instance().clearCache();
// Clear InnerClassAccessMap cache.
InnerClassAccessMap.instance().clearCache();
// Create a SyntheticRepository based on the current project,
// and make it current.
StringBuffer buf = new StringBuffer();
// Add aux class path entries specified in project
addCollectionToClasspath(project.getAuxClasspathEntryList(), buf);
// Add implicit class path entries determined from project jar files
addCollectionToClasspath(project.getImplicitClasspathEntryList(), buf);
// Add the system classpath entries
buf.append(ClassPath.getClassPath());
if (DEBUG) System.out.println("Using classpath: " + buf);
// Set up the Repository to use the combined classpath
ClassPath classPath = new ClassPath(buf.toString());
SyntheticRepository repository = SyntheticRepository.getInstance(classPath);
Repository.setRepository(repository);
}
/**
* Add the list of classpath entries to the provided buffer.
*
* @param collection the collection of classpath entries to add
*
* @param buf the buffer to which the entries should be added
*/
private void addCollectionToClasspath(Collection collection, StringBuffer buf) {
Iterator i = collection.iterator();
while (i.hasNext()) {
String entry = (String) i.next();
buf.append(entry);
buf.append(File.pathSeparatorChar);
}
}
/**
* Add all classes contained in given file to the BCEL Repository.
* @param fileName the file, which may be a jar/zip archive, a single class file,
* or a directory to be recursively searched for class files
* @param repositoryClassList a List to which all classes found in
* the archive or directory are added, so we later know
* which files to analyze
*/
private void addFileToRepository(String fileName, List<String> repositoryClassList)
throws IOException, InterruptedException {
try {
ClassProducer classProducer;
// Create the ClassProducer
if (fileName.endsWith(".jar") || fileName.endsWith(".zip")
|| fileName.endsWith(".war") || fileName.endsWith(".ear")
|| fileName.endsWith(".sar"))
classProducer = new ZipClassProducer(fileName);
else if (fileName.endsWith(".class"))
classProducer = new SingleClassProducer(fileName);
else {
File dir = new File(fileName);
if (!dir.isDirectory())
throw new IOException("Path " + fileName + " is not an archive, class file, or directory");
classProducer = new DirectoryClassProducer(fileName);
}
// Load all referenced classes into the Repository
for (;;) {
if (Thread.interrupted())
throw new InterruptedException();
try {
JavaClass jclass = classProducer.getNextClass();
if (jclass == null)
break;
if (DEBUG) System.out.println("Scanned " + jclass.getClassName());
Repository.addClass(jclass);
repositoryClassList.add(jclass.getClassName());
} catch (ClassFormatException e) {
e.printStackTrace();
bugReporter.logError(e.getMessage());
}
}
progressCallback.finishArchive();
// If the archive or directory scanned contained source files,
// add it to the end of the source path.
if (classProducer.containsSourceFiles())
project.addSourceDir(fileName);
} catch (IOException e) {
// You'd think that the message for a FileNotFoundException would include
// the filename, but you'd be wrong. So, we'll add it explicitly.
throw new IOException("Could not analyze " + fileName + ": " + e.getMessage());
}
}
/**
* Examine a single class by invoking all of the Detectors on it.
* @param className the fully qualified name of the class to examine
*/
private void examineClass(String className) throws InterruptedException {
if (DEBUG) System.out.println("Examining class " + className);
try {
JavaClass javaClass = Repository.lookupClass(className);
// Notify ClassObservers
for (Iterator<ClassObserver> i = classObserverList.iterator(); i.hasNext(); ) {
i.next().observeClass(javaClass);
}
// Create a ClassContext for the class
ClassContext classContext = AnalysisContext.instance().getClassContext(javaClass);
// Run the Detectors
for (int i = 0; i < detectors.length; ++i) {
if (Thread.interrupted())
throw new InterruptedException();
try {
Detector detector = detectors[i];
if (DEBUG) System.out.println(" running " + detector.getClass().getName());
detector.visitClassContext(classContext);
} catch (AnalysisException e) {
reportRecoverableException(className, e);
} catch (ArrayIndexOutOfBoundsException e) {
reportRecoverableException(className, e);
} catch (ClassCastException e) {
reportRecoverableException(className, e);
}
}
} catch (ClassNotFoundException e) {
// This should never happen unless there are bugs in BCEL.
bugReporter.reportMissingClass(e);
reportRecoverableException(className, e);
} catch (ClassFormatException e) {
reportRecoverableException(className, e);
}
progressCallback.finishClass();
}
private void reportRecoverableException(String className, Exception e) {
if (DEBUG) { e.printStackTrace(); }
bugReporter.logError("Exception analyzing " + className + ": " + e.toString());
}
/**
* Call report() on all detectors, to give them a chance to
* report any accumulated bug reports.
*/
private void reportFinal() throws InterruptedException {
for (int i = 0; i < detectors.length; ++i) {
if (Thread.interrupted())
throw new InterruptedException();
detectors[i].report();
}
}
/**
* Parse the data for a class to create a JavaClass object.
*/
private static JavaClass parseClass(String archiveName, InputStream in, String fileName)
throws IOException {
if (DEBUG) System.out.println("About to parse " + fileName + " in " + archiveName);
return new ClassParser(in, fileName).parse();
}
/**
* Parse the data for a class to create a JavaClass object.
*/
private static JavaClass parseClass(String fileName) throws IOException {
if (DEBUG) System.out.println("About to parse " + fileName);
return new ClassParser(fileName).parse();
}
/**
* Process -bugCategories option.
*/
private static void handleBugCategories(String categories) {
// Parse list of bug categories
HashSet<String> categorySet = new HashSet<String>();
StringTokenizer tok = new StringTokenizer(categories,",");
while (tok.hasMoreTokens()) {
categorySet.add(tok.nextToken());
}
// Enable only those detectors that can emit those categories
// (and the ones that produce unknown bug patterns, just to be safe).
// Skip disabled detectors, though.
for (Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator(); i.hasNext(); ) {
DetectorFactory factory = i.next();
if (!factory.isEnabled())
continue;
Collection<BugPattern> reported = factory.getReportedBugPatterns();
boolean enable = false;
if (reported.isEmpty()) {
// Don't know what bug patterns are produced by this detector
if (DEBUG) System.out.println("Unknown bug patterns for " + factory.getShortName());
enable = true;
} else {
for (Iterator<BugPattern> j = reported.iterator(); j.hasNext(); ) {
BugPattern bugPattern = j.next();
if (categorySet.contains(bugPattern.getCategory())) {
if (DEBUG) System.out.println("MATCH ==> " + categorySet +
" -- " + bugPattern.getCategory());
enable = true;
break;
}
}
}
if (DEBUG && enable) {
System.out.println("Enabling " + factory.getShortName());
}
factory.setEnabled(enable);
}
}
public static void main(String[] argv) {
try {
runMain(argv);
} catch (java.io.IOException e) {
// Probably a missing file
System.err.println("IO Error: " + e.getMessage());
System.exit(1);
} catch (FilterException e) {
System.err.println("Filter exception: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.err.println("Illegal argument: " + e.getMessage());
System.exit(1);
} catch (RuntimeException e) {
System.err.println("Fatal exception: " + e.toString());
e.printStackTrace();
System.err.println("Please report the failure to " + Version.SUPPORT_EMAIL);
System.exit(1);
}
}
private static void runMain(String[] argv)
throws java.io.IOException, RuntimeException, FilterException
{
FindBugsCommandLine commandLine = new FindBugsCommandLine();
int argCount = commandLine.parse(argv);
Project project = commandLine.getProject();
for (int i = argCount; i < argv.length; ++i)
project.addJar(argv[i]);
if (project.getNumJarFiles() == 0) {
System.out.println("FindBugs version " + Version.RELEASE + ", " + Version.WEBSITE);
System.out.println("Usage: findbugs -textui [options...] [jar/zip/class files, directories...]");
System.out.println("Options:");
commandLine.printUsage(System.out);
return;
}
FindBugs findBugs = commandLine.createEngine();
try {
findBugs.execute();
} catch (InterruptedException e) {
// Not possible when running from the command line
}
int bugCount = findBugs.getBugCount();
int missingClassCount = findBugs.getMissingClassCount();
int errorCount = findBugs.getErrorCount();
if (!commandLine.quiet() || commandLine.setExitCode()) {
if (bugCount > 0)
System.err.println("Warnings generated: " + bugCount);
if (missingClassCount > 0)
System.err.println("Missing classes: " + missingClassCount);
if (errorCount > 0)
System.err.println("Analysis errors: " + errorCount);
}
if (commandLine.setExitCode()) {
int exitCode = 0;
if (errorCount > 0)
exitCode |= ERROR_FLAG;
if (missingClassCount > 0)
exitCode |= MISSING_CLASS_FLAG;
if (bugCount > 0)
exitCode |= BUGS_FOUND_FLAG;
System.exit(exitCode);
}
}
}
// vim:ts=4 |
package ca.ualberta.lard;
import ca.ualberta.lard.model.GeoLocation;
import ca.ualberta.lard.model.Picture;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class NewCommentActivity extends Activity {
public final static int LOCATION_REQUEST_ID = 1;
private int pid;
private Picture picture;
private GeoLocation location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the parent id out of the intent
// will be -1 if this is a top level comment
Intent intent = getIntent();
pid = intent.getIntExtra("parentID", -1);
if (pid != -1) {
TextView lardTextView = (TextView) findViewById(R.id.lardTextView); // I am assuming that this is where the "Reply to:" goes
// TODO: Fix this
lardTextView.setText("Reply to: " + pid);
//lardTextView.setText("Reply to: " + CommentController.getCommentName(pid));
}
setContentView(R.layout.activity_new_comment);
}
// Not sure if we even need this function
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_comment, menu);
return true;
}
// Called when the SendButton Button is clicked
// Will do nothing if commentEditText field is empty
// TODO: Finish this function
public void onClickSendButton(View v) {
EditText commentText = (EditText) findViewById(R.id.commentEditText);
if (commentText.getText().toString().isEmpty()) {
return;
}
EditText usernameText = (EditText) findViewById(R.id.usernameEditText);
if (usernameText.getText().toString().isEmpty()) {
String name = "Anonymous";
}
else {
String name = usernameText.getText().toString();
}
// needs comment controller to exist
if (pid == -1) {
// create a top level comment
// CreateComment(commentText.getText().toString(), name, picture, location)
}
else {
// create a reply comment
// CreateComment(commentText.getText().toString(), name, picture, location, pid)
}
finish();
}
// Called when the AttachButton Button is clicked
// TODO: Finish this function
public void onClickAttachButton(View v) {
// needs picture model to exist
// picture = new Picture();
}
// Called when the LocationButton Button is clicked
// Launches the LocationSelectionActivity activity, which will return a GeoLocation that we chose for this comment
public void onClickLocationButton(View v) {
Intent intent = new Intent(this, LocationSelectionActivity.class);
startActivityForResult(intent, LOCATION_REQUEST_ID);
}
// Called when LocationSelectionActivity returns
// Gets the Geolocation data from LocationSelectionActivity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == LOCATION_REQUEST_ID) {
if (resultCode == RESULT_OK) {
String locationData = data.getStringExtra(LocationSelectionActivity.LOCATION_REQUEST);
location = GeoLocation.deserialization(locationData);
}
}
}
public int getPid() {
return pid;
}
public Picture getPicture() {
return picture;
}
public GeoLocation getGeoLocation() {
return location;
}
} |
package inialObservation;
import javax.swing.JOptionPane;
public class FindPrimes {
public static void simplePrimeUpto(int upto) {
//first loop, go through ints
for(int i = 1; i <= upto; i += 2) {
boolean isPrime = true;
//second loop, see if divisible by numbers less than it
for(int j = 2; j < i / 2; j++) {
if(i % j == 0) {
isPrime = false;
break;
}
}
if(isPrime) System.out.println(i);
}
}
public static void main(String[] args) {
int upto = Integer.parseInt(JOptionPane.showInputDialog("Enter a number to go upto"));
simplePrimeUpto(upto);
}
} |
/* CityLookupTest.java */
import com.maxmind.GeoIP.*;
import java.io.IOException;
/* sample of how to use the GeoIP Java API */
/* Usage: java CityLookupTest 64.4.4.4 */
class CityLookupTest {
public static void main(String[] args) {
try {
Lookup cl = new Lookup("/usr/local/share/GeoIP/GeoIPCity.dat");
Location l1 = cl.lookupLocation("213.52.50.8");
Location l2 = cl.lookupLocation(args[0]);
System.out.println("countryCode: " + l2.countryCode +
" countryName: " + l2.countryName +
" city: " + l2.city +
" postalCode: " + l2.postalCode +
" latitude: " + l2.latitude +
" longitude: " + l2.longitude +
" distance: " + l2.distance(l1) +
" distance: " + l1.distance(l2));
cl.close();
}
catch (IOException e) {
System.out.println("IO Exception");
}
}
} |
package com.dmdirc.util.io;
import java.io.InputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class StreamReaderTest {
@Test
public void testGetListDiscarding() throws Exception {
final InputStream inputStream = spy(getClass().getResource("test5.txt").openStream());
final StreamIgnorer streamReader = new StreamIgnorer(inputStream);
streamReader.run();
verify(inputStream, atLeastOnce()).read(any(byte[].class), anyInt(), anyInt());
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.venky.swf.routing;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import com.venky.cache.Cache;
import com.venky.core.log.SWFLogger;
import com.venky.core.string.StringUtil;
import com.venky.core.util.ObjectUtil;
import com.venky.core.util.PackageUtil;
/**
*
* @author venky
*/
public class Config {
private Config(){
properties = new Properties();
Enumeration<URL> propertyFileUrls;
try {
propertyFileUrls = getClass().getClassLoader().getResources("config/swf.properties");
} catch (IOException e) {
throw new RuntimeException(e);
}
resourceBaseurls = new ArrayList<URL>();
while(propertyFileUrls.hasMoreElements()){
URL url = propertyFileUrls.nextElement();
try {
Properties one = new Properties();
one.load((InputStream)url.getContent());
for (Object key : one.keySet()){
String nValue = one.getProperty((String)key);
String oValue = properties.getProperty((String)key);
if (oValue == null){
properties.put(key, nValue);
}else {
properties.put(key, oValue+","+nValue);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
url = new URL(url.toString().substring(0,url.toString().length()-"config/swf.properties".length()));
} catch (MalformedURLException ex) {
throw new RuntimeException(ex);
}
resourceBaseurls.add(url);
}
properties.putAll(System.getProperties());
properties.putAll(System.getenv());
}
private Properties properties;
private static Config _instance ;
public static Config instance(){
if (_instance != null){
return _instance;
}
synchronized (Config.class){
if (_instance == null) {
_instance = new Config();
}
}
return _instance;
}
public static void reset(){
synchronized (Config.class) {
_instance =null;
}
}
public String getHostName(){
return getProperty("swf.host","localhost");
}
public int getPortNumber(){
return Integer.valueOf(getPort());
}
private String getPort(){
return getProperty("swf.port",getProperty("PORT","8080"));
}
private String getExternalPort(){
return getProperty("swf.external.port",getPort());
}
private int getExternalPortNumber(){
if (ObjectUtil.isVoid(getExternalPort())){
return 80;
}else {
return Integer.valueOf(getExternalPort());
}
}
public String getServerBaseUrl(){
StringBuilder url = new StringBuilder().append("http://").append(getHostName());
if (getExternalPortNumber() != 80){
url.append(":").append(getExternalPortNumber());
}
return url.toString();
}
public String getClientId(String opendIdProvider){
return getProperty("swf."+opendIdProvider +".client.id");
}
public String getClientSecret(String opendIdProvider){
return getProperty("swf."+opendIdProvider +".client.secret");
}
private List<URL> resourceBaseurls = null;
public List<URL> getResourceBaseUrls(){
return resourceBaseurls;
}
public String getProperty(String name){
return getProperty(name,null);
}
public String getProperty(String name,String defaultValue){
return properties.getProperty(name, defaultValue);
}
public int getIntProperty(String name){
String sValue = getProperty(name);
return Integer.parseInt(sValue);
}
public int getIntProperty(String name,int defaultValue){
String sValue = getProperty(name, String.valueOf(defaultValue));
return Integer.parseInt(sValue);
}
public boolean getBooleanProperty(String name){
String sValue = getProperty(name);
return Boolean.parseBoolean(sValue);
}
public boolean getBooleanProperty(String name, boolean defaultValue){
String sValue = getProperty(name,String.valueOf(defaultValue));
return Boolean.parseBoolean(sValue);
}
public List<String> getPackageRoots(String rootPackage){
return getPropertyValueList(rootPackage);
}
private static final String MODEL_PACKAGE_ROOT = "swf.db.model.package.root";
public List<String> getModelPackageRoots(){
return getPackageRoots(MODEL_PACKAGE_ROOT);
}
private static final String EXTENSION_PACKAGE_ROOT = "swf.extn.package.root";
public List<String> getExtensionPackageRoots(){
return getPackageRoots(EXTENSION_PACKAGE_ROOT);
}
public List<String> getPropertyKeys(String regEx){
List<String> keys = new ArrayList<String>();
for (Object key: properties.keySet()){
String sKey = StringUtil.valueOf(key);
if (sKey.matches(regEx)) {
keys.add(sKey);
}
}
return keys;
}
private static final String MENU_BUILDER_CLASS = "swf.menu.builder.class";
String getMenuBuilderClassName(){
return properties.getProperty(MENU_BUILDER_CLASS);
}
private Cache<String,List<String>> sNToFQNs = new Cache<String, List<String>>(Cache.MAX_ENTRIES_UNLIMITED,Cache.PRUNE_FACTOR_DEFAULT) {
private static final long serialVersionUID = 8286215452116271529L;
@Override
protected List<String> getValue(String k) {
return new ArrayList<String>();
}
};
private void loadModelClasses(){
if (sNToFQNs.size() > 0){
return ;
}
for (String root : getModelPackageRoots()) {
for (URL url : getResourceBaseUrls()) {
for (String cn: PackageUtil.getClasses(url, root.replace('.', '/'))){
sNToFQNs.get(cn.substring(cn.lastIndexOf('.')+1)).add(cn);
}
}
}
}
public List<String> getModelClasses(String simpleModelName){
loadModelClasses();
return sNToFQNs.get(simpleModelName);
}
public List<String> getModelClasses(){
loadModelClasses();
List<String> modelClasses = new ArrayList<String>();
for (List<String> fQNs : sNToFQNs.values()) {
modelClasses.addAll(fQNs);
}
return modelClasses;
}
private static final String CONFIGURATION_INSTALLERS = "swf.default.configuration.installer";
private List<String> installers = null;
public List<String> getInstallers(){
if (installers == null){
installers = getPropertyValueList(CONFIGURATION_INSTALLERS);
Collections.reverse(installers);// To make sure framework installers are installed first.
}
return installers;
}
private Cache<String,List<String>> propertyValueList = new Cache<String, List<String>>() {
private static final long serialVersionUID = 4415548468945425620L;
@Override
protected List<String> getValue(String name) {
List<String> values = new ArrayList<String>();
StringTokenizer tok = new StringTokenizer(properties.getProperty(name,""),",");
while (tok.hasMoreTokens()) {
values.add(tok.nextToken());
}
return values;
}
};
private List<String> getPropertyValueList(String name){
return propertyValueList.get(name);
}
private Cache<String,SWFLogger> loggers = new Cache<String, SWFLogger>() {
private static final long serialVersionUID = 7431631281937883673L;
@Override
protected SWFLogger getValue(String k) {
return new SWFLogger(Logger.getLogger(k));
}
};
public SWFLogger getLogger(String name){
return loggers.get(name);
}
public boolean isDevelopmentEnvironment(){
String environment = getProperty("swf.env","development");
if ("development".equalsIgnoreCase(environment)){
return true;
}
return false;
}
private Boolean timerAdditive = null;
public boolean isTimerAdditive(){
if (timerAdditive == null){
timerAdditive = Boolean.valueOf(getProperty("swf.timer.additive", "true"));
}
return timerAdditive;
}
public void printStackTrace(Class<?> fromClazz, Throwable th){
StringWriter sw = new StringWriter();
PrintWriter w = new PrintWriter(sw);
if (isDevelopmentEnvironment() || ObjectUtil.isVoid(th.getMessage())){
th.printStackTrace(w);
}else {
w.write(th.getMessage());
}
getLogger(fromClazz.getName()).fine(sw.toString());
}
public Map<String,String> getGeoProviderParams(){
Map<String,String> params =new HashMap<>();
params.put("here.app_id",Config.instance().getProperty("geocoder.here.app_id"));
params.put("here.app_code",Config.instance().getProperty("geocoder.here.app_code"));
params.put("google.api_key",Config.instance().getProperty("geocoder.google.api_key"));
return params;
}
} |
package cz.xtf.core.openshift;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class OpenShiftBinary {
private final String path;
@Getter
private String ocConfigPath;
public OpenShiftBinary(String path) {
this.path = path;
}
public OpenShiftBinary(String path, String ocConfigPath) {
this(path);
this.ocConfigPath = ocConfigPath;
}
public void login(String url, String token) {
this.execute("login", url, "--insecure-skip-tls-verify=true", "--token=" + token);
}
public void login(String url, String username, String password) {
this.execute("login", url, "--insecure-skip-tls-verify=true", "-u", username, "-p", password);
}
/**
* Apply configuration file in the specified namespace.
* Delegates to `oc apply --filename='sourcepath' --namespace='namespace'`
*
* @param sourcePath path to configration file
* @param namespace namespace
*/
public void apply(String namespace, String sourcePath) {
this.execute("apply", "--namespace=" + namespace, "--filename=" + sourcePath);
}
/**
* Apply configuration file. Delegates to `oc apply --filename='sourcepath`
*
* @param sourcePath path to configration file
*/
public void apply(String sourcePath) {
this.execute("apply", "--filename=" + sourcePath);
}
/**
* Apply configuration files in the order they appear in the list
*
* @param sourcePaths list of paths to configuration files
*/
public void apply(List<String> sourcePaths) {
for (String sourcePath : sourcePaths) {
apply(sourcePath);
}
}
/**
* Apply configuration files in the order they appear in the list, using supplied namespace.
*
* @param namespace namespace in which the configuration files should be applied
* @param sourcePaths list of paths to configuration files
*/
public void apply(String namespace, List<String> sourcePaths) {
for (String sourcePath : sourcePaths) {
apply(namespace, sourcePath);
}
}
public void project(String projectName) {
this.execute("project", projectName);
}
public void startBuild(String buildConfig, String sourcePath) {
this.execute("start-build", buildConfig, "--from-dir=" + sourcePath);
}
// Common method for any oc command call
public String execute(String... args) {
if (ocConfigPath == null) {
return executeCommand(ArrayUtils.addAll(new String[] { path }, args));
} else {
return executeCommand(ArrayUtils.addAll(new String[] { path, "--kubeconfig=" + ocConfigPath }, args));
}
}
// Internal
private String executeCommand(String... args) {
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
pb.redirectError(ProcessBuilder.Redirect.PIPE);
try {
Process p = pb.start();
ExecutorService es = Executors.newFixedThreadPool(2);
Future<String> out = es.submit(() -> {
try (InputStream is = p.getInputStream(); StringWriter sw = new StringWriter()) {
IOUtils.copy(is, sw);
return sw.toString();
}
});
Future<String> err = es.submit(() -> {
try (InputStream is = p.getErrorStream(); StringWriter sw = new StringWriter()) {
IOUtils.copy(is, sw);
return sw.toString();
}
});
int result = p.waitFor();
if (result == 0) {
return out.get();
} else {
log.error("Failed while executing (code {}): {}", result, Arrays.toString(args));
log.error(err.get());
}
} catch (IOException | InterruptedException | ExecutionException e) {
log.error("Failed while executing: " + Arrays.toString(args), e);
}
return null;
}
} |
package com.pironet.tda.filter;
import com.pironet.tda.ThreadInfo;
import com.pironet.tda.utils.PrefManager;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.ListModel;
/**
* has a list of filters and checks for a given thread if it matches any of the filters.
* @author irockel
*/
public class FilterChecker {
/**
* filters checked by this checker instance.
*/
private Map filters = null;
private static Map generalFilters = null;
/**
* Creates a new instance of FilterChecker
*/
public FilterChecker(Map checkFilters) {
filters = checkFilters;
}
/**
* return a filter checker for all general filters
*/
public static FilterChecker getFilterChecker() {
if(generalFilters == null) {
setGeneralFilters();
}
return(new FilterChecker(generalFilters));
}
private static void setGeneralFilters() {
generalFilters = new HashMap();
ListModel filters = PrefManager.get().getFilters();
for(int i = 0; i < filters.getSize(); i++) {
Filter currentFilter = (Filter) filters.getElementAt(i);
if(currentFilter.isEnabled() && currentFilter.isGeneralFilter()) {
generalFilters.put(currentFilter.getName(), currentFilter);
}
}
}
/**
* add the given filter to the lists of filters
*/
public void addToFilters(Filter filter) {
if(filters == null) {
filters = new HashMap();
}
filters.put(filter.getName(), filter);
}
/**
* checks if the given thread info passes the filters of
* this filter checker instance
*/
public boolean check(ThreadInfo ti) {
boolean result = true;
Iterator filterIter = filters.values().iterator();
while(result && filterIter.hasNext()) {
Filter filter = (Filter) filterIter.next();
result = filter.matches(ti);
}
return(result);
}
public boolean recheck(ThreadInfo ti) {
// reset general filters
setGeneralFilters();
Iterator iter = filters.values().iterator();
// remove disabled filters
while(iter.hasNext()) {
Filter filter = (Filter) iter.next();
if(!filter.isEnabled()) {
filters.remove(filter.getName());
iter = filters.values().iterator();
}
}
// add new or enabled filters
iter = generalFilters.values().iterator();
while(iter.hasNext()) {
Filter filter = (Filter) iter.next();
addToFilters(filter);
}
return(check(ti));
}
/**
* get iterator on all set filters
*/
public Iterator iterOfFilters() {
return(filters.values().iterator());
}
} |
package jade.imtp.leap.JICP;
import jade.mtp.TransportAddress;
import jade.imtp.leap.*;
import java.io.*;
//#MIDP_EXCLUDE_BEGIN
import java.net.*;
//#MIDP_EXCLUDE_END
/*#MIDP_INCLUDE_BEGIN
import javax.microedition.io.*;
#MIDP_INCLUDE_END*/
import jade.util.Logger;
/**
* Class declaration
* @author Steffen Rusitschka - Siemens
*/
public class JICPConnection extends Connection {
//#MIDP_EXCLUDE_BEGIN
private Socket sc;
//#MIDP_EXCLUDE_END
/*#MIDP_INCLUDE_BEGIN
private StreamConnection sc;
#MIDP_INCLUDE_END*/
private InputStream is;
private OutputStream os;
protected JICPConnection() {
}
/**
* Constructor declaration
*/
public JICPConnection(TransportAddress ta) throws IOException {
//#MIDP_EXCLUDE_BEGIN
// For some reason the local address or port may be in use
while (true) {
try {
sc = new Socket(ta.getHost(), Integer.parseInt(ta.getPort()));
is = sc.getInputStream();
os = getOutputStream();
break;
}
catch (BindException be) {
// Do nothing and try again
}
}
//#MIDP_EXCLUDE_END
/*#MIDP_INCLUDE_BEGIN
String url = "socket://"+ta.getHost()+":"+ta.getPort();
sc = (StreamConnection) Connector.open(url, Connector.READ_WRITE, false);
is = sc.openInputStream();
os = getOutputStream();
#MIDP_INCLUDE_END*/
}
//#MIDP_EXCLUDE_BEGIN
/**
* Constructor declaration
*/
public JICPConnection(Socket s) {
sc = s;
}
//#MIDP_EXCLUDE_END
public JICPPacket readPacket() throws IOException {
if (sc != null) {
if (is == null) {
//#MIDP_EXCLUDE_BEGIN
is = sc.getInputStream();
//#MIDP_EXCLUDE_END
/*#MIDP_INCLUDE_BEGIN
is = sc.openInputStream();
#MIDP_INCLUDE_END*/
}
return JICPPacket.readFrom(is);
}
else {
throw new IOException("Connection closed");
}
}
public int writePacket(JICPPacket pkt) throws IOException {
if (sc != null) {
if (os == null) {
os = getOutputStream();
}
int ret = pkt.writeTo(os);
os.flush();
return ret;
}
else {
throw new IOException("Connection closed");
}
}
private OutputStream getOutputStream() throws IOException {
return new ByteArrayOutputStream() {
private OutputStream realOs = null;
public void flush() throws IOException {
if (realOs == null) {
//#MIDP_EXCLUDE_BEGIN
realOs = sc.getOutputStream();
//#MIDP_EXCLUDE_END
/*#MIDP_INCLUDE_BEGIN
realOs = sc.openOutputStream();
#MIDP_INCLUDE_END*/
}
realOs.write(buf, 0, count);
realOs.flush();
reset();
}
public void close() throws IOException {
super.close();
if (realOs != null) {
realOs.close();
realOs = null;
}
}
};
}
public void close() throws IOException {
try {is.close();} catch(Exception e) {}
is = null;
try {os.close();} catch(Exception e) {}
os = null;
try {sc.close();} catch(Exception e) {}
sc = null;
}
//#MIDP_EXCLUDE_BEGIN
public String getRemoteHost() throws Exception {
return sc.getInetAddress().getHostAddress();
}
//#MIDP_EXCLUDE_END
} |
package hudson.util;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SerializationMethodInvoker;
import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.core.util.Primitives;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Logger;
/**
* Custom {@link ReflectionConverter} that handle errors more gracefully.
*
* <ul>
* <li>If the field is missing, the value is ignored instead of causing an error.
* This makes evolution easy.
* <li>If the type found in XML is no longer available, the element is skipped
* instead of causing an error.
* </ul>
*
*/
public class RobustReflectionConverter implements Converter {
protected final ReflectionProvider reflectionProvider;
protected final Mapper mapper;
protected transient SerializationMethodInvoker serializationMethodInvoker;
private transient ReflectionProvider pureJavaReflectionProvider;
public RobustReflectionConverter(Mapper mapper, ReflectionProvider reflectionProvider) {
this.mapper = mapper;
this.reflectionProvider = reflectionProvider;
serializationMethodInvoker = new SerializationMethodInvoker();
}
public boolean canConvert(Class type) {
return true;
}
public void marshal(Object original, final HierarchicalStreamWriter writer, final MarshallingContext context) {
final Object source = serializationMethodInvoker.callWriteReplace(original);
if (source.getClass() != original.getClass()) {
writer.addAttribute(mapper.aliasForAttribute("resolves-to"), mapper.serializedClass(source.getClass()));
}
doMarshal(source, writer, context);
}
protected void doMarshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
final Set seenFields = new HashSet();
final Set seenAsAttributes = new HashSet();
// Attributes might be preferred to child elements ...
reflectionProvider.visitSerializableFields(source, new ReflectionProvider.Visitor() {
public void visit(String fieldName, Class type, Class definedIn, Object value) {
SingleValueConverter converter = mapper.getConverterFromItemType(fieldName, type);
if (converter == null) {
converter = mapper.getConverterFromItemType(type);
}
if (converter != null) {
if (value != null) {
final String str = converter.toString(value);
if (str != null) {
writer.addAttribute(mapper.aliasForAttribute(fieldName), str);
}
}
seenAsAttributes.add(fieldName);
}
}
});
// Child elements not covered already processed as attributes ...
reflectionProvider.visitSerializableFields(source, new ReflectionProvider.Visitor() {
public void visit(String fieldName, Class fieldType, Class definedIn, Object newObj) {
if (!seenAsAttributes.contains(fieldName) && newObj != null) {
Mapper.ImplicitCollectionMapping mapping = mapper.getImplicitCollectionDefForFieldName(source.getClass(), fieldName);
if (mapping != null) {
if (mapping.getItemFieldName() != null) {
Collection list = (Collection) newObj;
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object obj = iter.next();
writeField(fieldName, mapping.getItemFieldName(), mapping.getItemType(), definedIn, obj);
}
} else {
context.convertAnother(newObj);
}
} else {
writeField(fieldName, fieldName, fieldType, definedIn, newObj);
seenFields.add(fieldName);
}
}
}
private void writeField(String fieldName, String aliasName, Class fieldType, Class definedIn, Object newObj) {
if (!mapper.shouldSerializeMember(definedIn, aliasName)) {
return;
}
ExtendedHierarchicalStreamWriterHelper.startNode(writer, mapper.serializedMember(definedIn, aliasName), fieldType);
Class actualType = newObj.getClass();
Class defaultType = mapper.defaultImplementationOf(fieldType);
if (!actualType.equals(defaultType)) {
writer.addAttribute(mapper.aliasForAttribute("class"), mapper.serializedClass(actualType));
}
if (seenFields.contains(aliasName)) {
writer.addAttribute(mapper.aliasForAttribute("defined-in"), mapper.serializedClass(definedIn));
}
Field field = reflectionProvider.getField(definedIn,fieldName);
marshallField(context, newObj, field);
writer.endNode();
}
});
}
protected void marshallField(final MarshallingContext context, Object newObj, Field field) {
context.convertAnother(newObj);
}
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
Object result = instantiateNewInstance(reader, context);
result = doUnmarshal(result, reader, context);
return serializationMethodInvoker.callReadResolve(result);
}
public Object doUnmarshal(final Object result, final HierarchicalStreamReader reader, final UnmarshallingContext context) {
final SeenFields seenFields = new SeenFields();
Iterator it = reader.getAttributeNames();
// Process attributes before recursing into child elements.
while (it.hasNext()) {
String attrAlias = (String) it.next();
String attrName = mapper.attributeForAlias(attrAlias);
Class classDefiningField = determineWhichClassDefinesField(reader);
boolean fieldExistsInClass = reflectionProvider.fieldDefinedInClass(attrName, result.getClass());
if (fieldExistsInClass) {
SingleValueConverter converter = mapper.getConverterFromAttribute(attrName);
Class type = reflectionProvider.getFieldType(result, attrName, classDefiningField);
if (converter == null) {
converter = mapper.getConverterFromItemType(type);
}
if (converter != null) {
Object value = converter.fromString(reader.getAttribute(attrAlias));
if (type.isPrimitive()) {
type = Primitives.box(type);
}
if (value != null && !type.isAssignableFrom(value.getClass())) {
throw new ConversionException("Cannot convert type " + value.getClass().getName() + " to type " + type.getName());
}
reflectionProvider.writeField(result, attrName, value, classDefiningField);
seenFields.add(classDefiningField, attrName);
}
}
}
Map implicitCollectionsForCurrentObject = null;
while (reader.hasMoreChildren()) {
reader.moveDown();
try {
String fieldName = mapper.realMember(result.getClass(), reader.getNodeName());
boolean implicitCollectionHasSameName = mapper.getImplicitCollectionDefForFieldName(result.getClass(), reader.getNodeName()) != null;
Class classDefiningField = determineWhichClassDefinesField(reader);
boolean fieldExistsInClass = !implicitCollectionHasSameName && reflectionProvider.fieldDefinedInClass(fieldName, result.getClass());
Class type = determineType(reader, fieldExistsInClass, result, fieldName, classDefiningField);
final Object value;
if (fieldExistsInClass) {
Field field = reflectionProvider.getField(result.getClass(),fieldName);
value = unmarshallField(context, result, type, field);
// TODO the reflection provider should have returned the proper field in first place ....
Class definedType = reflectionProvider.getFieldType(result, fieldName, classDefiningField);
if (!definedType.isPrimitive()) {
type = definedType;
}
} else {
value = context.convertAnother(result, type);
}
if (value != null && !type.isAssignableFrom(value.getClass())) {
throw new ConversionException("Cannot convert type " + value.getClass().getName() + " to type " + type.getName());
}
if (fieldExistsInClass) {
reflectionProvider.writeField(result, fieldName, value, classDefiningField);
seenFields.add(classDefiningField, fieldName);
} else {
implicitCollectionsForCurrentObject = writeValueToImplicitCollection(context, value, implicitCollectionsForCurrentObject, result, fieldName);
}
} catch (CannotResolveClassException e) {
LOGGER.log(Level.WARNING,"Skipping a non-existend type",e);
}
reader.moveUp();
}
return result;
}
protected Object unmarshallField(final UnmarshallingContext context, final Object result, Class type, Field field) {
return context.convertAnother(result, type);
}
private Map writeValueToImplicitCollection(UnmarshallingContext context, Object value, Map implicitCollections, Object result, String itemFieldName) {
String fieldName = mapper.getFieldNameForItemTypeAndName(context.getRequiredType(), value.getClass(), itemFieldName);
if (fieldName != null) {
if (implicitCollections == null) {
implicitCollections = new HashMap(); // lazy instantiation
}
Collection collection = (Collection) implicitCollections.get(fieldName);
if (collection == null) {
Class fieldType = mapper.defaultImplementationOf(reflectionProvider.getFieldType(result, fieldName, null));
if (!Collection.class.isAssignableFrom(fieldType)) {
throw new ObjectAccessException("Field " + fieldName + " of " + result.getClass().getName() +
" is configured for an implicit Collection, but field is of type " + fieldType.getName());
}
if (pureJavaReflectionProvider == null) {
pureJavaReflectionProvider = new PureJavaReflectionProvider();
}
collection = (Collection)pureJavaReflectionProvider.newInstance(fieldType);
reflectionProvider.writeField(result, fieldName, collection, null);
implicitCollections.put(fieldName, collection);
}
collection.add(value);
}
return implicitCollections;
}
private Class determineWhichClassDefinesField(HierarchicalStreamReader reader) {
String definedIn = reader.getAttribute(mapper.aliasForAttribute("defined-in"));
return definedIn == null ? null : mapper.realClass(definedIn);
}
protected Object instantiateNewInstance(HierarchicalStreamReader reader, UnmarshallingContext context) {
String readResolveValue = reader.getAttribute(mapper.aliasForAttribute("resolves-to"));
Object currentObject = context.currentObject();
if (currentObject != null) {
return currentObject;
} else if (readResolveValue != null) {
return reflectionProvider.newInstance(mapper.realClass(readResolveValue));
} else {
return reflectionProvider.newInstance(context.getRequiredType());
}
}
private static class SeenFields {
private Set seen = new HashSet();
public void add(Class definedInCls, String fieldName) {
String uniqueKey = fieldName;
if (definedInCls != null) {
uniqueKey += " [" + definedInCls.getName() + "]";
}
if (seen.contains(uniqueKey)) {
throw new DuplicateFieldException(uniqueKey);
} else {
seen.add(uniqueKey);
}
}
}
private Class determineType(HierarchicalStreamReader reader, boolean validField, Object result, String fieldName, Class definedInCls) {
String classAttribute = reader.getAttribute(mapper.aliasForAttribute("class"));
if (classAttribute != null) {
return mapper.realClass(classAttribute);
} else if (!validField) {
Class itemType = mapper.getItemTypeForItemFieldName(result.getClass(), fieldName);
if (itemType != null) {
return itemType;
} else {
return mapper.realClass(reader.getNodeName());
}
} else {
return mapper.defaultImplementationOf(reflectionProvider.getFieldType(result, fieldName, definedInCls));
}
}
private Object readResolve() {
serializationMethodInvoker = new SerializationMethodInvoker();
return this;
}
public static class DuplicateFieldException extends ConversionException {
public DuplicateFieldException(String msg) {
super(msg);
add("duplicate-field", msg);
}
}
private static final Logger LOGGER = Logger.getLogger(RobustReflectionConverter.class.getName());
} |
package io.bitsquare.app;
import ch.qos.logback.classic.Level;
import io.bitsquare.BitsquareException;
import io.bitsquare.btc.BitcoinNetwork;
import io.bitsquare.btc.BtcOptionKeys;
import io.bitsquare.btc.UserAgent;
import io.bitsquare.common.CommonOptionKeys;
import io.bitsquare.common.crypto.KeyStorage;
import io.bitsquare.common.util.Utilities;
import io.bitsquare.dao.blockchain.RpcOptionKeys;
import io.bitsquare.network.NetworkOptionKeys;
import io.bitsquare.storage.Storage;
import io.bitsquare.util.spring.JOptCommandLinePropertySource;
import joptsimple.OptionSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePropertySource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Properties;
import static com.google.common.base.Preconditions.checkNotNull;
public class BitsquareEnvironment extends StandardEnvironment {
private static final Logger log = LoggerFactory.getLogger(BitsquareEnvironment.class);
private static final String BITCOIN_NETWORK_PROP = "bitcoinNetwork.properties";
public static void setDefaultAppName(String defaultAppName) {
DEFAULT_APP_NAME = defaultAppName;
}
public static String DEFAULT_APP_NAME = "Bitsquare";
public static final String DEFAULT_USER_DATA_DIR = defaultUserDataDir();
public static final String DEFAULT_APP_DATA_DIR = appDataDir(DEFAULT_USER_DATA_DIR, DEFAULT_APP_NAME);
//public static final String LOG_LEVEL_DEFAULT = (DevFlags.STRESS_TEST_MODE || DevFlags.DEV_MODE) ? Level.TRACE.levelStr : Level.INFO.levelStr;
public static final String LOG_LEVEL_DEFAULT = Level.INFO.levelStr;
static final String BITSQUARE_COMMANDLINE_PROPERTY_SOURCE_NAME = "bitsquareCommandLineProperties";
static final String BITSQUARE_APP_DIR_PROPERTY_SOURCE_NAME = "bitsquareAppDirProperties";
static final String BITSQUARE_HOME_DIR_PROPERTY_SOURCE_NAME = "bitsquareHomeDirProperties";
public static final String BITSQUARE_CLASSPATH_PROPERTY_SOURCE_NAME = "bitsquareClasspathProperties";
static final String BITSQUARE_DEFAULT_PROPERTY_SOURCE_NAME = "bitsquareDefaultProperties";
private final ResourceLoader resourceLoader = new DefaultResourceLoader();
private final String appName;
private final String userDataDir;
private final String appDataDir;
private final String btcNetworkDir;
private final String logLevel, providers;
private BitcoinNetwork bitcoinNetwork;
private final String btcNodes, seedNodes, ignoreDevMsg, useTorForBtc, rpcUser, rpcPassword, rpcPort, rpcBlockPort, rpcWalletPort,
myAddress, banList, dumpStatistics, maxMemory, socks5ProxyBtcAddress, socks5ProxyHttpAddress;
public BitsquareEnvironment(OptionSet options) {
this(new JOptCommandLinePropertySource(BITSQUARE_COMMANDLINE_PROPERTY_SOURCE_NAME, checkNotNull(
options)));
}
public BitcoinNetwork getBitcoinNetwork() {
return bitcoinNetwork;
}
public void saveBitcoinNetwork(BitcoinNetwork bitcoinNetwork) {
try {
Resource resource = getAppDirPropertiesResource();
File file = resource.getFile();
Properties properties = new Properties();
if (file.exists()) {
Object propertiesObject = appDirProperties().getSource();
if (propertiesObject instanceof Properties) {
properties = (Properties) propertiesObject;
} else {
log.warn("propertiesObject not instance of Properties");
}
}
properties.setProperty(BtcOptionKeys.BTC_NETWORK, bitcoinNetwork.name());
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
properties.store(fileOutputStream, null);
} catch (IOException e1) {
log.error(e1.getMessage());
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
public String getAppDataDir() {
return appDataDir;
}
protected BitsquareEnvironment(PropertySource commandLineProperties) {
logLevel = commandLineProperties.containsProperty(CommonOptionKeys.LOG_LEVEL_KEY) ?
(String) commandLineProperties.getProperty(CommonOptionKeys.LOG_LEVEL_KEY) :
LOG_LEVEL_DEFAULT;
userDataDir = commandLineProperties.containsProperty(AppOptionKeys.USER_DATA_DIR_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.USER_DATA_DIR_KEY) :
DEFAULT_USER_DATA_DIR;
appName = commandLineProperties.containsProperty(AppOptionKeys.APP_NAME_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.APP_NAME_KEY) :
DEFAULT_APP_NAME;
appDataDir = commandLineProperties.containsProperty(AppOptionKeys.APP_DATA_DIR_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.APP_DATA_DIR_KEY) :
appDataDir(userDataDir, appName);
ignoreDevMsg = commandLineProperties.containsProperty(AppOptionKeys.IGNORE_DEV_MSG_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.IGNORE_DEV_MSG_KEY) :
"";
dumpStatistics = commandLineProperties.containsProperty(AppOptionKeys.DUMP_STATISTICS) ?
(String) commandLineProperties.getProperty(AppOptionKeys.DUMP_STATISTICS) :
"";
maxMemory = commandLineProperties.containsProperty(AppOptionKeys.MAX_MEMORY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.MAX_MEMORY) :
"";
providers = commandLineProperties.containsProperty(AppOptionKeys.PROVIDERS) ?
(String) commandLineProperties.getProperty(AppOptionKeys.PROVIDERS) :
"";
seedNodes = commandLineProperties.containsProperty(NetworkOptionKeys.SEED_NODES_KEY) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.SEED_NODES_KEY) :
"";
rpcUser = commandLineProperties.containsProperty(RpcOptionKeys.RPC_USER) ?
(String) commandLineProperties.getProperty(RpcOptionKeys.RPC_USER) :
"";
rpcPassword = commandLineProperties.containsProperty(RpcOptionKeys.RPC_PASSWORD) ?
(String) commandLineProperties.getProperty(RpcOptionKeys.RPC_PASSWORD) :
"";
rpcPort = commandLineProperties.containsProperty(RpcOptionKeys.RPC_PORT) ?
(String) commandLineProperties.getProperty(RpcOptionKeys.RPC_PORT) :
"";
rpcBlockPort = commandLineProperties.containsProperty(RpcOptionKeys.RPC_BLOCK_PORT) ?
(String) commandLineProperties.getProperty(RpcOptionKeys.RPC_BLOCK_PORT) :
"";
rpcWalletPort = commandLineProperties.containsProperty(RpcOptionKeys.RPC_WALLET_PORT) ?
(String) commandLineProperties.getProperty(RpcOptionKeys.RPC_WALLET_PORT) :
"";
myAddress = commandLineProperties.containsProperty(NetworkOptionKeys.MY_ADDRESS) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.MY_ADDRESS) :
"";
banList = commandLineProperties.containsProperty(NetworkOptionKeys.BAN_LIST) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.BAN_LIST) :
"";
socks5ProxyBtcAddress = commandLineProperties.containsProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS) :
"";
socks5ProxyHttpAddress = commandLineProperties.containsProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS) :
"";
btcNodes = commandLineProperties.containsProperty(AppOptionKeys.BTC_NODES) ?
(String) commandLineProperties.getProperty(AppOptionKeys.BTC_NODES) :
"";
useTorForBtc = commandLineProperties.containsProperty(AppOptionKeys.USE_TOR_FOR_BTC) ?
(String) commandLineProperties.getProperty(AppOptionKeys.USE_TOR_FOR_BTC) :
"";
MutablePropertySources propertySources = this.getPropertySources();
propertySources.addFirst(commandLineProperties);
try {
bitcoinNetwork = BitcoinNetwork.valueOf(getProperty(BtcOptionKeys.BTC_NETWORK, BitcoinNetwork.DEFAULT.name()).toUpperCase());
btcNetworkDir = Paths.get(appDataDir, bitcoinNetwork.name().toLowerCase()).toString();
File btcNetworkDirFile = new File(btcNetworkDir);
if (!btcNetworkDirFile.exists())
btcNetworkDirFile.mkdir();
// btcNetworkDir used in defaultProperties
propertySources.addLast(defaultProperties());
} catch (Exception ex) {
throw new BitsquareException(ex);
}
}
private Resource getAppDirPropertiesResource() {
String location = String.format("file:%s/bitsquare.properties", appDataDir);
return resourceLoader.getResource(location);
}
PropertySource<?> appDirProperties() throws Exception {
Resource resource = getAppDirPropertiesResource();
if (!resource.exists())
return new PropertySource.StubPropertySource(BITSQUARE_APP_DIR_PROPERTY_SOURCE_NAME);
return new ResourcePropertySource(BITSQUARE_APP_DIR_PROPERTY_SOURCE_NAME, resource);
}
private PropertySource<?> homeDirProperties() throws Exception {
String location = String.format("file:%s/.bitsquare/bitsquare.properties", getProperty("user.home"));
Resource resource = resourceLoader.getResource(location);
if (!resource.exists())
return new PropertySource.StubPropertySource(BITSQUARE_HOME_DIR_PROPERTY_SOURCE_NAME);
return new ResourcePropertySource(BITSQUARE_HOME_DIR_PROPERTY_SOURCE_NAME, resource);
}
private PropertySource<?> classpathProperties() throws Exception {
Resource resource = resourceLoader.getResource("classpath:bitsquare.properties");
return new ResourcePropertySource(BITSQUARE_CLASSPATH_PROPERTY_SOURCE_NAME, resource);
}
private PropertySource<?> defaultProperties() {
return new PropertiesPropertySource(BITSQUARE_DEFAULT_PROPERTY_SOURCE_NAME, new Properties() {
private static final long serialVersionUID = -8478089705207326165L;
{
setProperty(CommonOptionKeys.LOG_LEVEL_KEY, logLevel);
setProperty(NetworkOptionKeys.SEED_NODES_KEY, seedNodes);
setProperty(NetworkOptionKeys.MY_ADDRESS, myAddress);
setProperty(NetworkOptionKeys.BAN_LIST, banList);
setProperty(NetworkOptionKeys.TOR_DIR, Paths.get(btcNetworkDir, "tor").toString());
setProperty(NetworkOptionKeys.NETWORK_ID, String.valueOf(bitcoinNetwork.ordinal()));
setProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS, socks5ProxyBtcAddress);
setProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS, socks5ProxyHttpAddress);
setProperty(AppOptionKeys.APP_DATA_DIR_KEY, appDataDir);
setProperty(AppOptionKeys.IGNORE_DEV_MSG_KEY, ignoreDevMsg);
setProperty(AppOptionKeys.DUMP_STATISTICS, dumpStatistics);
setProperty(AppOptionKeys.APP_NAME_KEY, appName);
setProperty(AppOptionKeys.MAX_MEMORY, maxMemory);
setProperty(AppOptionKeys.USER_DATA_DIR_KEY, userDataDir);
setProperty(AppOptionKeys.PROVIDERS, providers);
setProperty(RpcOptionKeys.RPC_USER, rpcUser);
setProperty(RpcOptionKeys.RPC_PASSWORD, rpcPassword);
setProperty(RpcOptionKeys.RPC_PORT, rpcPort);
setProperty(RpcOptionKeys.RPC_BLOCK_PORT, rpcBlockPort);
setProperty(RpcOptionKeys.RPC_WALLET_PORT, rpcWalletPort);
setProperty(AppOptionKeys.BTC_NODES, btcNodes);
setProperty(AppOptionKeys.USE_TOR_FOR_BTC, useTorForBtc);
setProperty(UserAgent.NAME_KEY, appName);
setProperty(UserAgent.VERSION_KEY, Version.VERSION);
setProperty(BtcOptionKeys.WALLET_DIR, btcNetworkDir);
setProperty(Storage.DIR_KEY, Paths.get(btcNetworkDir, "db").toString());
setProperty(KeyStorage.DIR_KEY, Paths.get(btcNetworkDir, "keys").toString());
}
});
}
public static String defaultUserDataDir() {
if (Utilities.isWindows())
return System.getenv("APPDATA");
else if (Utilities.isOSX())
return Paths.get(System.getProperty("user.home"), "Library", "Application Support").toString();
else // *nix
return Paths.get(System.getProperty("user.home"), ".local", "share").toString();
}
private static String appDataDir(String userDataDir, String appName) {
return Paths.get(userDataDir, appName).toString();
}
} |
package io.ddf.analytics;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import io.ddf.DDF;
import io.ddf.DDFManager;
import io.ddf.content.Schema.ColumnType;
import io.ddf.exception.DDFException;
import io.ddf.misc.ADDFFunctionalGroupHandler;
import org.apache.commons.lang.StringUtils;
import java.io.Serializable;
import java.util.*;
public abstract class AStatisticsSupporter extends ADDFFunctionalGroupHandler implements ISupportStatistics {
public AStatisticsSupporter(DDF theDDF) {
super(theDDF);
}
private Summary[] basicStats;
private SimpleSummary[] simpleSummary;
protected abstract Summary[] getSummaryImpl() throws DDFException;
protected abstract SimpleSummary[] getSimpleSummaryImpl() throws DDFException;
public Summary[] getSummary() throws DDFException {
this.basicStats = getSummaryImpl();
return basicStats;
}
public SimpleSummary[] getSimpleSummary() throws DDFException {
this.simpleSummary = this.getSimpleSummaryImpl();
return simpleSummary;
}
// This function does many things and thus violates the Do One Thing principle
// TODO: refactor the code to move the engine-specific computation to the corresponding ddf-on-x
@Override public FiveNumSummary[] getFiveNumSummary(List<String> columnNames) throws DDFException {
FiveNumSummary[] fivenums = new FiveNumSummary[columnNames.size()];
List<String> numericColumns = new ArrayList<String>();
// Filter non-numeric columns
for (String columnName : columnNames) {
if (ColumnType.isNumeric(this.getDDF().getColumn(columnName).getType())) {
numericColumns.add(columnName);
}
}
String[] rs = null;
if (numericColumns.size() > 0) {
if (this.getDDF().getEngineType().equals(DDFManager.EngineType.SPARK)) {
List<String> specs = Lists.newArrayList();
for (String columnName : columnNames) {
String query = fiveNumHiveFunction(columnName);
if (query != null && query.length() > 0) {
specs.add(query);
}
}
String command = String.format("SELECT %s FROM %%s", StringUtils.join(specs.toArray(new String[0]), ','));
mLog.info(">>>> command = " + command);
// a fivenumsummary of an Int/Long column is in the format "[min, max, 1st_quantile, median, 3rd_quantile]"
// each value can be a NULL
// a fivenumsummary of an Double/Float column is in the format "min \t max \t[1st_quantile, median, 3rd_quantile]"
// or "min \t max \t null"s
rs = this.getDDF()
.sql(command, String.format("Unable to get fivenum summary of the given columns from table %%s")).getRows()
.get(0).replaceAll("\\[|\\]| ", "").replaceAll(",", "\t").split("\t| ");
} else if (this.getDDF().getEngineType().equals(DDFManager.EngineType.POSTGRES)
|| this.getDDF().getEngineType().equals(DDFManager.EngineType.REDSHIFT)) {
rs = new String[numericColumns.size()*5];
int k = 0;
// Need to separately compute each column's five-num values
// Otherwise, combining all into a query will produce incorrect result in Redshift case
// May be due to the nature of its window functions
for(String column: numericColumns) {
String sql = buildPostgresFiveNumSql(column, this.getDDF().getTableName());
String[] ret = this.getDDF().getManager().sql(sql, this.getDDF().getEngineType().toString()).getRows().get(0).split("\t");
System.arraycopy(ret, 0, rs, k, 5);
k += 5;
}
} else {
throw new DDFException("Unsupported engine");
}
}
int k = 0;
for (int i = 0; i < columnNames.size(); i++) {
if (!numericColumns.contains(columnNames.get(i))) {
fivenums[i] = new FiveNumSummary(Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN);
} else {
fivenums[i] = new FiveNumSummary(parseDouble(rs[5 * k]), parseDouble(rs[5 * k + 1]),
parseDouble(rs[5 * k + 2]),
parseDouble(rs[5 * k + 3]), parseDouble(rs[5 * k + 4]));
k++;
}
}
return fivenums;
}
@Override
public Double[] getVectorVariance(String columnName) throws DDFException {
Double[] sd = new Double[2];
String command = String.format("select var_samp(%s) from @this", columnName);
if (!Strings.isNullOrEmpty(command)) {
List<String> result = this.getDDF()
.sql(command, String.format("Unable to compute the variance of the given column from table %%s")).getRows();
if (result != null && !result.isEmpty() && result.get(0) != null) {
Double a = Double.parseDouble(result.get(0));
sd[0] = a;
sd[1] = Math.sqrt(a);
return sd;
}
}
return null;
}
@Override
public Double getVectorMean(String columnName) throws DDFException {
Double mean = 0.0;
String command = String.format("select avg(%s) from @this", columnName);
if (!Strings.isNullOrEmpty(command)) {
List<String> result = this.getDDF()
.sql(command, String.format("Unable to compute the mean of the given column from table %%s")).getRows();
if (result != null && !result.isEmpty() && result.get(0) != null) {
mean = Double.parseDouble(result.get(0));
return mean;
}
}
return null;
}
@Override
public Double getVectorMin(String columnName) throws DDFException {
Double min = 0.0;
String command = String.format("select min(%s) from @this", columnName);
if (!Strings.isNullOrEmpty(command)) {
List<String> result = this.getDDF()
.sql(command, String.format("Unable to compute the minimum value of the given column from table %%s")).getRows();
if (result != null && !result.isEmpty() && result.get(0) != null) {
min = Double.parseDouble(result.get(0));
return min;
}
}
return null;
}
@Override
public Double getVectorMax(String columnName) throws DDFException {
Double max = 0.0;
String command = String.format("select max(%s) from @this", columnName);
if (!Strings.isNullOrEmpty(command)) {
List<String> result = this.getDDF()
.sql(command, String.format("Unable to compute the maximum value of the given column from table %%s")).getRows();
if (result != null && !result.isEmpty() && result.get(0) != null) {
max = Double.parseDouble(result.get(0));
return max;
}
}
return null;
}
@Override
public double getVectorCor(String xColumnName, String yColumnName) throws DDFException {
double corr = 0.0;
String command = String.format("select corr(%s, %s) from @this", xColumnName, yColumnName);
if (!Strings.isNullOrEmpty(command)) {
List<String> result = this.getDDF().sql(command,
String.format("Unable to compute correlation of %s and %s from table %%s", xColumnName, yColumnName)).getRows();
if (result != null && !result.isEmpty() && result.get(0) != null) {
corr = Double.parseDouble(result.get(0));
return corr;
}
}
return Double.NaN;
}
@Override
public double getVectorCovariance(String xColumnName, String yColumnName) throws DDFException {
double cov = 0.0;
String command = String.format("select covar_samp(%s, %s) from @this", xColumnName, yColumnName);
if (!Strings.isNullOrEmpty(command)) {
List<String> result = this.getDDF().sql(command,
String.format("Unable to compute covariance of %s and %s from table %%s", xColumnName, yColumnName)).getRows();
if (result != null && !result.isEmpty() && result.get(0) != null) {
System.out.println(">>>>> parseDouble: " + result.get(0));
cov = Double.parseDouble(result.get(0));
return cov;
}
}
return Double.NaN;
}
private double parseDouble(String s) {
mLog.info(">>>> parseDouble: " + s);
return ("NULL".equalsIgnoreCase(s.trim())) ? Double.NaN : Double.parseDouble(s);
}
private String buildPostgresFiveNumSql(String columnName, String tableName) {
List<String> minPart = new ArrayList<String>();
List<String> percentilePart = new ArrayList<String>();
String[] quantiles = {"0","1","0.25","0.5","0.75"};
for(int i = 0; i < 5; i++) {
String column = columnName+"_q"+i;
minPart.add(String.format("min(%s) as %s", column, column));
percentilePart.add(String.format("percentile_disc(%s) within group (order by %s) over() as %s", quantiles[i], columnName,column));
}
String sql =
"select %s from \n"
+ "(select %s from (%s) TMP_FIVENUM)";
String query = String
.format(sql, Joiner.on(",").join(minPart), Joiner.on(",").join(percentilePart), this.getDDF().getTableName());
return query;
}
private String fiveNumHiveFunction(String columnName) {
ColumnType colType = this.getDDF().getColumn(columnName).getType();
if(ColumnType.isIntegral(colType))
return String.format("PERCENTILE(%s, array(0, 1, 0.25, 0.5, 0.75))", columnName);
else if(ColumnType.isFractional(colType))
return String.format("MIN(%s), MAX(%s), PERCENTILE_APPROX(%s, array(0.25, 0.5, 0.75))", columnName, columnName,
columnName);
return "";
}
public static class HistogramBin {
private double x; // Bin center
private double y; // Bin weight
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
public static class FiveNumSummary implements Serializable {
private static final long serialVersionUID = 1L;
private double mMin = 0;
private double mMax = 0;
private double mFirst_quantile = 0;
private double mMedian = 0;
private double mThird_quantile = 0;
public FiveNumSummary() {
}
public FiveNumSummary(double mMin, double mMax, double first_quantile, double median, double third_quantile) {
this.mMin = mMin;
this.mMax = mMax;
this.mFirst_quantile = first_quantile;
this.mMedian = median;
this.mThird_quantile = third_quantile;
}
public double getMin() {
return mMin;
}
public void setMin(double mMin) {
this.mMin = mMin;
}
public double getMax() {
return mMax;
}
public void setMax(double mMax) {
this.mMax = mMax;
}
public double getFirstQuantile() {
return mFirst_quantile;
}
public void setFirstQuantile(double mFirst_quantile) {
this.mFirst_quantile = mFirst_quantile;
}
public double getMedian() {
return mMedian;
}
public void setMedian(double mMedian) {
this.mMedian = mMedian;
}
public double getThirdQuantile() {
return mThird_quantile;
}
public void setThirdQuantile(double mThird_quantile) {
this.mThird_quantile = mThird_quantile;
}
}
public Double[] getVectorQuantiles(String columnName, Double[] percentiles) throws DDFException {
return getVectorQuantiles(columnName, percentiles, 10000);
}
public Double[] getVectorQuantiles(String columnName, Double[] percentiles, Integer B) throws DDFException {
if (percentiles == null || percentiles.length == 0) {
throw new DDFException("Cannot compute quantiles for empty percenties");
}
if (Strings.isNullOrEmpty(columnName)) {
throw new DDFException("Column name must not be empty");
}
Set<Double> pSet = new HashSet(Arrays.asList(percentiles));
boolean hasZero = pSet.contains(0.0);
boolean hasOne = pSet.contains(1.0);
pSet.remove(0.0);
pSet.remove(1.0);
List<Double> pList = new ArrayList(pSet);
String pParams = "";
ColumnType columnType = this.getDDF().getColumn(columnName).getType();
mLog.info("Column type: " + columnType.name());
List<String> qmm = new ArrayList<String>();
if (!pList.isEmpty()) {
if (ColumnType.isIntegral(columnType)) {
pParams = "percentile(" + columnName + ", array(" + StringUtils.join(pList, ",") + "))";
} else if (ColumnType.isFractional(columnType)) {
pParams = "percentile_approx(" + columnName + ", array(" + StringUtils.join(pList, ",") + "), " + B.toString()
+ ")";
} else {
throw new DDFException("Only support numeric vectors!!!");
}
qmm.add(pParams);
}
if (hasZero)
qmm.add("min(" + columnName + ")");
if (hasOne)
qmm.add("max(" + columnName + ")");
String cmd = "SELECT " + StringUtils.join(qmm, ", ") + " FROM @this";
mLog.info(">>>>>>>>>>>>>> Command String = " + cmd);
List<String> rs = getDDF().sql(cmd, "Cannot get vector quantiles from SQL queries").getRows();
if (rs == null || rs.size() == 0) {
throw new DDFException("Cannot get vector quantiles from SQL queries");
}
String[] convertedResults = rs.get(0)
.replaceAll("\\[|\\]| ", "").replaceAll(",", "\t")
.replace("null", "NULL, NULL, NULL").split("\t");
mLog.info("Raw info " + StringUtils.join(rs, "\n"));
HashMap<Double, Double> mapValues = new HashMap<Double, Double>();
try {
for (int i = 0; i < pList.size(); i++) {
mapValues.put(pList.get(i), Double.parseDouble(convertedResults[i]));
}
if (hasZero && hasOne) {
mapValues.put(1.0, Double.parseDouble(convertedResults[convertedResults.length - 1]));
mapValues.put(0.0, Double.parseDouble(convertedResults[convertedResults.length - 2]));
} else if (hasOne) {
mapValues.put(1.0, Double.parseDouble(convertedResults[convertedResults.length - 1]));
} else if (hasZero) {
mapValues.put(0.0, Double.parseDouble(convertedResults[convertedResults.length - 1]));
}
} catch (NumberFormatException nfe) {
throw new DDFException("Cannot parse the returned values from vector quantiles query", nfe);
}
Double[] result = new Double[percentiles.length];
for (int i = 0; i < percentiles.length; i++) {
result[i] = mapValues.get(percentiles[i]);
}
return result;
}
} |
package jenkins.model;
import com.google.common.base.Predicate;
import hudson.Extension;
import hudson.Functions;
import hudson.model.Descriptor;
import hudson.model.ManagementLink;
import hudson.security.Permission;
import hudson.util.FormApply;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
@Extension(ordinal = Integer.MAX_VALUE - 220)
public class GlobalToolConfiguration extends ManagementLink {
@Override
public String getIconFileName() {
return "setting.png";
}
@Override
public String getDisplayName() {
return jenkins.management.Messages.ConfigureTools_DisplayName();
}
@Override
public String getDescription() {
return jenkins.management.Messages.ConfigureTools_Description();
}
@Override
public String getUrlName() {
return "configureTools";
}
@Override
public Permission getRequiredPermission() {
return Jenkins.ADMINISTER;
}
public synchronized void doConfigure(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, Descriptor.FormException {
boolean result = configure(req, req.getSubmittedForm());
LOGGER.log(Level.FINE, "tools saved: "+result);
FormApply.success(req.getContextPath() + "/manage").generateResponse(req, rsp, null);
}
private boolean configure(StaplerRequest req, JSONObject json) throws hudson.model.Descriptor.FormException, IOException {
Jenkins j = Jenkins.getInstance();
j.checkPermission(Jenkins.ADMINISTER);
boolean result = true;
for(Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfig(FILTER)){
result &= configureDescriptor(req, json, d);
}
Jenkins.getInstance().save();
return result;
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws Descriptor.FormException {
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
public static Predicate<GlobalConfigurationCategory> FILTER = new Predicate<GlobalConfigurationCategory>() {
public boolean apply(GlobalConfigurationCategory input) {
return input instanceof GlobalConfigurationCategory.Tools;
}
};
private static final Logger LOGGER = Logger.getLogger(GlobalToolConfiguration.class.getName());
} |
package org.mskcc.cbio.portal.servlet;
import org.mskcc.cbio.portal.model.*;
import org.mskcc.cbio.portal.web_api.*;
import org.mskcc.cbio.portal.util.XDebug;
import org.mskcc.cbio.portal.dao.DaoException;
import org.apache.commons.collections15.iterators.IteratorEnumeration;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.mskcc.cbio.portal.util.AccessControl;
import org.mskcc.cbio.portal.util.SpringUtil;
/**
* Central Servlet for Stable LinkOuts.
*/
public class LinkOut extends HttpServlet {
/**
* Handles HTTP GET Request.
*
* @param httpServletRequest Http Servlet Request Object.
* @param httpServletResponse Http Servelt Response Object.
* @throws javax.servlet.ServletException Servlet Error.
* @throws java.io.IOException IO Error.
*/
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException {
doPost(httpServletRequest, httpServletResponse);
}
/**
* Handles HTTP POST Request.
*
* @param httpServletRequest Http Servlet Request Object.
* @param httpServletResponse Http Servelt Response Object.
* @throws javax.servlet.ServletException Servlet Error.
* @throws java.io.IOException IO Error.
*/
protected void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException {
XDebug xdebug = new XDebug(httpServletRequest);
xdebug.startTimer();
PrintWriter writer = httpServletResponse.getWriter();
try {
LinkOutRequest linkOutRequest = new LinkOutRequest(httpServletRequest);
if (linkOutRequest.isIsCrossCancerQuery()) {
handleCrossCancerLink(linkOutRequest, httpServletRequest, httpServletResponse);
} else {
handleStudySpecificLink(linkOutRequest, httpServletRequest, httpServletResponse);
}
} catch (Exception e) {
writer.write("Link out error: " + e.getMessage());
}
}
private void handleCrossCancerLink(LinkOutRequest linkOutRequest,
HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws Exception {
String geneList = linkOutRequest.getGeneList();
ForwardingRequest forwardingRequest = new ForwardingRequest(httpServletRequest);
createCrossCancerForwardingUrl(forwardingRequest, geneList);
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/cross_cancer.do");
dispatcher.forward(forwardingRequest, httpServletResponse);
}
private void createCrossCancerForwardingUrl(ForwardingRequest forwardingRequest, String geneList) {
forwardingRequest.setParameterValue(QueryBuilder.GENE_LIST , geneList);
forwardingRequest.setParameterValue(QueryBuilder.ACTION_NAME, QueryBuilder.ACTION_SUBMIT);
if (forwardingRequest.getParameter(QueryBuilder.CANCER_STUDY_LIST) == null) {
AccessControl accessControl = SpringUtil.getAccessControl();
StringBuilder cancerStudyListBuilder = new StringBuilder();
try {
for (CancerStudy cs: accessControl.getCancerStudies()) {
cancerStudyListBuilder.append(",");
cancerStudyListBuilder.append(cs.getCancerStudyStableId());
}
forwardingRequest.setParameterValue(QueryBuilder.CANCER_STUDY_LIST, cancerStudyListBuilder.substring(1));
forwardingRequest.setParameterValue(QueryBuilder.CANCER_STUDY_ID, "all");
} catch (Exception e) {
}
}
}
private void handleStudySpecificLink(LinkOutRequest linkOutRequest,
HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws Exception {
String cancerStudyId = linkOutRequest.getCancerStudyId();
String output = linkOutRequest.getReport();
String geneList = linkOutRequest.getGeneList();
HashMap<String, GeneticProfile> defaultGeneticProfileSet = getDefaultGeneticProfileSet(cancerStudyId);
PatientList defaultCaseList = getDefaultPatientList(cancerStudyId);
ForwardingRequest forwardingRequest = new ForwardingRequest(httpServletRequest);
createStudySpecificForwardingUrl(forwardingRequest, cancerStudyId, geneList, defaultGeneticProfileSet,
defaultCaseList, output);
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/index.do");
dispatcher.forward(forwardingRequest, httpServletResponse);
}
private void createStudySpecificForwardingUrl(ForwardingRequest forwardingRequest, String cancerStudyId, String geneList,
HashMap<String, GeneticProfile> defaultGeneticProfileSet, PatientList defaultPatientList, String output) {
forwardingRequest.setParameterValue(QueryBuilder.GENE_LIST , geneList);
forwardingRequest.setParameterValue(QueryBuilder.CANCER_STUDY_ID, cancerStudyId);
forwardingRequest.setParameterValue(QueryBuilder.CASE_SET_ID, defaultPatientList.getStableId());
List<String> geneticProfileList = new ArrayList<String>();
for (String geneticProfileId: defaultGeneticProfileSet.keySet()) {
geneticProfileList.add(geneticProfileId);
}
forwardingRequest.setParameterValues(QueryBuilder.GENETIC_PROFILE_IDS,
geneticProfileList.toArray(new String[geneticProfileList.size()]));
forwardingRequest.setParameterValue(QueryBuilder.ACTION_NAME, QueryBuilder.ACTION_SUBMIT);
forwardingRequest.setParameterValue(QueryBuilder.TAB_INDEX, QueryBuilder.TAB_VISUALIZE);
if (output.toLowerCase().equals(LinkOutRequest.REPORT_ONCOPRINT_HTML)) {
forwardingRequest.setParameterValue(QueryBuilder.OUTPUT, "html");
}
}
private PatientList getDefaultPatientList(String cancerStudyId) throws DaoException {
ArrayList<PatientList> patientSetList = GetPatientLists.getPatientLists(cancerStudyId);
AnnotatedPatientSets annotatedPatientSets = new AnnotatedPatientSets(patientSetList);
PatientList defaultPatientList = annotatedPatientSets.getDefaultPatientList();
if (defaultPatientList == null) {
throw new DaoException("Could not determine patient set for: " + cancerStudyId);
}
return defaultPatientList;
}
private HashMap<String, GeneticProfile> getDefaultGeneticProfileSet(String cancerStudyId) throws DaoException {
ArrayList<GeneticProfile> geneticProfileList = GetGeneticProfiles.getGeneticProfiles (cancerStudyId);
CategorizedGeneticProfileSet categorizedGeneticProfileSet =
new CategorizedGeneticProfileSet(geneticProfileList);
return categorizedGeneticProfileSet.getDefaultMutationAndCopyNumberMap();
}
}
// Forwarding Request, so that we can clear out all request parameters.
class ForwardingRequest extends HttpServletRequestWrapper {
private Map<String, String[]> parameterMap = new HashMap<String, String[]>();
public ForwardingRequest(HttpServletRequest request) {
super(request);
}
public Map getParameterMap() {
return parameterMap;
}
public void setParameterValue(String key, String value) {
String values[] = new String[1];
values[0] = value;
parameterMap.put(key, values);
}
public void setParameterValues(String key, String[] values) {
parameterMap.put(key, values);
}
public Enumeration getParameterNames() {
return new IteratorEnumeration(parameterMap.keySet().iterator());
}
public String getParameter(String s) {
String values[] = parameterMap.get(s);
if (values != null && values.length > 0) {
return values[0];
} else {
return null;
}
}
public String[] getParameterValues(String s) {
return parameterMap.get(s);
}
} |
package org.verapdf.pdfa.validation;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.ScriptableObject;
import org.verapdf.core.ValidationException;
import org.verapdf.model.baselayer.Object;
import org.verapdf.pdfa.flavours.PDFAFlavour;
import org.verapdf.pdfa.results.Location;
import org.verapdf.pdfa.results.TestAssertion;
import org.verapdf.pdfa.results.TestAssertion.Status;
import org.verapdf.pdfa.results.ValidationResult;
import org.verapdf.pdfa.results.ValidationResults;
/**
* Validation logic
*
* @author Maksim Bezrukov
*/
public class Validator {
private static final int OPTIMIZATION_LEVEL = 9;
private static ProfileDirectory PROFILES = Profiles
.getVeraProfileDirectory();
private Context context;
private ScriptableObject scope;
private final Deque<Object> objectsStack = new ArrayDeque<>();
private final Deque<String> objectsContext = new ArrayDeque<>();
private final Deque<Set<String>> contextSet = new ArrayDeque<>();
private final Set<TestAssertion> results = new HashSet<>();
private Map<RuleId, Script> ruleScripts = new HashMap<>();
private Map<String, Script> variableScripts = new HashMap<>();
private Set<String> idSet = new HashSet<>();
private String rootType;
private ValidationProfile profile;
private final boolean logPassedAssertions;
/**
* Creates new Validator with given validation profile
*
* @param profile
* validation profile model for validator
*/
private Validator(final PDFAFlavour flavour, final boolean logPassedAssertions) {
this(PROFILES.getValidationProfileByFlavour(flavour), logPassedAssertions);
}
private Validator(final ValidationProfile profile, final boolean logPassedAssertions) {
super();
this.profile = profile;
this.logPassedAssertions = logPassedAssertions;
}
private ValidationResult validate(Object root) throws ValidationException {
initialize();
this.rootType = root.getObjectType();
this.objectsStack.push(root);
this.objectsContext.push("root");
Set<String> rootIDContext = new HashSet<>();
if (root.getID() != null) {
rootIDContext.add(root.getID());
this.idSet.add(root.getID());
}
this.contextSet.push(rootIDContext);
while (!this.objectsStack.isEmpty()) {
checkNext();
}
Context.exit();
return ValidationResults.resultFromValues(this.profile.getPDFAFlavour(), this.results);
}
private void initialize() {
this.context = Context.enter();
this.context.setOptimizationLevel(OPTIMIZATION_LEVEL);
this.scope = this.context.initStandardObjects();
this.objectsStack.clear();
this.objectsContext.clear();
this.contextSet.clear();
this.results.clear();
this.idSet.clear();
initializeAllVariables();
}
private void initializeAllVariables() {
for (Variable var : this.profile.getVariables()) {
if (var == null)
continue;
java.lang.Object res;
res = this.context.evaluateString(this.scope,
var.getDefaultValue(), null, 0, null);
if (res instanceof NativeJavaObject) {
res = ((NativeJavaObject) res).unwrap();
}
this.scope.put(var.getName(), this.scope, res);
}
}
private boolean checkNext() throws ValidationException,
ValidationException, ValidationException {
Object checkObject = this.objectsStack.pop();
String checkContext = this.objectsContext.pop();
Set<String> checkIDContext = this.contextSet.pop();
boolean res = checkAllRules(checkObject, checkContext);
updateVariables(checkObject);
addAllLinkedObjects(checkObject, checkContext, checkIDContext);
return res;
}
private void updateVariables(Object object) {
if (object != null) {
for (Variable var :this.profile
.getVariablesByObject(object.getObjectType())) {
if (var == null)
continue;
java.lang.Object variable = evalVariableResult(var, object);
this.scope.put(var.getName(), this.scope, variable);
}
}
}
private java.lang.Object evalVariableResult(Variable variable, Object object) {
Script script;
if (!this.variableScripts.containsKey(variable.getName())) {
String source = getStringScript(object, variable.getValue());
script = this.context.compileString(source, null, 0, null);
} else {
script = this.variableScripts.get(variable.getName());
}
this.scope.put("obj", this.scope, object);
java.lang.Object res = script.exec(this.context, this.scope);
if (res instanceof NativeJavaObject) {
res = ((NativeJavaObject) res).unwrap();
}
return res;
}
private void addAllLinkedObjects(Object checkObject, String checkContext,
Set<String> checkIDContext) throws ValidationException,
ValidationException, ValidationException {
List<String> links = checkObject.getLinks();
for (int j = links.size() - 1; j >= 0; --j) {
String link = links.get(j);
if (link == null) {
throw new ValidationException(
"There is a null link name in an object. Context: "
+ checkContext);
}
List<? extends Object> objects = checkObject.getLinkedObjects(link);
if (objects == null) {
throw new ValidationException(
"There is a null link in an object. Context: "
+ checkContext);
}
for (int i = 0; i < objects.size(); ++i) {
Object obj = objects.get(i);
StringBuilder path = new StringBuilder(checkContext);
path.append("/");
path.append(link);
path.append("[");
path.append(i);
path.append("]");
if (obj == null) {
throw new ValidationException(
"There is a null link in an object. Context of the link: "
+ path);
}
if (checkRequired(obj, checkIDContext)) {
this.objectsStack.push(obj);
Set<String> newCheckIDContext = new HashSet<>(
checkIDContext);
if (obj.getID() != null) {
path.append("(");
path.append(obj.getID());
path.append(")");
newCheckIDContext.add(obj.getID());
this.idSet.add(obj.getID());
}
this.objectsContext.push(path.toString());
this.contextSet.push(newCheckIDContext);
}
}
}
}
private boolean checkRequired(Object obj, Set<String> checkIDContext) {
if (obj.getID() == null) {
return true;
} else if (obj.isContextDependent() == null
|| obj.isContextDependent().booleanValue()) {
return !checkIDContext.contains(obj.getID());
} else {
return !this.idSet.contains(obj.getID());
}
}
private boolean checkAllRules(Object checkObject, String checkContext) {
boolean res = true;
Set<Rule> roolsForObject = this.profile.getRulesByObject(
checkObject.getObjectType());
for (Rule rule : roolsForObject) {
res &= checkObjWithRule(checkObject, checkContext, rule);
}
for (String checkType : checkObject.getSuperTypes()) {
roolsForObject = this.profile.getRulesByObject(checkType);
if (roolsForObject != null) {
for (Rule rule : roolsForObject) {
if (rule != null) {
res &= checkObjWithRule(checkObject, checkContext, rule);
}
}
}
}
return res;
}
private static String getScript(Object obj, Rule rule) {
return getStringScript(obj, "(" + rule.getTest() + ")==true");
}
private static String getStringScript(Object obj, String arg) {
return getScriptPrefix(obj, arg) + arg + getScriptSuffix();
}
private static String getScriptPrefix(Object obj, String test) {
StringBuilder builder = new StringBuilder();
String[] vars = test.split("\\W");
for (String prop : obj.getProperties()) {
if (contains(vars, prop)) {
builder.append("var ");
builder.append(prop);
builder.append(" = obj.get");
builder.append(prop);
builder.append("();\n");
}
}
for (String linkName : obj.getLinks()) {
if (contains(vars, linkName + "_size")) {
builder.append("var ");
builder.append(linkName);
builder.append("_size = obj.getLinkedObjects(\"");
builder.append(linkName);
builder.append("\").size();\n");
}
}
builder.append("function test(){return ");
return builder.toString();
}
private static boolean contains(String[] values, String prop) {
for (String value : values) {
if (value.equals(prop)) {
return true;
}
}
return false;
}
private static String getScriptSuffix() {
return ";}\ntest();";
}
private boolean checkObjWithRule(Object obj, String cntxtForRule, Rule rule) {
this.scope.put("obj", this.scope, obj);
Script scr;
if (!this.ruleScripts.containsKey(rule.getRuleId())) {
scr = this.context.compileString(getScript(obj, rule), null, 0,
null);
this.ruleScripts.put(rule.getRuleId(), scr);
} else {
scr = this.ruleScripts.get(rule.getRuleId());
}
boolean testEvalResult = false;
testEvalResult = ((Boolean) scr.exec(this.context, this.scope))
.booleanValue();
Status assertionStatus = (testEvalResult) ? Status.PASSED
: Status.FAILED;
Location location = ValidationResults.locationFromValues(this.rootType,
cntxtForRule);
TestAssertion assertion = ValidationResults.assertionFromValues(
rule.getRuleId(), assertionStatus,
rule.getError().getMessage(), location);
if ((assertionStatus == Status.FAILED) || this.logPassedAssertions) {
this.results.add(assertion);
}
return testEvalResult;
}
/**
* Generates validation info for objects with root {@code root} and
* validation profile structure {@code validationProfile}
* <p/>
* This method doesn't need to parse validation profile (it works faster
* than those ones, which parses profile).
*
* @param flavour
*
* @param root
* the root object for validation
* @return validation info structure
* @throws ValidationException
* when a problem occurs validating the PDF
*/
public static ValidationResult validate(PDFAFlavour flavour, Object root, boolean logSuccess)
throws ValidationException {
if (root == null)
throw new IllegalArgumentException(
"Parameter (Object root) cannot be null.");
if (flavour == null)
throw new IllegalArgumentException(
"Parameter (PDFAFlavour flavour) cannot be null.");
Validator validator = new Validator(flavour, logSuccess);
ValidationResult res = validator.validate(root);
return res;
}
/**
* Generates validation info for objects with root {@code root} and
* validation profile structure {@code validationProfile}
* <p/>
* This method doesn't need to parse validation profile (it works faster
* than those ones, which parses profile).
*
* @param profile
*
* @param root
* the root object for validation
* @param logSuccess
* @return validation info structure
* @throws ValidationException
* when a problem occurs validating the PDF
*/
public static ValidationResult validate(final ValidationProfile profile, final Object root, boolean logSuccess)
throws ValidationException {
if (root == null)
throw new IllegalArgumentException(
"Parameter (Object root) cannot be null.");
if (profile == null)
throw new IllegalArgumentException(
"Parameter (ValidationProfile profile) cannot be null.");
Validator validator = new Validator(profile, logSuccess);
ValidationResult res = validator.validate(root);
return res;
}
} |
package at.fhj.itm.pswe.unittest.dao;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.easymock.EasyMock;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import at.fhj.itm.pswe.dao.WebsiteDao;
import at.fhj.itm.pswe.dao.WordDao;
import at.fhj.itm.pswe.model.Website;
public class WebsiteMockTest {
@Test
public void testdeleteWebsite(){
//SETUP
Website w=new Website();
w.setId(1);
w.setDomain("http://test.at");
w.setActive(true);
w.setDescription("Test");
WebsiteDao wDao=new WebsiteDao();
EntityManager mockEm = createMock(EntityManager.class);
expect(mockEm.find(Website.class, w.getId())).andReturn(w);
mockEm.remove(w);
EasyMock.expectLastCall().once();
mockEm.flush();
EasyMock.expectLastCall().once();
replay(mockEm);
wDao.setEntityManager(mockEm);
//TEST SETUP
wDao.deleteWebsite(1);
//VERIFY
verify(mockEm);
}
@Test
public void testcreateWebsite(){
Website w = new Website();
w.setDomain("http://test.at");
w.setDescription("Test");
w.setCrawldepth(1);
w.setActive(true);
w.setLast_crawldate("1970-01-01");
w.setId(1);
EntityManager mockEm = EasyMock.createMock(EntityManager.class);
mockEm.persist(w);
EasyMock.expectLastCall();
//set to replay state
replay(mockEm);
//Set Mock Object
WebsiteDao wDao=new WebsiteDao();
wDao.setEntityManager(mockEm);
//TEST
Website result = wDao.createWebsite("http://test.at", "Test", 1);
//Verify
verify(mockEm);
}
@Test
public void testreadWebsite(){
//SETUP
Website w=new Website();
w.setId(1);
w.setDomain("http://test.at");
w.setActive(true);
w.setDescription("Test");
w.setLast_crawldate("2015-05-05");
List<Object[]> returnList = new ArrayList<Object[]>();
Object[] retArr= new Object[5];
retArr[0]=w.getId();
retArr[1]=w.getDomain();
retArr[2]=w.getLast_crawldate();
retArr[3]=w.getDescription();
retArr[4]=1;
returnList.add(retArr);
//QueryMock
Query mockedQuery = createMock(Query.class);
expect(mockedQuery.setParameter("url", w.getDomain())).andReturn(mockedQuery);
expect(mockedQuery.getResultList()).andReturn(returnList);
replay(mockedQuery);
EntityManager mockEm = createMock(EntityManager.class);
expect(mockEm.createQuery(
"SELECT ws.id, ws.domain, ws.last_crawl_date, ws.description, ws.active FROM Website ws WHERE ws.domain = :url")
).andReturn(mockedQuery);
replay(mockEm);
WebsiteDao wDao=new WebsiteDao();
wDao.setEntityManager(mockEm);
//TEST SETUP
wDao.readWebsite(w.getDomain());
//VERIFY
verify(mockEm);
}
@Test
public void testfindAllWebsites(){
//SETUP
List<Website> expected = new ArrayList<>();
Website w = new Website();
w.setId(1);
w.setDomain("http://test.at");
w.setActive(true);
w.setDescription("Test");
w.setLast_crawldate("2015-05-05");
expected.add(w);
//QueryMock
TypedQuery<Website> mockedQuery = createMock(TypedQuery.class);
expect(mockedQuery.getResultList()).andReturn(expected);
replay(mockedQuery);
EntityManager mockEm = createMock(EntityManager.class);
expect(mockEm.createQuery(
"SELECT DISTINCT w FROM Website w ORDER BY w.id", Website.class)
).andReturn(mockedQuery);
replay(mockEm);
WebsiteDao wDao=new WebsiteDao();
wDao.setEntityManager(mockEm);
//TEST SETUP
wDao.findAllWebsites();
//VERIFY
verify(mockEm);
}
@Test
public void testfindAllWebsitesJSON(){
//Setup JSON
long id = 1;
String address = "test.at";
String description = "Testseite";
boolean active = true;
String lCrawled = "2015-05-05";
int depth = 2;
JSONObject validatorObject= new JSONObject();
validatorObject.put("id", id);
validatorObject.put("address", address);
validatorObject.put("description", description);
validatorObject.put("active", active);
validatorObject.put("lCrawled", lCrawled);
validatorObject.put("depth", depth);
JSONArray validator= new JSONArray();
validator.put(validatorObject);
//SETUP Website
List<Website> expected = new ArrayList<>();
Website w = new Website();
w.setId(1);
w.setDomain("test.at");
w.setActive(true);
w.setDescription("Testseite");
w.setLast_crawldate("2015-05-05");
w.setCrawldepth(2);
expected.add(w);
//QueryMock
TypedQuery<Website> mockedQuery = createMock(TypedQuery.class);
expect(mockedQuery.getResultList()).andReturn(expected);
replay(mockedQuery);
EntityManager mockEm = createMock(EntityManager.class);
expect(mockEm.createQuery(
"SELECT DISTINCT w FROM Website w ORDER BY w.id", Website.class)
).andReturn(mockedQuery);
replay(mockEm);
WebsiteDao wDao=new WebsiteDao();
wDao.setEntityManager(mockEm);
//TEST SETUP
JSONArray testResult = wDao.findAllWebsitesJSON();
verify(mockEm);
Assert.assertEquals(validator.toString(),testResult.toString());
}
} |
package org.swellrt.api.js;
import com.google.gwt.core.client.JavaScriptObject;
import org.swellrt.api.WaveClient;
public class WaveClientJS extends JavaScriptObject {
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String READY = "ready";
public static final String ITEM_CHANGED = "item-changed";
public static final String ITEM_ADDED = "item-added";
public static final String ITEM_REMOVED = "item-removed";
public static final String PARTICIPANT_ADDED = "participant-added";
public static final String PARTICIPANT_REMOVED = "participant-removed";
public static final String DATA_STATUS_CHANGED = "data-status-changed";
public static final String NETWORK_DISCONNECTED = "network-disconnected";
public static final String NETWORK_CONNECTED = "network-connected";
public static final String NETWORK_CLOSED = "network-closed";
/** This shouldn't be used. Just for debugging purpose */
public static final String FATAL_EXCEPTION = "exception";
public static final String METHOD_START_SESSION = "startSession";
public static final String METHOD_OPEN_MODEL = "openModel";
public static final String METHOD_CREATE_MODEL = "createModel";
/**
* The JS Wave Client main interface. Backed by WaveClient
*
* Design ideas are:
*
* <li>Multiple waves opened simultaneously</li> <li>Multiple collaborative
* contents in a wave</li> <li>Provide UI for complex contents (e.g. text
* editor), hook in a DOM element</i>
*
*/
protected WaveClientJS() {
}
public final native void triggerEvent(String event, Object parameter) /*-{
if (Array.isArray(this.handlers[event])) {
for (var i = 0; i < this.handlers[event].length; i++) {
this.handlers[event][i](parameter);
}
}
}-*/;
} |
package uk.ac.ebi;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.support.ErrorPageFilter;
import org.springframework.context.annotation.*;
import org.springframework.http.CacheControl;
import org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import uk.ac.ebi.phenotype.web.util.DeploymentInterceptor;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Configuration
@ComponentScan(value = {"uk.ac.ebi",
"org.mousephenotype.cda.solr",
"org.mousephenotype.cda.utilities",
"org.mousephenotype.cda.db",
"uk.ac.ebi.phenotype.web.controller"},
excludeFilters = @ComponentScan.Filter(value = org.mousephenotype.cda.annotations.ComponentScanNonParticipant.class, type = FilterType.ANNOTATION))
@PropertySource("file:${user.home}/configfiles/${profile:dev}/application.properties")
@EnableScheduling
public class PhenotypeArchiveConfig {
private static final Logger logger = LoggerFactory.getLogger(PhenotypeArchiveConfig.class);
@Value("${drupal_base_url}")
private String drupalBaseUrl;
@Value("${solr_url}")
private String solrUrl;
@Value("${base_url}")
private String baseUrl;
@Value("${internal_solr_url}")
private String internalSolrUrl;
@Value("${media_base_url}")
private String mediaBaseUrl;
@Value("${impc_media_base_url}")
private String impcMediaBaseUrl;
@Value("${monarch_url}")
private String monarchUrl;
@Value("${pdf_thumbnail_url}")
private String pdfThumbnailUrl;
@Value("${google_analytics}")
private String googleAnalytics;
@Value("${live_site}")
private String liveSite;
@NotNull
@Value("${paBaseUrl}")
private String paBaseUrl;
@Bean
public ErrorPageFilter errorPageFilter() {
return new ErrorPageFilter();
}
@Bean
public FilterRegistrationBean disableSpringBootErrorFilter(ErrorPageFilter filter) {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(filter);
filterRegistrationBean.setEnabled(false);
return filterRegistrationBean;
}
@Bean(name = "globalConfiguration")
public Map<String, String> getGlobalConfig() {
Map<String, String> map = new HashMap<>();
map.put("baseUrl", baseUrl);
map.put("drupalBaseUrl", drupalBaseUrl);
map.put("solrUrl", solrUrl);
map.put("internalSolrUrl", internalSolrUrl);
map.put("mediaBaseUrl", mediaBaseUrl);
map.put("impcMediaBaseUrl", impcMediaBaseUrl);
map.put("monarchUrl", monarchUrl);
map.put("pdfThumbnailUrl", pdfThumbnailUrl);
map.put("googleAnalytics", googleAnalytics);
map.put("liveSite", liveSite);
map.put("paBaseUrl", paBaseUrl);
return map;
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver =
new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
OpenSessionInViewInterceptor getOpenSessionInViewInterceptor(SessionFactory session){
OpenSessionInViewInterceptor openSessionInViewInterceptor = new OpenSessionInViewInterceptor();
openSessionInViewInterceptor.setSessionFactory(session);
return openSessionInViewInterceptor;
}
@Bean
public WebMvcConfigurerAdapter adapter() {
return new WebMvcConfigurerAdapter() {
@Autowired
DeploymentInterceptor deploymentInterceptor;
// @Autowired
// OpenSessionInViewInterceptor openSessionInViewInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(deploymentInterceptor);
// registry.addInterceptor(openSessionInViewInterceptor);
super.addInterceptors(registry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.info("Adding WebMvc resources"); |
package armitage;
import sleep.runtime.*;
import sleep.interfaces.*;
import sleep.console.*;
import sleep.bridges.*;
import sleep.error.*;
import sleep.engine.*;
import java.util.*;
import java.io.*;
/**
* This class launches Armitage and loads the scripts that are part of it.
*/
public class ArmitageMain implements RuntimeWarningWatcher, Loadable, Function {
public void processScriptWarning(ScriptWarning warning) {
System.out.println(warning);
}
public Scalar evaluate(String name, ScriptInstance script, Stack args) {
try {
InputStream i = this.getClass().getClassLoader().getResourceAsStream(BridgeUtilities.getString(args, ""));
return SleepUtils.getScalar(i);
}
catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
protected ScriptVariables variables = new ScriptVariables();
public void scriptLoaded(ScriptInstance script) {
script.addWarningWatcher(this);
script.setScriptVariables(variables);
}
public void scriptUnloaded(ScriptInstance script) {
}
protected String[] getGUIScripts() {
return new String[] {
"scripts/log.sl",
"scripts/gui.sl",
"scripts/util.sl",
"scripts/targets.sl",
"scripts/attacks.sl",
"scripts/meterpreter.sl",
"scripts/process.sl",
"scripts/browser.sl",
"scripts/pivots.sl",
"scripts/services.sl",
"scripts/loot.sl",
"scripts/downloads.sl",
"scripts/shell.sl",
"scripts/screenshot.sl",
"scripts/hosts.sl",
"scripts/passhash.sl",
"scripts/jobs.sl",
"scripts/preferences.sl",
"scripts/modules.sl",
"scripts/menus.sl",
"scripts/collaborate.sl",
"scripts/armitage.sl"
};
}
protected String[] getServerScripts() {
return new String[] {
"scripts/util.sl",
"scripts/preferences.sl",
"scripts/server.sl"
};
}
public ArmitageMain(String[] args) {
Hashtable environment = new Hashtable();
environment.put("&resource", this);
/* set our command line arguments into a var */
variables.putScalar("@ARGV", ObjectUtilities.BuildScalar(false, args));
ScriptLoader loader = new ScriptLoader();
loader.addSpecificBridge(this);
/* check for server mode option */
boolean serverMode = false;
int x = 0;
for (x = 0; x < args.length; x++) {
if (args[x].equals("--server"))
serverMode = true;
}
/* load the appropriate scripts */
String[] scripts = serverMode ? getServerScripts() : getGUIScripts();
try {
for (x = 0; x < scripts.length; x++) {
InputStream i = this.getClass().getClassLoader().getResourceAsStream(scripts[x]);
ScriptInstance si = loader.loadScript(scripts[x], i, environment);
si.runScript();
}
}
catch (YourCodeSucksException yex) {
System.out.println("*** File: " + scripts[x]);
yex.printErrors(System.out);
}
catch (IOException ex) {
System.err.println(ex);
ex.printStackTrace();
}
}
public static void main(String args[]) {
new ArmitageMain(args);
}
} |
package com.thoughtworks.xstream.io.xml;
import com.megginson.sax.DataWriter;
import com.thoughtworks.acceptance.someobjects.X;
import com.thoughtworks.acceptance.someobjects.Y;
import com.thoughtworks.xstream.XStream;
import junit.framework.TestCase;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/*
* @author Laurent Bihanic
*/
public class SaxWriterTest extends TestCase {
private final static String IDENTITY_STYLESHEET =
"<xsl:stylesheet version=\"1.0\"" +
" xmlns:xsl=\"http:
"\n" +
" <xsl:output method=\"xml\"" +
" omit-xml-declaration=\"yes\" indent=\"no\"/>\n" +
"\n" +
" <xsl:template" +
" match=\"*|@*|comment()|processing-instruction()|text()\">\n" +
" <xsl:copy>\n" +
" <xsl:apply-templates" +
" select=\"*|@*|comment()|processing-instruction()|text()\"/>\n" +
" </xsl:copy>\n" +
" </xsl:template>\n" +
"</xsl:stylesheet>";
private XStream xstream;
private X testInput;
private Templates identityStylesheet;
protected void setUp() throws Exception {
super.setUp();
xstream = new XStream();
xstream.alias("x", X.class);
xstream.alias("y", Y.class);
testInput = new X();
testInput.anInt = 9;
testInput.aStr = "zzz";
testInput.innerObj = new Y();
testInput.innerObj.yField = "ooo";
identityStylesheet = TransformerFactory.newInstance().newTemplates(new StreamSource(new StringReader(IDENTITY_STYLESHEET)));
}
public void testMarshalsObjectToSAX() {
String expected =
"<?xml version=\"1.0\" standalone=\"yes\"?>\n\n" +
"<x>\n" +
" <aStr>zzz</aStr>\n" +
" <anInt>9</anInt>\n" +
" <innerObj>\n" +
" <yField>ooo</yField>\n" +
" </innerObj>\n" +
"</x>\n\n";
Writer buffer = new StringWriter();
SaxWriter writer = new SaxWriter();
DataWriter outputter = new DataWriter(writer, buffer);
outputter.setIndentStep(2);
writer.setContentHandler(outputter);
xstream.marshal(testInput, writer);
assertEquals(expected, buffer.toString());
}
public void testMarshalsObjectToTrAX() throws Exception {
String expected =
"<x><aStr>zzz</aStr><anInt>9</anInt>" +
"<innerObj><yField>ooo</yField></innerObj>" +
"</x>" +
"<y><yField>ooo</yField></y>";
TraxSource traxSource = new TraxSource();
traxSource.setXStream(xstream);
traxSource.setSourceAsList(Arrays.asList(new Object[]{testInput, testInput.innerObj}));
Writer buffer = new StringWriter();
Transformer transformer = identityStylesheet.newTransformer();
transformer.transform(traxSource, new StreamResult(buffer));
assertEquals(expected, buffer.toString());
}
public void testNullSourceObject() {
TraxSource traxSource = new TraxSource();
try {
traxSource.setSource(null);
fail("Null source object not rejected");
} catch (IllegalArgumentException e) { /* good! */
}
}
public void testNullSourceList() {
TraxSource traxSource = new TraxSource();
try {
traxSource.setSourceAsList(null);
fail("Null source list not rejected");
} catch (IllegalArgumentException e) { /* good! */
}
}
public void testEmptySourceList() {
TraxSource traxSource = new TraxSource();
try {
traxSource.setSourceAsList(Collections.EMPTY_LIST);
fail("Empty source list not rejected");
} catch (IllegalArgumentException e) { /* good! */
}
}
/**
* This method tests a quite insidious side-effect of
* XStreamSource delaying the allocation and configuration of
* the SAXWriter until the XSLT processor requests it.
* <p/>
* SAXWriter performs a copy of the source list contents upon
* property setting to avoid objects being added or removed from
* the list during the parse.</p>
* <p/>
* To avoid just another list copy, XStreamSource does not
* protect itself against list changes. Hence, it is possible
* for an application to configure the XStreamSource and then
* empty the list prior triggering the XSL transformation.</p>.
* <p/>
* This method ensures SAXWriter indeed checks the list content
* prior starting the parse.</p>
*/
public void testEmptySourceListAtParse() throws Exception {
TraxSource traxSource = new TraxSource();
Writer buffer = new StringWriter();
List list = new ArrayList();
list.add(testInput);
traxSource.setSourceAsList(list);
list.clear();
Transformer transformer = identityStylesheet.newTransformer();
transformer.setErrorListener(new TrAXErrorListener());
try {
transformer.transform(traxSource, new StreamResult(buffer));
fail("Empty source list not rejected");
} catch (Exception expectedException) {
if (expectedException.getMessage().endsWith("shall not be an empty list")) {
// Good!
} else {
throw expectedException;
}
}
}
private static class TrAXErrorListener implements ErrorListener {
public TrAXErrorListener() {
super();
}
public void warning(TransformerException e)
throws TransformerException {
/* Ignore... */
}
public void error(TransformerException e)
throws TransformerException {
/* Ignore... */
}
public void fatalError(TransformerException e)
throws TransformerException {
throw e;
}
}
} |
package to.us.harha.twitchai.bot;
import static to.us.harha.twitchai.util.Globals.*;
import static to.us.harha.twitchai.util.LogUtils.logMsg;
import static to.us.harha.twitchai.util.LogUtils.logErr;
import static to.us.harha.twitchai.util.GenUtils.exit;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import javax.net.ssl.HttpsURLConnection;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
import mclama.com.SMMHandler;
import to.us.harha.twitchai.util.FileUtils;
import java.time.*;
public class TwitchAI extends PircBot
{
private float m_cycleTime;
private float m_cmdTime;
private boolean m_hasMembership;
private boolean m_hasCommands;
private boolean m_hasTags;
private ArrayList<TwitchUser> m_moderators;
private ArrayList<TwitchChannel> m_channels;
public TwitchAI()
{
m_cycleTime = 0.0f;
m_cmdTime = 0.0f;
m_hasMembership = false;
m_hasCommands = false;
m_hasTags = true;
m_moderators = new ArrayList<TwitchUser>();
m_channels = new ArrayList<TwitchChannel>();
setName(g_bot_name);
setVersion(g_lib_version);
setVerbose(false);
setMessageDelay(300);
}
public void init_twitch(String address)
{
logMsg("Loading all registered TwitchAI moderators...");
ArrayList<String> loadedModerators = FileUtils.readTextFile("data/moderators.txt");
for (String m : loadedModerators)
{
String[] m_split = m.split(" ");
TwitchUser newmod = new TwitchUser(m_split[0], m_split[1]);
logMsg("Added a TwitchAI moderator (" + newmod + ") to m_moderators");
m_moderators.add(newmod);
}
logMsg("Attempting to connect to irc.twitch.tv...");
try
{
connect(address, 6667, g_bot_oauth);
} catch (IOException | IrcException e)
{
logErr(e.getStackTrace().toString());
exit(1);
}
if (g_bot_reqMembership)
{
logMsg("Requesting twitch membership capability for NAMES/JOIN/PART/MODE messages...");
sendRawLine(g_server_memreq);
}
else
{
logMsg("Membership request is disabled!");
m_hasMembership = true;
}
if (g_bot_reqCommands)
{
logMsg("Requesting twitch commands capability for NOTICE/HOSTTARGET/CLEARCHAT/USERSTATE messages... ");
sendRawLine(g_server_cmdreq);
}
else
{
logMsg("Commands request is disabled!");
m_hasCommands = true;
}
if (g_bot_reqTags)
{
logMsg("Requesting twitch tags capability for PRIVMSG/USERSTATE/GLOBALUSERSTATE messages... ");
sendRawLine(g_server_tagreq);
}
else
{
logMsg("Tags request is disabled!");
m_hasTags = true;
}
}
public void init_channels()
{
logMsg("Attempting to join all registered channels...");
ArrayList<String> loadedChannels = FileUtils.readTextFile("data/channels.txt");
for (String c : loadedChannels)
{
if (!c.startsWith("
{
c = "
}
joinToChannel(c);
}
sendMessage("#_mclamabot_1449386648724","/w fireblade212 Bot whisper test.");
}
public void joinToChannel(String channel)
{
logMsg("Attempting to join channel " + channel);
joinChannel(channel);
m_channels.add(new TwitchChannel(channel));
}
public void partFromChannel(String channel)
{
logMsg("Attempting to part from channel " + channel);
partChannel(channel);
m_channels.remove(getTwitchChannel(channel));
}
public void addChannel(String channel, String sender, String addChan)
{
ArrayList<String> addchan_channels = FileUtils.readTextFile("data/channels.txt");
if (addchan_channels.size() <= 0 || !addchan_channels.contains(addChan))
{
logMsg("Registering a new channel: " + addChan);
sendTwitchMessage(channel, "Registering a new channel: " + addChan);
FileUtils.writeToTextFile("data/", "channels.txt", addChan);
joinToChannel(addChan);
}
else
{
logErr("Failed to register a new channel: " + addChan);
sendTwitchMessage(channel, "That channel is already registered!");
}
return;
}
public void delChannel(String channel, String sender, String delChan)
{
if (!Arrays.asList(getChannels()).contains(delChan))
{
logErr("Can't delete channel " + delChan + " from the global channels list because it isn't in the joined channels list!");
return;
}
logMsg(sender + " Requested a deletion of channel: " + delChan);
sendTwitchMessage(channel, sender + " Requested a deletion of channel: " + delChan);
partFromChannel(delChan);
FileUtils.removeFromTextFile("data", "/channels.txt", delChan);
}
public void sendTwitchMessage(String channel, String message)
{
TwitchChannel twitch_channel = getTwitchChannel(channel);
TwitchUser twitch_user = twitch_channel.getUser(g_bot_name);
if (twitch_user == null)
{
twitch_user = g_nulluser;
}
if (twitch_user.isOperator())
{
if (twitch_channel.getCmdSent() <= 48)
{
twitch_channel.setCmdSent(twitch_channel.getCmdSent() + 1);
sendMessage(channel, message);
}
else
{
logErr("Cannot send a message to channel (" + twitch_channel + ")! 100 Messages per 30s limit nearly exceeded! (" + twitch_channel.getCmdSent() + ")");
}
}
else
{
if (twitch_channel.getCmdSent() <= 16)
{
twitch_channel.setCmdSent(twitch_channel.getCmdSent() + 1);
sendMessage(channel, message);
}
else
{
logErr("Cannot send a message to channel (" + twitch_channel + ")! 20 Messages per 30s limit nearly exceeded! (" + twitch_channel.getCmdSent() + ")");
}
}
}
public void sendWhisper(String sendTo, String message){
//if(g_dir.contains("desktop") || sendTo.equals("fireblade212"))
//{ //only send message to author if running from development
g_PBOT.sendMessage("#_mclamabot_1449386648724","/w " + sendTo + " " + message);
}
@Override
public void handleLine(String line)
{
//logMsg("handleLine | " + line);
super.handleLine(line);
if (!isInitialized())
{
if (line.equals(g_server_memans))
{
m_hasMembership = true;
}
if (line.equals(g_server_cmdans))
{
m_hasCommands = true;
}
if (line.equals(g_server_tagans))
{
m_hasTags = true;
}
}
if (line.contains("WHISPER"))
{
String[] line_array = line.split(g_bot_name.toLowerCase() + " :");
String sender = line_array[0].split("!")[0].replace(":","");
String message = line_array[1];
onPrivateMessage(sender,"","",message);
}
if (line.contains(":jtv "))
{
line = line.replace(":jtv ", "");
String[] line_array = line.split(" ");
if (line_array[0].equals("MODE") && line_array.length >= 4)
{
onMode(line_array[1], line_array[3], line_array[3], "", line_array[2]);
}
}
}
@Override
public void onUserList(String channel, User[] users)
{
super.onUserList(channel, users);
TwitchChannel twitch_channel = getTwitchChannel(channel);
if (twitch_channel == null)
{
logErr("Error on USERLIST, channel (" + channel + ") doesn't exist!");
return;
}
for (User u : users)
{
if (twitch_channel.getUser(u.getNick()) == null)
{
TwitchUser twitch_mod = getOfflineModerator(u.getNick());
String prefix = "";
if (twitch_mod != null)
{
prefix = twitch_mod.getPrefix();
}
TwitchUser user = new TwitchUser(u.getNick(), prefix);
twitch_channel.addUser(user);
logMsg("Adding new user (" + user + ") to channel (" + twitch_channel.toString() + ")");
}
}
}
@Override
public void onJoin(String channel, String sender, String login, String hostname)
{
super.onJoin(channel, sender, login, hostname);
TwitchChannel twitch_channel = getTwitchChannel(channel);
TwitchUser twitch_user = twitch_channel.getUser(sender);
TwitchUser twitch_mod = getOfflineModerator(sender);
if (twitch_channel != null && twitch_user == null)
{
String prefix = "";
if (twitch_mod != null)
{
prefix = twitch_mod.getPrefix();
}
TwitchUser user = new TwitchUser(sender, prefix);
twitch_channel.addUser(user);
logMsg("Adding new user (" + user + ") to channel (" + twitch_channel.toString() + ")");
}
}
@Override
public void onPart(String channel, String sender, String login, String hostname)
{
super.onPart(channel, sender, login, hostname);
TwitchChannel twitch_channel = getTwitchChannel(channel);
TwitchUser twitch_user = twitch_channel.getUser(sender);
if (twitch_channel != null && twitch_user != null)
{
twitch_channel.delUser(twitch_user);
logMsg("Removing user (" + twitch_user + ") from channel (" + twitch_channel.toString() + ")");
}
}
@Override
public void onMode(String channel, String sourceNick, String sourceLogin, String sourceHostname, String mode)
{
super.onMode(channel, sourceNick, sourceLogin, sourceHostname, mode);
TwitchChannel twitch_channel = getTwitchChannel(channel);
TwitchUser twitch_user = twitch_channel.getUser(sourceNick);
if (twitch_user == null)
{
logErr("Error on MODE, cannot find (" + twitch_user + ") from channel (" + twitch_channel.toString() + ")");
return;
}
if (mode.equals("+o"))
{
logMsg("Adding +o MODE for user (" + twitch_user + ") in channel (" + twitch_channel.toString() + ")");
twitch_user.addPrefixChar("@");
}
else if (mode.equals("-o"))
{
logMsg("Adding -o MODE for user (" + twitch_user + ") in channel (" + twitch_channel.toString() + ")");
twitch_user.delPrefixChar("@");
}
}
@Override
public void onMessage(String channel, String sender, String login, String hostname, String message)
{
logMsg("data/channels/" + channel, "/onMessage", "User: " + sender + /*" Hostname: " + hostname + */" Message: " + message);
TwitchChannel twitch_channel = getTwitchChannel(channel);
TwitchUser twitch_user = twitch_channel.getUser(sender);
TwitchUser twitch_mod = getOfflineModerator(sender);
if (twitch_channel != null && twitch_user == null)
{
String prefix = "";
if (twitch_mod != null)
{
prefix = twitch_mod.getPrefix();
}
TwitchUser user = new TwitchUser(sender, prefix);
twitch_channel.addUser(user);
logMsg("Adding new user (" + user + ") to channel (" + twitch_channel.toString() + ")");
}
//TwitchChannel twitch_channel = getTwitchChannel(g_bot_chan);
if (message.startsWith("!"))
{
//System.out.println(twitch_channel.getUsers().toString());
twitch_user = twitch_channel.getUser(sender);
if (twitch_user == null)
{
logErr("Error on ONMESSAGE, user (" + sender + ") doesn't exist! Creating a temp null user object for user!");
twitch_user = g_nulluser;
}
if (message.length() > 3)
{
if (twitch_user.getCmdTimer() > 0)
{
if (twitch_user.getCmdTimer() > 10 && twitch_channel.getCmdSent() < 32)
{
sendWhisper(sender, " Please wait " + twitch_user.getCmdTimer() + " seconds before sending a new command.");
}
twitch_user.setCmdTimer(twitch_user.getCmdTimer() + 5);
return;
}
else
{
if (!twitch_user.getName().equals("null"))
{
twitch_user.setCmdTimer(5);
}
}
}
message = message.replace("!", "");
String[] msg_array = message.split(" ");
String msg_command = msg_array[0];
String user_sender = sender;
String user_target;
String chan_sender = channel;
String chan_target;
float time;
long timeStart, timeEnd;
timeStart = System.nanoTime();
if (channel.equals(g_bot_chan))
{
switch (msg_command)
{
/*
* Normal commands
*/
case g_com_submit:
if(!g_smm_submits_open)
{
sendResponse(sender, ml_submit_open);
break;
}
if (msg_array.length < 2)
{
sendResponse(sender, ml_submit_with_no_level);
break;
}
if(SMMHandler.getUserLevelCount(sender)>=g_smm_max_queue){
sendResponse(sender, ml_submit_max_queue);
break;
}
if(SMMHandler.getUserLevelCount(sender)>=g_smm_submit_max_in_list){
sendResponse(sender, ml_submit_max_in_list);
break;
}
if(twitch_user != null || g_smm_submit_delay>0)
{
if((new Date().getTime() <= twitch_user.getLastSubmit() + (g_smm_submit_delay * 100000)) && twitch_user.getLastSubmit() != 0)
{
sendResponse(sender, ml_submit_delay);
break;
}
}
if(g_smm_follow_required){
if(!isUserFollowing(sender, g_bot_chan)){
sendResponse(sender, ml_require_follow);
break;
}
}
if(msg_array[1].charAt(msg_array[1].length()-1) == '.')
msg_array[1] = msg_array[1].substring(0, msg_array[1].length()-1);
String response = null;
if(g_smm_require_good_looking_code){
int minLength=16 + (msg_array[1].length() - msg_array[1].replace("-", "").length());
if(msg_array[1].length() < minLength)
{
sendResponse(sender, ml_require_good_looking_code);
break;
}
else
{
if(!msg_array[1].contains("-"))
{
msg_array[1] = insertPeriodically(msg_array[1], "-", 4);
}
}
response = sendGetRequest("https://supermariomakerbookmark.nintendo.net/courses/" + msg_array[1]);
//System.out.println("response: " + response);
if(response.contains("404"))
{
//System.out.println("invalid level");
sendResponse(sender, ml_require_good_looking_code);
break;
}
}
if(SMMHandler.isCodeDuplicate(msg_array[1])){
sendResponse(sender, ml_duplicate_submission);
break;
}
twitch_user.setLastSubmit(new Date().getTime());
SMMHandler.addLevel(sender, msg_array[1], response);
if(g_forms_use)
{
SMMHandler.sendPost(g_forms_url, false, msg_array[1], sender);
}
sendResponse(sender, ml_submit);
break;
case g_com_queue:
sendResponse(sender, ml_queue);
break;
case g_com_current:
sendResponse(sender, ml_current);
break;
case g_com_previous:
sendResponse(sender, ml_previous);
break;
case g_com_next:
if (!twitch_user.isModerator())
{
break;
}
if(SMMHandler.getNext())
{
sendResponse(sender, ml_on_next);
break;
}
sendResponse(sender, ml_no_queue);
break;
case g_com_random:
if (!twitch_user.isModerator())
{
break;
}
if(SMMHandler.getRandom())
{
sendResponse(sender, ml_on_random);
break;
}
sendResponse(sender, ml_no_queue);
break;
case g_com_commands:
{
sendResponse(sender, ml_commands_list);
break;
}
case g_com_queuelist:
{
sendResponse(sender, ml_queuelist);
break;
}
case g_com_close:
{
g_smm_submits_open = false;
sendResponse(sender, "Closed submissions!");
break;
}
case g_com_open:
{
g_smm_submits_open = true;
sendResponse(sender, "Opened submissions!");
break;
}
case g_com_delete:
{
if (msg_array.length < 2)
{
sendResponse(sender, ml_delete_with_no_level);
break;
}
if(msg_array[1].equals("all"))
{
if(SMMHandler.removeAllMyLevelsFromQueue(sender))
{
sendResponse(sender, ml_delete);
}
break;
}
if(g_smm_require_good_looking_code){
int minLength=16 + (msg_array[1].length() - msg_array[1].replace("-", "").length());
if(msg_array[1].length() < minLength)
{
sendResponse(sender, ml_require_good_looking_code);
break;
}
else
{
if(!msg_array[1].contains("-"))
{
msg_array[1] = insertPeriodically(msg_array[1], "-", 4);
}
}
response = sendGetRequest("https://supermariomakerbookmark.nintendo.net/courses/" + msg_array[1]);
//System.out.println("response: " + response);
if(response.contains("404"))
{
//System.out.println("invalid level");
sendResponse(sender, ml_require_good_looking_code);
break;
}
}
if(SMMHandler.removeLevelFromQueue(msg_array[1]))
{
sendResponse(sender, ml_delete);
break;
}
else{
sendResponse(sender, ml_delete_invalid);
break;
}
}
case g_com_list:
{
sendResponse(sender, ml_list);
break;
}
case g_com_completedlist:
{
sendResponse(sender, ml_list_completed);
break;
}
case g_com_streamerlist:
{
sendResponse(sender, ml_streamer_submission_list);
break;
}
case g_com_title:
{
sendResponse(sender, ml_current_title);
break;
}
}
}
timeEnd = System.nanoTime();
time = (float) (timeEnd - timeStart) / 1000000.0f;
setCmdTime(getCmdTime() * 0.1f + time * 0.9f);
}
}
public void sendResponse(String sender, String message) {
message = message.replace("{sender}", sender)
.replace("{place}", SMMHandler.getUserNextLevelPlace(sender))
.replace("{current}", SMMHandler.getCurrent_level().getLevel())
.replace("{currentauthor}", SMMHandler.getCurrent_level().getAuthor())
.replace("{previous}", SMMHandler.getPrevious_level().getLevel())
.replace("{previousauthor}", SMMHandler.getPrevious_level().getAuthor())
.replace("{delay}", g_smm_submit_delay+"")
.replace("{queue_size}", SMMHandler.getLevelCount()+"")
.replace("{max_queue_size}", g_smm_max_queue+"")
.replace("{max_user_submit}", g_smm_submit_max_in_list+"")
.replace("{next_levels}", SMMHandler.getNextFewLevels())
.replace("{submission_list}", g_smm_url_list)
.replace("{completed_list}", g_smm_url_list_completed)
.replace("{streamer_list_url}", g_smm_url_list_streamer)
.replace("{title}", SMMHandler.getCurrent_level().getName())
.replace("{difficulty}", SMMHandler.getCurrent_level().getDifficulty())
;
if(g_smm_message_all)
{
sendMessage(g_bot_chan, message);
}
else
{
sendWhisper(sender,message);
}
}
@Override
public void onPrivateMessage(String sender, String login, String hostname, String message)
{
//System.out.println("pm received");
logMsg("data/whisper", "/WHISPER", "User: " + sender + " Hostname: " + hostname + " Message: " + message);
}
public ArrayList<TwitchChannel> getTwitchChannels()
{
return m_channels;
}
public TwitchChannel getTwitchChannel(String name)
{
TwitchChannel result = null;
for (TwitchChannel tc : m_channels)
{
if (tc.getName().equals(name))
{
result = tc;
break;
}
}
return result;
}
public ArrayList<TwitchUser> getAllUsers()
{
ArrayList<TwitchUser> result = new ArrayList<TwitchUser>();
for (TwitchChannel tc : m_channels)
{
result.addAll(tc.getUsers());
}
return result;
}
public ArrayList<TwitchUser> getAllOperators()
{
ArrayList<TwitchUser> result = new ArrayList<TwitchUser>();
for (TwitchChannel tc : m_channels)
{
result.addAll(tc.getOperators());
}
return result;
}
public ArrayList<TwitchUser> getOnlineModerators()
{
ArrayList<TwitchUser> result = new ArrayList<TwitchUser>();
for (TwitchChannel tc : m_channels)
{
result.addAll(tc.getModerators());
}
return result;
}
public ArrayList<TwitchUser> getOfflineModerators()
{
return m_moderators;
}
public TwitchUser getOfflineModerator(String nick)
{
TwitchUser result = null;
for (TwitchUser tu : m_moderators)
{
if (tu.getName().equals(nick))
{
result = tu;
}
}
return result;
}
public float getCycleTime()
{
return m_cycleTime;
}
public void setCycleTime(float cycleTime)
{
m_cycleTime = cycleTime;
}
public float getCmdTime()
{
return m_cmdTime;
}
public void setCmdTime(float cmdTime)
{
m_cmdTime = cmdTime;
}
public boolean isInitialized()
{
return m_hasMembership & m_hasCommands & m_hasTags;
}
public boolean isUserInChat(String author) {
TwitchChannel bot_channel = null;
bot_channel = getTwitchChannel(g_bot_chan);
try {
if(bot_channel.getUser(author) != null)
return true;
} catch (Exception e) {
logErr("Failed to find user " + author + " in user list");
}
for (TwitchUser u : getAllUsers())
{
if (u.getName().replace("&","").equals("author"))
{
return true;
}
}
return false;
}
public boolean isUserFollowing(String sender, String channel){
String httpLink = "https://api.twitch.tv/kraken/users/" + sender + "/follows/channels/" + (channel.replace("
String response = sendGetRequest(httpLink);
if(response.contains(httpLink)){
return true;
}
return false;
}
public static String sendGetRequest(String httpLink){
try {
URL obj = new URL(httpLink);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "java");
int responseCode = con.getResponseCode();
if(responseCode == 404){
return "404";
}
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//System.out.println(response.toString());
return response.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "404";
}
public static String insertPeriodically(
String text, String insert, int period)
{
StringBuilder builder = new StringBuilder(
text.length() + insert.length() * (text.length()/period)+1);
int index = 0;
String prefix = "";
while (index < text.length())
{
// Don't put the insert in the very first iteration.
// This is easier than appending it *after* each substring
builder.append(prefix);
prefix = insert;
builder.append(text.substring(index,
Math.min(index + period, text.length())));
index += period;
}
return builder.toString();
}
} |
package jft.murinov;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PointTests {
@Test
public void distanceTest(){
PointWithMath p1 = new PointWithMath(10, 10);
PointWithMath p2 = new PointWithMath(20, 10);
Assert.assertEquals(p1.distance(p2), 10.0);
}
@Test
public void distanceTestZero(){
PointWithMath p1 = new PointWithMath(10, 10);
PointWithMath p2 = new PointWithMath(10, 10);
Assert.assertEquals(p1.distance(p2), 0.0);
}
@Test(enabled = false)
public void distanceTestInt(){
PointWithMath p1 = new PointWithMath(10, 10);
PointWithMath p2 = new PointWithMath(10, 10);
Assert.assertEquals(p1.distance(p2), 0);
}
@Test(enabled = false)
public void distanceTestLetter(){
PointWithMath p1 = new PointWithMath(10, 10);
PointWithMath p2 = new PointWithMath(25, 25);
Assert.assertEquals(p1.distance(p2), "A");
}
} |
package org.nutz.dao.test.normal;
import static org.junit.Assert.*;
import org.junit.Test;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.test.DaoCase;
import org.nutz.dao.test.meta.Fighter;
import org.nutz.dao.test.meta.Platoon;
public class UpdateTest extends DaoCase {
@Override
protected void before() {
pojos.initData();
}
@Override
protected void after() {}
@Test
public void batch_update_all() {
dao.update(Fighter.class, Chain.make("type", Fighter.TYPE.SU_35.name()), null);
assertEquals( 13,
dao.count(Fighter.class, Cnd.where("type", "=", Fighter.TYPE.SU_35.name())));
}
@Test
public void batch_update_partly() {
int re = dao.update(Fighter.class, Chain.make("type", "F15"), Cnd.where("type",
"=",
"SU_35"));
assertEquals(1, re);
int maxId = dao.getMaxId(Fighter.class);
re = dao.update(Fighter.class, Chain.make("type", "UFO"), Cnd.where("id", ">", maxId - 5));
assertEquals(5, re);
assertEquals(re, dao.count(Fighter.class, Cnd.where("type", "=", "UFO")));
}
@Test
public void batch_update_relation() {
dao.updateRelation( Fighter.class,
"base",
Chain.make("bname", "blue"),
Cnd.where("bname", "=", "red"));
assertEquals(13, dao.count("dao_m_base_fighter", Cnd.where("bname", "=", "blue")));
}
@Test
public void fetch_by_name_ignorecase() {
Platoon p = dao.fetch(Platoon.class, "sF");
assertEquals("SF", p.getName());
}
@Test
public void update_with_null_links() {
Platoon p = dao.fetch(Platoon.class, "sF");
p.setLeaderName("xyz");
dao.updateWith(p, null);
p = dao.fetch(Platoon.class, "sF");
assertEquals("xyz", p.getLeaderName());
}
@Test
public void updateIgnoreNull() {
Platoon p = dao.fetch(Platoon.class, "sF");
String name = p.getLeaderName(); // xyz
p.setLeaderName(null);
int re = dao.updateIgnoreNull(p);
assertEquals(1, re);
p = dao.fetch(Platoon.class, "sF");
assertEquals(name, p.getLeaderName());
}
} |
package net.bolbat.utils.crypt;
import java.util.Date;
import net.bolbat.utils.crypt.DigestUtils.Algorithm;
import net.bolbat.utils.test.CommonTester;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
/**
* {@link DigestUtils} test.
*
* @author Alexandr Bolbat
*/
public class DigestUtilsTest {
/**
* {@link Logger} instance.
*/
private static final Logger LOGGER = Logger.getLogger(DigestUtilsTest.class);
/**
* General test.
*/
@Test
public void generalTest() {
final String salt = "1234567890";
final long timestamp = System.currentTimeMillis();
final String value = "Hello world, current date and time: " + new Date(timestamp) + ", timestamp: " + timestamp;
LOGGER.info("
LOGGER.info("salt[" + salt + "], value[" + value + "]");
algorithmTest(Algorithm.MD2, salt, value);
algorithmTest(Algorithm.MD5, salt, value);
algorithmTest(Algorithm.SHA_1, salt, value);
algorithmTest(Algorithm.SHA_256, salt, value);
algorithmTest(Algorithm.SHA_384, salt, value);
algorithmTest(Algorithm.SHA_512, salt, value);
}
/**
* Error cases test.
*/
@Test
public void errorCasesTest() {
// digesting
try {
DigestUtils.digest(null, null, null);
Assert.fail("Exception shold be thrown before this step.");
} catch (IllegalArgumentException e) {
Assert.assertTrue("Exception should be there.", e.getMessage().startsWith("algorithm"));
}
try {
DigestUtils.digest(Algorithm.MD2, "mock", null);
Assert.fail("Exception shold be thrown before this step.");
} catch (IllegalArgumentException e) {
Assert.assertTrue("Exception should be there.", e.getMessage().startsWith("salt"));
}
// algorithm enumeration
try {
Algorithm.get(null);
Assert.fail("Exception shold be thrown before this step.");
} catch (IllegalArgumentException e) {
Assert.assertTrue("Exception should be there.", e.getMessage().startsWith("aAlgorithmName"));
}
try {
Algorithm.get("wrong");
Assert.fail("Exception shold be thrown before this step.");
} catch (DigestRuntimeException e) {
Assert.assertTrue("Exception should be there.", e.getMessage().startsWith("algorithm[wrong]"));
}
try {
Algorithm.MD2.digest(new byte[1], null);
Assert.fail("Exception shold be thrown before this step.");
} catch (IllegalArgumentException e) {
Assert.assertTrue("Exception should be there.", e.getMessage().startsWith("salt"));
}
}
/**
* Cases mostly for good code coverage.
*/
@Test
public void coverageTest() {
CommonTester.checkExceptionInstantiation(DigestRuntimeException.class);
Assert.assertEquals(Algorithm.MD2, Algorithm.get(Algorithm.MD2.getAlgorithmName()));
Assert.assertEquals(Algorithm.SHA_1, Algorithm.get(Algorithm.SHA_1.getAlgorithmName()));
Assert.assertEquals(Algorithm.SHA_512, Algorithm.get(Algorithm.SHA_512.getAlgorithmName()));
Assert.assertEquals(CipherUtils.EMPTY_STRING, DigestUtils.digest(Algorithm.MD2, null, null));
Assert.assertEquals(CipherUtils.EMPTY_BYTE_ARRAY, Algorithm.MD2.digest(null, null));
Assert.assertEquals(CipherUtils.EMPTY_BYTE_ARRAY, Algorithm.MD2.digest(new byte[0], null));
}
/**
* Real algorithm test.
*
* @param a
* algorithm
* @param salt
* secure salt
* @param value
* value to digest
*/
private static void algorithmTest(final Algorithm a, final String salt, final String value) {
LOGGER.info("
long startTimestamp = System.currentTimeMillis();
String digest1 = DigestUtils.digest(a, value, salt);
LOGGER.info("digest1[" + digest1 + "], time[" + (System.currentTimeMillis() - startTimestamp) + "ms]");
Assert.assertNotNull(digest1);
Assert.assertNotEquals(value, digest1);
String digest2 = DigestUtils.digest(a, value, salt);
LOGGER.info("digest2[" + digest2 + "], time[" + (System.currentTimeMillis() - startTimestamp) + "ms]");
Assert.assertNotNull(digest2);
Assert.assertNotEquals(value, digest2);
Assert.assertEquals(digest1, digest2);
String digestWithDoubleSalt = DigestUtils.digest(a, value, salt + salt);
LOGGER.info("digestWithDoubleSalt[" + digestWithDoubleSalt + "], time[" + (System.currentTimeMillis() - startTimestamp) + "ms]");
Assert.assertNotNull(digestWithDoubleSalt);
Assert.assertNotEquals(value, digestWithDoubleSalt);
Assert.assertNotEquals(digest1, digestWithDoubleSalt);
Assert.assertNotEquals(digest2, digestWithDoubleSalt);
}
} |
package org.handwerkszeug.riak.op;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.handwerkszeug.riak.RiakException;
import org.handwerkszeug.riak._;
import org.handwerkszeug.riak.mapreduce.JavaScriptPhase;
import org.handwerkszeug.riak.mapreduce.MapReduceInputs;
import org.handwerkszeug.riak.mapreduce.MapReduceKeyFilters;
import org.handwerkszeug.riak.mapreduce.MapReduceQuery;
import org.handwerkszeug.riak.mapreduce.MapReduceQueryConstructor;
import org.handwerkszeug.riak.mapreduce.MapReduceResponse;
import org.handwerkszeug.riak.mapreduce.NamedFunctionPhase;
import org.handwerkszeug.riak.model.Bucket;
import org.handwerkszeug.riak.model.DefaultGetOptions;
import org.handwerkszeug.riak.model.DefaultPutOptions;
import org.handwerkszeug.riak.model.DefaultRiakObject;
import org.handwerkszeug.riak.model.Erlang;
import org.handwerkszeug.riak.model.JavaScript;
import org.handwerkszeug.riak.model.KeyResponse;
import org.handwerkszeug.riak.model.Link;
import org.handwerkszeug.riak.model.Location;
import org.handwerkszeug.riak.model.PutOptions;
import org.handwerkszeug.riak.model.Quorum;
import org.handwerkszeug.riak.model.RiakContentsResponse;
import org.handwerkszeug.riak.model.RiakFuture;
import org.handwerkszeug.riak.model.RiakObject;
import org.handwerkszeug.riak.model.RiakResponse;
import org.handwerkszeug.riak.transport.internal.DefaultCompletionChannelHandler;
import org.handwerkszeug.riak.transport.protobuf.ProtoBufRiakOperationsTest;
import org.handwerkszeug.riak.util.JsonUtil;
import org.handwerkszeug.riak.util.LogbackUtil;
import org.handwerkszeug.riak.util.Streams;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author taichi
*/
public abstract class RiakOperationsTest {
ClientBootstrap bootstrap;
Channel channel;
RiakOperations target;
@Before
public void setUp() throws Exception {
this.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
this.bootstrap.setPipelineFactory(newChannelPipelineFactory());
ChannelFuture future = this.bootstrap.connect(connectTo());
this.channel = future.awaitUninterruptibly().getChannel();
this.target = newTarget(this.channel);
}
protected abstract ChannelPipelineFactory newChannelPipelineFactory();
protected abstract SocketAddress connectTo();
protected abstract RiakOperations newTarget(Channel channel);
@After
public void tearDown() throws Exception {
this.channel.close().awaitUninterruptibly();
this.bootstrap.releaseExternalResources();
}
@Test
public void testPing() throws Exception {
final boolean[] is = { false };
RiakFuture waiter = this.target.ping(new TestingHandler<String>() {
@Override
public void handle(RiakContentsResponse<String> response)
throws RiakException {
assertEquals("pong", response.getContents());
is[0] = true;
}
});
wait(waiter, is);
}
@Test
public void testListBuckets() throws Exception {
final boolean[] is = { false };
RiakFuture waiter = this.target
.listBuckets(new TestingHandler<List<String>>() {
@Override
public void handle(
RiakContentsResponse<List<String>> response)
throws RiakException {
List<String> keys = response.getContents();
assertNotNull(keys);
assertTrue(0 < keys.size());
is[0] = true;
}
});
wait(waiter, is);
}
@Test
public void testListKeys() throws Exception {
String bucket = "testListKeys";
String testdata = new SimpleDateFormat().format(new Date()) + "\n";
try {
for (int i = 0; i < 20; i++) {
Location l = new Location(bucket, String.valueOf(i));
testPut(l, testdata);
}
testListKeys(bucket, 20);
} finally {
for (int i = 0; i < 20; i++) {
Location l = new Location(bucket, String.valueOf(i));
testDelete(l);
}
}
}
public void testListKeys(String bucket, int allsize) throws Exception {
final boolean[] is = { false };
final int[] counter = { 0 };
RiakFuture waiter = this.target.listKeys(bucket,
new TestingHandler<KeyResponse>() {
@Override
public void handle(
RiakContentsResponse<KeyResponse> response)
throws RiakException {
KeyResponse kr = response.getContents();
List<String> list = kr.getKeys();
counter[0] += list.size();
if (kr.getDone()) {
is[0] = true;
}
}
});
wait(waiter, is);
assertEquals(allsize, counter[0]);
}
@Test
public void testBucket() throws Exception {
Location location = new Location("bucketSetGet", "1");
String testdata = new SimpleDateFormat().format(new Date()) + "\n";
try {
testPut(location, testdata);
Bucket exp = testBucketGet(location.getBucket());
testBucketSet(exp);
Bucket act = testBucketGet(location.getBucket());
assertEquals(exp.getNumberOfReplicas(), act.getNumberOfReplicas());
assertEquals(exp.getAllowMulti(), act.getAllowMulti());
} finally {
testDelete(location);
}
}
public void testBucketSet(Bucket bucket) throws Exception {
final boolean[] is = { false };
bucket.setAllowMulti(true);
bucket.setNumberOfReplicas(1);
RiakFuture waiter = this.target.setBucket(bucket,
new TestingHandler<_>() {
@Override
public void handle(RiakContentsResponse<_> response)
throws RiakException {
is[0] = true;
}
});
wait(waiter, is);
}
public Bucket testBucketGet(String bucket) throws Exception {
final boolean[] is = { false };
final Bucket[] bu = new Bucket[1];
RiakFuture waiter = this.target.getBucket(bucket,
new TestingHandler<Bucket>() {
@Override
public void handle(RiakContentsResponse<Bucket> response)
throws RiakException {
assertNotNull(response.getContents());
bu[0] = response.getContents();
is[0] = true;
}
});
wait(waiter, is);
return bu[0];
}
@Test
public void testPutGetDel() throws Exception {
Location location = new Location("testBucket", "testKey");
String testdata = new SimpleDateFormat().format(new Date()) + "\n";
testPut(location, testdata);
testGet(location, testdata);
testDelete(location);
}
public void testGet(Location location, final String testdata)
throws Exception {
final boolean[] is = { false };
RiakFuture waiter = this.target.get(location,
new TestingHandler<RiakObject<byte[]>>() {
@Override
public void handle(
RiakContentsResponse<RiakObject<byte[]>> response)
throws RiakException {
RiakObject<byte[]> content = response.getContents();
String actual = new String(content.getContent());
assertEquals(testdata, actual);
is[0] = true;
}
});
wait(waiter, is);
}
public void testPut(Location location, final String testdata)
throws Exception {
DefaultRiakObject ro = new DefaultRiakObject(location);
ro.setContent(testdata.getBytes());
ro.setCharset("UTF-8");
List<Link> links = new ArrayList<Link>();
links.add(new Link(new Location(location.getBucket(), "tag"), "foo"));
links.add(new Link(new Location(location.getBucket(), "tag"), "bar"));
ro.setLinks(links);
Map<String, String> map = new HashMap<String, String>();
map.put("mmm", "ddd");
map.put("nn", "eee");
map.put("o", "fff");
ro.setUserMetadata(map);
final boolean[] is = { false };
RiakFuture waiter = this.target.put(ro, new TestingHandler<_>() {
@Override
public void handle(RiakContentsResponse<_> response)
throws RiakException {
is[0] = true;
}
});
wait(waiter, is);
}
public void testDelete(Location location) throws Exception {
final boolean[] is = { false };
RiakFuture waiter = this.target.delete(location,
new TestingHandler<_>() {
@Override
public void handle(RiakContentsResponse<_> response)
throws RiakException {
is[0] = true;
}
});
wait(waiter, is);
}
@Test
public void testGetWithOpt() throws Exception {
final Location location = new Location("testGetWithOpt", "testKey");
byte[] data = new byte[1024 * 2];
Random r = new Random();
r.nextBytes(data);
final String testdata = Arrays.toString(data);
testPut(location, testdata);
try {
testGetWithOpt(location, testdata);
} finally {
testDelete(location);
}
}
protected void testGetWithOpt(final Location location, final String testdata)
throws InterruptedException {
final boolean[] is = { false };
final String[] result = new String[1];
RiakFuture waiter = this.target.get(location, new DefaultGetOptions() {
@Override
public Quorum getReadQuorum() {
return Quorum.of(2);
}
}, new TestingHandler<RiakObject<byte[]>>() {
@Override
public void handle(RiakContentsResponse<RiakObject<byte[]>> response)
throws Exception {
RiakObject<byte[]> ro = response.getContents();
assertEquals(location, ro.getLocation());
result[0] = new String(ro.getContent());
is[0] = true;
}
});
wait(waiter, is);
assertEquals(testdata, result[0]);
}
@Test
public void testGetNoContents() throws Exception {
final boolean[] is = { false };
Location location = new Location("testGetNoContents", "nocont");
RiakFuture waiter = this.target.get(location,
new RiakResponseHandler<RiakObject<byte[]>>() {
@Override
public void onError(RiakResponse response)
throws RiakException {
assertNotNull(response.getMessage());
assertFalse(response.getMessage().isEmpty());
is[0] = true;
}
@Override
public void handle(
RiakContentsResponse<RiakObject<byte[]>> response)
throws RiakException {
fail(response.getMessage());
}
});
wait(waiter, is);
}
protected abstract void testSetClientId(String id) throws Exception;
@Test
public void testSibling() throws Exception {
// for slow test problem.
// sibling message body is huge.
LogbackUtil.suppressLogging(new LogbackUtil.Action() {
@Override
public void execute() throws Exception {
final Location location = new Location("testSibling", "testKey");
testPut(location, "1");
try {
Bucket bucket = testBucketGet(location.getBucket());
bucket.setAllowMulti(true);
testBucketSet(bucket);
// remove current entry.
testDelete(location);
List<String> testdatas = new ArrayList<String>();
Random r = new Random();
byte[] bytes = new byte[1024 * 128];
r.nextBytes(bytes);
testdatas.add(Arrays.toString(bytes));
r.nextBytes(bytes);
testdatas.add(Arrays.toString(bytes));
r.nextBytes(bytes);
testdatas.add(Arrays.toString(bytes));
testSetClientId("AAAA");
testPut(location, testdatas.get(0));
testSetClientId("BBBB");
testPut(location, testdatas.get(1));
testSetClientId("CCCC");
testPutWithSibling(location, testdatas.get(2), testdatas);
testGetWithSibling(location, testdatas);
} finally {
// for CUI manually check.
// testDelete(location);
}
}
}, DefaultCompletionChannelHandler.class);
}
protected void testGetWithSibling(final Location location,
final List<String> testdatas) throws InterruptedException {
final boolean[] is = { false };
final boolean[] beginEnd = new boolean[2];
final List<String> actuals = new ArrayList<String>();
RiakFuture waiter = this.target.get(location, new DefaultGetOptions(),
new SiblingHandler() {
@Override
public void begin() {
beginEnd[0] = true;
}
@Override
public void onError(RiakResponse response)
throws RiakException {
fail(response.getMessage());
}
@Override
public void handle(
RiakContentsResponse<RiakObject<byte[]>> response)
throws RiakException {
RiakObject<byte[]> ro = response.getContents();
assertEquals(location, ro.getLocation());
actuals.add(new String(ro.getContent()));
is[0] = true;
}
@Override
public void end(RiakResponse response) {
beginEnd[1] = true;
}
});
assertTrue("test is timeout.", waiter.await(20, TimeUnit.SECONDS));
assertTrue(is[0]);
assertEquals(3, actuals.size());
for (String s : testdatas) {
assertTrue(s, actuals.contains(s));
}
assertTrue("begin", beginEnd[0]);
assertTrue("end", beginEnd[1]);
}
protected void testPutWithSibling(final Location location,
final String testdata, final List<String> testdatas)
throws Exception {
final boolean[] is = { false };
final boolean[] beginEnd = new boolean[2];
DefaultRiakObject ro = new DefaultRiakObject(location);
ro.setContent(testdata.getBytes());
final List<String> actuals = new ArrayList<String>();
RiakFuture waiter = this.target.put(ro, new DefaultPutOptions() {
@Override
public boolean getReturnBody() {
return true;
}
}, new SiblingHandler() {
@Override
public void onError(RiakResponse response) throws Exception {
fail(response.getMessage());
}
@Override
public void begin() {
beginEnd[0] = true;
}
@Override
public void handle(RiakContentsResponse<RiakObject<byte[]>> response)
throws Exception {
RiakObject<byte[]> ro = response.getContents();
assertEquals(location, ro.getLocation());
actuals.add(new String(ro.getContent()));
is[0] = true;
}
@Override
public void end(RiakResponse response) {
beginEnd[1] = true;
}
});
assertTrue("test is timeout.", waiter.await(20, TimeUnit.SECONDS));
assertTrue(is[0]);
assertEquals(3, actuals.size());
for (String s : testdatas) {
assertTrue(s, actuals.contains(s));
}
assertTrue("begin", beginEnd[0]);
assertTrue("end", beginEnd[1]);
}
@Test
public void testPutWithOpt() throws Exception {
final Location location = new Location("testPutWithOpt", "testKey");
final String testdata = new SimpleDateFormat().format(new Date())
+ "\n";
try {
testPutWithOpt(location, testdata);
} finally {
testDelete(location);
}
}
public void testPutWithOpt(Location location, final String testdata)
throws Exception {
final boolean[] is = { false };
final boolean[] beginEnd = new boolean[2];
DefaultRiakObject ro = new DefaultRiakObject(location);
ro.setContent(testdata.getBytes());
RiakFuture waiter = this.target.put(ro, new DefaultPutOptions() {
@Override
public boolean getReturnBody() {
return true;
}
}, new SiblingHandler() {
@Override
public void onError(RiakResponse response) throws Exception {
fail(response.getMessage());
}
@Override
public void begin() {
beginEnd[0] = true;
}
@Override
public void handle(RiakContentsResponse<RiakObject<byte[]>> response)
throws Exception {
RiakObject<byte[]> ro = response.getContents();
assertEquals(testdata, new String(ro.getContent()));
is[0] = true;
}
@Override
public void end(RiakResponse response) {
beginEnd[1] = true;
}
});
wait(waiter, is);
assertTrue("begin", beginEnd[0]);
assertTrue("end", beginEnd[1]);
}
@Test
public void testDeleteWithQuorum() throws Exception {
Location location = new Location("testDeleteWithQuorum", "delkey");
testPut(location, "aaa");
testDeleteWithQuorum(location);
}
public void testDeleteWithQuorum(Location location) throws Exception {
final boolean[] is = { false };
RiakFuture waiter = this.target.delete(location, Quorum.of(2),
new TestingHandler<_>() {
@Override
public void handle(RiakContentsResponse<_> response)
throws RiakException {
is[0] = true;
}
});
wait(waiter, is);
}
@Test
public void testMove() throws Exception {
final String from = "testMoveFrom";
final String to = "testMoveTo";
final int recordCount = 100;
for (int i = 0; i < recordCount; i++) {
testPut(new Location(from, String.valueOf(i)), "data" + i);
}
final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger(0);
this.target.listKeys(from, new TestingHandler<KeyResponse>() {
@Override
public void handle(RiakContentsResponse<KeyResponse> response)
throws Exception {
KeyResponse kr = response.getContents();
if (kr.getDone()) {
return;
}
counter.addAndGet(kr.getKeys().size());
for (final String k : kr.getKeys()) {
RiakOperationsTest.this.target.delete(
new Location(from, k), new TestingHandler<_>() {
@Override
public void handle(
RiakContentsResponse<_> response)
throws Exception {
DefaultRiakObject ro = new DefaultRiakObject(
new Location(to, k));
ro.setContent("data".getBytes());
RiakOperationsTest.this.target.put(ro,
new TestingHandler<_>() {
@Override
public void handle(
RiakContentsResponse<_> response)
throws Exception {
int i = counter
.decrementAndGet();
System.out.println("less "
+ i);
if (i < 1) {
latch.countDown();
}
}
});
}
});
}
}
});
try {
assertTrue("test is timeout.", latch.await(20, TimeUnit.SECONDS));
} finally {
for (int i = 0; i < recordCount; i++) {
testDelete(new Location(to, String.valueOf(i)));
}
}
}
@Test
public void testMapReduce() throws Exception {
String bucket = "testMapReduce";
try {
for (int i = 0; i < 20; i++) {
Location l = new Location(bucket, String.valueOf(i));
int val = i + 10;
testPut(l, String.valueOf(val));
}
testMapReduce(bucket);
} finally {
for (int i = 0; i < 20; i++) {
Location l = new Location(bucket, String.valueOf(i));
testDelete(l);
}
}
}
protected void testMapReduce(final String bucket) throws Exception {
final boolean[] is = { false };
final int[] actual = new int[1];
RiakFuture waiter = this.target.mapReduce(
new MapReduceQueryConstructor() {
@Override
public void cunstruct(MapReduceQuery query) {
query.setInputs(MapReduceInputs.keyFilter(bucket,
MapReduceKeyFilters.Transform.stringToInt(),
MapReduceKeyFilters.Predicates.lessThanEq(10)));
query.setQueries(
NamedFunctionPhase.map(Erlang.map_object_value,
false),
NamedFunctionPhase.reduce(
Erlang.reduce_string_to_integer, false),
NamedFunctionPhase.reduce(Erlang.reduce_sum,
true));
}
}, new TestingHandler<MapReduceResponse>() {
@Override
public void handle(
RiakContentsResponse<MapReduceResponse> response)
throws RiakException {
if (response.getContents().getDone()) {
is[0] = true;
} else {
ArrayNode an = response.getContents().getResponse();
JsonNode jn = an.get(0);
actual[0] = jn.getIntValue();
}
}
});
wait(waiter, is);
assertEquals(165, actual[0]);
}
@Test
public void testMapReduceByRawJson() throws Exception {
String bucket = "testMapReduceByRawJson";
for (int i = 0; i < 20; i++) {
Location l = new Location(bucket, String.valueOf(i));
int val = i + 10;
testPut(l, String.valueOf(val));
}
try {
testMapReduceByRawJson(JsonUtil.getJsonPath(
RiakOperationsTest.class, "testMapReduceByRawJson"));
} finally {
for (int i = 0; i < 20; i++) {
Location l = new Location(bucket, String.valueOf(i));
testDelete(l);
}
}
}
public void testMapReduceByRawJson(final String path) throws Exception {
final boolean[] is = { false };
final int[] actual = new int[1];
RiakFuture waiter = this.target.mapReduce(loadJson(path),
new TestingHandler<MapReduceResponse>() {
@Override
public void handle(
RiakContentsResponse<MapReduceResponse> response)
throws RiakException {
if (response.getContents().getDone()) {
is[0] = true;
} else {
ArrayNode an = response.getContents().getResponse();
JsonNode jn = an.get(0);
actual[0] = jn.getIntValue();
}
}
});
wait(waiter, is);
assertEquals(165, actual[0]);
}
String loadJson(final String path) {
final String[] json = new String[1];
new Streams.using<InputStream, IOException>() {
@Override
public InputStream open() throws IOException {
ClassLoader cl = ProtoBufRiakOperationsTest.class
.getClassLoader();
return cl.getResourceAsStream(path);
}
@Override
public void handle(InputStream stream) throws IOException {
json[0] = Streams.readText(stream);
}
@Override
public void happen(IOException exception) {
throw new Streams.IORuntimeException(exception);
}
};
return json[0];
}
@Test
public void testMapReduceContainsJson() throws Exception {
final String bucket = "testMapReduceContainsJson";
String key = "left::right";
Location location = new Location(bucket, key);
String data = "{\"a\":\"xxxx\",\"b\":\"c\"}";
testPut(location, data);
final boolean[] is = { false };
RiakFuture waiter = this.target.mapReduce(
new MapReduceQueryConstructor() {
@Override
public void cunstruct(MapReduceQuery query) {
query.setInputs(MapReduceInputs
.keyFilter(bucket,
MapReduceKeyFilters.Transform.tokenize(
"::", 1),
MapReduceKeyFilters.Predicates
.equal("left")));
query.setQueries(JavaScriptPhase.BuiltIns.map(
JavaScript.mapValuesJson, true));
}
}, new TestingHandler<MapReduceResponse>() {
@Override
public void handle(
RiakContentsResponse<MapReduceResponse> response)
throws Exception {
MapReduceResponse mrr = response.getContents();
if (mrr.getDone()) {
} else {
ArrayNode an = mrr.getResponse();
JsonNode jn = an.get(0);
assertNotNull(jn);
assertEquals(jn.getClass(), ObjectNode.class);
is[0] = true;
}
}
});
wait(waiter, is);
testDelete(location);
}
@Test
public void testFromOfficialsByRawJson() throws Exception {
final String bucket = "alice";
String p1 = "Alice was beginning to get very tired of sitting by her sister on the"
+ " bank, and of having nothing to do: once or twice she had peeped into the"
+ " book her sister was reading, but it had no pictures or conversations in"
+ " it, 'and what is the use of a book,' thought Alice 'without pictures or"
+ " conversation?'";
testPut(new Location(bucket, "p1"), p1);
String p2 = "So she was considering in her own mind (as well as she could, for the"
+ " hot day made her feel very sleepy and stupid), whether the pleasure"
+ " of making a daisy-chain would be worth the trouble of getting up and"
+ " picking the daisies, when suddenly a White Rabbit with pink eyes ran"
+ " close by her.";
testPut(new Location(bucket, "p2"), p2);
String p5 = "The rabbit-hole went straight on like a tunnel for some way, and then"
+ " dipped suddenly down, so suddenly that Alice had not a moment to think"
+ " about stopping herself before she found herself falling down a very deep"
+ " well.";
testPut(new Location(bucket, "p5"), p5);
final boolean[] is = { false };
String query = loadJson(JsonUtil.getJsonPath(RiakOperationsTest.class,
"testFromOfficialsByRawJson"));
final ArrayNode[] actual = new ArrayNode[1];
RiakFuture waiter = this.target.mapReduce(query,
new TestingHandler<MapReduceResponse>() {
@Override
public void handle(
RiakContentsResponse<MapReduceResponse> response)
throws Exception {
MapReduceResponse mrr = response.getContents();
if (mrr.getDone()) {
is[0] = true;
} else {
actual[0] = mrr.getResponse();
}
}
});
wait(waiter, is);
testDelete(new Location(bucket, "p1"));
testDelete(new Location(bucket, "p2"));
testDelete(new Location(bucket, "p5"));
JsonNode expected = JsonUtil.read(RiakOperationsTest.class,
"testFromOfficialsByRawJson_Expected");
assertEquals(expected, actual[0]);
}
protected void wait(final RiakFuture waiter, final boolean[] is)
throws InterruptedException {
assertTrue("test is timeout.", waiter.await(3, TimeUnit.SECONDS));
assertTrue(is[0]);
assertTrue(waiter.isDone());
}
@Test
public void testPost() throws Exception {
Location location = new Location("testPost", "");
String testdata = new Date() + "\n";
Location returned = testPost(location, testdata);
testDelete(returned);
returned = testPostWithReturn(location, testdata);
testDelete(returned);
}
public Location testPost(final Location location, final String testdata)
throws Exception {
final boolean[] is = { false };
DefaultRiakObject ro = new DefaultRiakObject(location);
ro.setContent(testdata.getBytes());
final Location[] loc = new Location[1];
RiakFuture waiter = this.target.post(ro,
new TestingHandler<RiakObject<byte[]>>() {
@Override
public void handle(
RiakContentsResponse<RiakObject<byte[]>> response)
throws Exception {
RiakObject<byte[]> returned = response.getContents();
assertNotNull(returned.getLocation());
Location l = returned.getLocation();
assertEquals(location.getBucket(), l.getBucket());
assertFalse(l.getKey().isEmpty());
loc[0] = l;
is[0] = true;
}
});
assertTrue("time is over.", waiter.await(5, TimeUnit.SECONDS));
// wait(waiter, is);
return loc[0];
}
public Location testPostWithReturn(final Location location,
final String testdata) throws Exception {
final boolean[] is = { false };
DefaultRiakObject ro = new DefaultRiakObject(location);
ro.setContent(testdata.getBytes());
PutOptions options = new DefaultPutOptions() {
@Override
public boolean getReturnBody() {
return true;
}
};
final Location[] loc = new Location[1];
RiakFuture waiter = this.target.post(ro, options,
new TestingHandler<RiakObject<byte[]>>() {
@Override
public void handle(
RiakContentsResponse<RiakObject<byte[]>> response)
throws Exception {
RiakObject<byte[]> returned = response.getContents();
assertNotNull(returned.getLocation());
Location l = returned.getLocation();
assertEquals(location.getBucket(), l.getBucket());
assertFalse(l.getKey().isEmpty());
loc[0] = l;
is[0] = true;
}
});
wait(waiter, is);
return loc[0];
}
} |
package com.browseengine.bobo.test;
import com.browseengine.bobo.test.section.TestSectionSearch;
import com.browseengine.bobo.test.solr.BoboSolrTestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
public class UnitTestSuite {
public static Test suite(){
TestSuite suite=new TestSuite();
suite.addTestSuite(BoboTestCase.class);
suite.addTestSuite(ProtoBufConvertTest.class);
suite.addTestSuite(FacetHandlerTest.class);
suite.addTestSuite(TestSectionSearch.class);
suite.addTestSuite(BoboSolrTestCase.class);
suite.addTestSuite(BoboFacetIteratorTest.class);
suite.addTestSuite(FacetNotValuesTest.class);
return suite;
}
/**
* @param args
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
} |
package util.propnet.architecture;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import util.gdl.grammar.GdlConstant;
import util.gdl.grammar.GdlFunction;
import util.gdl.grammar.GdlProposition;
import util.gdl.grammar.GdlTerm;
import util.logging.GamerLogger;
import util.propnet.architecture.components.Proposition;
import util.propnet.architecture.components.Transition;
import util.statemachine.Role;
/**
* The PropNet class is designed to represent Propositional Networks.
*
* A propositional network (also known as a "propnet") is a way of representing
* a game as a logic circuit. States of the game are represented by assignments
* of TRUE or FALSE to "base" propositions, each of which represents a single
* fact that can be true about the state of the game. For example, in a game of
* Tic-Tac-Toe, the fact (cell 1 1 x) indicates that the cell (1,1) has an 'x'
* in it. That fact would correspond to a base proposition, which would be set
* to TRUE to indicate that the fact is true in the current state of the game.
* Likewise, the base corresponding to the fact (cell 1 1 o) would be false,
* because in that state of the game there isn't an 'o' in the cell (1,1).
*
* A state of the game is uniquely determined by the assignment of truth values
* to the base propositions in the propositional network. Every assignment of
* truth values to base propositions corresponds to exactly one unique state of
* the game.
*
* Given the values of the base propositions, you can use the connections in
* the network (AND gates, OR gates, NOT gates) to determine the truth values
* of other propositions. For example, you can determine whether the terminal
* proposition is true: if that proposition is true, the game is over when it
* reaches this state. Otherwise, if it is false, the game isn't over. You can
* also determine the value of the goal propositions, which represent facts
* like (goal xplayer 100). If that proposition is true, then that fact is true
* in this state of the game, which means that xplayer has 100 points.
*
* You can also use a propositional network to determine the next state of the
* game, given the current state and the moves for each player. First, you set
* the input propositions which correspond to each move to TRUE. Once that has
* been done, you can determine the truth value of the transitions. Each base
* proposition has a "transition" component going into it. This transition has
* the truth value that its base will take on in the next state of the game.
*
* For further information about propositional networks, see:
*
* "Decomposition of Games for Efficient Reasoning" by Eric Schkufza.
* "Factoring General Games using Propositional Automata" by Evan Cox et al.
*
* @author Sam Schreiber
*/
public final class PropNet implements Serializable
{
private static final long serialVersionUID = -6425163053203784512L;
/** References to every component in the PropNet. */
private final Set<Component> components;
/** References to every Proposition in the PropNet. */
private final Set<Proposition> propositions;
/** References to every BaseProposition in the PropNet, indexed by name. */
private final Map<GdlTerm, Proposition> basePropositions;
/** References to every InputProposition in the PropNet, indexed by name. */
private final Map<GdlTerm, Proposition> inputPropositions;
private final Map<Role, Set<Proposition>> legalPropositions;
/** References to every GoalProposition in the PropNet, indexed by role. */
private final Map<Role, Set<Proposition>> goalPropositions;
/** A reference to the single, unique, InitProposition. */
private final Proposition initProposition;
/** A reference to the single, unique, TerminalProposition. */
private final Proposition terminalProposition;
private final Map<Proposition, Proposition> legalInputMap;
/** A helper list of all of the roles. */
private final List<Role> roles;
public void addComponent(Component c)
{
components.add(c);
if (c instanceof Proposition) propositions.add((Proposition)c);
}
/**
* Creates a new PropNet from a list of Components, along with indices over
* those components.
*
* @param components
* A list of Components.
*/
public PropNet(List<Role> roles, Set<Component> components)
{
this.roles = roles;
this.components = components;
this.propositions = recordPropositions();
this.basePropositions = recordBasePropositions();
this.inputPropositions = recordInputPropositions();
this.legalPropositions = recordLegalPropositions();
this.goalPropositions = recordGoalPropositions();
this.initProposition = recordInitProposition();
this.terminalProposition = recordTerminalProposition();
this.legalInputMap = makeLegalInputMap();
for (Proposition p : propositions)
{
for (Component c : p.getOutputs())
{
for (Component c2 : c.getOutputs())
{
if (!(c2 instanceof Proposition))
{
System.out.println(p + " " + c + " " + c2);
}
}
}
}
}
public List<Role> getRoles()
{
return roles;
}
public Map<Proposition, Proposition> getLegalInputMap()
{
return legalInputMap;
}
private Map<Proposition, Proposition> makeLegalInputMap() {
Map<Proposition, Proposition> legalInputMap = new HashMap<Proposition, Proposition>();
for (Proposition inputProp : inputPropositions.values())
{
List<GdlTerm> inputPropBody = ((GdlFunction)inputProp.getName()).getBody();
for (Set<Proposition> legalProps : legalPropositions.values())
{
for (Proposition legalProp : legalProps)
{
List<GdlTerm> legalPropBody = ((GdlFunction)legalProp.getName()).getBody();
if (legalPropBody.equals(inputPropBody))
{
legalInputMap.put(inputProp, legalProp);
legalInputMap.put(legalProp, inputProp);
}
}
}
}
return legalInputMap;
}
/**
* Getter method.
*
* @return References to every BaseProposition in the PropNet, indexed by
* name.
*/
public Map<GdlTerm, Proposition> getBasePropositions()
{
return basePropositions;
}
/**
* Getter method.
*
* @return References to every Component in the PropNet.
*/
public Set<Component> getComponents()
{
return components;
}
/**
* Getter method.
*
* @return References to every GoalProposition in the PropNet, indexed by
* player name.
*/
public Map<Role, Set<Proposition>> getGoalPropositions()
{
return goalPropositions;
}
/**
* Getter method. A reference to the single, unique, InitProposition.
*
* @return
*/
public Proposition getInitProposition()
{
return initProposition;
}
/**
* Getter method.
*
* @return References to every InputProposition in the PropNet, indexed by
* name.
*/
public Map<GdlTerm, Proposition> getInputPropositions()
{
return inputPropositions;
}
public Map<Role, Set<Proposition>> getLegalPropositions()
{
return legalPropositions;
}
/**
* Getter method.
*
* @return References to every Proposition in the PropNet.
*/
public Set<Proposition> getPropositions()
{
return propositions;
}
/**
* Getter method.
*
* @return A reference to the single, unique, TerminalProposition.
*/
public Proposition getTerminalProposition()
{
return terminalProposition;
}
/**
* Returns a representation of the PropNet in .dot format.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("digraph propNet\n{\n");
for ( Component component : components )
{
sb.append("\t" + component.toString() + "\n");
}
sb.append("}");
return sb.toString();
}
/**
* Outputs the propnet in .dot format to a particular file.
* This can be viewed with tools like Graphviz and ZGRViewer.
*
* @param filename the name of the file to output to
*/
public void renderToFile(String filename) {
try {
File f = new File(filename);
FileOutputStream fos = new FileOutputStream(f);
OutputStreamWriter fout = new OutputStreamWriter(fos, "UTF-8");
fout.write(toString());
fout.close();
fos.close();
} catch(Exception e) {
GamerLogger.logStackTrace("StateMachine", e);
}
}
/**
* Builds an index over the BasePropositions in the PropNet.
*
* @return An index over the BasePropositions in the PropNet.
*/
private Map<GdlTerm, Proposition> recordBasePropositions()
{
Map<GdlTerm, Proposition> basePropositions = new HashMap<GdlTerm, Proposition>();
for ( Proposition proposition : propositions )
{
if ( proposition.getInputs().size() > 0 )
{
Component component = proposition.getSingleInput();
if ( component instanceof Transition )
{
basePropositions.put(proposition.getName(), proposition);
}
}
}
return basePropositions;
}
/**
* Builds an index over the GoalPropositions in the PropNet.
*
* @return An index over the GoalPropositions in the PropNet.
*/
private Map<Role, Set<Proposition>> recordGoalPropositions()
{
Map<Role, Set<Proposition>> goalPropositions = new HashMap<Role, Set<Proposition>>();
for ( Proposition proposition : propositions )
{
if ( proposition.getName() instanceof GdlFunction )
{
GdlFunction function = (GdlFunction) proposition.getName();
if ( function.getName().getValue().equals("goal") )
{
GdlConstant name = (GdlConstant) function.get(0);
GdlProposition prop = (GdlProposition)name.toSentence();
Role r = new Role(prop);
if ( !goalPropositions.containsKey(r) )
{
goalPropositions.put(r, new HashSet<Proposition>());
}
goalPropositions.get(r).add(proposition);
}
}
}
return goalPropositions;
}
/**
* Returns a reference to the single, unique, InitProposition.
*
* @return A reference to the single, unique, InitProposition.
*/
private Proposition recordInitProposition()
{
for ( Proposition proposition : propositions )
{
if ( proposition.getName() instanceof GdlConstant )
{
GdlConstant constant = (GdlConstant) proposition.getName();
if ( constant.getValue().equals("INIT") )
{
return proposition;
}
}
}
return null;
}
/**
* Builds an index over the InputPropositions in the PropNet.
*
* @return An index over the InputPropositions in the PropNet.
*/
private Map<GdlTerm, Proposition> recordInputPropositions()
{
Map<GdlTerm, Proposition> inputPropositions = new HashMap<GdlTerm, Proposition>();
for ( Proposition proposition : propositions )
{
if ( proposition.getName() instanceof GdlFunction )
{
GdlFunction function = (GdlFunction) proposition.getName();
if ( function.getName().getValue().equals("does") )
{
inputPropositions.put(proposition.getName(), proposition);
}
}
}
return inputPropositions;
}
private Map<Role, Set<Proposition>> recordLegalPropositions()
{
Map<Role, Set<Proposition>> legalPropositions = new HashMap<Role, Set<Proposition>>();
for ( Proposition proposition : propositions )
{
if ( proposition.getName() instanceof GdlFunction )
{
GdlFunction function = (GdlFunction) proposition.getName();
if ( function.getName().getValue().equals("legal") )
{
GdlConstant name = (GdlConstant) function.get(0);
GdlProposition prop = (GdlProposition)name.toSentence();
Role r = new Role(prop);
if ( !legalPropositions.containsKey(r) )
{
legalPropositions.put(r, new HashSet<Proposition>());
}
legalPropositions.get(r).add(proposition);
}
}
}
return legalPropositions;
}
/**
* Builds an index over the Propositions in the PropNet.
*
* @return An index over Propositions in the PropNet.
*/
private Set<Proposition> recordPropositions()
{
Set<Proposition> propositions = new HashSet<Proposition>();
for ( Component component : components )
{
if ( component instanceof Proposition )
{
propositions.add((Proposition) component);
}
}
return propositions;
}
/**
* Records a reference to the single, unique, TerminalProposition.
*
* @return A reference to the single, unqiue, TerminalProposition.
*/
private Proposition recordTerminalProposition()
{
for ( Proposition proposition : propositions )
{
if ( proposition.getName() instanceof GdlConstant )
{
GdlConstant constant = (GdlConstant) proposition.getName();
if ( constant.getValue().equals("terminal") )
{
return proposition;
}
}
}
return null;
}
} |
package mod._sc;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.SOfficeFactory;
import com.sun.star.document.XImporter;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
/**
* Test for object which is represented by service
* <code>com.sun.star.comp.Calc.XMLContentImporter</code>. <p>
* Object implements the following interfaces :
* <ul>
* <li><code>com::sun::star::lang::XInitialization</code></li>
* <li><code>com::sun::star::document::XImporter</code></li>
* <li><code>com::sun::star::document::XFilter</code></li>
* <li><code>com::sun::star::document::ImportFilter</code></li>
* <li><code>com::sun::star::beans::XPropertySet</code></li>
* <li><code>com::sun::star::xml::sax::XDocumentHandler</code></li>
* </ul>
* @see com.sun.star.lang.XInitialization
* @see com.sun.star.document.XImporter
* @see com.sun.star.document.XFilter
* @see com.sun.star.document.ImportFilter
* @see com.sun.star.beans.XPropertySet
* @see com.sun.star.xml.sax.XDocumentHandler
* @see ifc.lang._XInitialization
* @see ifc.document._XImporter
* @see ifc.document._XFilter
* @see ifc.document._XExporter
* @see ifc.beans._XPropertySet
* @see ifc.xml.sax._XDocumentHandler
*/
public class XMLContentImporter extends TestCase {
XSpreadsheetDocument xSheetDoc;
XComponent comp ;
/**
* New spreadsheet document created.
*/
protected void initialize( TestParameters tParam, PrintWriter log ) {
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() );
try {
log.println( "creating a Spreadsheet document" );
xSheetDoc = SOF.createCalcDoc( null );
comp = (XComponent) UnoRuntime.queryInterface
(XComponent.class, xSheetDoc) ;
} catch ( com.sun.star.uno.Exception e ) {
// Some exception occures.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
/**
* Spreadsheet document destroyed.
*/
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing document " );
util.DesktopTools.closeDoc(comp);
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* Creates an instance of the service
* <code>com.sun.star.comp.Calc.XMLContentImporter</code><p>
*
* The calc document is set as a target document for importer.
* Imported XML-data contains only content tags including table
* with test table name.
* After import table name getting from
* target document is checked.
* Object relations created :
* <ul>
* <li> <code>'XDocumentHandler.XMLData'</code> for
* {@link ifc.xml.sax._XDocumentHandler} interface </li>
* <li> <code>'XDocumentHandler.ImportChecker'</code> for
* {@link ifc.xml.sax._XDocumentHandler} interface </li>
* <li> <code>'TargetDocument'</code> for
* {@link ifc.document._XImporter} interface </li>
* </ul>
*/
public synchronized TestEnvironment createTestEnvironment( TestParameters tParam,
PrintWriter log )
throws StatusException {
XInterface oObj = null;
Object oInt = null ;
// creation of testobject here
// first we write what we are intend to do to log file
log.println( "creating a test environment" );
XMultiServiceFactory xMSF = (XMultiServiceFactory)tParam.getMSF() ;
try {
oInt = xMSF.createInstance
("com.sun.star.comp.Calc.XMLContentImporter") ;
XImporter imp = (XImporter) UnoRuntime.queryInterface
(XImporter.class, oInt) ;
imp.setTargetDocument(comp);
} catch (com.sun.star.uno.Exception e) {
e.printStackTrace(log) ;
throw new StatusException("Can't create component.", e) ;
}
oObj = (XInterface) oInt ;
// create testobject here
log.println( "creating a new environment for Paragraph object" );
TestEnvironment tEnv = new TestEnvironment( oObj );
// adding relations
tEnv.addObjRelation("TargetDocument", comp) ;
final String impValue = "XMLContentImporter_test" ;
// adding relation for XDocumentHandler
String[][] xml = new String[][] {
{"start", "office:document-content",
"xmlns:office", "CDATA", "http://openoffice.org/2000/office",
"xmlns:text", "CDATA", "http://openoffice.org/2000/text",
"xmlns:table", "CDATA", "http://openoffice.org/2000/table",
"office:class", "CDATA", "spreadsheet"
},
{"start", "office:body"},
{"start", "table:table",
"table:name", "CDATA", impValue},
{"end", "table:table"},
{"end", "office:body"},
{"end", "office:document-content"}} ;
tEnv.addObjRelation("XDocumentHandler.XMLData", xml) ;
//save to log content before import
final PrintWriter fLog = log;
final XSpreadsheets xSheets = xSheetDoc.getSheets();
log.println("Sheets before importing :") ;
String[] names = xSheets.getElementNames() ;
for (int i = 0; i < names.length; i++) {
log.println(" " + names[i]) ;
}
tEnv.addObjRelation("XDocumentHandler.ImportChecker",
new ifc.xml.sax._XDocumentHandler.ImportChecker() {
public boolean checkImport() {
fLog.println("Sheet names :") ;
String[] snames = xSheets.getElementNames() ;
for (int i = 0; i < snames.length; i++) {
fLog.println(" " + snames[i]) ;
}
return xSheets.hasByName(impValue) ;
}
}) ;
return tEnv;
} // finish method getTestEnvironment
} |
package com.thoughtworks.xstream.core;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import java.lang.reflect.Field;
import java.security.AccessControlException;
import java.text.AttributedString;
import java.util.HashMap;
import java.util.Map;
public class JVM {
private ReflectionProvider reflectionProvider;
private Map loaderCache = new HashMap();
private final boolean supportsAWT = loadClass("java.awt.Color") != null;
private final boolean supportsSQL = loadClass("java.sql.Date") != null;
private static final boolean reverseFieldOrder;
private static final String vendor = System.getProperty("java.vm.vendor");
private static final float majorJavaVersion = getMajorJavaVersion();
static final float DEFAULT_JAVA_VERSION = 1.3f;
static {
boolean reverse = false;
final Field[] fields = AttributedString.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equals("text")) {
reverse = i > 3;
}
}
reverseFieldOrder = reverse;
}
/**
* Parses the java version system property to determine the major java version,
* ie 1.x
*
* @return A float of the form 1.x
*/
private static final float getMajorJavaVersion() {
try {
return Float.parseFloat(System.getProperty("java.specification.version"));
} catch ( NumberFormatException e ){
// Some JVMs may not conform to the x.y.z java.version format
return DEFAULT_JAVA_VERSION;
}
}
public static boolean is14() {
return majorJavaVersion >= 1.4f;
}
public static boolean is15() {
return majorJavaVersion >= 1.5f;
}
public static boolean is16() {
return majorJavaVersion >= 1.6f;
}
private static boolean isSun() {
return vendor.indexOf("Sun") != -1;
}
private static boolean isApple() {
return vendor.indexOf("Apple") != -1;
}
private static boolean isHPUX() {
return vendor.indexOf("Hewlett-Packard Company") != -1;
}
private static boolean isIBM() {
return vendor.indexOf("IBM") != -1;
}
private static boolean isBlackdown() {
return vendor.indexOf("Blackdown") != -1;
}
/*
* Support for sun.misc.Unsafe and sun.reflect.ReflectionFactory is present
* in JRockit versions R25.1.0 and later, both 1.4.2 and 5.0 (and in future
* 6.0 builds).
*/
private static boolean isBEAWithUnsafeSupport() {
// This property should be "BEA Systems, Inc."
if (vendor.indexOf("BEA") != -1) {
/*
* Recent 1.4.2 and 5.0 versions of JRockit have a java.vm.version
* string starting with the "R" JVM version number, i.e.
* "R26.2.0-38-57237-1.5.0_06-20060209..."
*/
String vmVersion = System.getProperty("java.vm.version");
if (vmVersion.startsWith("R")) {
/*
* We *could* also check that it's R26 or later, but that is
* implicitly true
*/
return true;
}
/*
* For older JRockit versions we can check java.vm.info. JRockit
* 1.4.2 R24 -> "Native Threads, GC strategy: parallel" and JRockit
* 5.0 R25 -> "R25.2.0-28".
*/
String vmInfo = System.getProperty("java.vm.info");
if (vmInfo != null) {
// R25.1 or R25.2 supports Unsafe, other versions do not
return (vmInfo.startsWith("R25.1") || vmInfo
.startsWith("R25.2"));
}
}
// If non-BEA, or possibly some very old JRockit version
return false;
}
private static boolean isHitachi() {
return vendor.indexOf("Hitachi") != -1;
}
private static boolean isSAP() {
return vendor.indexOf("SAP AG") != -1;
}
public Class loadClass(String name) {
try {
Class clazz = (Class)loaderCache.get(name);
if (clazz == null) {
clazz = Class.forName(name, false, getClass().getClassLoader());
loaderCache.put(name, clazz);
}
return clazz;
} catch (ClassNotFoundException e) {
return null;
}
}
public synchronized ReflectionProvider bestReflectionProvider() {
if (reflectionProvider == null) {
try {
if ( canUseSun14ReflectionProvider() ) {
String cls = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider";
reflectionProvider = (ReflectionProvider) loadClass(cls).newInstance();
} else {
reflectionProvider = new PureJavaReflectionProvider();
}
} catch (InstantiationException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (IllegalAccessException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (AccessControlException e) {
// thrown when trying to access sun.misc package in Applet context.
reflectionProvider = new PureJavaReflectionProvider();
}
}
return reflectionProvider;
}
private boolean canUseSun14ReflectionProvider() {
return (isSun() || isApple() || isHPUX() || isIBM() || isBlackdown() || isBEAWithUnsafeSupport() || isHitachi() || isSAP()) && is14() && loadClass("sun.misc.Unsafe") != null;
}
public static boolean reverseFieldDefinition() {
return reverseFieldOrder;
}
/**
* Checks if the jvm supports awt.
*/
public boolean supportsAWT() {
return this.supportsAWT;
}
/**
* Checks if the jvm supports sql.
*/
public boolean supportsSQL() {
return this.supportsSQL;
}
public static void main(String[] args) {
JVM jvm = new JVM();
System.out.println("XStream JVM diagnostics");
System.out.println("java.specification.version: " + System.getProperty("java.specification.version"));
System.out.println("java.vm.vendor: " + vendor);
System.out.println("Version: " + majorJavaVersion);
System.out.println("Reverse field order: " + reverseFieldOrder);
System.out.println("XStream support for enhanced Mode: " + jvm.canUseSun14ReflectionProvider());
System.out.println("Supports AWT: " + jvm.supportsAWT());
System.out.println("Supports SQL: " + jvm.supportsSQL());
}
} |
package org.jetel.logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SafeLogUtils {
/** Pattern for identifying URL with password in a given text */
private static final Pattern URL_PASSWORD_PATTERN = Pattern.compile(".+://([^/]*?):([^\\*]*?)@.+", Pattern.DOTALL);
/*
* a://b:c@d
*
* Input text matches:
* group #0 = a://b:c@d
* group #1 = b
* group #2 = c
*
*/
/**
* Obfuscates passwords in URLs in given text.
* Moreover secure parameters are backward resolved if it is possible.
*
* @param text - text to obfuscate passwords
* @return obfuscated text
*/
public static String obfuscateSensitiveInformation(String text) {
if (text == null) {
return null;
}
//secondly, try to detect passwords in possible URLs
boolean changed = false;
String result = text;
do {
changed = false;
Matcher m = URL_PASSWORD_PATTERN.matcher(result);
if (m.matches()) {
StringBuilder builder = new StringBuilder(result.substring(0, m.start(2)));
builder.append("***");
builder.append(result.substring(m.end(2)));
result = builder.toString();
changed = true;
}
} while (changed);
return result;
}
private SafeLogUtils() {
}
} |
import java.util.Scanner;
public class Studienberatung {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String antwort = "";
System.out.println("Hast du Abitur[j/n]?");
antwort = scanner.next();
} |
package lib.form;
import hudson.model.AbstractProject;
import hudson.model.FreeStyleProject;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import javax.inject.Inject;
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
public class TextAreaTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Inject
public TestBuilder.DescriptorImpl d;
@Test
@Issue("JENKINS-19457")
public void validation() throws Exception {
j.jenkins.getInjector().injectMembers(this);
FreeStyleProject p = j.createFreeStyleProject();
p.getBuildersList().add(new TestBuilder());
j.configRoundtrip(p);
assertEquals("This is text1", d.text1);
assertEquals("Received This is text1", d.text2);
}
public static class TestBuilder extends Builder {
@DataBoundConstructor
public TestBuilder() {}
public String getText1() {
return "This is text1";
}
public String getText2() {
return "This is text2";
}
@TestExtension
public static class DescriptorImpl extends BuildStepDescriptor<Builder> {
String text1, text2;
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public FormValidation doCheckText1(@QueryParameter String value) {
this.text1 = value;
return FormValidation.ok();
}
public FormValidation doCheckText2(@QueryParameter String text1) {
this.text2 = "Received " + text1;
return FormValidation.ok();
}
}
}
@Issue("JENKINS-27505")
@Test
public void text() throws Exception {
{
String TEXT_TO_TEST = "some\nvalue\n";
FreeStyleProject p = j.createFreeStyleProject();
TextareaTestBuilder target = new TextareaTestBuilder(TEXT_TO_TEST);
p.getBuildersList().add(target);
j.configRoundtrip(p);
j.assertEqualDataBoundBeans(target, p.getBuildersList().get(TextareaTestBuilder.class));
}
// test for a textarea beginning with a empty line.
{
String TEXT_TO_TEST = "\nbegin\n\nwith\nempty\nline\n\n";
FreeStyleProject p = j.createFreeStyleProject();
TextareaTestBuilder target = new TextareaTestBuilder(TEXT_TO_TEST);
p.getBuildersList().add(target);
j.configRoundtrip(p);
j.assertEqualDataBoundBeans(target, p.getBuildersList().get(TextareaTestBuilder.class));
}
// test for a textarea beginning with two empty lines.
{
String TEXT_TO_TEST = "\n\nbegin\n\nwith\ntwo\nempty\nline\n\n";
FreeStyleProject p = j.createFreeStyleProject();
TextareaTestBuilder target = new TextareaTestBuilder(TEXT_TO_TEST);
p.getBuildersList().add(target);
j.configRoundtrip(p);
j.assertEqualDataBoundBeans(target, p.getBuildersList().get(TextareaTestBuilder.class));
}
}
public static class TextareaTestBuilder extends Builder {
private String text;
@DataBoundConstructor
public TextareaTestBuilder(String text) {
this.text = text;
}
public String getText() {
return text;
}
@TestExtension
public static class DescriptorImpl extends BuildStepDescriptor<Builder> {
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
}
}
} |
package traffic.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.jdom.JDOMException;
import org.junit.Test;
import traffic.graph.Graph;
import traffic.graph.GraphNode;
import traffic.strategy.LookaheadShortestPathCarStrategy;
import traffic.strategy.QuadraticSpeedStrategy;
/**
* @author Jochen Wuttke - wuttkej@gmail.com
*
*/
public class SimulationFactoryTest {
@Test (expected=FileNotFoundException.class)
public void testFileNotFound() throws JDOMException, IOException, ConfigurationException {
SimulationFactory.buildSimulator( new File("bad config") );
}
@Test
public void testStart() throws JDOMException, IOException, ConfigurationException {
List<Car> cars = SimulationFactory.buildSimulator( new File("resources/test/config.xml" )).getCars();
assertEquals(cars.get(0).getCurrent(), 0);
assertEquals(cars.get(1).getCurrent(), 4);
assertEquals(cars.get(2).getCurrent(), 3);
assertEquals(cars.get(3).getCurrent(), 8);
assertEquals(cars.get(4).getCurrent(), 3);
}
@Test
public void testCarNum() throws JDOMException, IOException, ConfigurationException {
List<Car> cars = SimulationFactory.buildSimulator( new File("resources/test/config.xml" )).getCars();
assertEquals(cars.get(0).getCarNumber(), 0);
assertEquals(cars.get(1).getCarNumber(), 1);
assertEquals(cars.get(2).getCarNumber(), 2);
assertEquals(cars.get(3).getCarNumber(), 3);
assertEquals(cars.get(4).getCarNumber(), 4);
}
@Test
public void invalidCarStrategyDefaultsCorrectly() throws JDOMException, IOException, ConfigurationException {
List<Car> cars = SimulationFactory.buildSimulator( new File("resources/test/invalid-strategy.xml" )).getCars();
assertEquals( LookaheadShortestPathCarStrategy.class, cars.get(1).getStrategy().getClass() );
}
@Test(expected=ConfigurationException.class)
public void invalidDefaultCarStrategyThrows() throws JDOMException, IOException, ConfigurationException {
List<Car> cars = SimulationFactory.buildSimulator( new File("resources/test/illegal-default-car-strategy.xml" )).getCars();
}
@Test(expected=ConfigurationException.class)
public void noCarThrows() throws JDOMException, IOException, ConfigurationException {
List<Car> cars = SimulationFactory.buildSimulator( new File("resources/test/no-car.xml" )).getCars();
fail( "This should throw a meaningful exception to be handled by main()" );
}
@Test(expected=ConfigurationException.class)
public void noCarsThrows() throws JDOMException, IOException, ConfigurationException {
List<Car> cars = SimulationFactory.buildSimulator( new File("resources/test/no-cars.xml" )).getCars();
fail( "This should throw a meaningful exception to be handled by main()" );
}
@Test
public void invalidStartEndIsIgnored() throws JDOMException, IOException, ConfigurationException {
List<Car> cars = SimulationFactory.buildSimulator( new File("resources/test/invalid-start.xml" )).getCars();
assertEquals( 3, cars.size() );
assertEquals( 0, cars.get(0).getCarNumber() );
assertEquals( 3, cars.get(1).getCarNumber() );
assertEquals( 4, cars.get(2).getCarNumber() );
}
@Test
public void testStrategies() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/config.xml" ) ).getGraph();
assertEquals(g.getNode(6).getCurrentDelay(), 1);
g.addCarAtNode(0, 6);
g.addCarAtNode(1, 6);
assertEquals(5, g.getNode(6).getCurrentDelay()); //Tests Quadratic Speed Strategy
assertEquals(1, g.getNode(1).getCurrentDelay());
g.addCarAtNode(2, 1);
g.addCarAtNode(3, 1);
assertEquals(3, g.getNode(1).getCurrentDelay() ); //Tests Linear Speed Strategy
}
@Test
public void testNeighbors() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/config.xml")).getGraph();
List<GraphNode> neighbors = g.getNodes().get(2).getNeighbors();
int first = neighbors.get(0).getID();
assertEquals(first, 4);
int second = neighbors.get(1).getID();
assertEquals(second, 7);
int third = neighbors.get(2).getID();
assertEquals(third, 9);
}
@Test
public void emptyNeighborListIsIgnored() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/unconnected-node.xml")).getGraph();
assertEquals( g.getNodes().size(), 9);
}
@Test(expected=ConfigurationException.class)
public void noNodesThrows() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator(new File("resources/test/no-nodes.xml")).getGraph();
}
@Test(expected=ConfigurationException.class)
public void noGraphThrows() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/no-graph.xml" )).getGraph();
}
@Test
public void invalidNeighborIsIgnored() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/invalid-neighbor.xml")).getGraph();
List<GraphNode> neighbors = g.getNeighbors( 0 );
assertEquals(1, neighbors.size() );
assertEquals(4, neighbors.get(0).getID() );
neighbors = g.getNeighbors( 1 );
assertEquals(null, neighbors );
}
@Test
public void invalidSpeedStrategyDefaultsCorrectly() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/invalid-strategy2.xml")).getGraph();
assertEquals( QuadraticSpeedStrategy.class, g.getNodes().get(1).getSpeedStrategy().getClass() );
}
@Test
public void loadsAutoGeneratedConfig() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/auto-generated.xml")).getGraph();
//this passes when no unexpected exceptions are thrown
}
@Test
public void setsDelayCorrectly() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/config-weights.xml")).getGraph();
assertEquals( 7, g.getNodes().get(1).getDelay() );
}
@Test
public void setsDelayCorrectly2() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/shortest-path-test-weights.xml")).getGraph();
assertEquals( 4, g.getNodes().get(3).getDelay() );
}
@Test()
public void invalidDelayDefaults() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/config-weights-invalid.xml")).getGraph();
assertEquals( 1, g.getNodes().get(1).getDelay() );
}
@Test()
public void negativeDelayDefaults() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/config-weights-invalid2.xml")).getGraph();
assertEquals( 1, g.getNodes().get(1).getDelay() );
}
@Test
public void nodesHaveAllCars() throws FileNotFoundException, ConfigurationException {
Graph g = SimulationFactory.buildSimulator( new File("resources/test/shortest-path-test-weights.xml")).getGraph();
assertEquals( 3, g.getNode(2).getCars().size() );
}
} |
package org.voltdb.planner;
import java.net.URL;
import java.util.List;
import junit.framework.TestCase;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Table;
import org.voltdb.plannodes.AbstractPlanNode;
public class PlannerTestCase extends TestCase {
private PlannerTestAideDeCamp m_aide;
private boolean m_byDefaultPlanForSinglePartition;
protected void failToCompile(String sql, String... patterns)
{
int paramCount = 0;
for (int ii = 0; ii < sql.length(); ii++) {
// Yes, we ARE assuming that test queries don't contain quoted question marks.
if (sql.charAt(ii) == '?') {
paramCount++;
}
}
List<AbstractPlanNode> pn = null;
try {
pn = m_aide.compile(sql, paramCount, m_byDefaultPlanForSinglePartition, null);
fail();
}
catch (PlanningErrorException ex) {
String result = ex.toString();
for (String pattern : patterns) {
if ( ! result.contains(pattern)) {
System.out.println("Did not find pattern '" + pattern + "' in error string '" + result + "'");
fail();
}
}
}
}
protected CompiledPlan compileAdHocPlan(String sql) {
CompiledPlan cp = null;
try {
cp = m_aide.compileAdHocPlan(sql);
assertTrue(cp != null);
}
catch (Exception ex) {
ex.printStackTrace();
fail();
}
return cp;
}
/** A helper here where the junit test can assert success */
protected List<AbstractPlanNode> compileToFragments(String sql)
{
int paramCount = 0;
for (int ii = 0; ii < sql.length(); ii++) {
// Yes, we ARE assuming that test queries don't contain quoted question marks.
if (sql.charAt(ii) == '?') {
paramCount++;
}
}
boolean planForSinglePartitionFalse = false;
return compileWithJoinOrderToFragments(sql, paramCount, planForSinglePartitionFalse, null);
}
/** A helper here where the junit test can assert success */
protected List<AbstractPlanNode> compileWithJoinOrderToFragments(String sql, int paramCount, boolean planForSinglePartition, String joinOrder)
{
List<AbstractPlanNode> pn = null;
try {
pn = m_aide.compile(sql, paramCount, planForSinglePartition, joinOrder);
}
catch (Exception ex) {
ex.printStackTrace();
fail();
}
assertTrue(pn != null);
assertFalse(pn.isEmpty());
if (planForSinglePartition) {
assertTrue(pn.size() == 1);
}
return pn;
}
protected AbstractPlanNode compileWithJoinOrder(String sql, String joinOrder)
{
int paramCount = 0;
for (int ii = 0; ii < sql.length(); ii++) {
// Yes, we ARE assuming that test queries don't contain quoted question marks.
if (sql.charAt(ii) == '?') {
paramCount++;
}
}
return compileWithJoinOrder(sql, paramCount, joinOrder);
}
/** A helper here where the junit test can assert success */
protected AbstractPlanNode compileWithJoinOrder(String sql, int paramCount, String joinOrder)
{
List<AbstractPlanNode> pn = null;
try {
pn = compileWithJoinOrderToFragments(sql, paramCount, m_byDefaultPlanForSinglePartition, joinOrder);
}
catch (Exception ex) {
ex.printStackTrace();
fail();
}
assertTrue(pn != null);
assertFalse(pn.isEmpty());
assertTrue(pn.get(0) != null);
return pn.get(0);
}
/** A helper here where the junit test can assert success */
protected AbstractPlanNode compile(String sql)
{
int paramCount = 0;
for (int ii = 0; ii < sql.length(); ii++) {
// Yes, we ARE assuming that test queries don't contain quoted question marks.
if (sql.charAt(ii) == '?') {
paramCount++;
}
}
return compile(sql, paramCount);
}
/** A helper here where the junit test can assert success */
protected AbstractPlanNode compile(String sql, int paramCount)
{
List<AbstractPlanNode> pn = null;
try {
pn = compileWithJoinOrderToFragments(sql, paramCount, m_byDefaultPlanForSinglePartition, null);
}
catch (Exception ex) {
ex.printStackTrace();
fail();
}
assertTrue(pn.get(0) != null);
return pn.get(0);
}
protected void setupSchema(URL ddlURL, String basename,
boolean planForSinglePartition) throws Exception
{
m_aide = new PlannerTestAideDeCamp(ddlURL, basename);
m_byDefaultPlanForSinglePartition = planForSinglePartition;
}
protected void forceReplication()
{
// Set all tables to non-replicated.
Cluster cluster = m_aide.getCatalog().getClusters().get("cluster");
CatalogMap<Table> tmap = cluster.getDatabases().get("database").getTables();
for (Table t : tmap) {
// t.setIsreplicated(true);
assertTrue(t.getIsreplicated());
}
}
protected void forceReplicationExceptForOneTable(String table, String column)
{
// Set all tables to non-replicated.
Cluster cluster = m_aide.getCatalog().getClusters().get("cluster");
CatalogMap<Table> tmap = cluster.getDatabases().get("database").getTables();
for (Table t : tmap) {
assertTrue(t.getIsreplicated());
if (t.getTypeName().equalsIgnoreCase(table)) {
t.setIsreplicated(false);
t.setPartitioncolumn(t.getColumns().get(column));
}
}
}
// TODO: Phase out this functionality, possibly by phasing out PlannerTestAideDeCamp in favor
// of some other utility class -- one that supports inline PARTITION statements in the DDL.
// It really is a hack because it creates an otherwise unlikely condition of
// partitioned tables with no identified partitioning column.
protected void forceHackPartitioning() {
// Set all tables to non-replicated.
Cluster cluster = m_aide.getCatalog().getClusters().get("cluster");
CatalogMap<Table> tmap = cluster.getDatabases().get("database").getTables();
for (Table t : tmap) {
t.setIsreplicated(false);
}
}
Database getDatabase() {
return m_aide.getDatabase();
}
} |
import java.util.Map;
import java.util.Observable;
import java.util.Set;
import java.util.TreeMap;
/*Tournament.java is runnable, main method asks what tournament to create, then calls TournamentModel constructor
* TournamentModel is the brains of the class,
* calls singleton class Brackets with # of brackets, size and type (hold info abt bracket)
* TournamentView displays the bracket, and can tell the Model the results of matches
*/
import java.util.TreeSet;
public class TournamentModel extends Observable{
private Set<Person>[] competitors; //Each index is a bracket
public void setup(int num, int size){ //If dflt no param constructor, init brackets
competitors = new Set[num];
for(int i = 0; i < num; i++) competitors[i] = new TreeSet<Person>();
Brackets.setBrackets(num,size);
setChanged();
notifyObservers();
}
public TournamentModel(int num, int size){ //Number, size of brackets, plus if the brackets are double or single elim
setup(num, size);
}
public void addPerson(Person person, int bracket){
competitors[bracket].add(person);
Brackets.getBracket(bracket).addPerson(person);
setChanged();
notifyObservers();
}
public void advancePerson(Person person, int bracket, String notes){
Brackets.getBracket(bracket).recordWin(person, notes);
}
public Set<Person> getCompetitors(int bracket){
return competitors[bracket];
}
public int getNumBrackets(){return Brackets.getNum();}
} |
package org.yamcs.web.rest;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.protobuf.Rest.GetApiOverviewResponse;
import org.yamcs.protobuf.SchemaRest;
import org.yamcs.security.AuthenticationToken;
import org.yamcs.web.HttpException;
import org.yamcs.web.HttpHandler;
import org.yamcs.web.InternalServerErrorException;
import org.yamcs.web.MethodNotAllowedException;
import org.yamcs.web.RouteHandler;
import org.yamcs.web.rest.archive.ArchiveAlarmRestHandler;
import org.yamcs.web.rest.archive.ArchiveCommandRestHandler;
import org.yamcs.web.rest.archive.ArchiveDownloadRestHandler;
import org.yamcs.web.rest.archive.ArchiveEventRestHandler;
import org.yamcs.web.rest.archive.ArchiveIndexRestHandler;
import org.yamcs.web.rest.archive.ArchivePacketRestHandler;
import org.yamcs.web.rest.archive.ArchiveParameterRestHandler;
import org.yamcs.web.rest.archive.ArchiveStreamRestHandler;
import org.yamcs.web.rest.archive.ArchiveTableRestHandler;
import org.yamcs.web.rest.archive.ArchiveTagRestHandler;
import org.yamcs.web.rest.mdb.MDBAlgorithmRestHandler;
import org.yamcs.web.rest.mdb.MDBCommandRestHandler;
import org.yamcs.web.rest.mdb.MDBContainerRestHandler;
import org.yamcs.web.rest.mdb.MDBParameterRestHandler;
import org.yamcs.web.rest.mdb.MDBRestHandler;
import org.yamcs.web.rest.processor.ProcessorCommandQueueRestHandler;
import org.yamcs.web.rest.processor.ProcessorCommandRestHandler;
import org.yamcs.web.rest.processor.ProcessorParameterRestHandler;
import org.yamcs.web.rest.processor.ProcessorRestHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.QueryStringDecoder;
/**
* Matches a request uri to a registered route handler. Stops on the first
* match. Every instance can register a different set of routes, if the magic
* token :instance appears in the path, than this is used to point to an
* instance-specific route, otherwise the first registered match from any
* instance is called.
* <p>
* The Router itself has the same granularity as HttpServer: one instance only.
* <p>
* When matching a route, priority is first given to built-in routes, only if
* none match the first matching instance-specific dynamic route is matched.
* These latter routes usually mention ':instance' in their url, which will be
* expanded upon registration into the actual yamcs instance.
*/
public class Router {
private static final Pattern ROUTE_PATTERN = Pattern.compile("(\\/)?:(\\w+)([\\?\\*])?");
private static final Logger log = LoggerFactory.getLogger(Router.class);
// Order, because patterns are matched top-down in insertion order
private LinkedHashMap<Pattern, Map<HttpMethod, RouteConfig>> defaultRoutes = new LinkedHashMap<>();
private LinkedHashMap<Pattern, Map<HttpMethod, RouteConfig>> dynamicRoutes = new LinkedHashMap<>();
public Router() {
registerRouteHandler(null, new ClientRestHandler());
registerRouteHandler(null, new DisplayRestHandler());
registerRouteHandler(null, new InstanceRestHandler());
registerRouteHandler(null, new LinkRestHandler());
registerRouteHandler(null, new UserRestHandler());
registerRouteHandler(null, new ArchiveAlarmRestHandler());
registerRouteHandler(null, new ArchiveCommandRestHandler());
registerRouteHandler(null, new ArchiveDownloadRestHandler());
registerRouteHandler(null, new ArchiveEventRestHandler());
registerRouteHandler(null, new ArchiveIndexRestHandler());
registerRouteHandler(null, new ArchivePacketRestHandler());
registerRouteHandler(null, new ArchiveParameterRestHandler());
registerRouteHandler(null, new ArchiveStreamRestHandler());
registerRouteHandler(null, new ArchiveTableRestHandler());
registerRouteHandler(null, new ArchiveTagRestHandler());
registerRouteHandler(null, new ProcessorRestHandler());
registerRouteHandler(null, new ProcessorParameterRestHandler());
registerRouteHandler(null, new ProcessorCommandRestHandler());
registerRouteHandler(null, new ProcessorCommandQueueRestHandler());
registerRouteHandler(null, new MDBRestHandler());
registerRouteHandler(null, new MDBParameterRestHandler());
registerRouteHandler(null, new MDBContainerRestHandler());
registerRouteHandler(null, new MDBCommandRestHandler());
registerRouteHandler(null, new MDBAlgorithmRestHandler());
registerRouteHandler(null, new OverviewRouteHandler());
}
// Using method handles for better invoke performance
public void registerRouteHandler(String instance, RouteHandler routeHandler) {
MethodHandles.Lookup lookup = MethodHandles.lookup();
Method[] declaredMethods = routeHandler.getClass().getDeclaredMethods();
// Temporary structure used to sort before map insertion
List<RouteConfig> routeConfigs = new ArrayList<>();
try {
for (int i = 0; i < declaredMethods.length; i++) {
Method reflectedMethod = declaredMethods[i];
if (reflectedMethod.isAnnotationPresent(Route.class) || reflectedMethod.isAnnotationPresent(Routes.class)) {
MethodHandle handle = lookup.unreflect(reflectedMethod);
Route[] anns = reflectedMethod.getDeclaredAnnotationsByType(Route.class);
for (Route ann : anns) {
for (String m : ann.method()) {
HttpMethod httpMethod = HttpMethod.valueOf(m);
routeConfigs.add(new RouteConfig(routeHandler, ann.path(), ann.priority(), httpMethod, handle));
}
}
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException("Could not access @Route annotated method in " + routeHandler.getClass());
}
// Sort in a way that increases chances of a good URI match
// 1. @Route(priority=true) first
// 2. Descending on path length
// 3. Actual path contents (should not matter too much)
Collections.sort(routeConfigs);
LinkedHashMap<Pattern, Map<HttpMethod, RouteConfig>> targetRoutes;
targetRoutes = (instance == null) ? defaultRoutes : dynamicRoutes;
for (RouteConfig routeConfig : routeConfigs) {
String routeString = routeConfig.originalPath;
if (instance != null) { // Expand :instance upon registration (only for dynamic routes)
routeString = routeString.replace(":instance", instance);
}
Pattern pattern = toPattern(routeString);
targetRoutes.putIfAbsent(pattern, new LinkedHashMap<>());
Map<HttpMethod, RouteConfig> configByMethod = targetRoutes.get(pattern);
configByMethod.put(routeConfig.httpMethod, routeConfig);
}
}
public void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req, AuthenticationToken token) {
QueryStringDecoder qsDecoder = new QueryStringDecoder(req.getUri());
RestRequest restReq = new RestRequest(ctx, req, qsDecoder, token);
try {
// Decode first the path/qs difference, then url-decode the path
String uri = new URI(qsDecoder.path()).getPath();
RouteMatch match = matchURI(req.getMethod(), uri);
restReq.setRouteMatch(match);
if (match != null) {
dispatch(restReq, match);
} else {
HttpHandler.sendPlainTextError(ctx, HttpResponseStatus.NOT_FOUND);
}
} catch (URISyntaxException e) {
RestHandler.sendRestError(restReq, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
} catch (MethodNotAllowedException e) {
RestHandler.sendRestError(restReq, e.getStatus(), e);
}
}
protected RouteMatch matchURI(HttpMethod method, String uri) throws MethodNotAllowedException {
Set<HttpMethod> allowedMethods = null;
for (Entry<Pattern, Map<HttpMethod, RouteConfig>> entry : defaultRoutes.entrySet()) {
Matcher matcher = entry.getKey().matcher(uri);
if (matcher.matches()) {
Map<HttpMethod, RouteConfig> byMethod = entry.getValue();
if (byMethod.containsKey(method)) {
return new RouteMatch(matcher, byMethod.get(method));
} else {
if (allowedMethods == null) {
allowedMethods = new HashSet<>(4);
}
allowedMethods.addAll(byMethod.keySet());
}
}
}
for (Entry<Pattern, Map<HttpMethod, RouteConfig>> entry : dynamicRoutes.entrySet()) {
Matcher matcher = entry.getKey().matcher(uri);
if (matcher.matches()) {
Map<HttpMethod, RouteConfig> byMethod = entry.getValue();
if (byMethod.containsKey(method)) {
return new RouteMatch(matcher, byMethod.get(method));
} else {
if (allowedMethods == null) {
allowedMethods = new HashSet<>(4);
}
allowedMethods.addAll(byMethod.keySet());
}
}
}
if (allowedMethods != null) { // One or more rules matched, but with wrong method
throw new MethodNotAllowedException(method, uri, allowedMethods);
} else { // No rule was matched
return null;
}
}
protected void dispatch(RestRequest req, RouteMatch match) {
try {
RouteHandler target = match.routeConfig.routeHandler;
// FIXME handleRequest must never return null! Futures are used to follow up on handling
ChannelFuture responseFuture = (ChannelFuture) match.routeConfig.handle.invoke(target, req);
if (responseFuture == null) return; // Allowed, when the specific handler prefers to do this
/**
* Follow-up on the successful write, to provide some hints when a future was not actually
* successfully delivered.
*/
responseFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
log.error("Error writing out response to client", future.cause());
future.channel().close();
}
}
});
} catch (InternalServerErrorException e) {
log.error("Reporting internal server error to client", e);
RestHandler.sendRestError(req, e.getStatus(), e);
} catch (HttpException e) {
log.warn("Sending nominal exception back to client: {}", e.getMessage());
RestHandler.sendRestError(req, e.getStatus(), e);
} catch (Throwable t) {
log.error("Unexpected error " + t, t);
RestHandler.sendRestError(req, HttpResponseStatus.INTERNAL_SERVER_ERROR, t);
}
}
/*
* Pattern matching loosely inspired from angular and express.js
*/
private Pattern toPattern(String route) {
Matcher matcher = ROUTE_PATTERN.matcher(route);
StringBuffer buf = new StringBuffer("^");
while (matcher.find()) {
boolean star = ("*".equals(matcher.group(3)));
boolean optional = ("?".equals(matcher.group(3)));
String slash = (matcher.group(1) != null) ? matcher.group(1) : "";
StringBuffer replacement = new StringBuffer();
if (optional) {
replacement.append("(?:");
replacement.append(slash);
replacement.append("(?<").append(matcher.group(2)).append(">");
replacement.append(star ? ".+?" : "[^/]+");
replacement.append(")?)?");
} else {
replacement.append(slash);
replacement.append("(?<").append(matcher.group(2)).append(">");
replacement.append(star ? ".+?" : "[^/]+");
replacement.append(")");
}
matcher.appendReplacement(buf, replacement.toString());
}
matcher.appendTail(buf);
return Pattern.compile(buf.append("$").toString());
}
/**
* Struct containing all non-path route configuration
*/
public static final class RouteConfig implements Comparable<RouteConfig> {
final RouteHandler routeHandler;
final String originalPath;
final boolean priority;
final HttpMethod httpMethod;
final MethodHandle handle;
RouteConfig(RouteHandler routeHandler, String originalPath, boolean priority, HttpMethod httpMethod, MethodHandle handle) {
this.routeHandler = routeHandler;
this.originalPath = originalPath;
this.priority = priority;
this.httpMethod = httpMethod;
this.handle = handle;
}
@Override
public int compareTo(RouteConfig o) {
int priorityCompare = Boolean.compare(priority, o.priority);
if (priorityCompare != 0) {
return -priorityCompare;
} else {
int pathLengthCompare = Integer.compare(originalPath.length(), o.originalPath.length());
if (pathLengthCompare != 0) {
return -pathLengthCompare;
} else {
return originalPath.compareTo(o.originalPath);
}
}
}
}
/**
* Represents a matched route pattern
*/
public static final class RouteMatch {
final Matcher regexMatch;
final RouteConfig routeConfig;
RouteMatch(Matcher regexMatch, RouteConfig routeConfig) {
this.regexMatch = regexMatch;
this.routeConfig = routeConfig;
}
}
/**
* 'Documents' all registered resources
*/
private final class OverviewRouteHandler extends RestHandler {
@Route(path="/api", method="GET")
public ChannelFuture getApiOverview(RestRequest req) throws HttpException {
// Unique accross http methods, and according to insertion order
Set<String> urls = new LinkedHashSet<>();
for (Map<HttpMethod, RouteConfig> map : defaultRoutes.values()) {
map.values().forEach(v -> urls.add(v.originalPath));
}
GetApiOverviewResponse.Builder responseb = GetApiOverviewResponse.newBuilder();
urls.forEach(url -> responseb.addUrl(url));
return sendOK(req, responseb.build(), SchemaRest.GetApiOverviewResponse.WRITE);
}
}
} |
package brockbadgers.flock.Services;
import android.content.Context;
import android.content.Intent;
import android.app.Service;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import brockbadgers.flock.R;
import classes.Person;
@SuppressWarnings("ResourceType")
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
DatabaseReference database;
@Nullable
@Override
public IBinder onBind(Intent intent){
return null;
}
@Override
public void onCreate(){
database = FirebaseDatabase.getInstance().getReference();
listener = new LocationListener(){
@Override
public void onLocationChanged(Location location){
//Publish to the DB
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String ref = sharedPref.getString(getString(R.string.user_id), null);
database.child("users").child(ref).child("lat").setValue(location.getLatitude());
database.child("users").child(ref).child("long").setValue(location.getLongitude());
/*Person person = new Person(location.getLatitude(), location.getLongitude());
person.setId(ref);
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("users").child(person.getId()).setValue(person);*/
Log.d("Long", ""+location.getLongitude());
Log.d("Lat", ""+location.getLatitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
}
@Override
public void onDestroy()
{
super.onDestroy();
if(locationManager != null){
locationManager.removeUpdates(listener);
}
}
} |
package engg2800.image.processing;
import engg2800.image.TransmittedImage;
import engg2800.image.Point;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
/**
* Join two BufferedImage
* @author Aaron Hayes
*/
public class JoinBufferedImages {
/**
* Join three BufferedImages to make one.
* @param a BufferedImage 1
* @param b BufferedImage 2
* @param c BufferedImage 3
* @param offsetA offset from engg2800.image 1 to 2
* @param offsetB offset from engg2800.image 2 to 3
* @return BufferedImage
*/
public static BufferedImage join(BufferedImage a, BufferedImage b, BufferedImage c, int offsetA, int offsetB) {
int width = a.getWidth() + b.getWidth() + c.getWidth() - offsetA - offsetB;
BufferedImage result = new BufferedImage(width, a.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = result.getGraphics();
g.drawImage(a, 0, 0, null);
g.drawImage(b, a.getWidth() - offsetA, 0, null);
g.drawImage(c, width - c.getWidth(), 0, null);
g.dispose();
return result;
}
/**
* Join a number of images from a list
* @param images List of TransmittedImages to be joint
* @param num number of images to be joint
* @return BufferedImage result of joining
*/
public static BufferedImage join(ArrayList<TransmittedImage> images, int num) {
if (images == null) return null;
if (images.size() < num) return null;
TransmittedImage[] transmittedImages = new TransmittedImage[num];
/* Get required dimensions for final engg2800.image */
int width = 0;
int height = 0;
for (int x = 0; x < num; x++) {
transmittedImages[x] = images.get(images.size() - num + x);
if (x > 0) {
width += transmittedImages[x].getWidth();
width -= transmittedImages[x].getXOffset();
} else {
width += transmittedImages[x].getWidth();
height += transmittedImages[x].getHeight();
}
}
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = result.getGraphics();
g.drawImage(transmittedImages[0].getBufferedImage(), 0, 0, null);
int currentWidth = transmittedImages[0].getWidth();
for (int x = 1; x < num; x++) {
g.drawImage(transmittedImages[x].getBufferedImage(), currentWidth - transmittedImages[x].getXOffset(), 0, null);
currentWidth += (transmittedImages[x].getWidth() - transmittedImages[x].getXOffset());
}
g.dispose();
return result;
}
/**
* Join an Matrix of Buffered Into one buffered Image
* @param images BufferedImage Array of Arrays
* @param width Width of Buffered Image
* @param height Height of Buffered Image
* @return A joint buffered engg2800.image with dimensions (width, height)
*/
public static BufferedImage stitchArray(BufferedImage[][] images, int width, int height) {
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = result.getGraphics();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
graphics.drawImage(images[y][x], x, y, null);
}
}
graphics.dispose();
return result;
}
public static BufferedImage stitchTwoTransmittedImages(TransmittedImage image1, TransmittedImage image2) {
if (image1 == null || image2 == null) {
return null;
}
/* Get required dimensions for final engg2800.image */
int width = image1.getWidth() + image2.getWidth();
int height = image1.getHeight();
Point[] compare1 = SIFT.compareMerge(image1, image2);
if (compare1[0] == null || compare1[1] == null) {
System.err.println("Unable to Join Images");
return null;
}
width -= (image1.getWidth() - compare1[0].getX());
//width -= compare1[0].getX();
//height += Math.abs(compare1[0].getY() - compare1[1].getY());
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = bufferedImage.getGraphics();
int x2 = compare1[0].getX();
int y2 = Math.abs(compare1[0].getY() - compare1[1].getY());
int x = 0;
int y = 0;
g.drawImage(CropBufferedImage.crop(image1.getBufferedImage(), x, y), x, y, null);
g.drawImage(CropBufferedImage.crop(image2.getBufferedImage(), x, 0), x2, 0, null);
g.dispose();
return bufferedImage;
}
public static BufferedImage stitchThreeTransmittedImages(TransmittedImage image1, TransmittedImage image2, TransmittedImage image3) {
if (image1 == null || image2 == null || image3 == null) {
return null;
}
/* Get required dimensions for final engg2800.image */
int width = image1.getWidth() + image2.getWidth() + image3.getWidth();
int height = image1.getHeight();
Point[] compare1 = SIFT.compareMerge(image1, image2);
if (compare1[0] == null || compare1[1] == null) {
System.err.println("Unable to Join Images");
return null;
}
Point[] compare2 = SIFT.compareMerge(image2, image3);
if (compare2[0] == null || compare2[1] == null) {
System.err.println("Unable to Join Images");
return null;
}
width -= (image1.getWidth() - compare1[0].getX());
//width -= compare1[0].getX();
width -= (image2.getWidth() - compare2[0].getX());
//width -= compare2[0].getX();
//height += Math.abs(compare1[0].getY() - compare1[1].getY());
//height += Math.abs(compare2[0].getY() - compare2[1].getY());
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = bufferedImage.getGraphics();
int x3 = width - image3.getWidth();
//image1.getWidth() - (image1.getWidth() - compare1[0].getX() + compare1[1].getX()) + image2.getWidth() - (image2.getWidth() - compare2[0].getX() + compare2[1].getX());
int y3 = Math.abs(compare2[0].getY() - compare2[1].getY());
int x2 = compare1[0].getX();
int y2 = Math.abs(compare1[0].getY() - compare1[1].getY());
int x = 0;
int y = Math.abs(compare1[0].getY() - compare1[1].getY());
g.drawImage(image1.getBufferedImage(), x, 0, null);
g.drawImage(image2.getBufferedImage(), x2, 0, null);
g.drawImage(image3.getBufferedImage(), x3, 0, null);
g.dispose();
return bufferedImage;
}
} |
package nl.nn.adapterframework.receivers;
import nl.nn.adapterframework.core.INamedObject;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.HasPhysicalDestination;
import nl.nn.adapterframework.core.IAdapter;
import nl.nn.adapterframework.core.IReceiver;
import nl.nn.adapterframework.core.IReceiverStatistics;
import nl.nn.adapterframework.core.IPullingListener;
import nl.nn.adapterframework.core.ITransactionalStorage;
import nl.nn.adapterframework.core.IXAEnabled;
import nl.nn.adapterframework.core.ListenerException;
import nl.nn.adapterframework.core.ISender;
import nl.nn.adapterframework.core.HasSender;
import nl.nn.adapterframework.core.PipeLineResult;
import nl.nn.adapterframework.core.SenderException;
import nl.nn.adapterframework.util.Counter;
import nl.nn.adapterframework.util.RunStateEnum;
import nl.nn.adapterframework.util.RunStateManager;
import nl.nn.adapterframework.util.StatisticsKeeper;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import javax.transaction.Status;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import javax.transaction.UserTransaction;
/**
* This {@link IReceiver Receiver} may be used as a base-class for developing 'pulling' receivers.
*
* <p><b>Configuration:</b>
* <table border="1">
* <tr><th>attributes</th><th>description</th><th>default</th></tr>
* <tr><td>classname</td><td>name of the class, mostly a class that extends this class</td><td> </td></tr>
* <tr><td>{@link #setName(String) name}</td> <td>name of the receiver as known to the adapter</td><td> </td></tr>
* <tr><td>{@link #setNumThreads(int) numThreads}</td><td>the number of threads listening in parallel for messages</td><td>1</td></tr>
* <tr><td>{@link #setCommitOnState(String) commitOnState}</td><td>exit state required to commit messages</td><td>success</td></tr>
* <tr><td>{@link #setOnError(String) onError}</td><td>one of 'continue' or 'close'. Controls the behaviour of the receiver when it encounters an error sending a reply</td><td>continue</td></tr>
* <tr><td>{@link #setTransacted(boolean) transacted}</td><td>if set to <code>true, messages will be received and processed under transaction control. If processing fails, messages will be sent to the error-sender. (see below)</code></td><td><code>false</code></td></tr>
* </table>
* </p>
* <p>
* <table border="1">
* <tr><th>nested elements (accessible in descender-classes)</th><th>description</th></tr>
* <tr><td>{@link nl.nn.adapterframework.core.IPullingListener listener}</td><td>the listener used to receive messages from</td></tr>
* <tr><td>{@link nl.nn.adapterframework.core.ITransactionalStorage inProcessStorage}</td><td>mandatory for {@link #setTransacted(boolean) transacted} receivers: place to store messages during processing.</td></tr>
* <tr><td>{@link nl.nn.adapterframework.core.ISender errorSender}</td><td>optional for {@link #setTransacted(boolean) transacted} receviers:
* will be called to store messages that failed to process. If no errorSender is specified, failed messages will remain in inProcessStorage</td></tr>
* </table>
* </p>
* <p><b>Transaction control</b><br>
* If {@link #setTransacted(boolean) transacted} is set to <code>true, messages will be received and processed under transaction control.
* This means that after a message has been read and processed and the transaction has ended, one of the following apply:
* <ul>
* <table border="1">
* <tr><th>situation</th><th>input listener</th><th>Pipeline</th><th>inProcess storage</th><th>errorSender</th><th>summary of effect</th></tr>
* <tr><td>successful</td><td>message read and committed</td><td>message processed</td><td>unchanged</td><td>unchanged</td><td>message processed</td></tr>
* <tr><td>procesing failed</td><td>message read and committed</td><td>message processing failed and rolled back</td><td>unchanged</td><td>message sent</td><td>message only transferred from listener to errroSender</td></tr>
* <tr><td>listening failed</td><td>unchanged: listening rolled back</td><td>no processing performed</td><td>unchanged</td><td>unchanged</td><td>no changes, input message remains on input available for listener</td></tr>
* <tr><td>transfer to inprocess storage failed</td><td>unchanged: listening rolled back</td><td>no processing performed</td><td>unchanged</td><td>unchanged</td><td>no changes, input message remains on input available for listener</td></tr>
* <tr><td>transfer to errorSender failed</td><td>message read and committed</td><td>message processing failed and rolled back</td><td>message present</td><td>unchanged</td><td>message only transferred from listener to inProcess storage</td></tr>
* </table>
* If the application or the server crashes in the middle of one or more transactions, these transactions
* will be recovered and rolled back after the server/application is restarted. Then allways exactly one of
* the following applies for any message touched at any time by Ibis by a transacted receiver:
* <ul>
* <li>It is processed correctly by the pipeline and removed from the input-queue,
* not present in inProcess storage and not send to the errorSender</li>
* <li>It is not processed at all by the pipeline, or processing by the pipeline has been rolled back;
* the message is removed from the input queue and either (one of) still in inProcess storage <i>or</i> sent to the errorSender</li>
* </ul>
* </p>
*
* <p><b>commit or rollback</b><br>
* If {@link #setTransacted(boolean) transacted} is set to <code>true, messages will be either committed or rolled back.
* All message-processing transactions are committed, unless one or more of the following apply:
* <ul>
* <li>the exitState of the pipeline is not equal {@link #setCommitOnState(String) commitOnState} (that defaults to 'success')</li>
* <li>a PipeRunException or another runtime-exception has been thrown by any Pipe or by the PipeLine</li>
* <li>the setRollBackOnly() method has been called on the userTransaction (not accessible by Pipes)</li>
* </ul>
* </p>
*
* @version Id
* @author Gerrit van Brakel
* @since 4.0
*/
public class PullingReceiverBase
implements IReceiver, IReceiverStatistics, Runnable, HasSender {
public static final String version="$Id: PullingReceiverBase.java,v 1.11 2004-08-18 09:19:57 a1909356#db2admin Exp $";
public static final String ONERROR_CONTINUE = "continue";
public static final String ONERROR_CLOSE = "close";
protected Logger log = Logger.getLogger(this.getClass());
private String name;
private String onError = ONERROR_CONTINUE;
private RunStateManager runState = new RunStateManager();
// the number of threads that listen in parallel to the queue
private int numThreads = 1;
private Counter threadsRunning = new Counter(0);
private Counter threadsProcessing = new Counter(0);
// number of messages received
private Counter numReceived = new Counter(0);
private ArrayList processStatistics = new ArrayList();
private ArrayList idleStatistics = new ArrayList();
// the adapter that handles the messages and initiates this listener
private IAdapter adapter;
private IPullingListener listener;
private ITransactionalStorage inProcessStorage=null;
private ISender errorSender=null;
private boolean transacted=false;
/**
* this method is called from the run method after the last thread has exited !!<br/>
* The receiver and connection is closed and reset. If a sender
* is configured it is stopped also.
*/
private void closeAllResources() {
/*
// the setStopped is placed here, to enably trying to start the receiver again.
this.setStopped();
*/
try {
log.debug("closing Receiver ["+ getName()+ "]");
getListener().close();
log.info("closed Receiver ["+ getName()+ "]");
} catch (ListenerException e) {
log.error(
"Receiver [" + getName()+ "]: error closing connection", e);
}
if (inProcessStorage != null) {
try {
inProcessStorage.close();
} catch (Exception e) {
log.error("Receiver [" + getName()+ "]: error closing inProcessStorage", e);
}
}
if (errorSender != null) {
try {
errorSender.close();
} catch (Exception e) {
log.error("Receiver [" + getName()+ "]: error closing errorSender", e);
}
}
}
/**
* sends a warning to the log and to the messagekeeper of the adapter
*/
public void warn(String msg) {
log.warn(msg);
if (adapter != null)
adapter.getMessageKeeper().add("WARNING: " + msg);
}
/**
* sends an informational message to the log and to the messagekeeper of the adapter
*/
public void info(String msg) {
log.info(msg);
if (adapter != null)
adapter.getMessageKeeper().add(msg);
}
public void configure() throws ConfigurationException {
try {
if (getListener()==null) {
throw new ConfigurationException("Receiver ["+getName()+"] has no listener");
}
getListener().configure();
if (getListener() instanceof HasPhysicalDestination) {
info("Receiver ["+getName()+"] has listener on "+((HasPhysicalDestination)getListener()).getPhysicalDestinationName());
}
if (getListener() instanceof HasSender) {
ISender sender = ((HasSender)getListener()).getSender();
if (sender instanceof HasPhysicalDestination) {
info("Listener of receiver ["+getName()+"] has sender on "+((HasPhysicalDestination)sender).getPhysicalDestinationName());
}
}
if (isTransacted()) {
if (!(getListener() instanceof IXAEnabled && ((IXAEnabled)getListener()).isTransacted())) {
warn("Receiver ["+getName()+"] sets transacted=true, but listener not. Transactional integrity is not guaranteed");
}
if (getInProcessStorage()==null) {
throw new ConfigurationException("Receiver ["+getName()+"] sets transacted=true, but has no inProcessStorage.");
}
if (!(getInProcessStorage() instanceof IXAEnabled && ((IXAEnabled)getInProcessStorage()).isTransacted())) {
warn("Receiver ["+getName()+"] sets transacted=true, but inProcessStorage not. Transactional integrity is not guaranteed");
}
getInProcessStorage().configure();
if (getInProcessStorage() instanceof HasPhysicalDestination) {
info("Receiver ["+getName()+"] has inProcessStorage in "+((HasPhysicalDestination)getInProcessStorage()).getPhysicalDestinationName());
}
if (getErrorSender()==null) {
warn("Receiver ["+getName()+"] sets transacted=true, but has no error sender. Messages processed with errors will get lost");
}
else {
getErrorSender().configure();
if (getErrorSender() instanceof HasPhysicalDestination) {
info("Receiver ["+getName()+"] has errorSender to "+((HasPhysicalDestination)getErrorSender()).getPhysicalDestinationName());
}
if (!(getErrorSender() instanceof IXAEnabled && ((IXAEnabled)getErrorSender()).isTransacted())) {
warn("Receiver ["+getName()+"] sets transacted=true, but errorSender is not. Transactional integrity is not guaranteed");
}
}
}
processStatistics.ensureCapacity(getNumThreads());
idleStatistics.ensureCapacity(getNumThreads());
for (int i=0; i<getNumThreads(); i++) {
processStatistics.add(i, new StatisticsKeeper(i+1+" threads processing"));
idleStatistics.add(i, new StatisticsKeeper(i+" threads processing"));
}
if (adapter != null) {
adapter.getMessageKeeper().add("Receiver ["+getName()+"] initialization complete");
}
} catch(ConfigurationException e){
log.debug("Errors occured during configuration, setting runstate to ERROR");
runState.setRunState(RunStateEnum.ERROR);
throw e;
}
}
protected void finishProcessingMessage(long processingDuration) {
synchronized (threadsProcessing) {
int threadCount = (int) threadsProcessing.decrease();
((StatisticsKeeper)processStatistics.get(threadCount)).addValue(processingDuration);
}
log.debug("receiver ["+getName()+"] finishes processing message");
}
/**
* Returns an iterator over the idle-statistics
* @return iterator
*/
public Iterator getIdleStatisticsIterator() {
return idleStatistics.iterator();
}
/**
* Get the number of messages received.
* @return long
*/
public long getMessagesReceived() {
return numReceived.getValue();
}
public Iterator getProcessStatisticsIterator() {
return processStatistics.iterator();
}
protected void moveInProcessToError(String message, String messageId) {
UserTransaction utx;
log.info("receiver ["+getName()+"] moves message ["+messageId+"] to errorSender");
ISender sender = getErrorSender();
if (sender==null) {
log.warn("["+getName()+"] has no errorSender, message with id ["+messageId+"] will remain in inProcessStorage");
return;
}
try {
utx = adapter.getUserTransaction();
utx.begin();
} catch (Exception e) {
log.error("["+getName()+"] Exception preparing to move input message to error sender", e);
// no use trying again to send message on errorSender, will cause same exception!
return;
}
try {
getInProcessStorage().deleteMessage(messageId);
sender.sendMessage(messageId, message);
utx.commit();
} catch (Exception e) {
log.error("["+getName()+"] Exception moving message with id ["+messageId+"] to error sender, original message: ["+message+"]",e);
try {
utx.rollback();
} catch (Exception rbe) {
log.error("["+getName()+"] Exception while rolling back transaction for message with id ["+messageId+"], original message: ["+message+"]", rbe);
}
}
}
public Object getRawMessage(HashMap threadContext) throws ListenerException {
if (isTransacted()) {
String message;
String messageId;
Object rawMessage;
IPullingListener listener = getListener();
UserTransaction utx = null;
try {
utx = adapter.getUserTransaction();
utx.begin();
} catch (Exception e) {
throw new ListenerException("["+getName()+"] Exception preparing to read input message", e);
// no need to send message on errorSender, did not even try to read message
}
try {
rawMessage = listener.getRawMessage(threadContext);
if (rawMessage==null) {
try {
utx.rollback();
} catch (Exception e) {
log.warn("["+getName()+"] Exception while rolling back transaction after timeout on retrieving message", e);
}
return null;
}
message = listener.getStringFromRawMessage(rawMessage,threadContext);
messageId = listener.getIdFromRawMessage(rawMessage,threadContext);
getInProcessStorage().storeMessage(messageId,message);
log.debug("["+getName()+"] commiting transfer of message to inProcessStorage");
utx.commit();
} catch (Exception e) {
try {
utx.rollback();
} catch (Exception rbe) {
log.error("["+getName()+"] Exception while rolling back transaction after catching exception", rbe);
}
throw new ListenerException("["+getName()+"] Exception retrieving/storing message under transaction control",e);
// no need to send message on errorSender, message will remain on input channel due to rollback
}
return rawMessage;
} else {
return getListener().getRawMessage(threadContext);
}
}
/**
* All messages that for this receiver are pumped down to this method, so it actually
* callst he {@link nl.nn.adapterframework.core.Adapter adapter} to process the message.<br/>
* This specific implementation delegates the sending of results to a
* seperate sender, retrieved from the adapter.
* @see javax.jms.Message
* @param message message that was received.
*/
private PipeLineResult onMessage(String message, String id, HashMap threadContext) {
PipeLineResult result = null;
String state = "";
if (null!=adapter) {
if (isTransacted()) {
UserTransaction utx = null;
try {
log.debug("["+getName()+"] starting transaction for processing of message");
utx = adapter.getUserTransaction();
utx.begin();
log.debug("["+getName()+"] deleting message from inProcessStorage as part of message processing transaction");
getInProcessStorage().deleteMessage(id);
result = adapter.processMessage(id, message);
state = result.getState();
if (utx.getStatus()==Status.STATUS_ACTIVE){
try {
log.info("receiver [" + getName() + "] got exitState ["+state+"] from pipeline, committing transaction ["+utx+"] for messageid ["+id+"]");
utx.commit();
} catch (Exception e) {
log.error("receiver [" + getName() + "] exception committing transaction", e);
moveInProcessToError(message,id);
if (ONERROR_CLOSE.equalsIgnoreCase(getOnError())) {
log.info("receiver [" + getName() + "] closing after exception in committing transaction");
stopRunning();
}
}
} else {
log.warn("receiver [" + getName() + "] got exitState ["+state+"] from pipeline, rolling back transaction ["+utx+"] for messageid ["+id+"]");
try {
utx.rollback();
} catch (Exception e) {
log.error("receiver [" + getName() + "] exception rolling back transaction", e);
}
moveInProcessToError(message,id);
}
} catch (Exception e) {
log.error("["+getName()+"] Exception processing message under transaction control",e);
try {
utx.rollback();
} catch (Exception rbe) {
log.error("["+getName()+"] Exception while rolling back transaction after catching exception", rbe);
}
}
} else {
try {
result = adapter.processMessage(id, message);
state = result.getState();
log.debug("["+getName()+"] proccessed request with exitState ["+state+"]");
} catch (Throwable e) {
log.error("Receiver [" + getName() + "]:"+ToStringBuilder.reflectionToString(e,ToStringStyle.MULTI_LINE_STYLE), e);
}
}
} else {
log.warn("["+getName()+"] has no adapter to process message");
}
return result;
}
private void afterMessageProcessed(PipeLineResult pipeLineResult, Object rawMessage, String id, HashMap threadContext) {
try {
getListener().afterMessageProcessed(pipeLineResult, rawMessage,threadContext);
} catch (ListenerException e) {
String msg = "receiver [" + getName() + "] caught exception in message post processing";
log.error(msg, e);
if (null != adapter) {
adapter.getMessageKeeper().add(msg+":" + e.getMessage());
}
if (ONERROR_CLOSE.equalsIgnoreCase(getOnError())) {
log.info("receiver [" + getName() + "] closing after exception in post processing");
stopRunning();
}
}
}
/**
* Starts the receiver. This method is called by the startRunning method.<br/>
* Basically:
* <ul>
* <li> it opens the threads</li>
* <li>it calls the getRawMessage method to get a message<li>
* <li> it performs the onMessage method, resulting a PipeLineResult</li>
* <li>it calls the afterMessageProcessed() method of the listener<li>
* <li> it optionally sends the result using the sender</li>
* </ul>
*/
public void run() {
threadsRunning.increase();
try {
HashMap threadContext = getListener().openThread();
if (threadContext==null) {
threadContext = new HashMap();
}
long startProcessingTimestamp;
long finishProcessingTimestamp = System.currentTimeMillis();
runState.setRunState(RunStateEnum.STARTED);
while (getRunState().equals(RunStateEnum.STARTED)) {
Object rawMessage = getRawMessage(threadContext);
if (rawMessage!=null) {
startProcessingTimestamp = System.currentTimeMillis();
startProcessingMessage(startProcessingTimestamp-finishProcessingTimestamp);
numReceived.increase();
String message = getListener().getStringFromRawMessage(rawMessage, threadContext);
String id = getListener().getIdFromRawMessage(rawMessage, threadContext);
PipeLineResult pipeLineResult = onMessage(message, id, threadContext);
afterMessageProcessed(pipeLineResult,rawMessage, id, threadContext);
finishProcessingTimestamp = System.currentTimeMillis();
finishProcessingMessage(finishProcessingTimestamp-startProcessingTimestamp);
}
}
getListener().closeThread(threadContext);
} catch (Throwable e) {
log.error("error occured in receiver [" + getName() + "]: ["+e.toString()+"]", e);
if (null != adapter)
adapter.getMessageKeeper().add(
"error occured on receiver [" + getName() + "]:" + e.getMessage());
} finally {
long stillRunning=threadsRunning.decrease();
if (stillRunning>0) {
log.info("a thread of Receiver ["+getName()+"] exited, ["+stillRunning+"] are still running");
return;
}
log.info("the last thread of Receiver ["+getName()+"] exited, cleaning up");
closeAllResources();
if (adapter != null) {
adapter.getMessageKeeper().add("Receiver [" + getName() + "] stopped");
}
runState.setRunState(RunStateEnum.STOPPED);
}
}
public void setAdapter(IAdapter adapter) {
this.adapter = adapter;
}
protected void startProcessingMessage(long waitingDuration) {
synchronized (threadsProcessing) {
int threadCount = (int) threadsProcessing.getValue();
((StatisticsKeeper)idleStatistics.get(threadCount)).addValue(waitingDuration);
threadsProcessing.increase();
}
log.debug("receiver ["+getName()+"] starts processing message");
}
/**
* Start the adapter. The thread-name will be set tot the adapter's name
*/
public void startRunning() {
// if this receiver is on an adapter, the StartListening method
// may only be executed when the adapter is started.
if (adapter != null) {
RunStateEnum adapterRunState = adapter.getRunState();
if (!adapterRunState.equals(RunStateEnum.STARTED)) {
log.warn(
"Receiver ["
+ getName()
+ "] on adapter ["
+ adapter.getName()
+ "] was tried to start, but the adapter is in state ["+adapterRunState+"]. Ignoring command.");
adapter.getMessageKeeper().add(
"ignored start command on [" + getName() + "]; adapter is in state ["+adapterRunState+"]");
return;
}
}
try {
String msg=("Receiver [" + getName() + "] starts listening.");
log.info(msg);
adapter.getMessageKeeper().add(msg);
runState.setRunState(RunStateEnum.STARTING);
getListener().open();
// start all threads
if (getNumThreads() > 1) {
for (int i = 1; i <= getNumThreads(); i++) {
Thread t = new Thread(this, getName() + "[" + i+"]");
t.start();
}
} else {
Thread t = new Thread(this, getName());
t.start();
}
} catch (ListenerException e) {
log.error("error occured while starting receiver [" + getName() + "]", e);
if (null != adapter)
adapter.getMessageKeeper().add(
"error occured while starting receiver [" + getName() + "]:" + e.getMessage());
runState.setRunState(RunStateEnum.ERROR);
}
}
public void stopRunning() {
if (getRunState().equals(RunStateEnum.STOPPED)){
return;
}
if (!getRunState().equals(RunStateEnum.ERROR))
runState.setRunState(RunStateEnum.STOPPING);
else {
closeAllResources();
runState.setRunState(RunStateEnum.STOPPED);
}
}
/**
* Returns a toString of this class by introspection and the toString() value of its listener.
*
* @return Description of the Return Value
*/
public String toString() {
String result = super.toString();
ToStringBuilder ts=new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);
ts.append("name", getName() );
result += ts.toString();
result+=" listener ["+(listener==null ? "-none-" : listener.toString())+"]";
return result;
}
public void waitForRunState(RunStateEnum requestedRunState) throws InterruptedException {
runState.waitForRunState(requestedRunState);
}
/**
* Get the {@link RunStateEnum runstate} of this receiver.
*/
public RunStateEnum getRunState() {
return runState.getRunState();
}
public ISender getSender() {
IPullingListener listener = getListener();
if (listener instanceof HasSender) {
return ((HasSender)listener).getSender();
} else {
return null;
}
}
/**
* Returns the listener
* @return IPullingListener
*/
public IPullingListener getListener() {
return listener;
protected void setListener(IPullingListener newListener) {
listener = newListener;
if (listener instanceof INamedObject) {
if (StringUtils.isEmpty(((INamedObject)listener).getName())) {
((INamedObject) listener).setName("listener of ["+getName()+"]");
}
}
}
/**
* Returns the inProcessStorage.
* @return ITransactionalStorage
*/
public ITransactionalStorage getInProcessStorage() {
return inProcessStorage;
}
/**
* Sets the inProcessStorage.
* @param inProcessStorage The inProcessStorage to set
*/
public void setInProcessStorage(ITransactionalStorage inProcessStorage) {
this.inProcessStorage = inProcessStorage;
inProcessStorage.setName("inProcessStorage of ["+getName()+"]");
}
/**
* Returns the errorSender.
* @return ISender
*/
public ISender getErrorSender() {
return errorSender;
}
/**
* Sets the errorSender.
* @param errorSender The errorSender to set
*/
protected void setErrorSender(ISender errorSender) {
this.errorSender = errorSender;
errorSender.setName("errorSender of ["+getName()+"]");
}
/**
* Controls the use of XA-transactions.
*/
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
public boolean isTransacted() {
return transacted;
}
/**
* Sets the name of the Receiver.
* If the listener implements the {@link nl.nn.adapterframework.core.INamedObject name} interface and <code>getName()</code>
* of the listener is empty, the name of this object is given to the listener.
*/
public void setName(String newName) {
name = newName;
IPullingListener listener=getListener();
if (listener instanceof INamedObject) {
if (StringUtils.isEmpty(((INamedObject)listener).getName())) {
((INamedObject) listener).setName("listner of ["+newName+"]");
}
}
ITransactionalStorage inProcess = getInProcessStorage();
if (inProcess != null) {
inProcess.setName("inProcessStorage of ["+newName+"]");
}
ISender errorSender = getErrorSender();
if (errorSender != null) {
errorSender.setName("errorSender of ["+newName+"]");
}
}
public String getName() {
return name;
}
/**
* The number of threads that this receiver is working with.
*/
public void setNumThreads(int newNumThreads) {
numThreads = newNumThreads;
}
public int getNumThreads() {
return numThreads;
}
public void setOnError(String newOnError) {
onError = newOnError;
}
public String getOnError() {
return onError;
}
} |
package Ventanas;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* @author sebas
*/
public class Inicio extends JFrame implements ActionListener {
private JLabel labelClase;
private JTextField textFieldRut, textFieldBuscar, textFieldNombre;
private JComboBox comboCategoria;
private JButton bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9, bt10, bt11, bt12, bt13, bt14, bt15, bt16, bt17,
bt18, bt19,bt20, bt21, bt22, bt23, bt24, bt25, bt26,bt27, bt28, bt29, bt30, bt31, bt32, bt33,
bt34, bt35, bt36, bt37, bt38, bt39, bt40, bt41,bt42,bt43,bt44,bt45,bt46,bt47,bt48,bt49,bt50, botonBuscar;
public Inicio() {
super("UfroTrack");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//finaliza el programa cuando se da click en la X
this.setSize(1000, 500);
this.setResizable(false);
//Labels
labelClase = new JLabel("Rut");
labelClase.setText("Rut");
labelClase.setBounds(600, 10, 100, 25);
this.add(labelClase);
labelClase = new JLabel("Nombre");
labelClase.setText("Nombre");
labelClase.setBounds(10, 10, 100, 25);
this.add(labelClase);
labelClase = new JLabel("Lunes");
labelClase.setText("Lunes");
labelClase.setBounds(10, 60, 100, 25);
this.add(labelClase);
labelClase = new JLabel("Martes");
labelClase.setText("Martes");
labelClase.setBounds(110, 60, 100, 25);
this.add(labelClase);
labelClase = new JLabel("Miercoles");
labelClase.setText("Miercoles");
labelClase.setBounds(210, 60, 100, 25);
this.add(labelClase);
labelClase = new JLabel("Jueves");
labelClase.setText("Jueves");
labelClase.setBounds(310, 60, 100, 25);
this.add(labelClase);
labelClase = new JLabel("Viernes");
labelClase.setText("Viernes");
labelClase.setBounds(410, 60, 100, 25);
this.add(labelClase);
//TextFields
textFieldRut = new JTextField();
textFieldRut.setEditable(false);
textFieldRut.setBounds(700, 10, 100, 25);
textFieldRut.setText("");
this.add(textFieldRut);
textFieldBuscar = new JTextField();
textFieldBuscar.setBounds(600, 110, 100, 25);
textFieldBuscar.setText("Buscar");
this.add(textFieldBuscar);
textFieldNombre = new JTextField();
textFieldNombre.setEditable(false);
textFieldNombre.setBounds(110, 10, 100, 25);
textFieldNombre.setText("");
this.add(textFieldNombre);
//ComboBox
String[] opc2 = {};
comboCategoria = new JComboBox(opc2);
comboCategoria.setBounds(700, 110, 100, 25);
comboCategoria.addItem("Categoria");
comboCategoria.addActionListener(this);
this.setLayout(null);
this.add(comboCategoria);
//JButtons
bt1 = new JButton("Terminar");
bt1.setBounds(0, 100, 100, 25);
this.add(bt1);
setLayout(null);
bt1.addActionListener(this);
bt2 = new JButton("Terminar");
bt2.setBounds(0, 125, 100, 25);
this.add(bt2);
setLayout(null);
bt2.addActionListener(this);
bt3 = new JButton("Terminar");
bt3.setBounds(0, 175, 100, 25);
this.add(bt3);
setLayout(null);
bt3.addActionListener(this);
bt4 = new JButton("Terminar");
bt4.setBounds(0, 200, 100, 25);
this.add(bt4);
setLayout(null);
bt4.addActionListener(this);
bt5 = new JButton("Terminar");
bt5.setBounds(0, 250, 100, 25);
this.add(bt5);
setLayout(null);
bt5.addActionListener(this);
bt6 = new JButton("Terminar");
bt6.setBounds(0, 275, 100, 25);
this.add(bt6);
setLayout(null);
bt6.addActionListener(this);
bt7 = new JButton("Terminar");
bt7.setBounds(0, 325, 100, 25);
this.add(bt7);
setLayout(null);
bt7.addActionListener(this);
bt8 = new JButton("Terminar");
bt8.setBounds(0, 350, 100, 25);
this.add(bt8);
setLayout(null);
bt8.addActionListener(this);
bt9 = new JButton("Terminar");
bt9.setBounds(0, 400, 100, 25);
this.add(bt9);
setLayout(null);
bt9.addActionListener(this);
bt10 = new JButton("Terminar");
bt10.setBounds(0, 425, 100, 25);
this.add(bt10);
setLayout(null);
bt10.addActionListener(this);
bt11 = new JButton("Terminar");
bt11.setBounds(100, 100, 100, 25);
this.add(bt11);
setLayout(null);
bt11.addActionListener(this);
bt12 = new JButton("Terminar");
bt12.setBounds(100, 125, 100, 25);
this.add(bt12);
setLayout(null);
bt12.addActionListener(this);
bt13 = new JButton("Terminar");
bt13.setBounds(100, 175, 100, 25);
this.add(bt13);
setLayout(null);
bt13.addActionListener(this);
bt14 = new JButton("Terminar");
bt14.setBounds(100, 200, 100, 25);
this.add(bt14);
setLayout(null);
bt14.addActionListener(this);
bt15 = new JButton("Terminar");
bt15.setBounds(100, 250, 100, 25);
this.add(bt15);
setLayout(null);
bt15.addActionListener(this);
bt16 = new JButton("Terminar");
bt16.setBounds(100, 275, 100, 25);
this.add(bt16);
setLayout(null);
bt16.addActionListener(this);
bt17 = new JButton("Terminar");
bt17.setBounds(100, 325, 100, 25);
this.add(bt17);
setLayout(null);
bt17.addActionListener(this);
bt18 = new JButton("Terminar");
bt18.setBounds(100, 350, 100, 25);
this.add(bt18);
setLayout(null);
bt18.addActionListener(this);
bt19 = new JButton("Terminar");
bt19.setBounds(100, 400, 100, 25);
this.add(bt19);
setLayout(null);
bt19.addActionListener(this);
bt20 = new JButton("Terminar");
bt20.setBounds(100, 425, 100, 25);
this.add(bt20);
setLayout(null);
bt20.addActionListener(this);
bt21 = new JButton("Terminar");
bt21.setBounds(200, 100, 100, 25);
this.add(bt21);
setLayout(null);
bt21.addActionListener(this);
bt22 = new JButton("Terminar");
bt22.setBounds(200, 125, 100, 25);
this.add(bt22);
setLayout(null);
bt22.addActionListener(this);
bt23 = new JButton("Terminar");
bt23.setBounds(200, 175, 100, 25);
this.add(bt23);
setLayout(null);
bt23.addActionListener(this);
bt24 = new JButton("Terminar");
bt24.setBounds(200, 200, 100, 25);
this.add(bt24);
setLayout(null);
bt24.addActionListener(this);
bt25 = new JButton("Terminar");
bt25.setBounds(200, 250, 100, 25);
this.add(bt25);
setLayout(null);
bt25.addActionListener(this);
bt26 = new JButton("Terminar");
bt26.setBounds(200, 275, 100, 25);
this.add(bt26);
setLayout(null);
bt26.addActionListener(this);
bt27 = new JButton("Terminar");
bt27.setBounds(200, 325, 100, 25);
this.add(bt27);
setLayout(null);
bt27.addActionListener(this);
bt28 = new JButton("Terminar");
bt28.setBounds(200, 350, 100, 25);
this.add(bt28);
setLayout(null);
bt28.addActionListener(this);
bt29 = new JButton("Terminar");
bt29.setBounds(200, 400, 100, 25);
this.add(bt29);
setLayout(null);
bt29.addActionListener(this);
bt30 = new JButton("Terminar");
bt30.setBounds(200, 425, 100, 25);
this.add(bt30);
setLayout(null);
bt30.addActionListener(this);
bt31 = new JButton("Terminar");
bt31.setBounds(300, 100, 100, 25);
this.add(bt31);
setLayout(null);
bt31.addActionListener(this);
bt32 = new JButton("Terminar");
bt32.setBounds(300, 125, 100, 25);
this.add(bt32);
setLayout(null);
bt32.addActionListener(this);
bt33 = new JButton("Terminar");
bt33.setBounds(300, 175, 100, 25);
this.add(bt33);
setLayout(null);
bt33.addActionListener(this);
bt34 = new JButton("Terminar");
bt34.setBounds(300, 200, 100, 25);
this.add(bt34);
setLayout(null);
bt34.addActionListener(this);
bt35 = new JButton("Terminar");
bt35.setBounds(300, 250, 100, 25);
this.add(bt35);
setLayout(null);
bt35.addActionListener(this);
bt36 = new JButton("Terminar");
bt36.setBounds(300, 275, 100, 25);
this.add(bt36);
setLayout(null);
bt36.addActionListener(this);
bt37 = new JButton("Terminar");
bt37.setBounds(300, 325, 100, 25);
this.add(bt37);
setLayout(null);
bt37.addActionListener(this);
bt38 = new JButton("Terminar");
bt38.setBounds(300, 350, 100, 25);
this.add(bt38);
setLayout(null);
bt38.addActionListener(this);
bt39 = new JButton("Terminar");
bt39.setBounds(300, 400, 100, 25);
this.add(bt39);
setLayout(null);
bt39.addActionListener(this);
bt40 = new JButton("Terminar");
bt40.setBounds(300, 425, 100, 25);
this.add(bt40);
setLayout(null);
bt40.addActionListener(this);
bt41 = new JButton("Terminar");
bt41.setBounds(400, 100, 100, 25);
this.add(bt41);
setLayout(null);
bt41.addActionListener(this);
bt42 = new JButton("Terminar");
bt42.setBounds(400, 125, 100, 25);
this.add(bt42);
setLayout(null);
bt42.addActionListener(this);
bt43 = new JButton("Terminar");
bt43.setBounds(400, 175, 100, 25);
this.add(bt43);
setLayout(null);
bt43.addActionListener(this);
bt44 = new JButton("Terminar");
bt44.setBounds(400, 200, 100, 25);
this.add(bt44);
setLayout(null);
bt44.addActionListener(this);
bt45 = new JButton("Terminar");
bt45.setBounds(400, 250, 100, 25);
this.add(bt45);
setLayout(null);
bt45.addActionListener(this);
bt46 = new JButton("Terminar");
bt46.setBounds(400, 275, 100, 25);
this.add(bt46);
setLayout(null);
bt46.addActionListener(this);
bt47 = new JButton("Terminar");
bt47.setBounds(400, 325, 100, 25);
this.add(bt47);
setLayout(null);
bt47.addActionListener(this);
bt48 = new JButton("Terminar");
bt48.setBounds(400, 350, 100, 25);
this.add(bt48);
setLayout(null);
bt48.addActionListener(this);
bt49 = new JButton("Terminar");
bt49.setBounds(400, 400, 100, 25);
this.add(bt49);
setLayout(null);
bt49.addActionListener(this);
bt50 = new JButton("Terminar");
bt50.setBounds(400, 425, 100, 25);
this.add(bt50);
setLayout(null);
bt50.addActionListener(this);
botonBuscar = new JButton("Buscar");
botonBuscar.setBounds(600, 135, 100, 25);
this.add(botonBuscar);
setLayout(null);
botonBuscar.addActionListener(this);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Inicio().setVisible(true);
}
});
}
@Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
} |
package com.lucythemoocher.controls;
import java.util.Iterator;
import java.util.LinkedList;
import com.lucythemoocher.Globals.Globals;
import com.lucythemoocher.graphics.Camera;
import com.lucythemoocher.actors.PlayerCharacter;
import android.util.Log;
import android.view.MotionEvent;
/**
* Control a PlayerCharacter
* Don't forget to call setPlayer() after the constructor
* before updating
*
*/
public class PlayerController extends TouchListener {
private static final int LEFT = 0;
private static final int RIGHT = 1;
private static final int DOWN = 2;
private static final int UP = 3;
private static final float DOUBLE_TOUCH_SENSIBILITY = 200;
private float[] lastTouch_;
private boolean[] pushed_;
private LinkedList<Point> pos_;
private PlayerCharacter player_;
/**
* Constructor
*/
public PlayerController() {
lastTouch_ = new float[5];
player_ = null;
pushed_ = new boolean[4];
pos_ = new LinkedList<Point>();
}
/**
* Setter
* @param player, targeted controlled
*/
public void setPlayer(PlayerCharacter player) {
player_ = player;
}
/**
* Fill a list of point according to the touch events
* @param event
*/
synchronized public void motion(MotionEvent event) {
//dumpEvent(event);
if ( event.getActionMasked() == MotionEvent.ACTION_DOWN ||
event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN ||
event.getActionMasked() == MotionEvent.ACTION_MOVE ) {
down(event);
} else if ( event.getActionMasked() == MotionEvent.ACTION_UP ||
event.getActionMasked() == MotionEvent.ACTION_POINTER_UP ) {
up(event);
}
}
/**
* Call the actions of the controlled according to the action array
*/
synchronized public void update() {
refreshPushed();
//Check whether no button is pushed
boolean allDown = true;
for ( int i=0; i<4; i++) {
for ( int j=0; j<3; j++) {
allDown &= !pushed_[i];
}
}
if ( allDown ) {
player_.moveStop();
return;
}
boolean moveLeft = pushed_[LEFT];
boolean moveRight = pushed_[RIGHT];
if ( moveLeft ) {
if ( Globals.getInstance().getGame().getTime()-lastTouch_[LEFT] < DOUBLE_TOUCH_SENSIBILITY) {
player_.moveFastLeft();
} else {
if ( moveRight && lastTouch_[LEFT] < lastTouch_[RIGHT] ) {
player_.moveRight();
} else {
player_.moveLeft();
}
}
} else if ( moveRight ) {
if ( Globals.getInstance().getGame().getTime()-lastTouch_[RIGHT] < DOUBLE_TOUCH_SENSIBILITY) {
player_.moveFastRight();
} else {
player_.moveRight();
}
}
if ( !moveLeft && !moveRight ) {
player_.moveStop();
}
boolean moveUp = pushed_[UP];
if ( moveUp ) {
player_.moveUp();
}
boolean moveDown = pushed_[DOWN];
if ( moveDown ) {
player_.moveDown();
}
}
private void down(MotionEvent event) {
pos_.clear();
for (int i=0; i<event.getPointerCount(); i++ ) {
if ( i>=3 ) {
break;
}
pos_.add(new Point(event.getX(i), event.getY(i), event.getPointerId(i)));
}
}
private void up(MotionEvent event) {
if ( pos_.size() == 1 ) {
lastTouch_[getPos(pos_.get(0))] = Globals.getInstance().getGame().getTime();
pos_.clear();
} else {
Iterator<Point> it = pos_.iterator();
while ( it.hasNext() ) {
Point p = it.next();
if ( p.pid == event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT) {
lastTouch_[getPos(p)] = Globals.getInstance().getGame().getTime();
it.remove();
}
}
}
}
/**
* Update action event
*/
private void refreshPushed() {
Camera cam = Globals.getInstance().getCamera();
for ( int i=0; i<4; i++) {
pushed_[i] = false;
}
for ( Point p : pos_ ) {
if ( p.y < cam.physicalH()/5) {
pushed_[UP] = true;
}
if ( p.x > 4*cam.physicalW()/5) {
pushed_[RIGHT] = true;
}
if (p.x < cam.physicalW()/5) {
pushed_[LEFT] = true;
}
if ( p.y > 4*cam.physicalH()/5) {
pushed_[DOWN] = true;
}
}
}
private int getPos(Point p) {
Camera cam = Globals.getInstance().getCamera();
if ( p.y < cam.physicalH()/5) {
return UP;
}
if ( p.x > 4*cam.physicalW()/5 &&
p.y > cam.physicalH()/5 &&
p.y < 4*cam.physicalH()/5) {
return RIGHT;
}
if (p.x < cam.physicalW()/5 &&
p.y > cam.physicalH()/5 &&
p.y < 4*cam.physicalH()/5) {
return LEFT;
}
if ( p.y > 4*cam.physicalH()/5) {
return DOWN;
}
return 4;
}
/**
* To print event in details
* @param event
*/
@SuppressWarnings("unused")
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" ,
"POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_" ).append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid " ).append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")" );
}
sb.append("[" );
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#" ).append(i);
sb.append("(pid " ).append(event.getPointerId(i));
sb.append(")=" ).append((int) event.getX(i));
sb.append("," ).append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";" );
}
sb.append("]" );
Log.d("Ctr", "###"+sb.toString());
}
}
class Point {
public float x;
public float y;
public int pid;
public Point() {
x = -1;
y = -1;
}
public Point(float x, float y, int pid) {
this.x = x;
this.y = y;
this.pid = pid;
}
public void init() {
x = -1;
y = -1;
}
public void move(float x, float y) {
this.x = x;
this.y = y;
}
public boolean equals(Point p) {
return x == p.x && y == p.y;
}
} |
/**
* @author sliva
*/
package compiler.phases.seman;
import java.util.*;
import compiler.common.report.*;
import compiler.data.abstree.*;
import compiler.data.abstree.AbsAtomExpr.Type;
import compiler.data.abstree.visitor.*;
import compiler.data.type.*;
import compiler.data.type.property.*;
/**
* Type resolving: the result is stored in {@link SemAn#declaresType},
* {@link SemAn#isType}, and {@link SemAn#ofType}.
*
* @author sliva
*/
public class TypeResolverResolvingStage extends TypeResolver {
private SemType AtomTypeResolution(AbsAtomType atomType) {
switch (atomType.type) {
case VOID:
return new SemVoidType();
case INT:
return new SemIntType();
case CHAR:
return new SemCharType();
case BOOL:
return new SemBoolType();
default:
throw new Report.Error(atomType.location(), "This type is not supported atomic type");
}
}
private SemType AtomExpresionResolution(AbsAtomExpr atomExpr) {
switch (atomExpr.type) {
case VOID:
return new SemVoidType();
case INT:
return new SemIntType();
case CHAR:
return new SemCharType();
case BOOL:
return new SemBoolType();
default:
throw new Report.Error(atomExpr.location(), "This type is not supported atomic type");
}
}
private SemType LinkTypes(AbsType type) {
if (type instanceof AbsAtomType) {
AbsAtomType atomType = (AbsAtomType) type;
SemType semAtomType = AtomTypeResolution(atomType);
SemAn.isType.put(type, semAtomType);
return semAtomType;
} else if (type instanceof AbsTypName) {
AbsTypName namedType = (AbsTypName) type;
SemNamedType semNamedType = SemAn.declaresType.get((AbsTypDecl) SemAn.declaredAt.get(namedType));
SemAn.isType.put(type, semNamedType);
return semNamedType;
} else if (type instanceof AbsArrType) {
AbsArrType arrType = (AbsArrType) type;
long len = 0;
if (arrType.len instanceof AbsAtomExpr) {
AbsAtomExpr lenExpr = (AbsAtomExpr) arrType.len;
if (lenExpr.type == Type.INT) {
len = Long.parseLong(lenExpr.expr);
if (len < 0) {
throw new Report.Error(arrType.location(), "Len of array is negative");
}
} else {
throw new Report.Error(arrType.location(),
"Atom expresion: " + lenExpr.expr + " is not of type INT");
}
} else {
throw new Report.Error(arrType.location(), "Array expresion is not of type Atom Expresion");
}
SemType semElemType = LinkTypes(arrType.elemType);
SemArrType semArrType = new SemArrType(len, semElemType);
SemAn.isType.put(type, semArrType);
return semArrType;
} else if (type instanceof AbsPtrType) {
AbsPtrType ptrType = (AbsPtrType) type;
SemPtrType semPtrType = new SemPtrType(LinkTypes(ptrType.ptdType));
SemAn.isType.put(type, semPtrType);
return semPtrType;
} else if (type instanceof AbsRecType) {
AbsRecType recType = (AbsRecType) type;
AbsCompDecls componentDeclarations = (AbsCompDecls) recType.compDecls;
Vector<AbsCompDecl> vComponentDeclarations = componentDeclarations.compDecls();
Vector<SemType> semComponentTypes = new Vector<SemType>();
SymbTable recSymTab = new SymbTable();
for (AbsCompDecl compDecl : vComponentDeclarations) {
try {
recSymTab.ins(compDecl.name, compDecl);
} catch (Exception e) {
throw new Report.Error(compDecl.location(),
"This component name: " + compDecl.name + " declerad twice in one record");
}
SemType semComponentType = LinkTypes(compDecl.type);
semComponentTypes.add(semComponentType);
}
SemRecType semRecType = new SemRecType(semComponentTypes);
symbTables.put(semRecType, recSymTab);
SemAn.isType.put(type, semRecType);
return semRecType;
}
throw new Report.Error(type.location(), "Not link for this type was found");
}
@Override
public SemType visit(AbsTypDecl typDecl, Object visArg) {
SemNamedType semType = SemAn.declaresType.get(typDecl);
semType.define(LinkTypes(typDecl.type));
super.visit(typDecl, visArg);
return null;
}
@Override
public SemType visit(AbsAtomExpr atomExpr, Object visArg) {
SemType atomType = AtomExpresionResolution(atomExpr);
SemAn.ofType.put(atomExpr, atomType);
super.visit(atomExpr, visArg);
return null;
}
@Override
public SemType visit(AbsAtomType atomType, Object visArg) {
SemType semAtomType = AtomTypeResolution(atomType);
SemAn.isType.put(atomType, semAtomType);
super.visit(atomType, visArg);
return null;
}
} |
package water.fvec;
import water.parser.BufferedString;
import water.util.PrettyPrint;
public abstract class ChunkVisitor {
public boolean expandedVals() {
return false;
}
void addValue(BufferedString bs) {
throw new UnsupportedOperationException();
}
void addValue(long uuid_lo, long uuid_hi) {
throw new UnsupportedOperationException();
}
void addValue(int val) {
throw new UnsupportedOperationException();
}
void addValue(double val) {
throw new UnsupportedOperationException();
}
void addValue(long val) {
throw new UnsupportedOperationException();
}
void addValue(long m, int e) {
addValue(PrettyPrint.pow10(m,e));
}
void addZeros(int zeros) {
throw new UnsupportedOperationException();
}
void addNAs(int nas) {
throw new UnsupportedOperationException();
}
/**
* Visitor wrapper around NewChunk. Usefull for extracting rows from chunks.
*/
public static final class NewChunkVisitor extends ChunkVisitor {
final NewChunk _nc;
NewChunkVisitor(NewChunk nc){_nc = nc;}
@Override
public boolean expandedVals(){return true;}
@Override
void addValue(BufferedString bs){_nc.addStr(bs);}
@Override
void addValue(long uuid_lo, long uuid_hi){_nc.addUUID(uuid_lo,uuid_hi);}
@Override
void addValue(int val) {_nc.addNum(val,0);}
@Override
void addValue(long val) {_nc.addNum(val,0);}
@Override
void addValue(long val, int exp) {_nc.addNum(val,exp);}
@Override
void addValue(double val) {_nc.addNum(val);}
@Override
void addZeros(int zeros) {_nc.addZeros(zeros);}
@Override
void addNAs(int nas) {_nc.addNAs(nas);}
}
/**
* Simple chunk visitor for extracting rows from chunks into a double array.
*/
public static final class DoubleAryVisitor extends ChunkVisitor {
public final double [] vals;
private int _k = 0;
private final double _na;
DoubleAryVisitor(double [] vals){this(vals,Double.NaN);}
DoubleAryVisitor(double [] vals, double NA){
this.vals = vals; _na = NA;}
@Override
void addValue(int val) {
vals[_k++] = val;}
@Override
void addValue(long val) {
vals[_k++] = val;}
@Override
void addValue(double val) {
vals[_k++] = Double.isNaN(val)?_na:val;}
@Override
void addZeros(int zeros) {
int k = _k;
int kmax = k +zeros;
for(;k < kmax; k++) vals[k] = 0;
_k = kmax;
}
@Override
void addNAs(int nas) {
int k = _k;
int kmax = k + nas;
for(;k < kmax; k++) vals[k] = _na;
_k = kmax;
}
}
/**
* Simple chunk visitor for extracting rows from chunks into a sparse double array.
*/
public static final class SparseDoubleAryVisitor extends ChunkVisitor {
public final boolean naSparse;
public final double [] vals;
public final int [] ids;
private int _sparseLen;
private int _len;
private final double _na;
public int sparseLen(){return _sparseLen;}
SparseDoubleAryVisitor(double [] vals, int [] ids){this(vals,ids,false,Double.NaN);}
SparseDoubleAryVisitor(double [] vals, int [] ids, boolean naSparse){this(vals, ids, naSparse, Double.NaN);}
SparseDoubleAryVisitor(double [] vals, int [] ids, boolean naSparse, double NA){this.vals = vals; this.ids = ids; _na = NA; this.naSparse = naSparse;}
@Override
void addValue(int val) {ids[_sparseLen] = _len++; vals[_sparseLen++] = val;}
@Override
void addValue(long val) {ids[_sparseLen] = _len++; vals[_sparseLen++] = val;}
@Override
void addValue(double val) {ids[_sparseLen] = _len++; vals[_sparseLen++] = Double.isNaN(val)?_na:val;}
@Override
void addZeros(int zeros) {
if(naSparse) {
int kmax = _sparseLen + zeros;
for (int k = _sparseLen; k < kmax; k++) {
ids[k] = _len++;
vals[k] = 0;
}
_sparseLen = kmax;
} else
_len += zeros;
}
@Override
void addNAs(int nas) {
if(!naSparse) {
int kmax = _sparseLen + nas;
for (int k = _sparseLen; k < kmax; k++) {
ids[k] = _len++;
vals[k] = _na;
}
_sparseLen = kmax;
} else
_len += nas;
}
}
/**
* Simple chunk visitor for extracting rows from chunks into a integer array.
*/
public static final class IntAryVisitor extends ChunkVisitor {
public final int [] vals;
private int _k = 0;
private final int _na;
IntAryVisitor(int [] vals){this(vals,(int)C4Chunk._NA);}
IntAryVisitor(int [] vals, int NA){this.vals = vals; _na = NA;}
@Override
public void addValue(int val) {vals[_k++] = val;}
@Override
public void addValue(long val) {
if(Integer.MAX_VALUE < val || val < Integer.MIN_VALUE)
throw new RuntimeException(val + " does not fit into int");
vals[_k++] = (int)val;
}
@Override
public void addValue(double val) {
if (Double.isNaN(val)) {
vals[_k++] = _na;
} else {
int i = (int) val;
if (i != val)
throw new RuntimeException(val + " does not fit into int");
vals[_k++] = i;
}
}
@Override
public void addZeros(int zeros) {
int k = _k;
int kmax = k +zeros;
for(;k < kmax; k++)vals[k] = 0;
_k = kmax;
}
@Override
public void addNAs(int nas) {
int k = _k;
int kmax = k + nas;
for(;k < kmax; k++)vals[k] = _na;
_k = kmax;
}
}
} |
//todo: T {} == T
package scalac.symtab;
import ch.epfl.lamp.util.Position;
import scalac.ApplicationError;
import scalac.util.*;
import scalac.Global;
public class Type implements Modifiers, Kinds, TypeTags, EntryTags {
public static boolean explainSwitch = false;
private static int indent = 0;
public case ErrorType; // not used after analysis
public case AnyType; // not used after analysis
public case NoType;
/** C.this.type
*/
public case ThisType(Symbol sym);
/** pre.sym.type
* sym represents a valueS
*/
public case SingleType(Type pre, Symbol sym) {
assert this instanceof ExtSingleType;
}
/** pre.sym[args]
* sym represents a type
* for example: scala.List[java.lang.String] is coded as
*
* TypeRef(
* SingleType(ThisType(definitions.ROOT_CLASS), definitions.SCALA),
* <List>,
* new Type[]{
* TypeRef(
* SingleType(
* SingleType(ThisType(definitions.ROOT_CLASS), definitions.JAVA),
* definitions.LANG),
* definitions.STRING,
* new Type[]{})}).
*
*/
public case TypeRef(Type pre, Symbol sym, Type[] args) {
assert pre.isLegalPrefix() || pre == ErrorType : pre + "#" + sym;
}
/** parts_1 with ... with parts_n { members }
*/
public case CompoundType(Type[] parts, Scope members) {
assert this instanceof ExtCompoundType;
}
/** synthetic type of a method def ...(vparams): result = ...
*/
public case MethodType(Symbol[] vparams, Type result);
/** synthetic type of a method def ...[tparams]result
* For instance, given def f[a](x: a): a
* f has type PolyType(new Symbol[]{<a>},
* MethodType(new Symbol[]{<x>}, <a>.type()))
*
* if tparams is empty, this is the type of a parameterless method
* def ... =
* For instance, given def f = 1
* f has type PolyType(new Symbol[]{}, <scala.Int>.type())
*/
public case PolyType(Symbol[] tparams, Type result);
/** synthetic type of an overloaded value whose alternatives are
* alts_1, ..., alts_n, with respective types alttypes_1, ..., alttypes_n
*
* For instance, if there are two definitions of `f'
* def f: int
* def f: String
* then there are three symbols:
* ``f1'' corresponding to def f: int
* ``f2'' corresponding to def f: String
* ``f3'' corresponding to both
* f3 has type
* OverloadedType(
* new Symbol[]{<f1>, <f2>},
* new Type[]{PolyType(new Symbol[]{}, <int>),
* PolyType(new Symbol[]{}, <String>),
*
*/
public case OverloadedType(Symbol[] alts, Type[] alttypes);
/** Hidden case to implement delayed evaluation of types.
* No need to pattern match on this type; it will never come up.
*/
public case LazyType();
/** Hidden case to implement local type inference.
* Later phases do not need to match on this type.
*/
public case TypeVar(Type origin, Constraint constr);
/** Hidden cases to implement type erasure.
* Earlier phases do not need to match on these types.
*/
public case UnboxedType(int tag);
public case UnboxedArrayType(Type elemtp);
/** Force evaluation of a lazy type. No cycle
* check is needed; since this is done in Symbol.
* @see Symbol.info().
*/
public void complete(Symbol p) {}
/** An owner-less ThisType
*/
public static Type localThisType = ThisType(Symbol.NONE);
/** An empty Type array */
public static final Type[] EMPTY_ARRAY = new Type[0];
public static SingleType singleType(Type pre, Symbol sym) {
if (pre.isStable() || pre == ErrorType) {
return new ExtSingleType(pre, sym);
} else {
throw new Type.Error(
"malformed type: " + pre + "#" + sym.nameString() + ".type");
}
}
public static TypeRef appliedType(Type tycon, Type[] args) {
switch (tycon) {
case TypeRef(Type pre, Symbol sym, Type[] args1):
if (args == args1) return (TypeRef)tycon;
else return TypeRef(pre, sym, args);
default:
throw new ApplicationError();
}
}
public static CompoundType compoundType(Type[] parts, Scope members,
Symbol clazz) {
ExtCompoundType res = new ExtCompoundType(parts, members);
res.tsym = clazz;
return res;
}
public static CompoundType compoundType(Type[] parts, Scope members) {
ExtCompoundType res = new ExtCompoundType(parts, members);
res.tsym = new ClassSymbol(
Position.NOPOS, Names.COMPOUND_NAME.toTypeName(), Symbol.NONE,
SYNTHETIC | ABSTRACTCLASS);
res.tsym.setInfo(res);
res.tsym.constructor().setInfo(
Type.MethodType(Symbol.EMPTY_ARRAY, Type.NoType));
return res;
}
public static Type typeRef(Type pre, Symbol sym, Type[] args) {
if (pre.isLegalPrefix() || pre == ErrorType)
return TypeRef(pre, sym, args);
else if (sym.kind == ALIAS)
return pre.memberInfo(sym);
else // todo: handle Java-style inner classes
throw new Type.Error(
"malformed type: " + pre + "#" + sym.nameString());
}
static class ExtSingleType extends SingleType {
Type tp = null;
int definedId = -1;
ExtSingleType(Type pre, Symbol sym) {
super(pre, sym);
}
public Type singleDeref() {
if (definedId != Global.instance.currentPhase.id) {
definedId = Global.instance.currentPhase.id;
tp = pre.memberType(sym).resultType();
}
return tp;
}
}
static class ExtCompoundType extends CompoundType {
Symbol tsym;
ExtCompoundType(Type[] parts, Scope members) {
super(parts, members);
}
public Symbol symbol() {
return tsym;
}
void validate() {//debug
for (Scope.Entry e = members.elems; e != Scope.Entry.NONE; e = e.next)
assert e.sym.owner() == tsym;
}
}
void validate() {//debug
}
/** If this is a thistype, named type, applied type, singleton type, or compound type,
* its symbol, otherwise Symbol.NONE.
*/
public Symbol symbol() {
switch (this) {
case ErrorType:
return Symbol.ERROR;
case ThisType(Symbol sym):
return sym;
case TypeRef(_, Symbol sym, _):
return sym;
case SingleType(_, Symbol sym):
return sym;
case TypeVar(Type origin, _):
return origin.symbol();
case CompoundType(_, _):
// overridden in ExtCompoundType
throw new ApplicationError();
default:
return Symbol.NONE;
}
}
public static Symbol[] symbol(Type[] tps) {
Symbol[] syms = new Symbol[tps.length];
for (int i = 0; i < syms.length; i++)
syms[i] = tps[i].symbol();
return syms;
}
/** The upper bound of this type. Returns always a TypeRef whose
* symbol is a class.
*/
public Type bound() {
switch (this) {
case TypeRef(Type pre, Symbol sym, _):
if (sym.kind == ALIAS) return unalias().bound();
if (sym.kind == TYPE) return pre.memberInfo(sym).bound();
assert sym.isClass() : Debug.show(sym) + " -- " + this;
return this;
case ThisType(_):
case SingleType(_, _):
return singleDeref().bound();
case TypeVar(_, _):
return unalias().bound();
default:
throw Debug.abort("illegal case", this);
}
}
/** If this type is a thistype or singleton type, its type,
* otherwise the type itself.
*/
public Type singleDeref() {
switch (this) {
case ThisType(Symbol sym):
return sym.typeOfThis();
case SingleType(Type pre, Symbol sym):
// overridden in ExtSingleType
throw new ApplicationError();
case TypeVar(Type origin, Constraint constr):
if (constr.inst != NoType) return constr.inst.singleDeref();
else return this;
default:
return this;
}
}
/** If this type is a thistype or singleton type, its underlying object type,
* otherwise the type itself.
*/
public Type widen() {
Type tp = singleDeref();
switch (tp) {
case ThisType(_):
case SingleType(_, _):
return tp.widen();
default:
return tp;
}
}
private static Map widenMap = new Map() {
public Type apply(Type t) {
return t.widen();
}
};
public static Type[] widen(Type[] tps) {
return widenMap.map(tps);
}
/** The thistype or singleton type corresponding to values of this type.
*/
public Type narrow() {
switch (this) {
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym.kind == ALIAS) return pre.memberInfo(sym).narrow();
else if (sym.kind == CLASS) return sym.thisType();
else return ThisType(sym);
case CompoundType(_, _):
return symbol().thisType();
default:
return this;
}
}
/** The lower approximation of this type (which must be a typeref)
*/
public Type loBound() {
switch (unalias()) {
case TypeRef(Type pre, Symbol sym, Type[] args):
Type lb = Global.instance.definitions.ALL_TYPE;
if (sym.kind == TYPE) {
lb = pre.memberLoBound(sym);
}
if (lb.symbol() == Global.instance.definitions.ALL_CLASS &&
this.symbol() != Global.instance.definitions.ALL_CLASS &&
this.isSubType(Global.instance.definitions.ANYREF_TYPE)) {
lb = Global.instance.definitions.ALLREF_TYPE;
}
return lb;
default:
throw new ApplicationError();
}
}
/** If this is a this-type, named-type, applied type or single-type, its prefix,
* otherwise NoType.
*/
public Type prefix() {
switch (this) {
case ThisType(Symbol sym): return sym.owner().thisType();
case TypeRef(Type pre, _, _): return pre;
case SingleType(Type pre, _): return pre;
case TypeVar(Type origin, Constraint constr):
if (constr.inst != NoType) return constr.inst.prefix();
else return NoType;
default: return NoType;
}
}
/** Get all type arguments of this type.
*/
public Type[] typeArgs() {
switch (unalias()) {
case TypeRef(_, _, Type[] args):
return args;
default:
return Type.EMPTY_ARRAY;
}
}
/** Get type of `this' symbol corresponding to this type, extend
* homomorphically to function types and poly types.
*/
public Type instanceType() {
switch (unalias()) {
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym != sym.thisSym())
return sym.typeOfThis()
.asSeenFrom(pre, sym.owner())
.subst(sym.typeParams(), args);
break;
case MethodType(Symbol[] params, Type restp):
Type restp1 = restp.instanceType();
if (restp1 != restp)
return MethodType(params, restp1);
break;
case PolyType(Symbol[] tparams, Type restp):
Type restp1 = restp.instanceType();
if (restp1 != restp)
return PolyType(tparams, restp1);
break;
}
return this;
}
/** Remove all aliases
*/
public Type unalias() {
Type result = unalias(0);//debug
//if (this != result) System.out.println(this + " ==> " + result);//DEBUG
return result;
}
private Type unalias(int n) {
if (n == 100)
throw new Type.Error("alias chain too long (recursive type alias?): " + this);
switch (this) {
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym.kind == ALIAS) return pre.memberInfo(sym).unalias(n + 1);
break;
case TypeVar(Type origin, Constraint constr):
if (constr.inst != NoType) return constr.inst.unalias(n + 1);
else return this;
}
return this;
}
/** The (prefix/argument-adapted) parents of this type.
*/
public Type[] parents() {
switch (unalias()) {
case ThisType(_):
case SingleType(_, _):
return singleDeref().parents();
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym.kind == ALIAS)
return unalias().parents();
else if (sym.kind == CLASS) {
assert sym.typeParams().length == args.length : sym + " " + ArrayApply.toString(args);//debug
return subst(asSeenFrom(sym.info().parents(), pre, sym.owner()),
sym.typeParams(), args);
} else
return new Type[]{sym.info().asSeenFrom(pre, sym.owner())};
case CompoundType(Type[] parts, _):
return parts;
default:
return Type.EMPTY_ARRAY;
}
}
/** Get type parameters of method type (a PolyType or MethodType)
* or EMPTY_ARRAY if method type is not polymorphic.
*/
public Symbol[] typeParams() {
switch (this) {
case PolyType(Symbol[] tparams, _):
return tparams;
case MethodType(Symbol[] vparams, _):
return Symbol.EMPTY_ARRAY;
case TypeRef(_, Symbol sym, Type[] args):
if (args.length == 0) return sym.typeParams();
else return Symbol.EMPTY_ARRAY;
default:
return Symbol.EMPTY_ARRAY;
}
}
/** Get value parameters of method type (a PolyType or MethodType)
* or EMPTY_ARRAY if method type has no value parameter section.
*/
public Symbol[] valueParams() {
return valueParams(false);
}
private Symbol[] valueParams(boolean ok) {
switch (this) {
case PolyType(_, Type result):
return result.valueParams(true);
case MethodType(Symbol[] vparams, _):
return vparams;
default:
if (ok) return Symbol.EMPTY_ARRAY;
throw Debug.abort("illegal case", this);
}
}
/** If this type is a (possibly polymorphic) method type, its result type
* after applying all method argument sections,
* otherwise the type itself.
*/
public Type resultType() {
switch (this) {
case PolyType(_, Type tpe):
return tpe.resultType();
case MethodType(_, Type tpe):
return tpe.resultType();
default:
return this;
}
}
/** The number of value parameter sections of this type.
*/
public int paramSectionCount() {
switch (this) {
case PolyType(_, Type restpe):
return restpe.paramSectionCount();
case MethodType(_, Type restpe):
return restpe.paramSectionCount() + 1;
default: return 0;
}
}
/** The first parameter section of this type.
*/
public Symbol[] firstParams() {
switch (this) {
case PolyType(_, Type restpe):
return restpe.firstParams();
case MethodType(Symbol[] params, _):
return params;
default: return Symbol.EMPTY_ARRAY;
}
}
/** If this type is overloaded, its alternative types,
* otherwise an array consisting of this type itself.
*/
public Type[] alternatives() {
switch (this) {
case OverloadedType(_, Type[] alttypes):
return alttypes;
default:
return new Type[]{this};
}
}
/** If type is a this type of a module class, transform to singletype of
* module.
*/
public Type expandModuleThis() {
switch (this) {
case ThisType(Symbol sym):
if ((sym.flags & MODUL) != 0 && sym.module() != Symbol.NONE) {
return singleType(
sym.owner().thisType().expandModuleThis(), sym.module());
}
}
return this;
}
/** Is this type a this type or singleton type?
*/
public boolean isStable() {
switch (unalias()) {
case ThisType(_):
case SingleType(_, _):
return true;
default:
return false;
}
}
public boolean isLegalPrefix() {
switch (unalias()) {
case ThisType(_):
case SingleType(_, _):
return true;
case TypeRef(_, Symbol sym, _):
return sym.kind == CLASS &&
((sym.flags & JAVA) != 0 ||
(sym.flags & (TRAIT | ABSTRACTCLASS)) == 0);
default:
return false;
}
}
/** Is this type a reference to an object type?
* todo: replace by this.isSubType(global.definitions.ANY_TYPE)?
*/
public boolean isObjectType() {
switch (unalias()) {
case ThisType(_):
case SingleType(_, _):
case CompoundType(_, _):
return true;
case TypeRef(Type pre, Symbol sym, _):
return sym.kind != ALIAS || unalias().isObjectType();
default:
return false;
}
}
/** Is this type of the form scala.FunctionN[T_1, ..., T_n, +T] or
* scala.Object with scala.FunctionN[T_1, ..., T_n, +T]?
*/
public boolean isFunctionType() {
switch (this) {
case TypeRef(Type pre, Symbol sym, Type[] args):
return sym.fullName().startsWith(Names.scala_Function) &&
args.length > 0;
case CompoundType(Type[] parents, Scope members):
return members.elems == Scope.Entry.NONE &&
parents.length == 2 &&
parents[0].symbol().fullName() == Names.scala_Object &&
parents[1].isFunctionType();
}
return false;
}
/** Get the scope containing the local members of this type.
* Symbols in this scope are not prefix-adapted!
*/
public Scope members() {
switch (this) {
case ErrorType:
return new Scope();
case TypeRef(_, Symbol sym, _):
return sym.info().members();
case SingleType(_, Symbol sym):
return singleDeref().members();
case CompoundType(Type[] basetypes, Scope members):
return members;
default:
return Scope.EMPTY;
}
}
/** Lookup symbol with given name among all local and inherited members
* of this type; return Symbol.NONE if not found.
*/
public Symbol lookup(Name name) {
switch (this) {
case ErrorType:
return Symbol.ERROR;
case ThisType(_):
case SingleType(_, _):
return singleDeref().lookup(name);
case TypeRef(_, Symbol sym, _):
return sym.info().lookup(name);
case CompoundType(Type[] parts, Scope members):
Symbol sym = members.lookup(name);
if (sym.kind != NONE) return sym;
else return lookupNonPrivate(name);
default:
return Symbol.NONE;
}
}
/** Lookup non-private symbol with given name among all local and
* inherited members of this type; return Symbol.NONE if not found.
*/
public Symbol lookupNonPrivate(Name name) {
return lookupNonPrivate(name, 0);
}
/** Same as before, but with additional parameter `start'.
* If start == 0, lookup in all basetypes of a compound type.
* If start == 1, lookup only in mixin classes.
*/
private Symbol lookupNonPrivate(Name name, int start) {
switch (this) {
case ErrorType:
return Symbol.ERROR;
case ThisType(_):
case SingleType(_, _):
return singleDeref().lookupNonPrivate(name);
case TypeRef(_, Symbol sym, _):
return sym.info().lookupNonPrivate(name, start);
case CompoundType(Type[] parts, Scope members):
Symbol sym = members.lookup(name);
if (sym.kind != NONE && (sym.flags & PRIVATE) == 0)
return sym;
// search base types in reverse; non-abstract members
// take precedence over abstract ones.
int i = parts.length;
sym = Symbol.NONE;
while (i > start && (sym.kind == NONE || (sym.flags & DEFERRED) != 0)) {
i
Symbol sym1 = parts[i].lookupNonPrivate(name, i == 0 ? 0 : 1);
if (sym1.kind != NONE &&
(sym1.flags & PRIVATE) == 0 &&
(sym.kind == NONE || (sym1.flags & DEFERRED) == 0))
sym = sym1;
}
return sym;
default:
return Symbol.NONE;
}
}
/** The type of type-to-type functions.
*/
public abstract static class Map {
public abstract Type apply(Type t);
/**
* This method assumes that all symbols in MethodTypes and
* PolyTypes have already been cloned.
*/
public Type applyParams(Type type) {
switch (type) {
case MethodType(Symbol[] vparams, Type result):
map(vparams, true);
Type result1 = applyParams(result);
return result == result1 ? type : MethodType(vparams, result1);
case PolyType(Symbol[] tparams, Type result):
map(tparams, true);
Type result1 = applyParams(result);
return result == result1 ? type : PolyType(tparams, result1);
default:
return apply(type);
}
}
/** Apply map to all top-level components of this type.
*/
public Type map(Type tp) {
switch (tp) {
case ErrorType:
case AnyType:
case NoType:
case UnboxedType(_):
case TypeVar(_, _):
case ThisType(_):
return tp;
case TypeRef(Type pre, Symbol sym, Type[] args):
Type pre1 = apply(pre);
Type[] args1 = map(args);
if (pre1 == pre && args1 == args) return tp;
else return typeRef(pre1, sym, args1);
case SingleType(Type pre, Symbol sym):
Type pre1 = apply(pre);
if (pre1 == pre) return tp;
else return singleType(pre1, sym);
case CompoundType(Type[] parts, Scope members):
Type[] parts1 = map(parts);
Scope members1 = map(members);
if (parts1 == parts && members1 == members) {
return tp;
} else if (members1 == members && !tp.symbol().isCompoundSym()) {
return compoundType(parts1, members, tp.symbol());
} else {
Scope members2 = new Scope();
//Type tp1 = compoundType(parts1, members2);
Type tp1 = (tp.symbol().isCompoundSym()) ? compoundType(parts1, members2)
: compoundType(parts1, members2, tp.symbol());
Symbol[] syms1 = members1.elements();
Symbol[] syms2 = new Symbol[syms1.length];
for (int i = 0; i < syms2.length; i++) {
syms2[i] = syms1[i].cloneSymbol(tp1.symbol());
}
for (int i = 0; i < syms2.length; i++) {
syms2[i].setInfo(syms1[i].info().subst(syms1, syms2));
if (syms2[i].kind == TYPE)
syms2[i].setLoBound(syms1[i].loBound().subst(syms1, syms2));
}
for (int i = 0; i < syms2.length; i++) {
members2.enter(syms2[i]);
}
return tp1;
}
case MethodType(Symbol[] vparams, Type result):
Symbol[] vparams1 = map(vparams);
Type result1 = apply(result);
if (vparams1 == vparams && result1 == result) return tp;
else return MethodType(vparams1, result1);
case PolyType(Symbol[] tparams, Type result):
Symbol[] tparams1 = map(tparams);
Type result1 = apply(result);
if (tparams1 != tparams) result1 = result1.subst(tparams, tparams1);
if (tparams1 == tparams && result1 == result) return tp;
else return PolyType(tparams1, result1);
case OverloadedType(Symbol[] alts, Type[] alttypes):
Type[] alttypes1 = map(alttypes);
if (alttypes1 == alttypes) return tp;
else return OverloadedType(alts, alttypes1);
case UnboxedArrayType(Type elemtp):
Type elemtp1 = apply(elemtp);
if (elemtp1 == elemtp) return tp;
else return UnboxedArrayType(elemtp1);
default:
throw new ApplicationError(tp + " " + tp.symbol());
}
}
public final Symbol map(Symbol sym) {
return map(sym, false);
}
public Symbol map(Symbol sym, boolean dontClone) {
Type tp = sym.info();
Type tp1 = apply(tp);
if (tp != tp1) {
if (!dontClone) sym = sym.cloneSymbol();
sym.setInfo(tp1);
dontClone = true;
}
if (sym.kind == TYPE) {
Type lb = sym.loBound();
Type lb1 = apply(lb);
if (lb != lb1) {
if (!dontClone) sym = sym.cloneSymbol();
sym.setLoBound(lb1);
}
}
return sym;
}
public Type[] map(Type[] tps) {
Type[] tps1 = tps;
for (int i = 0; i < tps.length; i++) {
Type tp = tps[i];
Type tp1 = apply(tp);
if (tp1 != tp && tps1 == tps) {
tps1 = new Type[tps.length];
System.arraycopy(tps, 0, tps1, 0, i);
}
tps1[i] = tp1;
}
return tps1;
}
/** Apply map to all elements of this array of symbols,
* preserving recursive references to symbols in the array.
*/
public final Symbol[] map(Symbol[] syms) {
return map(syms, false);
}
public Symbol[] map(Symbol[] syms, boolean dontClone) {
Symbol[] syms1 = syms;
for (int i = 0; i < syms.length; i++) {
Symbol sym = syms[i];
Symbol sym1 = map(sym, dontClone);
if (sym != sym1 && syms1 == syms) {
syms1 = new Symbol[syms.length];
System.arraycopy(syms, 0, syms1, 0, i);
}
syms1[i] = sym1;
}
if (syms1 != syms) {
for (int i = 0; i < syms1.length; i++) {
if (syms1[i] == syms[i])
syms1[i] = syms[i].cloneSymbol();
}
new SubstSymMap(syms, syms1).map(syms1, true);
}
return syms1;
}
/** Apply map to all elements of this array of this scope.
*/
public Scope map(Scope s) {
Symbol[] members = s.elements();
Symbol[] members1 = map(members);
if (members == members1) return s;
else return new Scope(members1);
}
}
public abstract static class MapOnlyTypes extends Map {
public Symbol map(Symbol sym, boolean dontClone) { return sym; }
public Symbol[] map(Symbol[] syms, boolean dontClone) { return syms; }
public Scope map(Scope s) { return s; }
}
/** Return the base type of this type whose symbol is `clazz', or NoType, if
* such a type does not exist.
*/
public Type baseType(Symbol clazz) {
//System.out.println(this + ".baseType(" + clazz + ")");//DEBUG
switch (this) {
case ErrorType:
return ErrorType;
case ThisType(_):
case SingleType(_, _):
return singleDeref().baseType(clazz);
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym == clazz)
return this;
else if (sym.kind == TYPE || sym.kind == ALIAS)
return pre.memberInfo(sym).baseType(clazz);
else if (clazz.isCompoundSym())
return NoType;
else {
return sym.baseType(clazz)
.asSeenFrom(pre, clazz.owner())
.subst(sym.typeParams(), args);
}
case CompoundType(Type[] parts, _):
for (int i = parts.length - 1; i >= 0; i
Type result = parts[i].baseType(clazz);
if (result != NoType) return result;
}
break;
case UnboxedArrayType(_):
if (clazz == Global.instance.definitions.ANY_CLASS ||
clazz == Global.instance.definitions.ANYREF_CLASS)
return clazz.type();
}
return NoType;
}
/** Return overriding instance of `sym' in this type,
* or `sym' itself if none exists.
*/
public Symbol rebind(Symbol sym) {
Symbol sym1 = lookupNonPrivate(sym.name);
if (sym1.kind != NONE) {
//System.out.println("rebinding " + sym + " to " + sym1);//DEBUG
return sym1;
}
else return sym;
}
/** A map to implement `asSeenFrom'.
*/
static class AsSeenFromMap extends Map {
private Type pre;
private Symbol clazz;
AsSeenFromMap(Type pre, Symbol clazz) {
this.pre = pre; this.clazz = clazz;
}
public Type apply(Type t) {
if (pre == NoType || clazz.kind != CLASS)
return t;
switch (t) {
case ThisType(Symbol sym):
return t.toPrefix(sym, pre, clazz);
case TypeRef(Type prefix, Symbol sym, Type[] args):
if (sym.kind == ALIAS) {
return apply(t.unalias());
} else if (sym.owner().isPrimaryConstructor()) {
assert sym.kind == TYPE;
Type t1 = t.toInstance(sym, pre, clazz);
//System.out.println(t + ".toInstance(" + pre + "," + clazz + ") = " + t1);//DEBUG
return t1;
} else {
Type prefix1 = apply(prefix);
Symbol sym1 = (prefix1 == prefix || (sym.flags & MODUL) != 0)
? sym : prefix1.rebind(sym);
Type[] args1 = map(args);
if (prefix1 == prefix && args1 == args) return t;
else return typeRef(prefix1, sym1, args1);
}
case SingleType(Type prefix, Symbol sym):
try {
Type prefix1 = apply(prefix);
if (prefix1 == prefix) return t;
else return singleType(prefix1, prefix1.rebind(sym));
} catch (Type.Error ex) {}
return apply(t.singleDeref());
default:
return map(t);
}
}
}
//where
Type toInstance(Symbol sym, Type pre, Symbol clazz) {
if (pre == NoType || clazz.kind != CLASS)
return this;
Symbol ownclass = sym.owner().primaryConstructorClass();
if (ownclass == clazz &&
pre.widen().symbol().isSubClass(ownclass)) {
switch (pre.baseType(ownclass)) {
case TypeRef(_, Symbol basesym, Type[] baseargs):
Symbol[] baseparams = basesym.typeParams();
for (int i = 0; i < baseparams.length; i++) {
if (sym == baseparams[i]) return baseargs[i];
}
//System.out.println(sym + " " + basesym + " " + ArrayApply.toString(baseparams));//DEBUG
break;
case ErrorType:
return ErrorType;
}
throw new ApplicationError(
this + " in " + ownclass + " cannot be instantiated from " + pre.widen()
);
} else {
return toInstance(sym, pre.baseType(clazz).prefix(), clazz.owner());
}
}
Type toPrefix(Symbol sym, Type pre, Symbol clazz) {
if (pre == NoType || clazz.kind != CLASS)
return this;
else if (sym.isSubClass(clazz) &&
pre.widen().symbol().isSubClass(sym))
return pre;
else
return toPrefix(sym, pre.baseType(clazz).prefix(), clazz.owner());
}
/** This type as seen from prefix `pre' and class `clazz'. This means:
* Replace all thistypes of `clazz' or one of its superclasses by `pre'
* and instantiate all parameters by arguments of `pre'.
* Proceed analogously for thistypes referring to outer classes.
*/
public Type asSeenFrom(Type pre, Symbol clazz) {
//System.out.println("computing asseenfrom of " + this + " with " + pre + "," + clazz);//DEBUG
return new AsSeenFromMap(pre, clazz).apply(this);
}
/** Types `these' as seen from prefix `pre' and class `clazz'.
*/
public static Type[] asSeenFrom(Type[] these, Type pre, Symbol clazz) {
return new AsSeenFromMap(pre, clazz).map(these);
}
/** The info of `sym', seen as a member of this type.
*/
public Type memberInfo(Symbol sym) {
return sym.info().asSeenFrom(this, sym.owner());
}
/** The type of `sym', seen as a member of this type.
*/
public Type memberType(Symbol sym) {
return sym.type().asSeenFrom(this, sym.owner());
}
/** The low bound of `sym', seen as a member of this type.
*/
public Type memberLoBound(Symbol sym) {
return sym.loBound().asSeenFrom(this, sym.owner());
}
/** A common map superclass for symbol/symbol and type/symbol substitutions.
*/
public static abstract class SubstMap extends Map {
private Symbol[] from;
SubstMap(Symbol[] from) {
this.from = from;
}
public boolean matches(Symbol sym1, Symbol sym2) {
return sym1 == sym2;
}
/** Produce replacement type
* @param i The index in `from' of the symbol to be replaced.
* @param fromtp The type referring to this symbol.
*/
protected abstract Type replacement(int i, Type fromtp);
/** Produce new substitution where some symbols are excluded.
* @param newfrom The new array of from symbols (without excluded syms)
* @param excluded The array of excluded sysmbols
*/
protected abstract SubstMap exclude(Symbol[] newfrom, Symbol[] excluded);
public Type apply(Type t) {
switch (t) {
case TypeRef(ThisType(_), Symbol sym, Type[] args):
for (int i = 0; i < from.length; i++) {
if (matches(sym, from[i])) return replacement(i, t);
}
break;
case SingleType(ThisType(_), Symbol sym):
for (int i = 0; i < from.length; i++) {
if (matches(sym, from[i])) return replacement(i, t);
}
break;
case PolyType(Symbol[] tparams, Type result):
Symbol[] from1 = excludeSyms(from, tparams, from);
if (from1 != from) {
SubstMap f = exclude(from1, tparams);
Symbol[] tparams1 = f.map(tparams);
Type result1 = f.apply(result);
if (tparams1 != tparams)
result1 = result1.subst(tparams, tparams1);
if (tparams1 == tparams && result1 == result) return t;
else return PolyType(tparams1, result1);
}
}
return map(t);
}
//where
private boolean contains1(Symbol[] syms, Symbol sym) {
int i = 0;
while (i < syms.length && syms[i] != sym) i++;
return i < syms.length;
}
private int nCommon(Symbol[] from, Symbol[] tparams) {
int cnt = 0;
for (int i = 0; i < from.length; i++) {
if (contains1(tparams, from[i])) cnt++;
}
return cnt;
}
private Symbol[] excludeSyms(Symbol[] from, Symbol[] tparams, Symbol[] syms) {
int n = nCommon(from, tparams);
if (n == 0) {
return syms;
} else {
Symbol[] syms1 = new Symbol[syms.length - n];
int j = 0;
for (int i = 0; i < from.length; i++) {
if (!contains1(tparams, from[i])) syms1[j++] = syms[i];
}
return syms1;
}
}
private Type[] excludeTypes(Symbol[] from, Symbol[] tparams, Type[] types) {
int n = nCommon(from, tparams);
if (n == 0) {
return types;
} else {
Type[] types1 = new Type[types.length - n];
int j = 0;
for (int i = 0; i < from.length; i++) {
if (!contains1(tparams, from[i])) types1[j++] = types[i];
}
return types1;
}
}
}
/** A map for symbol/symbol substitutions
*/
public static class SubstSymMap extends SubstMap {
Symbol[] to;
protected SubstSymMap(Symbol[] from, Symbol[] to) {
super(from);
this.to = to;
}
protected Type replacement(int i, Type fromtp) {
switch (fromtp) {
case TypeRef(Type pre, Symbol sym, Type[] args):
return typeRef(pre, to[i], args);
case SingleType(Type pre, Symbol sym):
return singleType(pre, to[i]);
default:
throw new ApplicationError();
}
}
protected SubstMap exclude(Symbol[] newfrom, Symbol[] excluded) {
return new SubstSymMap(newfrom, excludeSyms(from, excluded, to));
}
}
/** A map for type/symbol substitutions
*/
public static class SubstTypeMap extends SubstMap {
Type[] to;
protected SubstTypeMap(Symbol[] from, Type[] to) {
super(from);
this.to = to;
}
protected Type replacement(int i, Type fromtp) {
return to[i];
}
protected SubstMap exclude(Symbol[] newfrom, Symbol[] excluded) {
return new SubstTypeMap(newfrom, excludeTypes(from, excluded, to));
}
}
/** Substitute symbols `to' for occurrences of symbols `from' in this type.
*/
public Type subst(Symbol[] from, Symbol[] to) {
if (to.length != 0 && from != to) {
assert from.length == to.length
: this + ": " + from.length + " != " + to.length;
return new SubstSymMap(from, to).apply(this);
} else return this;
}
/** Substitute symbols `to' for occurrences of symbols `from' in these types.
*/
public static Type[] subst(Type[] these, Symbol[] from, Symbol[] to) {
if (these.length != 0 && to.length != 0 && from != to) {
assert from.length == to.length;
return new SubstSymMap(from, to).map(these);
} else return these;
}
/** Substitute types `to' for occurrences of symbols `from' in this type.
*/
public Type subst(Symbol[] from, Type[] to) {
if (to.length != 0) {
assert from.length == to.length
: this + ": " + Debug.show(from) + " <> " + ArrayApply.toString(to);
return new SubstTypeMap(from, to).apply(this);
} else return this;
}
/** Substitute types `to' for occurrences of symbols `from' in these types.
*/
public static Type[] subst(Type[] these, Symbol[] from, Type[] to) {
if (these.length != 0 && to.length != 0) {
assert from.length == to.length;
return new SubstTypeMap(from, to).map(these);
} else return these;
}
/** A map for substitutions of thistypes.
*/
public static class SubstThisMap extends Map {
Symbol from;
Type to;
public SubstThisMap(Symbol from, Type to) {
this.from = from;
this.to = to;
}
public SubstThisMap(Symbol oldSym, Symbol newSym) {
this(oldSym, newSym.thisType());
}
public Type apply(Type t) {
switch (t) {
case ThisType(Symbol sym):
if (sym == from) return to;
else return t;
default:
return map(t);
}
}
}
public Type substThis(Symbol from, Type to) {
return new SubstThisMap(from, to).apply(this);
}
public static Type[] substThis(Type[] these, Symbol from, Type to) {
return new SubstThisMap(from, to).map(these);
}
static class ContainsMap extends Map {
boolean result = false;
Symbol sym;
ContainsMap(Symbol sym) {
this.sym = sym;
}
public Type apply(Type t) {
if (!result) {
switch (t) {
case TypeRef(Type pre, Symbol sym1, Type[] args):
if (sym == sym1) result = true;
else { map(pre); map(args); }
break;
case SingleType(Type pre, Symbol sym1):
map(pre);
if (sym == sym1) result = true;
break;
default:
map(t);
}
}
return t;
}
}
/** Does this type contain symbol `sym'?
*/
public boolean contains(Symbol sym) {
ContainsMap f = new ContainsMap(sym);
f.apply(this);
return f.result;
}
/** Does this type contain any of the symbols `syms'?
*/
public boolean containsSome(Symbol[] syms) {
for (int i = 0; i < syms.length; i++)
if (contains(syms[i])) return true;
return false;
}
/**
* Clones a type i.e. returns a new type where all symbols in
* MethodTypes and PolyTypes have been cloned.
*/
public Type cloneType(Symbol oldOwner, Symbol newOwner) {
switch (this) {
case MethodType(Symbol[] vparams, Type result):
Symbol[] clones = new Symbol[vparams.length];
for (int i = 0; i < clones.length; i++) {
assert vparams[i].owner() == oldOwner : Debug.show(vparams[i]);
clones[i] = vparams[i].cloneSymbol(newOwner);
}
result = result.cloneType(oldOwner, newOwner);
Type clone = Type.MethodType(clones, result);
if (vparams.length != 0)
clone = new SubstSymMap(vparams, clones).applyParams(clone);
return clone;
case PolyType(Symbol[] tparams, Type result):
Symbol[] clones = new Symbol[tparams.length];
for (int i = 0; i < clones.length; i++) {
assert tparams[i].owner() == oldOwner : Debug.show(tparams[i]);
clones[i] = tparams[i].cloneSymbol(newOwner);
}
result = result.cloneType(oldOwner, newOwner);
Type clone = Type.PolyType(clones, result);
if (tparams.length != 0)
clone = new SubstSymMap(tparams, clones).applyParams(clone);
return clone;
default:
return this;
}
}
/**
* Clones a type i.e. returns a new type where all symbols in
* MethodTypes and PolyTypes have been cloned. This method
* performs no substitution on the type of the cloned symbols.
* Typically, the type of those symbols will be fixed later by
* applying some Map.applyParams method to the returned type.
*/
public Type cloneTypeNoSubst(SymbolCloner cloner) {
switch (this) {
case MethodType(Symbol[] vparams, Type result):
Symbol[] clones = cloner.cloneSymbols(vparams);
return Type.MethodType(clones, result.cloneTypeNoSubst(cloner));
case PolyType(Symbol[] tparams, Type result):
Symbol[] clones = cloner.cloneSymbols(tparams);
return Type.PolyType(clones, result.cloneTypeNoSubst(cloner));
default:
return this;
}
}
/** Is this type a subtype of that type?
*/
public boolean isSubType(Type that) {
if (explainSwitch) {
for (int i = 0; i < indent; i++) System.out.print(" ");
System.out.println(this + " < " + that + "?");
indent++;
}
boolean result = isSubType0(that);
if (explainSwitch) {
indent
for (int i = 0; i < indent; i++) System.out.print(" ");
System.out.println(result);
}
return result;
}
public boolean isSubType0(Type that) {
if (this == that) return true;
switch (this) {
case ErrorType:
case AnyType:
return true;
}
switch (that) {
case ErrorType:
case AnyType:
return true;
case NoType:
return false;
case ThisType(_):
case SingleType(_, _):
switch (this) {
case ThisType(_):
case SingleType(_, _):
return this.isSameAs(that);
}
break;
case TypeRef(Type pre1, Symbol sym1, Type[] args1):
switch (this) {
case TypeRef(Type pre, Symbol sym, Type[] args):
boolean samepre = pre.isSameAs(pre1);
if ((samepre && sym == sym1 /* fast case */ ||
!samepre && pre.isSubType(pre1) && sym == pre.rebind(sym1)) &&
isSubArgs(args, args1, sym.typeParams())
||
sym.kind == TYPE && pre.memberInfo(sym).isSubType(that))
return true;
break;
}
if (sym1.kind == CLASS) {
Type base = this.baseType(sym1);
if (this != base && base.isSubType(that))
return true;
}
break;
case CompoundType(Type[] parts1, Scope members1):
int i = 0;
while (i < parts1.length && isSubType(parts1[i])) i++;
if (i == parts1.length && specializes(members1))
return true;
break;
case MethodType(Symbol[] ps1, Type res1):
switch (this) {
case MethodType(Symbol[] ps, Type res):
if (ps.length != ps1.length) return false;
for (int i = 0; i < ps.length; i++) {
Symbol p1 = ps1[i];
Symbol p = ps[i];
if (!p1.type().isSubType(p.type()) ||
(p1.flags & (Modifiers.DEF | Modifiers.REPEATED)) !=
(p.flags & (Modifiers.DEF | Modifiers.REPEATED)))
return false;
}
return res.isSubType(res1);
}
break;
case PolyType(Symbol[] ps1, Type res1):
switch (this) {
case PolyType(Symbol[] ps, Type res):
if (ps.length != ps1.length) return false;
for (int i = 0; i < ps.length; i++)
if (!ps1[i].info().subst(ps1, ps).isSubType(ps[i].info()) ||
!ps[i].loBound().isSubType(ps1[i].loBound().subst(ps1, ps)))
return false;
return res.isSubType(res1.subst(ps1, ps));
}
break;
case OverloadedType(Symbol[] alts1, Type[] alttypes1):
for (int i = 0; i < alttypes1.length; i++) {
if (!isSubType(alttypes1[i]))
return false;
}
return true;
case UnboxedType(int tag1):
switch (this) {
case UnboxedType(int tag):
return tag == tag1 ||
(tag < tag1 && tag1 <= DOUBLE && tag1 != CHAR);
}
break;
case UnboxedArrayType(UnboxedType(int tag1)):
switch (this) {
case UnboxedArrayType(UnboxedType(int tag)):
return tag1 == tag;
}
break;
case UnboxedArrayType(Type elemtp1):
switch (this) {
case UnboxedArrayType(Type elemtp):
return elemtp.isSubType(elemtp1);
}
break;
case TypeVar(Type origin, Constraint constr):
//todo: should we test for equality with origin?
if (constr.inst != NoType) {
return this.isSubType(constr.inst);
} else {
constr.lobounds = new List(this, constr.lobounds);
return true;
}
default:
throw new ApplicationError(this + " <: " + that);
}
switch (this) {
case NoType:
return false;
case ThisType(_):
case SingleType(_, _):
if (this.singleDeref().isSubType(that)) return true;
break;
case TypeVar(Type origin, Constraint constr):
if (constr.inst != NoType) {
return constr.inst.isSubType(that);
} else {
constr.hibounds = new List(that, constr.hibounds);
return true;
}
case TypeRef(_, Symbol sym, _):
switch (that) {
case TypeRef(Type pre1, Symbol sym1, _):
if (sym1.kind == TYPE && this.isSubType(that.loBound()))
return true;
}
if (sym.kind == ALIAS)
return this.unalias().isSubType(that);
else if (sym == Global.instance.definitions.ALL_CLASS)
return that.isSubType(Global.instance.definitions.ANY_TYPE);
else if (sym == Global.instance.definitions.ALLREF_CLASS)
return
that.symbol() == Global.instance.definitions.ANY_CLASS ||
(that.symbol() != Global.instance.definitions.ALL_CLASS &&
that.isSubType(Global.instance.definitions.ANYREF_TYPE));
break;
case OverloadedType(Symbol[] alts, Type[] alttypes):
for (int i = 0; i < alttypes.length; i++) {
if (alttypes[i].isSubType(that)) return true;
}
break;
}
switch (that) {
case TypeRef(_, Symbol sym1, _):
if (sym1.kind == ALIAS) return this.isSubType(that.unalias());
break;
}
return false;
}
/** Are types `these' subtypes of corresponding types `those'?
*/
public static boolean isSubType(Type[] these, Type[] those) {
if (these.length != those.length) return false;
for (int i = 0; i < these.length; i++) {
if (!these[i].isSubType(those[i])) return false;
}
return true;
}
/** Are types `these' arguments types conforming to corresponding types `those'?
*/
static boolean isSubArgs(Type[] these, Type[] those, Symbol[] tparams) {
if (these.length != those.length) return false;
for (int i = 0; i < these.length; i++) {
if ((tparams[i].flags & COVARIANT) != 0) {
if (!these[i].isSubType(those[i])) return false;
} else if ((tparams[i].flags & CONTRAVARIANT) != 0) {
//System.out.println("contra: " + these[i] + " " + those[i] + " " + those[i].isSubType(these[i]));//DEBUG
if (!those[i].isSubType(these[i])) return false;
} else {
if (!these[i].isSameAs(those[i])) return false;
}
}
return true;
}
public static boolean isSubSet(Type[] alts, Type[] alts1) {
for (int i = 0; i < alts.length; i++) {
int j = 0;
while (j < alts1.length && !alts1[j].isSameAs(alts[i])) j++;
if (j == alts1.length) return false;
}
return true;
}
/** Does this type implement all symbols in scope `s' with same or stronger types?
*/
public boolean specializes(Scope s) {
for (Scope.Entry e = s.elems; e != Scope.Entry.NONE; e = e.next)
if (!specializes(e.sym)) return false;
return true;
}
/** Does this type implement symbol `sym1' with same or stronger type?
*/
public boolean specializes(Symbol sym1) {
if (explainSwitch) {
for (int i = 0; i < indent; i++) System.out.print(" ");
System.out.println(this + " specializes " + sym1 + "?");
indent++;
}
boolean result = specializes0(sym1);
if (explainSwitch) {
indent
for (int i = 0; i < indent; i++) System.out.print(" ");
System.out.println(result);
}
return result;
}
public boolean specializes0(Symbol sym1) {
Symbol sym = lookup(sym1.name);
Type self = narrow();
Symbol[] tparams = symbol().typeParams();
Type[] targs = typeArgs();
return
sym == sym1
||
(sym.kind == sym1.kind || sym1.kind == TYPE) &&
self.memberInfo(sym).subst(tparams, targs)
.isSubType(sym1.info().substThis(sym.owner(), self)) &&
sym1.loBound().substThis(sym.owner(), self)
.isSubType(self.memberLoBound(sym).subst(tparams, targs))
||
(sym.kind == TYPE && sym1.kind == ALIAS &&
sym1.info().unalias().isSameAs(sym.type()));
}
/** Is this type the same as that type?
*/
public boolean isSameAs(Type that) {
if (explainSwitch) {
for (int i = 0; i < indent; i++) System.out.print(" ");
System.out.println(this + " = " + that + "?");
indent++;
}
boolean result = isSameAs0(that);
if (explainSwitch) {
indent
for (int i = 0; i < indent; i++) System.out.print(" ");
System.out.println(result);
}
return result;
}
public boolean isSameAs0(Type that) {
if (this == that) return true;
switch (this) {
case ErrorType:
case AnyType:
return true;
case ThisType(Symbol sym):
switch (that) {
case ThisType(Symbol sym1):
return sym == sym1;
case SingleType(Type pre1, Symbol sym1):
return sym1.isModule()
&& sym == sym1.moduleClass()
&& sym.owner().thisType().isSameAs(pre1)
||
deAlias(that) != that &&
this.isSameAs(deAlias(that));
}
break;
case SingleType(Type pre, Symbol sym):
switch (that) {
case SingleType(Type pre1, Symbol sym1):
return sym == sym1 && pre.isSameAs(pre1)
||
(deAlias(this) != this || deAlias(that) != that) &&
deAlias(this).isSameAs(deAlias(that));
case ThisType(Symbol sym1):
return sym.isModule()
&& sym.moduleClass() == sym1
&& pre.isSameAs(sym1.owner().thisType())
||
deAlias(this) != this &&
deAlias(this).isSameAs(that);
}
break;
case TypeRef(Type pre, Symbol sym, Type[] args):
switch (that) {
case TypeRef(Type pre1, Symbol sym1, Type[] args1):
if (sym == sym1 && pre.isSameAs(pre1) && isSameAs(args, args1))
return true;
}
break;
case CompoundType(Type[] parts, Scope members):
switch (that) {
case CompoundType(Type[] parts1, Scope members1):
if (parts.length != parts1.length) return false;
for (int i = 0; i < parts.length; i++)
if (!parts[i].isSameAs(parts1[i])) return false;
return isSameAs(members, members1);
}
break;
case MethodType(Symbol[] ps, Type res):
switch (that) {
case MethodType(Symbol[] ps1, Type res1):
if (ps.length != ps1.length) return false;
for (int i = 0; i < ps.length; i++) {
Symbol p1 = ps1[i];
Symbol p = ps[i];
if (!p1.type().isSameAs(p.type()) ||
(p1.flags & (Modifiers.DEF | Modifiers.REPEATED)) !=
(p.flags & (Modifiers.DEF | Modifiers.REPEATED)))
return false;
}
return res.isSameAs(res1);
}
break;
case PolyType(Symbol[] ps, Type res):
switch (that) {
case PolyType(Symbol[] ps1, Type res1):
if (ps.length != ps1.length) return false;
for (int i = 0; i < ps.length; i++)
if (!ps1[i].info().subst(ps1, ps).isSameAs(ps[i].info()) ||
!ps1[i].loBound().subst(ps1, ps).isSameAs(ps[i].loBound()))
return false;
return res.isSameAs(res1.subst(ps1, ps));
}
break;
case OverloadedType(Symbol[] alts, Type[] alttypes):
switch (that) {
case OverloadedType(Symbol[] alts1, Type[] alttypes1):
return isSubSet(alttypes1, alttypes)
&& isSubSet(alttypes, alttypes1);
}
break;
case UnboxedType(int kind):
switch (that) {
case UnboxedType(int kind1):
return kind == kind1;
}
break;
case UnboxedArrayType(Type elemtp):
switch (that) {
case UnboxedArrayType(Type elemtp1):
return elemtp.isSameAs(elemtp1);
}
break;
}
switch (that) {
case ErrorType:
case AnyType:
return true;
case NoType:
return false;
case TypeVar(Type origin, Constraint constr):
if (constr.inst != NoType) return constr.inst.isSameAs(this);
else return constr.instantiate(this.any2typevar());
}
switch (this) {
case NoType:
return false;
case TypeRef(_, Symbol sym, _):
if (sym.kind == ALIAS) return this.unalias().isSameAs(that);
break;
case TypeVar(Type origin, Constraint constr):
if (constr.inst != NoType) return constr.inst.isSameAs(that);
else return constr.instantiate(that.any2typevar());
}
switch (that) {
case TypeRef(_, Symbol sym, _):
if (sym.kind == ALIAS) return this.isSameAs(that.unalias());
}
return false;
}
//where
Type deAlias(Type tp) {
switch (tp) {
case SingleType(_, _):
Type tp1 = tp.singleDeref();
if (tp1.isStable()) return deAlias(tp1);
}
return tp;
}
/** Are types `these' the same as corresponding types `those'?
*/
public static boolean isSameAs(Type[] these, Type[] those) {
if (these.length != those.length) return false;
for (int i = 0; i < these.length; i++) {
if (!these[i].isSameAs(those[i])) return false;
}
return true;
}
/** Do scopes `s1' and `s2' define he same symbols with the same kinds and infos?
*/
public boolean isSameAs(Scope s1, Scope s2) {
return isSubScope(s1, s2) && isSubScope(s2, s1);
}
/** Does scope `s1' define all symbols of scope `s2' with the same kinds and infos?
*/
private boolean isSubScope(Scope s1, Scope s2) {
for (Scope.Entry e = s2.elems; e != Scope.Entry.NONE; e = e.next) {
Symbol sym2 = e.sym;
Symbol sym1 = s1.lookup(sym2.name);
if (sym1.kind != sym2.kind ||
!sym1.info().isSameAs(
sym2.info().substThis(
sym2.owner(), sym1.owner().thisType())) ||
!sym1.loBound().isSameAs(
sym2.loBound().substThis(
sym2.owner(), sym1.owner().thisType())))
return false;
}
return true;
}
boolean isSameAsAll(Type[] tps) {
int i = 1;
while (i < tps.length && isSameAs(tps[i])) i++;
return i == tps.length;
}
/** Map every occurrence of AnyType to a fresh type variable.
*/
public static Map any2typevarMap = new Map() {
public Type apply(Type t) { return t.any2typevar(); }
};
public Type any2typevar() {
switch (this) {
case AnyType:
return TypeVar(this, new Constraint());
default:
return any2typevarMap.map(this);
}
}
/** The closure of this type, i.e. the widened type itself followed by all
* its direct and indirect (pre-) base types, sorted by Symbol.isLess().
*/
public Type[] closure() {
switch (this.widen().unalias()) {
case TypeRef(Type pre, Symbol sym, Type[] args):
return subst(
asSeenFrom(sym.closure(), pre, sym.owner()),
sym.typeParams(), args);
case CompoundType(Type[] parts, Scope members):
Type[][] closures = new Type[parts.length][];
for (int i = 0; i < parts.length; i++)
closures[i] = parts[i].closure();
return union(closures);
default:
return new Type[]{this};
}
}
/** return union of array of closures. It is assumed that
* for any two base types with the same class symbols the later one
* is a subtype of the former.
*/
static private Type[] union(Type[][] closures) {
if (closures.length == 1) return closures[0]; // fast special case
int[] index = new int[closures.length];
int totalsize = 0;
for (int i = 0; i < index.length; i++) {
index[i] = 0;
totalsize = totalsize + closures[i].length;
}
Type[] res = new Type[totalsize];
int j = 0;
while (true) {
// find minimal element
Type min = null;
for (int i = 0; i < index.length; i++) {
if (index[i] < closures[i].length) {
Type cltype = closures[i][index[i]];
if (min == null ||
cltype.symbol().isLess(min.symbol()) ||
cltype.symbol() == min.symbol()) {
min = cltype;
}
}
}
if (min == null) break;
res[j] = min;
j = j + 1;
// bump all indices that start with minimal element
for (int i = 0; i < index.length; i++) {
if (index[i] < closures[i].length &&
closures[i][index[i]].symbol() == min.symbol())
index[i] = index[i] + 1;
}
}
Type[] result = new Type[j];
System.arraycopy(res, 0, result, 0, j);
return result;
}
/** return intersection of non-empty array of closures
*/
static private Type[] intersection(Type[][] closures) {
if (closures.length == 1) return closures[0]; // fast special case
int[] index = new int[closures.length];
Type[] mintypes = new Type[closures.length];
int minsize = Integer.MAX_VALUE;
for (int i = 0; i < index.length; i++) {
index[i] = 0;
if (closures[i].length < minsize) minsize = closures[i].length;
}
Type[] res = new Type[minsize];
int j = 0;
L:
while (true) {
// find minimal element
Symbol minsym = null;
for (int i = 0; i < index.length; i++) {
if (index[i] == closures[i].length) break L;
Symbol clsym = closures[i][index[i]].symbol();
if (minsym == null || clsym.isLess(minsym)) minsym = clsym;
}
boolean agree = true;
// bump all indices that start with minimal element
for (int i = 0; i < index.length; i++) {
Type cltype = closures[i][index[i]];
if (cltype.symbol() == minsym) {
mintypes[i] = cltype;
index[i] = index[i] + 1;
} else {
agree = false;
}
}
if (agree) {
Type mintype = argLub(mintypes);
if (mintype.symbol().kind == CLASS) {
res[j] = mintype;
j = j + 1;
}
}
}
Type[] result = new Type[j];
System.arraycopy(res, 0, result, 0, j);
return result;
}
/** same as lub, but all types are instances of the same class,
* possibly with different prefixes and arguments.
*/
//todo: catch lubs not within bounds.
static Type argLub(Type[] tps) {
tps = elimRedundant(tps, true);
if (tps.length == 1) return tps[0];
Type pre = tps[0].prefix();
Symbol sym = tps[0].symbol();
Symbol[] tparams = sym.typeParams();
Type[] args = new Type[tparams.length];
Type[][] argss = new Type[args.length][tps.length];
for (int i = 0; i < tps.length; i++) {
switch (tps[i]) {
case TypeRef(Type pre1, Symbol sym1, Type[] args1):
assert sym == sym1;
assert args1.length == args.length;
if (!pre.isSameAs(pre1)) return NoType;
for (int j = 0; j < args1.length; j++)
argss[j][i] = args1[j];
break;
case ErrorType:
return ErrorType;
default:
assert false : tps[i];
}
}
for (int j = 0; j < args.length; j++) {
if ((tparams[j].flags & COVARIANT) != 0)
args[j] = lub(argss[j]);
else if ((tparams[j].flags & CONTRAVARIANT) != 0)
args[j] = glb(argss[j]);
else return NoType;
}
return typeRef(pre, sym, args);
}
/** The frontier of a closure C is the minimal set of types such that
* the union of the closures of these types equals C.
*/
static private Type[] frontier(Type[] closure) {
Type[] front = new Type[closure.length];
int j = 0;
for (int i = 0; i < closure.length; i++) {
int k = 0;
Type tp = closure[i];
while (k < j && !front[k].symbol().isSubClass(tp.symbol()))
k++;
if (k == j) {
front[j] = tp;
j++;
}
}
Type[] result = new Type[j];
System.arraycopy(front, 0, result, 0, j);
return result;
}
/** remove types that are subtypes of some other type.
*/
static private Type[] elimRedundant(Type[] tps, boolean elimLower) {
Type.List tl = Type.List.EMPTY;
int nredundant = 0;
boolean[] redundant = new boolean[tps.length];
for (int i = 0; i < tps.length; i++) {
if (tps[i] == ErrorType) {
return new Type[]{ErrorType};
} else {
assert tps[i].isObjectType() : tps[i];
for (int j = 0; j < i && !redundant[i]; j++) {
if (!redundant[j]) {
if (tps[i].isSubType(tps[j])) {
redundant[elimLower ? i : j] = true;
nredundant++;
} else if (tps[j].isSubType(tps[i])) {
redundant[elimLower ? j : i] = true;
nredundant++;
}
}
}
}
}
if (nredundant != 0) {
Type[] tps1 = new Type[tps.length - nredundant];
int n = 0;
for (int i = 0; i < tps.length; i++) {
if (!redundant[i]) tps1[n++] = tps[i];
}
return tps1;
} else {
return tps;
}
}
/** Return the least upper bound of non-empty array of types `tps'.
*/
public static Type lub(Type[] tps) {
//System.out.println("lub" + ArrayApply.toString(tps));//DEBUG
if (tps.length == 0) return Global.instance.definitions.ALL_TYPE;
// remove types that are subtypes of some other type.
tps = elimRedundant(tps, true);
if (tps.length == 1) return tps[0];
// intersect closures and build frontier.
Type[][] closures = new Type[tps.length][];
for (int i = 0; i < tps.length; i++) {
closures[i] = tps[i].closure();
}
Type[] allBaseTypes = intersection(closures);
Type[] leastBaseTypes = frontier(allBaseTypes);
assert leastBaseTypes.length > 0 : ArrayApply.toString(tps);
// add refinements where necessary
Scope members = new Scope();
Type lubType = compoundType(leastBaseTypes, members);
Type lubThisType = lubType.narrow();
//System.out.println("lubtype = " + lubType);//DEBUG
Symbol[] rsyms = new Symbol[tps.length];
Type[] rtps = new Type[tps.length];
Type[] rlbs = new Type[tps.length];
for (int i = 0; i < allBaseTypes.length; i++) {
for (Scope.Entry e = allBaseTypes[i].members().elems;
e != Scope.Entry.NONE;
e = e.next) {
Name name = e.sym.name;
if ((e.sym.flags & PRIVATE) == 0 && lubType.lookup(name) == e.sym) {
Type symType = memberTp(lubThisType, e.sym);
Type symLoBound = lubThisType.memberLoBound(e.sym);
int j = 0;
while (j < tps.length) {
rsyms[j] = tps[j].lookupNonPrivate(name);
if (rsyms[j] == e.sym) break;
if (rsyms[j].isMethod()) break; // since methods cannot
// appear in refinements.
rtps[j] = memberTp(tps[j], rsyms[j])
.substThis(tps[j].symbol(), lubThisType);
rlbs[j] = tps[j].memberLoBound(rsyms[j])
.substThis(tps[j].symbol(), lubThisType);
if (rtps[j].isSameAs(symType) &&
rlbs[j].isSameAs(symLoBound)) break;
j++;
}
if (j == tps.length) {
Symbol lubSym = lub(rsyms, rtps, rlbs, lubType.symbol());
if (lubSym.kind != NONE &&
!(lubSym.kind == e.sym.kind &&
lubSym.info().isSameAs(symType) &&
lubSym.loBound().isSameAs(symType)))
members.enter(lubSym);
}
}
}
}
//System.out.print("lub "); System.out.print(ArrayApply.toString(tps)); System.out.println(" = " + lubType);//DEBUG
if (leastBaseTypes.length == 1 && members.elems == Scope.Entry.NONE)
return leastBaseTypes[0];
else return lubType;
}
//where
private static Type memberTp(Type base, Symbol sym) {
return sym.kind == CLASS ? base.memberType(sym) : base.memberInfo(sym);
}
private static Symbol lub(Symbol[] syms, Type[] tps, Type[] lbs, Symbol owner) {
//System.out.println("lub" + ArrayApply.toString(syms));//DEBUG
int lubKind = syms[0].kind;
for (int i = 1; i < syms.length; i++) {
Symbol sym = syms[i];
if (sym.kind == ERROR) return Symbol.NONE;
if (sym.isType() && sym.kind != lubKind) lubKind = TYPE;
}
if (lubKind == syms[0].kind && tps[0].isSameAsAll(tps)) {
return syms[0].cloneSymbol();
}
Type lubType = lub(tps);
if (lubType == Type.NoType) return Symbol.NONE;
Symbol lubSym;
switch (lubKind) {
case VAL:
lubSym = new TermSymbol(syms[0].pos, syms[0].name, owner, 0);
break;
case TYPE: case ALIAS: case CLASS:
lubSym = new AbsTypeSymbol(syms[0].pos, syms[0].name, owner, 0);
lubSym.setLoBound(glb(lbs));
break;
default:
throw new ApplicationError();
}
lubSym.setInfo(lubType);
return lubSym;
}
public static Type glb(Type[] tps) {
if (tps.length == 0) return Global.instance.definitions.ANY_TYPE;
// step one: eliminate redunandant types; return if one one is left
tps = elimRedundant(tps, false);
if (tps.length == 1) return tps[0];
// step two: build arrays of all typerefs and all refinements
Type.List treftl = Type.List.EMPTY;
Type.List comptl = Type.List.EMPTY;
for (int i = 0; i < tps.length; i++) {
switch (tps[i]) {
case TypeRef(_, _, _):
treftl = new Type.List(tps[i], treftl);
break;
case CompoundType(Type[] parents, Scope members):
if (members.elems != Scope.Entry.NONE)
comptl = new Type.List(tps[i], comptl);
for (int j = 0; j < parents.length; j++)
treftl = new Type.List(parents[i], treftl);
break;
case ThisType(_):
case SingleType(_, _):
return Global.instance.definitions.ALL_TYPE;
}
}
CompoundType glbType = compoundType(Type.EMPTY_ARRAY, new Scope());
Type glbThisType = glbType.narrow();
// step 3: compute glb of all refinements.
Scope members = Scope.EMPTY;
if (comptl != List.EMPTY) {
Type[] comptypes = comptl.toArrayReverse();
Scope[] refinements = new Scope[comptypes.length];
for (int i = 0; i < comptypes.length; i++)
refinements[i] = comptypes[i].members();
if (!setGlb(glbType.members, refinements, glbThisType)) {
// refinements don't have lower bound, so approximate
// by AllRef
glbType.members = Scope.EMPTY;
treftl = new Type.List(
Global.instance.definitions.ALLREF_TYPE, treftl);
}
}
// eliminate redudant typerefs
Type[] treftypes = elimRedundant(treftl.toArrayReverse(), false);
if (treftypes.length != 1 || glbType.members.elems != Scope.Entry.NONE) {
// step 4: replace all abstract types by their lower bounds.
boolean hasAbstract = false;
for (int i = 0; i < treftypes.length; i++) {
if (treftypes[i].unalias().symbol().kind == TYPE)
hasAbstract = true;
}
if (hasAbstract) {
treftl = Type.List.EMPTY;
for (int i = 0; i < treftypes.length; i++) {
if (treftypes[i].unalias().symbol().kind == TYPE)
treftl = new Type.List(treftypes[i].loBound(), treftl);
else
treftl = new Type.List(treftypes[i], treftl);
}
treftypes = elimRedundant(treftl.toArrayReverse(), false);
}
}
if (treftypes.length != 1) {
// step 5: if there are conflicting instantiations of same
// class, replace them by lub/glb of arguments or lower bound.
Type lb = NoType;
for (int i = 0;
i < treftypes.length &&
lb.symbol() != Global.instance.definitions.ALL_CLASS;
i++) {
for (int j = 0; j < i; j++) {
if (treftypes[j].symbol() == treftypes[i].symbol())
lb = argGlb(treftypes[j], treftypes[i]);
}
}
if (lb != NoType) return lb;
}
if (treftypes.length == 1 && glbType.members.elems == Scope.Entry.NONE) {
return treftypes[0];
} else {
glbType.parts = treftypes;
return glbType;
}
}
private static Type argGlb(Type tp1, Type tp2) {
switch (tp1) {
case TypeRef(Type pre1, Symbol sym1, Type[] args1):
switch (tp2) {
case TypeRef(Type pre2, Symbol sym2, Type[] args2):
assert sym1 == sym2;
if (pre1.isSameAs(pre2)) {
Symbol[] tparams = sym1.typeParams();
Type[] args = new Type[tparams.length];
for (int i = 0; i < tparams.length; i++) {
if (args1[i].isSameAs(args2[i]))
args[i] = args1[i];
else if ((tparams[i].flags & COVARIANT) != 0)
args[i]= lub(new Type[]{args1[i], args2[i]});
else if ((tparams[i].flags & CONTRAVARIANT) != 0)
args[i]= glb(new Type[]{args1[i], args2[i]});
else
return glb(new Type[]{tp1.loBound(), tp2.loBound()});
}
return typeRef(pre1, sym1, args);
}
}
}
return glb(new Type[]{tp1.loBound(), tp2.loBound()});
}
/** Set scope `result' to glb of scopes `ss'. Return true iff succeeded.
*/
private static boolean setGlb(Scope result, Scope[] ss, Type glbThisType) {
for (int i = 0; i < ss.length; i++)
for (Scope.Entry e = ss[i].elems; e != Scope.Entry.NONE; e = e.next)
if (!addMember(result, e.sym, glbThisType)) return false;
return true;
}
/** Add member `sym' to scope `s'. If`s' has already a member with same name,
* overwrite its info/low bound to form glb of both symbols.
*/
private static boolean addMember(Scope s, Symbol sym, Type glbThisType) {
Type syminfo = sym.info().substThis(sym.owner(), glbThisType);
Type symlb = sym.loBound().substThis(sym.owner(), glbThisType);
Scope.Entry e = s.lookupEntry(sym.name);
if (e == Scope.Entry.NONE) {
Symbol sym1 = sym.cloneSymbol(glbThisType.symbol());
sym1.setInfo(syminfo);
if (sym1.kind == TYPE) sym1.setLoBound(symlb);
s.enter(sym1);
} else {
Type einfo = e.sym.info();
if (einfo.isSameAs(syminfo)) {
} else if (einfo.isSubType(syminfo) && sym.kind != ALIAS) {
} else if (syminfo.isSubType(einfo) && e.sym.kind != ALIAS) {
e.sym.setInfo(syminfo);
} else if (sym.kind == VAL && e.sym.kind == VAL ||
sym.kind == TYPE && e.sym.kind == TYPE) {
e.sym.setInfo(glb(new Type[]{einfo, syminfo}));
} else {
return false;
}
if (e.sym.kind == TYPE && sym.kind == TYPE) {
Type elb = e.sym.loBound();
if (elb.isSameAs(symlb)) {
} else if (symlb.isSubType(elb)) {
} else if (elb.isSubType(symlb)) {
e.sym.setLoBound(symlb);
} else {
e.sym.setLoBound(lub(new Type[]{elb, symlb}));
}
}
}
return true;
}
public static Map erasureMap = new MapOnlyTypes() {
public Type apply(Type t) { return t.erasure(); }
};
private static final Type[] unboxedType =
new Type[LastUnboxedTag + 1 - FirstUnboxedTag];
private static final Type[] unboxedArrayType =
new Type[LastUnboxedTag + 1 - FirstUnboxedTag];
private static final Name[] unboxedName =
new Name[LastUnboxedTag + 1 - FirstUnboxedTag];
private static final Name[] boxedName =
new Name[LastUnboxedTag + 1 - FirstUnboxedTag];
private static final Name[] boxedFullName =
new Name[LastUnboxedTag + 1 - FirstUnboxedTag];
private static void mkStdClassType(int kind, String unboxedstr, String boxedstr) {
unboxedType[kind - FirstUnboxedTag] = UnboxedType(kind);
unboxedArrayType[kind - FirstUnboxedTag] = UnboxedArrayType(unboxedType(kind));
unboxedName[kind - FirstUnboxedTag] = Name.fromString(unboxedstr);
boxedName[kind - FirstUnboxedTag] = Name.fromString(boxedstr);
boxedFullName[kind - FirstUnboxedTag] = Name.fromString("scala." + boxedstr);
}
static {
mkStdClassType(BYTE, "byte", "Byte");
mkStdClassType(SHORT, "short", "Short");
mkStdClassType(CHAR, "char", "Char");
mkStdClassType(INT, "int", "Int");
mkStdClassType(LONG, "long", "Long");
mkStdClassType(FLOAT, "float", "Float");
mkStdClassType(DOUBLE, "double", "Double");
mkStdClassType(BOOLEAN, "boolean", "Boolean");
mkStdClassType(UNIT, "void", "Unit");
}
/** Return unboxed type of given kind.
*/
public static Type unboxedType(int kind) {
return unboxedType[kind - FirstUnboxedTag];
}
/** Return unboxed array type of given element kind.
*/
public static Type unboxedArrayType(int kind) {
return unboxedArrayType[kind - FirstUnboxedTag];
}
/** Return the name of unboxed type of given kind.
*/
public static Name unboxedName(int kind) {
return unboxedName[kind - FirstUnboxedTag];
}
/** Return the name of boxed type of given kind.
*/
public static Name boxedName(int kind) {
return boxedName[kind - FirstUnboxedTag];
}
/** Return the full name of boxed type of given kind.
*/
public static Name boxedFullName(int kind) {
return boxedFullName[kind - FirstUnboxedTag];
}
/** If type is boxed, return its unboxed equivalent; otherwise return the type
* itself.
*/
public Type unbox() {
switch (this) {
case TypeRef(Type pre, Symbol sym, Type[] args):
if ((sym.flags & MODUL) == 0) {
Name fullname = sym.fullName();
if (fullname == Names.scala_Array && args.length == 1) {
Type bound = upperBound(args[0]);
// todo: check with Philippe if this is what we want.
if (bound.symbol() != Global.instance.definitions.ANY_CLASS &&
bound.symbol() != Global.instance.definitions.ANYVAL_CLASS)
{
return UnboxedArrayType(args[0].erasure());
}
}
for (int i = 0; i < boxedFullName.length; i++) {
if (boxedFullName[i] == fullname) return unboxedType[i];
}
}
}
return this;
}
//where
private Type upperBound(Type tp) {
switch (tp) {
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym.kind == ALIAS || sym.kind == TYPE)
return upperBound(pre.memberInfo(sym));
}
return tp;
}
/** Return the erasure of this type.
*/
public Type erasure() {
switch (this) {
case ThisType(_):
case SingleType(_, _):
return singleDeref().erasure();
case TypeRef(Type pre, Symbol sym, Type[] args):
switch (sym.kind) {
case ALIAS: case TYPE:
return pre.memberInfo(sym).erasure();
case CLASS:
if (sym == Global.instance.definitions.UNIT_CLASS) return this;
Name fullname = sym.fullName();
if (fullname == Names.java_lang_Object ||
fullname == Names.scala_AnyRef ||
fullname == Names.scala_AnyVal ||
fullname == Names.scala_All ||
fullname == Names.scala_AllRef)
return Global.instance.definitions.ANY_TYPE;
else {
Type this1 = unbox();
if (this1 != this) return this1;
else return sym.typeConstructor();
}
default: throw new ApplicationError();
}
case CompoundType(Type[] parents, _):
if (parents.length > 0) return parents[0].erasure();
else return this;
case MethodType(Symbol[] params, Type tp):
Symbol[] params1 = erasureMap.map(params);
Type tp1 = tp.fullErasure();
switch (tp1) {
case MethodType(Symbol[] params2, Type tp2):
Symbol[] newparams = new Symbol[params1.length + params2.length];
System.arraycopy(params1, 0, newparams, 0, params1.length);
System.arraycopy(params2, 0, newparams, params1.length, params2.length);
return MethodType(newparams, tp2);
default:
if (params1 == params && tp1 == tp) return this;
else return MethodType(params1, tp1);
}
case PolyType(_, Type result):
return result.erasure();
default:
return erasureMap.map(this);
}
}
/** Return the full erasure of the type. Full erasure is the same
* as "normal" erasure, except that the "Unit" type is erased to
* the "void" type.
*/
public Type fullErasure() {
if (Global.instance.definitions.UNIT_CLASS == symbol())
return unbox();
else
return erasure();
}
public String toString() {
return new SymbolTablePrinter().printType(this).toString();
}
public String toLongString() {
String str = toString();
if (str.endsWith(".type")) return str + " (with underlying type " + widen() + ")";
else return str;
}
public int hashCode() {
switch (this) {
case ErrorType:
return ERROR;
case NoType:
return NOtpe;
case ThisType(Symbol sym):
return THIStpe
^ (sym.hashCode() * 41);
case TypeRef(Type pre, Symbol sym, Type[] args):
return TYPEREFtpe
^ (pre.hashCode() * 41)
^ (sym.hashCode() * (41*41))
^ (hashCode(args) * (41*41*41));
case SingleType(Type pre, Symbol sym):
return SINGLEtpe
^ (pre.hashCode() * 41)
^ (sym.hashCode() * (41*41));
case CompoundType(Type[] parts, Scope members):
return symbol().hashCode();
//return COMPOUNDtpe
// ^ (hashCode(parts) * 41)
// ^ (members.hashCode() * (41 * 41));
case MethodType(Symbol[] vparams, Type result):
int h = METHODtpe;
for (int i = 0; i < vparams.length; i++)
h = (h << 4) ^ (vparams[i].flags & SOURCEFLAGS);
return h
^ (hashCode(Symbol.type(vparams)) * 41)
^ (result.hashCode() * (41 * 41));
case PolyType(Symbol[] tparams, Type result):
return POLYtpe
^ (hashCode(tparams) * 41)
^ (result.hashCode() * (41 * 41));
case OverloadedType(Symbol[] alts, Type[] alttypes):
return OVERLOADEDtpe
^ (hashCode(alts) * 41)
^ (hashCode(alttypes) * (41 * 41));
case UnboxedType(int kind):
return UNBOXEDtpe
^ (kind * 41);
case UnboxedArrayType(Type elemtp):
return UNBOXEDARRAYtpe
^ (elemtp.hashCode() * 41);
default:
throw new ApplicationError();
}
}
public static int hashCode(Object[] elems) {
int h = 0;
for (int i = 0; i < elems.length; i++)
h = h * 41 + elems[i].hashCode();
return h;
}
public static int hashCode(Scope.Entry elems) {
int h = 0;
for (Scope.Entry e = elems; e != Scope.Entry.NONE; e = e.next)
h = h * 41
+ e.sym.kind
+ e.sym.name.hashCode()
+ e.sym.info().hashCode();
return h;
}
// todo: change in relation to needs.
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Type) {
Type that = (Type) other;
switch (this) {
case ErrorType:
return that == ErrorType;
case NoType:
return that == NoType;
case ThisType(Symbol sym):
switch (that) {
case ThisType(Symbol sym1):
return sym == sym1;
default: return false;
}
case TypeRef(Type pre, Symbol sym, Type[] args):
switch (that) {
case TypeRef(Type pre1, Symbol sym1, Type[] args1):
return pre.equals(pre1) && sym == sym1 && equals(args, args1);
default: return false;
}
case SingleType(Type pre, Symbol sym):
switch (that) {
case SingleType(Type pre1, Symbol sym1):
return pre.equals(pre1) && sym == sym1;
default: return false;
}
case CompoundType(Type[] parts, Scope members):
switch (that) {
case CompoundType(Type[] parts1, Scope members1):
return this.symbol() == that.symbol();
//return parts.equals(parts1) && members.equals(members1);
default: return false;
}
case MethodType(Symbol[] vparams, Type result):
switch (that) {
case MethodType(Symbol[] vparams1, Type result1):
if (vparams.length != vparams1.length)
return false;
for (int i = 0; i < vparams.length; i++)
if ((vparams[i].flags & SOURCEFLAGS) !=
(vparams1[i].flags & SOURCEFLAGS))
return false;
return
equals(Symbol.type(vparams), Symbol.type(vparams1)) &&
result.equals(result1);
default: return false;
}
case PolyType(Symbol[] tparams, Type result):
switch (that) {
case PolyType(Symbol[] tparams1, Type result1):
return equals(tparams, tparams1) && result.equals(result1);
default: return false;
}
case OverloadedType(Symbol[] alts, Type[] alttypes):
switch (that) {
case OverloadedType(Symbol[] alts1, Type[] alttypes1):
return equals(alts, alts1) && equals(alttypes, alttypes1);
default: return false;
}
case UnboxedType(int kind):
switch (that) {
case UnboxedType(int kind1):
return kind == kind1;
default: return false;
}
case UnboxedArrayType(Type elemtp):
switch (that) {
case UnboxedArrayType(Type elemtp1):
return elemtp.equals(elemtp1);
default: return false;
}
default:
}
}
return false;
}
public static boolean equals(Object[] elems1, Object[] elems2) {
if (elems1.length != elems2.length) return false;
for (int i = 0; i < elems1.length; i++) {
if (!elems1[i].equals(elems2[i])) return false;
}
return true;
}
/** A class for lists of types.
*/
public static class List {
public Type head;
public List tail;
public List(Type head, List tail) {
this.head = head; this.tail = tail;
}
public int length() {
return (this == EMPTY) ? 0 : 1 + tail.length();
}
public Type[] toArray() {
Type[] ts = new Type[length()];
copyToArray(ts, 0, 1);
return ts;
}
public void copyToArray(Type[] ts, int start, int delta) {
if (this != EMPTY) {
ts[start] = head;
tail.copyToArray(ts, start+delta, delta);
}
}
public Type[] toArrayReverse() {
Type[] ts = new Type[length()];
copyToArray(ts, ts.length - 1, -1);
return ts;
}
public String toString() {
if (this == EMPTY) return "List()";
else return head + "::" + tail;
}
public static List EMPTY = new List(null, null);
public static List append(List l, Type tp) {
return (l == EMPTY) ? new List(tp, EMPTY)
: new List(l.head, append(l.tail, tp));
}
}
/** A class for keeping sub/supertype constraints and instantiations
* of type variables.
*/
public static class Constraint {
public List lobounds = List.EMPTY;
public List hibounds = List.EMPTY;
public Type inst = NoType;
public boolean instantiate(Type tp) {
for (List l = lobounds; l != List.EMPTY; l = l.tail) {
if (!l.head.isSubType(tp)) return false;
}
for (List l = hibounds; l != List.EMPTY; l = l.tail) {
if (!tp.isSubType(l.head)) return false;
}
inst = tp;
return true;
}
}
/** A class for throwing type errors
*/
public static class Error extends java.lang.Error {
public String msg;
public Error(String msg) {
super(msg);
this.msg = msg;
}
}
/** A class for throwing type errors
*/
public static class VarianceError extends Error {
public VarianceError(String msg) {
super(msg);
}
}
public static void explainTypes(Type found, Type required) {
if (Global.instance.explaintypes) {
boolean s = explainSwitch;
explainSwitch = true;
found.isSubType(required);
explainSwitch = s;
}
}
}
/* A standard pattern match:
case ErrorType:
case AnyType:
case NoType:
case ThisType(Symbol sym):
case TypeRef(Type pre, Symbol sym, Type[] args):
case SingleType(Type pre, Symbol sym):
case CompoundType(Type[] parts, Scope members):
case MethodType(Symbol[] vparams, Type result):
case PolyType(Symbol[] tparams, Type result):
case OverloadedType(Symbol[] alts, Type[] alttypes):
*/ |
package com.asxtecnologia.helpme.service;
import java.nio.channels.NotYetConnectedException;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class tracker {
public static Double Latitude=0.00;
public static Double Longitude=0.00;
private static Double lastLatitude=0.00;
private static Double lastLongitude=0.00;
public static Location myLocation;
public static Location newLocation;
private static Boolean paused=false;
public tracker()
{
}
private static final int TWO_MINUTES = 1000 * 60 * 2;
/** Determines whether one Location reading is better than the current Location fix
* @param location The new Location that you want to evaluate
* @param currentBestLocation The current Location fix, to which you want to compare the new one
*/
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
public void IniciarServico( LocationManager lcm )
{
paused = false;
LocationManager locationManager = lcm;
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Atualizar(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, locationListener);
}
public static void Pause()
{
paused = true;
}
public static void Resume()
{
paused = false;
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, locationListener);
}
private void Atualizar(Location location)
{
//if(!paused)
{
newLocation = location;
//Maps.SetMyLocation(location);
}
//Token.SetGeo(, geo)
if(isBetterLocation(newLocation, myLocation))
{
Latitude = location.getLatitude();
Longitude = location.getLongitude();
AtualizaServer();
}
myLocation = location;
}
private void AtualizaServer()
{
if((lastLatitude - Latitude>0.0001 || lastLatitude - Latitude < -0.0001)
|| (lastLongitude - Longitude>0.0001 || lastLongitude - Longitude <-0.0001))
{
//new geoLocationService().execute(Security.Key,Longitude.toString(),Latitude.toString());
lastLatitude = Latitude;
lastLongitude = Longitude;
try{
try {
if(AsxSocket.Socket.isOpen())
{
AsxSocket.Socket.send( "{\"MessageType\":\"GPS\",\"Token\":\""+Token.Token+"\",\"Latitude\":"+ Latitude +",\"Longitude\":"+Longitude+"}");
}
} catch (NotYetConnectedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}finally
{
}
}
}
} |
package edu.pdx.cs410J.chances;
import edu.pdx.cs410J.AbstractAppointmentBook;
import edu.pdx.cs410J.ParserException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
/**
* The main class for the CS410J appointment book Project
*/
public class Project2
{
public static final String USAGE_DOCUMENTATION = "usage: java edu.pdx.cs410J.chances.Project1 [options] <args>\n" +
"\targs are (in this order):\n" +
"\t\towner\t\tThe person whose owns the appt book\n" +
"\t\tdescription\tA description of the appointment\n" +
"\t\tbeginTime\tWhen the appt begins (24-hour time)\n" +
"\t\tendTime\t\tWhen the appt ends (24-hour time)\n" +
"\toptions are (options may appear in any order):\n" +
"\t\t-textFile file\tWhere to read/write the appointment book\n" +
"\t\t-print\t\t\tPrints a description of the new appointment\n" +
"\t\t-README\t\t\tPrints a README for this project and exits\n" +
"\tDate and time should be in the format: mm/dd/yyyy hh:mm";
public static final int EXPECTED_NUM_ARGS = 6;
public static void main(String[] args) {
// Refer to one of Dave's classes so that we can be sure it is on the classpath
Class c = AbstractAppointmentBook.class;
ArrayList<String> argsList = new ArrayList<>(Arrays.asList(args));
// Print the README if flag is present or zero arguments
if (argsList.contains("-README") || argsList.size() == 0) {
System.out.println("Chance Snow - Project 1\n" +
"\tAppointment Book Application\n\n" +
"Create an appointment in a new appointment book.\n");
System.out.print(USAGE_DOCUMENTATION);
System.exit(0);
}
// Handle print option
boolean shouldPrintDescription = argsList.get(0).equals("-print");
if (shouldPrintDescription) {
argsList.remove(0);
}
AppointmentBook book = null;
// Handle file arg option and parse appointment book if necessary
boolean shouldUseFile = argsList.contains("-textFile");
String filePath;
if (shouldUseFile) {
int fileOptionIndex = argsList.indexOf("-textFile");
argsList.remove(fileOptionIndex);
try {
filePath = argsList.get(fileOptionIndex);
TextParser parser = new TextParser(filePath);
book = (AppointmentBook) parser.parse();
argsList.remove(fileOptionIndex);
} catch (IndexOutOfBoundsException | ParserException ex) {
if (ex instanceof ParserException) {
} else {
// The file path option parameter could not be parsed
// Therefore, no file should be written to later on
shouldUseFile = false;
}
}
}
if (book == null) {
book = new AppointmentBook();
}
// Handle too few or extraneous arguments
int argsListSize = argsList.size();
if (argsListSize < EXPECTED_NUM_ARGS) {
System.err.println("Too few command line arguments");
} else if (argsListSize > EXPECTED_NUM_ARGS) {
System.err.println("Too many command line arguments");
}
// Parse appointment args
String owner = argsList.get(0);
String description = argsList.get(1);
String beginTime = String.join(" ", argsList.get(2), argsList.get(3));
String endTime = String.join(" ", argsList.get(4), argsList.get(5));
book.setOwnerName(owner);
DateFormat[] formats = new DateFormat[]{
new SimpleDateFormat("mm/dd/yyyy kk:mm"),
new SimpleDateFormat("mm/dd/yyyy k:mm"),
new SimpleDateFormat("m/dd/yyyy kk:mm"),
new SimpleDateFormat("m/dd/yyyy k:mm"),
new SimpleDateFormat("mm/d/yyyy kk:mm"),
new SimpleDateFormat("mm/d/yyyy k:mm"),
new SimpleDateFormat("m/d/yyyy kk:mm"),
new SimpleDateFormat("m/d/yyyy k:mm")
};
for (DateFormat format : formats) {
format.setLenient(false);
}
Date begin = tryParseDate(formats, beginTime);
Date end = tryParseDate(formats, endTime);
if (begin == null) {
System.err.println("Malformed begin time");
} else if (end == null) {
System.err.println("Malformed end time");
} else {
Appointment appointment = new Appointment(description);
appointment.setBeginTime(begin);
appointment.setEndTime(end);
// Add the successfully parsed appointment to the book
book.addAppointment(appointment);
if (shouldPrintDescription) {
System.out.println(appointment);
}
System.exit(0);
}
// Default to error
System.err.println();
System.err.println(USAGE_DOCUMENTATION);
System.exit(1);
}
/**
* Try to parse a date-time string given an array of DateFormat
*
* @param formats Array of DateFormat objects
* @param dateTime Date-time string to try to parse
* @return Null or successfully parsed Date
*/
static Date tryParseDate(DateFormat[] formats, String dateTime) {
for (DateFormat format : formats) {
Date date = tryParseDate(format, dateTime);
if (date != null) {
return date;
}
}
return null;
}
/**
* Try to parse a date-time string given a DateFormat
*
* @param format DateFormat object
* @param dateTime Date-time string to try to parse
* @return Null or successfully parsed Date
*/
static Date tryParseDate(DateFormat format, String dateTime) {
try {
return format.parse(dateTime);
} catch (ParseException ex) {
return null;
}
}
} |
package org.drools.games;
import javax.swing.*;
import java.awt.*;
public class GameFrame extends JFrame {
private final Object redrawLock = new Object();
public GameFrame() throws HeadlessException {
}
public GameFrame(String title) throws HeadlessException {
super(title);
}
@Override
public void paint(Graphics g) {
// this will iterate the children, calling paintComponent
super.paint(g);
Toolkit.getDefaultToolkit().sync();
}
public void waitForPaint() {
repaint();
}
} |
package amu.zhcetstudent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show());
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
} |
package com.dd7.lurkerhn;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.dd7.lurkerhn.adapter.ClickListener;
import com.dd7.lurkerhn.adapter.StoryCardAdapter;
import com.dd7.lurkerhn.rest.client.RestClientFactory;
import com.dd7.lurkerhn.rest.client.HackerNewsApiClient;
import com.dd7.lurkerhn.rest.model.Item;
import com.dd7.lurkerhn.service.PreferenceService;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends ActionBarActivity {
private static final String[] ACTIVITIES = {"Saved Stories", "Settings"};
private static Map<String, Class> ACTIVITY_CLASSES;
private static int MAX_STORIES = 50;
private String mPreferredCat;
private Context mContext;
private SwipeRefreshLayout mSwipeRefreshLayout;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private HackerNewsApiClient mService;
@Override
protected void onCreate(Bundle savedInstanceState) {
ACTIVITY_CLASSES = new HashMap<>();
ACTIVITY_CLASSES.put(ACTIVITIES[0], SavedStoriesActivity.class);
ACTIVITY_CLASSES.put(ACTIVITIES[1], SettingsActivity.class);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mService = RestClientFactory.createHackerNewsService();
getPreferences();
prepareDrawerList();
final StoryCardAdapter mStoryCardAdapter = prepareRecyclerViewAndGetCardAdapter();
setUpSupportActionBar();
prepareDrawerToggle();
prepareSwipeRefreshLayout(mStoryCardAdapter);
loadTopStories(mStoryCardAdapter, mService);
}
private void prepareSwipeRefreshLayout(StoryCardAdapter storyCardAdapter) {
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(() -> {
loadTopStories(storyCardAdapter, mService);
});
}
private void setUpSupportActionBar() {
mActivityTitle = getTitle().toString();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void getPreferences() {
PreferenceService preferenceService = new PreferenceService(mContext);
MAX_STORIES = preferenceService.getMaxStoriesPref();
mPreferredCat = preferenceService.getCategoryPref();
}
private void prepareDrawerList() {
ListView mDrawerList = (ListView) findViewById(R.id.drawerList);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.item_drawer_list, ACTIVITIES));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private StoryCardAdapter prepareRecyclerViewAndGetCardAdapter() {
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.story_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
final StoryCardAdapter mStoryCardAdapter = new StoryCardAdapter(this);
mStoryCardAdapter.setOnItemClickListener(new ItemClickListener());
mRecyclerView.setAdapter(mStoryCardAdapter);
return mStoryCardAdapter;
}
private void prepareDrawerToggle() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu();
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void loadTopStories(final StoryCardAdapter storyCardAdapter, HackerNewsApiClient service) {
storyCardAdapter.clear();
Observable<List<Integer>> stories;
String[] categories = getResources().getStringArray(R.array.pref_categories);
if (mPreferredCat.isEmpty() || mPreferredCat.equals(categories[0])) {
stories = service.getTopStories();
} else if (mPreferredCat.equals(categories[1])) {
stories = service.getBestStories();
} else if (mPreferredCat.equals(categories[2])) {
stories = service.getNewStories();
} else if (mPreferredCat.equals(categories[3])) {
stories = service.getShowStories();
} else if (mPreferredCat.equals(categories[4])) {
stories = service.getAskStories();
} else {
stories = service.getTopStories();
}
stories.flatMapIterable(ids -> ids)
.take(MAX_STORIES)
.concatMapEager(id -> service.getItem(id))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Item>() {
@Override
public void onCompleted() {
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onError(Throwable e) {
mSwipeRefreshLayout.setRefreshing(false);
Log.e("NETWORKERROR", "Something went wrong" + e.getMessage(), e);
Toast.makeText(mContext, "Something went wrong" + e.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onNext(Item item) {
storyCardAdapter.addData(item);
}
});
}
private class ItemClickListener implements ClickListener {
@Override
public void onItemClick(int position, View v, List<Item> items) {
Item item = items.get(position);
Intent intent = new Intent(mContext, StoryContentActivity.class);
intent.putExtra("item", item);
startActivity(intent);
}
@Override
public void onItemLongClick(int position, View v, List<Item> items) {
Item item = items.get(position);
Intent intent = new Intent(mContext, StoryWebViewActivity.class);
intent.putExtra("item", item);
startActivity(intent);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
Intent intent = new Intent(mContext, Class.forName(ACTIVITY_CLASSES.get(ACTIVITIES[position]).getName()));
startActivity(intent);
} catch (ClassNotFoundException e) {
Toast.makeText(mContext, "Could not find activity " + ACTIVITIES[position], Toast.LENGTH_SHORT).show();
}
}
}
} |
package com.gh4a.job;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import com.evernote.android.job.Job;
import com.evernote.android.job.JobManager;
import com.evernote.android.job.JobRequest;
import com.gh4a.R;
import com.gh4a.activities.home.HomeActivity;
import com.gh4a.loader.NotificationHolder;
import com.gh4a.loader.NotificationListLoader;
import com.gh4a.resolver.BrowseFilter;
import com.gh4a.utils.ApiHelpers;
import com.gh4a.utils.AvatarHandler;
import com.gh4a.utils.UiUtils;
import org.eclipse.egit.github.core.Notification;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.User;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class NotificationsJob extends Job {
private static final String CHANNEL_GITHUB_NOTIFICATIONS = "channel_notifications";
private static final String GROUP_ID_GITHUB = "github_notifications";
private static final int NOTIFICATION_ID_BASE = 10000;
public static final String TAG = "job_notifications";
public static void scheduleJob(int intervalMinutes) {
new JobRequest.Builder(TAG)
.setPeriodic(TimeUnit.MINUTES.toMillis(intervalMinutes),
TimeUnit.MINUTES.toMillis(5))
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setUpdateCurrent(true)
.build()
.schedule();
}
public static void cancelJob() {
JobManager.instance().cancelAllForTag(NotificationsJob.TAG);
}
public static void createNotificationChannels(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationChannel channel = new NotificationChannel(CHANNEL_GITHUB_NOTIFICATIONS,
context.getString(R.string.channel_notifications_name),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(context.getString(R.string.channel_notifications_description));
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
@NonNull
@Override
protected Result onRunJob(Params params) {
try {
List<NotificationHolder> notifications =
NotificationListLoader.loadNotifications(false, false);
// strip out repo items
Iterator<NotificationHolder> iter = notifications.iterator();
while (iter.hasNext()) {
if (iter.next().notification == null) {
iter.remove();
}
}
if (notifications.isEmpty()) {
return Result.SUCCESS;
}
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getContext());
notificationManager.cancelAll();
int accentColor = UiUtils.resolveColor(getContext(), R.attr.colorAccent);
showSummaryNotification(notificationManager, notifications.size(), accentColor);
for (int i = 0; i < notifications.size(); i++) {
showSingleNotification(notificationManager, accentColor,
notifications.get(i).notification, i);
}
} catch (IOException e) {
return Result.FAILURE;
}
return Result.SUCCESS;
}
private void showSingleNotification(NotificationManagerCompat notificationManager,
int accentColor, Notification notification, int index) {
Repository repository = notification.getRepository();
User owner = repository.getOwner();
String title = owner.getLogin() + "/" + repository.getName();
long when = notification.getUpdatedAt() != null
? notification.getUpdatedAt().getTime()
: System.currentTimeMillis();
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext(),
CHANNEL_GITHUB_NOTIFICATIONS)
.setSmallIcon(R.drawable.octodroid)
.setLargeIcon(loadRoundUserAvatar(owner))
.setGroup(GROUP_ID_GITHUB)
.setWhen(when)
.setShowWhen(true)
.setColor(accentColor)
.setContentTitle(title)
.setAutoCancel(true)
.setContentText(notification.getSubject().getTitle());
String url = notification.getSubject().getUrl();
if (url != null) {
Uri uri = ApiHelpers.normalizeUri(Uri.parse(url));
Intent intent = BrowseFilter.makeRedirectionIntent(getContext(), uri, null);
PendingIntent pendingIntent =
PendingIntent.getActivity(getContext(), 0, intent, 0);
builder.setContentIntent(pendingIntent);
}
notificationManager.notify(NOTIFICATION_ID_BASE + index, builder.build());
}
private void showSummaryNotification(NotificationManagerCompat notificationManager,
int numNotifications, int accentColor) {
String title = getContext().getString(R.string.unread_notifications_summary_title);
String text = getContext().getResources()
.getQuantityString(R.plurals.unread_notifications_summary_text, numNotifications,
numNotifications);
PendingIntent contentIntent = PendingIntent.getActivity(getContext(), 0,
HomeActivity.makeIntent(getContext(), R.id.notifications), 0);
notificationManager.notify(NOTIFICATION_ID_BASE, new NotificationCompat.Builder(
getContext(), CHANNEL_GITHUB_NOTIFICATIONS)
.setSmallIcon(R.drawable.octodroid)
.setGroup(GROUP_ID_GITHUB)
.setGroupSummary(true)
.setColor(accentColor)
.setContentIntent(contentIntent)
.setContentTitle(title)
.setContentText(text)
.setNumber(numNotifications)
.build());
}
private Bitmap loadRoundUserAvatar(User user) {
Bitmap avatar = AvatarHandler.loadUserAvatarSynchronously(getContext(), user);
if (avatar == null) {
return null;
}
final Bitmap output = Bitmap.createBitmap(avatar.getWidth(), avatar.getHeight(),
Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, avatar.getWidth(), avatar.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.BLACK);
canvas.drawOval(new RectF(rect), paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(avatar, rect, rect, paint);
return output;
}
} |
package com.t28.rxweather.model;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
public class Photo extends Model {
private static final String FORMAT_IMAGE_URL = "https://farm%d.staticflickr.com/%d/%d_%s_%s.jpg";
private static final String FORMAT_PHOTO_URL = "https:
private final int mId;
private final int mFarmId;
private final int mServerId;
private final String mUserId;
private final String mSecret;
private Photo(Builder builder) {
mId = builder.mId;
mFarmId = builder.mFarmId;
mServerId = builder.mServerId;
mUserId = builder.mUserId;
mSecret = builder.mSecret;
}
@Override
public boolean isValid() {
if (mId < 0) {
return false;
}
if (mFarmId < 0) {
return false;
}
if (mServerId < 0) {
return false;
}
if (TextUtils.isEmpty(mUserId)) {
return false;
}
if (TextUtils.isEmpty(mSecret)) {
return false;
}
return true;
}
public int getId() {
return mId;
}
public int getFarmId() {
return mFarmId;
}
public int getServerId() {
return mServerId;
}
public String getUserId() {
return mUserId;
}
public String getSecret() {
return mSecret;
}
public Uri toImageUri(@NonNull PhotoSize size) {
final String urlString = String.format(
FORMAT_IMAGE_URL, mFarmId, mServerId, mId, mSecret, size.toSuffix()
);
return Uri.parse(urlString);
}
public Uri toPhotoUri() {
final String urlString = String.format(
FORMAT_PHOTO_URL, mUserId, mId
);
return Uri.parse(urlString);
}
public static class Builder {
private int mId;
private int mFarmId;
private int mServerId;
private String mUserId;
private String mSecret;
public Builder() {
}
public Builder setId(int id) {
mId = id;
return this;
}
public Builder setFarmId(int id) {
mFarmId = id;
return this;
}
public Builder setServerId(int id) {
mServerId = id;
return this;
}
public Builder setUserId(String id) {
mUserId = id;
return this;
}
public Builder setSecret(String secret) {
mSecret = secret;
return this;
}
public Photo build() {
return new Photo(this);
}
}
} |
package edhyah.com.qbot;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import java.util.List;
import hanqis.com.qbot.Sample_algorithm;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
public class MobotActivity extends IOIOActivity implements CameraBridgeViewBase.CvCameraViewListener2,
MobotLooper.MobotDriver {
private static final String TAG = "MobotActivity";
private static final int LINE_THICKNESS = 5;
private static final int POINT_THICKNESS = 2;
private static final int LEFT = 1;
private static final int RIGHT = 0;
private static final int DEFUALT_ANGLE_PICK = 0;
private static final int ANGLE_SHARP = 25;
private SharedPreferences mSharedPref;
private PortraitCameraView mOpenCvCameraView;
private boolean mStatusConnected;
private MobotLooper mobotLooper;
private Sample_algorithm mAlgorithm = new Sample_algorithm();
private ParameterFiltering mFilt;
private TurnDetector mTurnDetector = new TurnDetector();
private HillDetection mHillDetect;
private double[] mAngles = new double[2];
private double mAngleFinal = 0.0;
private int mTurnRight = 0;
private boolean mMadeDecision = false;
private boolean mLineIgnore = false;
private double mTunning = 0;
private double mSpeed = 0;
private double mMaxSpeed = MobotLooper.MAX_SPEED;
private ParameterBar mTestBar;
/* need to be in [0,3) */
private double mThreshold = 0.5;
private int mSamplingPoints = 2000;
private int mStdThreshold = 25;
private int mDimension = 2;
private int mCounter1 = 0;
private int mCounter2 = 0;
private int mSplitTimeCounter = 0;
private int mSplitThreshold = 2;
private int mTimeDelay = 3;
private int mPrevChoice = LEFT;
private int[] TURNS_2_LEFT = new int[]{LEFT,RIGHT,LEFT,LEFT,RIGHT,RIGHT,LEFT,LEFT,RIGHT,RIGHT,LEFT,LEFT};
private int[] TURNS_2_RIGHT = new int[]{RIGHT,LEFT,RIGHT,RIGHT,LEFT,LEFT,RIGHT,RIGHT,LEFT,LEFT,RIGHT,RIGHT};
private int[] TURNS_2015_COURSE = new int[]{RIGHT, LEFT, RIGHT, RIGHT, LEFT, LEFT, RIGHT, RIGHT, LEFT, RIGHT};
private int[] mFinalTurns;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
@Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_mobot);
// OpenCV
mOpenCvCameraView = (PortraitCameraView) findViewById(R.id.video_surface);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
addSpeedBar();
mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
mThreshold = mSharedPref.getFloat(MainActivity.PREF_THRESHOLD, -1);
Log.i(TAG, "Thresh " + mThreshold);
mFilt = new ParameterFiltering(getP(), getI(), getD());
mStdThreshold = (int) mSharedPref.getFloat(MainActivity.PREF_STD_THRESHOLD,50);
mDimension = (int) mSharedPref.getFloat(MainActivity.PREF_DIMENSION, 2);
int turningPatternChoice = (int) mSharedPref.getFloat(MainActivity.PREF_TUNNING,0);
mFinalTurns = TURNS_2015_COURSE;//(turningPatternChoice == 1) ? TURNS_2_RIGHT : TURNS_2_LEFT;
mTurnRight = (int) mSharedPref.getFloat(MainActivity.PREF_TURN_DIRECTION,0);
mSplitThreshold = (int) mSharedPref.getFloat(MainActivity.PREF_STD_SPLITTH,2);
// Hill Detection
float hillThresh = mSharedPref.getFloat(MainActivity.PREF_HILL_THRESH,0);
mHillDetect = new HillDetection(this, hillThresh);
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
protected IOIOLooper createIOIOLooper() {
Log.i(TAG, "Created Looper");
mobotLooper = new MobotLooper(this,this);
return mobotLooper;
}
public void onCameraViewStarted(int width, int height) {
}
public void onCameraViewStopped() {
}
@Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Mat img = inputFrame.rgba();
double[] angles = mAlgorithm.Sampling(img,mDimension,mThreshold,mSamplingPoints,mStdThreshold);
boolean split = mAlgorithm.getSplit();
int numHills = mHillDetect.getNumHillsPassed();
boolean onHill = mHillDetect.isOnHill();
// Update turn with prev angle
TurnDetector.Turn turn = mTurnDetector.updateTurn(mAngleFinal);
int lineChoice = pickAngle(split, numHills, turn,angles);
double finalAngle = angles[lineChoice];
// On hill decision
if (onHill) {
finalAngle = mFilt.onHillFilter(finalAngle);
} else if (numHills == 0) {
// Slow drive angle in first part too
finalAngle = mFilt.beginningFilter(finalAngle);
}
// Filtering
finalAngle = mFilt.filter(finalAngle);
// Update UI
updateAngle(finalAngle);
updateAlgParams(mAlgorithm.getResStd(), numHills, split, turn, onHill);
addSelectedPoints(img, split, lineChoice);
addFoundLines(img, finalAngle, angles, split, lineChoice);
// Save
mAngleFinal = finalAngle;
mAngles = angles;
return img;
}
private int pickAngle(boolean split, int numHills, TurnDetector.Turn turn,double[] angles) {
//mSplitTimeCounter needs to be at least 2 for the two lines to become available
if (split) {
mSplitTimeCounter++;
} else {
//Reset mSplitTimeCounter when there is no two lines appear.
mSplitTimeCounter = 0;
//And be ready for the next turn.
//if (!split && numHills == 2) mCounter2++;
//if (!split && numHills == 1) mCounter1++;
}
boolean splitAtHill1 = split && numHills == 1 && mSplitTimeCounter >= mSplitThreshold;
boolean splitAtHill2 = split && numHills == 2 && mSplitTimeCounter >= mSplitThreshold;
int lineChoice = DEFUALT_ANGLE_PICK;
if (splitAtHill2 /*&& (mCounter2 < mFinalTurns.length)*/) {
mCounter2 = (mCounter2++) % mTimeDelay;
// Splits after hill 2, choice section
//lineChoice = mFinalTurns[mCounter2];
if (Math.abs(angles[LEFT]) <= 2 * TurnDetector.ANGLE_EPSILON &&
Math.abs(angles[RIGHT]) >= ANGLE_SHARP && mCounter2 == 0) {
lineChoice = RIGHT;
} else if (Math.abs(angles[RIGHT]) <= 2 * TurnDetector.ANGLE_EPSILON &&
Math.abs(angles[LEFT]) >= ANGLE_SHARP && mCounter2 == 0) {
lineChoice = LEFT;
} else if (mCounter2 != 0) {
lineChoice = mPrevChoice;
} else {
lineChoice = 1 - mPrevChoice;
}
mPrevChoice = lineChoice;
} else if (splitAtHill1) {
// Splits after hill 1 for error correction
if (turn == TurnDetector.Turn.LEFT)
lineChoice = LEFT;
else if (turn == TurnDetector.Turn.RIGHT) {
lineChoice = RIGHT;
}
}
return lineChoice;
}
private void addFoundLines(Mat img, double angleFinal, double[] anglesFound, boolean split,
int lineChoice) {
int height = img.height();
int width = img.width();
Point centerPt = new Point(width / 2, height);
Point p0 = getEndPoint(angleFinal,width, height, height);
Point p1 = getEndPoint(anglesFound[0],width, height, height/3);
Point p2 = getEndPoint(anglesFound[1],width, height, height/3);
int red = Color.RED;
int blue = Color.CYAN;
int green = Color.GREEN;
// Display green is choice line
if (lineChoice == RIGHT) {
Core.line(img, centerPt, p1, new Scalar(Color.red(green), Color.blue(green), Color.green(green)), LINE_THICKNESS);
Core.line(img, centerPt, p2, new Scalar(Color.red(blue), Color.blue(blue), Color.green(blue)), LINE_THICKNESS);
} else {
Core.line(img, centerPt, p2, new Scalar(Color.red(green), Color.blue(green), Color.green(green)), LINE_THICKNESS);
Core.line(img, centerPt, p1, new Scalar(Color.red(blue), Color.blue(blue), Color.green(blue)), LINE_THICKNESS);
}
// Display filtered angle line
Core.line(img, centerPt, p0, new Scalar(Color.red(red), Color.blue(red), Color.green(red)), LINE_THICKNESS);
}
private Point getEndPoint(double angle, int w, int h, int len) {
return new Point(w / 2 + len * Math.sin(Math.toRadians(angle)),
h - len*Math.cos(Math.toRadians(angle)));
}
private void addSelectedPoints(Mat img, boolean split, int lineChoice){
int green = Color.GREEN;
int yellow = Color.YELLOW;
Scalar sGreen = new Scalar(Color.red(green),Color.green(green),Color.blue(green));
Scalar sYellow = new Scalar(Color.red(yellow),Color.green(yellow),Color.blue(yellow));
if (!split) {
List<Point> pts = mAlgorithm.getSelectedPoints().get(0);
for (int i = 0;i < pts.size();i++){
Core.circle(img,pts.get(i),2,sYellow,POINT_THICKNESS);
}
} else {
List<Point> ptsA = mAlgorithm.getSelectedPoints().get(0);
List<Point> ptsB = mAlgorithm.getSelectedPoints().get(1);
if (lineChoice == RIGHT) {
for (int i = 0; i < ptsA.size(); i++) {
Core.circle(img, ptsA.get(i), 2, sYellow, POINT_THICKNESS);
}
for (int i = 0; i < ptsB.size(); i++) {
Core.circle(img, ptsB.get(i), 2, sGreen, POINT_THICKNESS);
}
} else {
for (int i = 0; i < ptsA.size(); i++) {
Core.circle(img, ptsA.get(i), 2, sGreen, POINT_THICKNESS);
}
for (int i = 0; i < ptsB.size(); i++) {
Core.circle(img, ptsB.get(i), 2, sYellow, POINT_THICKNESS);
}
}
}
}
private void addSpeedBar() {
SeekBar speedBar = (SeekBar) findViewById(R.id.speed_bar);
mSpeed = updateSpeed(speedBar.getProgress(), speedBar.getMax());
speedBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mSpeed = updateSpeed(seekBar.getProgress(), seekBar.getMax());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mSpeed = updateSpeed(seekBar.getProgress(), seekBar.getMax());
}
});
}
private double updateSpeed(int val, int maxVal) {
final double speed = 1.0 * val / maxVal;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView msg = (TextView) findViewById(R.id.speed_val);
msg.setText(String.format("%.2f", speed));
}
});
return speed;
}
@Override
public double getDriveAngle() {
return mAngleFinal;
}
@Override
public double getDriveSpeed() {
return mSpeed;
}
@Override
public double getTunning() { return mSharedPref.getFloat(MainActivity.PREF_TUNNING, 0); }
@Override
public double getMaxSpeed() { return mSharedPref.getFloat(MainActivity.PREF_MAX_SPEED, 0); }
public double getP() { return mSharedPref.getFloat(MainActivity.PREF_PID_P, 0); }
public double getI() { return mSharedPref.getFloat(MainActivity.PREF_PID_I, 0); }
public double getD() { return mSharedPref.getFloat(MainActivity.PREF_PID_D, 0); }
@Override
public void setStatusOnline(boolean status) {
mStatusConnected = status;
if (status) {
updateMsg(getString(R.string.connected_msg));
} else {
updateMsg(getString(R.string.not_connected_msg));
}
}
private void updateAngle(final Double a){
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView angle = (TextView) findViewById(R.id.angle_test);
angle.setText(String.format("Angle: %.2f", a));
}
});
}
private void updateAlgParams(final double st, final int hills, final boolean split,
final TurnDetector.Turn turn, final boolean onHill){
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView angle = (TextView) findViewById(R.id.std_test);
angle.setText(String.format("Std:%.0f Hills:%d(%s) Split:%s Turn:%s",st,hills,
bool2Str(onHill),bool2Str(split),turn));
}
});
}
private String bool2Str(boolean b) {
return b ? "T" : "F";
}
private void updateMsg(final String m) {
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView msg = (TextView) findViewById(R.id.mobot_messages);
msg.setText(m);
}
});
}
} |
package org.wikipedia.util;
import android.os.Build;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.TypefaceSpan;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import org.json.JSONArray;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Collator;
import java.text.Normalizer;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public final class StringUtil {
private static final String CSV_DELIMITER = ",";
@NonNull
public static String listToCsv(@NonNull List<String> list) {
return TextUtils.join(CSV_DELIMITER, list);
}
/** @return Nonnull immutable list. */
@NonNull
public static List<String> csvToList(@NonNull String csv) {
return delimiterStringToList(csv, CSV_DELIMITER);
}
/** @return Nonnull immutable list. */
@NonNull
public static List<String> delimiterStringToList(@NonNull String delimitedString,
@NonNull String delimiter) {
return Arrays.asList(TextUtils.split(delimitedString, delimiter));
}
/**
* Creates an MD5 hash of the provided string and returns its ASCII representation
* @param s String to hash
* @return ASCII MD5 representation of the string passed in
*/
@NonNull public static String md5string(@NonNull String s) {
StringBuilder hexStr = new StringBuilder();
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes(StandardCharsets.UTF_8));
byte[] messageDigest = digest.digest();
final int maxByteVal = 0xFF;
for (byte b : messageDigest) {
hexStr.append(Integer.toHexString(maxByteVal & b));
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return hexStr.toString();
}
/**
* Remove leading and trailing whitespace from a CharSequence. This is useful after using
* the fromHtml() function to convert HTML to a CharSequence.
* @param str CharSequence to be trimmed.
* @return The trimmed CharSequence.
*/
@NonNull public static CharSequence strip(@Nullable CharSequence str) {
if (str == null || str.length() == 0) {
return "";
}
int len = str.length();
int start = 0;
int end = len - 1;
while (start < len && Character.isWhitespace(str.charAt(start))) {
start++;
}
while (end > 0 && Character.isWhitespace(str.charAt(end))) {
end
}
if (end > start) {
return str.subSequence(start, end + 1);
}
return "";
}
@NonNull
public static String intToHexStr(int i) {
return String.format("x%08x", i);
}
public static String addUnderscores(@NonNull String text) {
return text.replace(" ", "_");
}
public static String removeUnderscores(@NonNull String text) {
return text.replace("_", " ");
}
public static boolean hasSectionAnchor(@NonNull String text) {
return text.contains("
}
public static String removeSectionAnchor(String text) {
return text.substring(0, text.indexOf("
}
public static String removeNamespace(@NonNull String text) {
if (text.length() > text.indexOf(":")) {
return text.substring(text.indexOf(":") + 1);
} else {
return text;
}
}
public static String removeHTMLTags(@NonNull String text) {
return fromHtml(text).toString();
}
public static String sanitizeText(@NonNull String selectedText) {
return selectedText.replaceAll("\\[\\d+\\]", "")
.replaceAll("\\s*/[^/]+/;?\\s*", "")
.replaceAll("\\(\\s*;\\s*", "\\(") // (; -> ( hacky way for IPA remnants
.replaceAll("\\s{2,}", " ")
.trim();
}
// Compare two strings based on their normalized form, using the Unicode Normalization Form C.
// This should be used when comparing or verifying strings that will be exchanged between
// different platforms (iOS, desktop, etc) that may encode strings using inconsistent
// composition, especially for accents, diacritics, etc.
public static boolean normalizedEquals(@Nullable String str1, @Nullable String str2) {
if (str1 == null || str2 == null) {
return (str1 == null && str2 == null);
}
return Normalizer.normalize(str1, Normalizer.Form.NFC)
.equals(Normalizer.normalize(str2, Normalizer.Form.NFC));
}
/**
* @param source String that may contain HTML tags.
* @return returned Spanned string that may contain spans parsed from the HTML source.
*/
@NonNull public static Spanned fromHtml(@Nullable String source) {
if (source == null) {
return new SpannedString("");
}
if (!source.contains("<") && !source.contains("&")) {
// If the string doesn't contain any hints of HTML entities, then skip the expensive
// processing that fromHtml() performs.
return new SpannedString(source);
}
source = source.replaceAll("‎", "\u200E")
.replaceAll("‏", "\u200F")
.replaceAll("&", "&");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY);
} else {
//noinspection deprecation
return Html.fromHtml(source);
}
}
@NonNull
public static SpannableStringBuilder boldenSubstrings(@NonNull String text, @NonNull List<String> subStrings) {
SpannableStringBuilder sb = new SpannableStringBuilder(text);
String textLowerCase = text.toLowerCase();
for (String subString : subStrings) {
int index = textLowerCase.indexOf(subString.toLowerCase());
if (index != -1 && index + subString.length() < sb.length()) {
sb.setSpan(new TypefaceSpan("sans-serif-medium"),
index, index + subString.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
}
return sb;
}
public static void highlightEditText(@NonNull EditText editText, @NonNull String parentText, @NonNull String highlightText) {
String[] words = highlightText.split("\\s+");
int pos = 0;
for (String word : words) {
pos = parentText.indexOf(word, pos);
if (pos == -1) {
break;
}
}
if (pos == -1) {
pos = parentText.indexOf(words[words.length - 1]);
}
if (pos >= 0) {
// TODO: Programmatic selection doesn't seem to work with RTL content...
editText.setSelection(pos, pos + words[words.length - 1].length());
editText.performLongClick();
}
}
public static void boldenKeywordText(@NonNull TextView textView, @NonNull String parentText, @Nullable String searchQuery) {
int startIndex = indexOf(parentText, searchQuery);
if (startIndex >= 0) {
parentText = parentText.substring(0, startIndex)
+ "<strong>"
+ parentText.substring(startIndex, startIndex + searchQuery.length())
+ "</strong>"
+ parentText.substring(startIndex + searchQuery.length());
textView.setText(StringUtil.fromHtml(parentText));
} else {
textView.setText(parentText);
}
}
// case insensitive indexOf, also more lenient with similar chars, like chars with accents
private static int indexOf(@NonNull String original, @Nullable String search) {
if (!TextUtils.isEmpty(search)) {
Collator collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
for (int i = 0; i <= original.length() - search.length(); i++) {
if (collator.equals(search, original.substring(i, i + search.length()))) {
return i;
}
}
}
return -1;
}
@NonNull
public static String getBase26String(@IntRange(from = 1) int number) {
final int base = 26;
String str = "";
while (--number >= 0) {
str = (char)('A' + number % base) + str;
number /= base;
}
return str;
}
@NonNull
public static String listToJsonArrayString(@NonNull List<String> list) {
return new JSONArray(list).toString();
}
public static String stringToListMapToJSONString(@Nullable Map<String, List<Integer>> map) {
return new Gson().toJson(map);
}
public static String listToJSONString(@Nullable List<Integer> list) {
return new Gson().toJson(list);
}
private StringUtil() {
}
} |
package org.commcare.android.tasks;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.http.AndroidHttpClient;
import android.util.Log;
import net.sqlcipher.database.SQLiteDatabase;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.conn.ConnectTimeoutException;
import org.commcare.android.crypt.CryptUtil;
import org.commcare.android.database.SqlStorage;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.database.user.models.ACase;
import org.commcare.android.database.user.models.User;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.net.HttpRequestGenerator;
import org.commcare.android.tasks.templates.CommCareTask;
import org.commcare.android.util.AndroidStreamUtil;
import org.commcare.android.util.AndroidStreamUtil.StreamReadObserver;
import org.commcare.android.util.CommCareUtil;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.util.bitcache.BitCache;
import org.commcare.android.util.bitcache.BitCacheFactory;
import org.commcare.cases.ledger.Ledger;
import org.commcare.cases.ledger.LedgerPurgeFilter;
import org.commcare.cases.util.CasePurgeFilter;
import org.commcare.dalvik.application.CommCareApp;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns;
import org.commcare.dalvik.services.CommCareSessionService;
import org.commcare.data.xml.DataModelPullParser;
import org.commcare.resources.model.CommCareOTARestoreListener;
import org.commcare.xml.CommCareTransactionParserFactory;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.AbstractTreeElement;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.storage.IStorageIterator;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.model.xform.XPathReference;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.crypto.SecretKey;
/**
* @author ctsims
*/
public abstract class DataPullTask<R> extends CommCareTask<Void, Integer, Integer, R> implements CommCareOTARestoreListener {
private final String server;
private final String username;
private final String password;
private final Context c;
private int mCurrentProgress = -1;
private int mTotalItems = -1;
private long mSyncStartTime;
private boolean wasKeyLoggedIn = false;
public static final int DATA_PULL_TASK_ID = 10;
public static final int DOWNLOAD_SUCCESS = 0;
public static final int AUTH_FAILED = 1;
public static final int BAD_DATA = 2;
public static final int UNKNOWN_FAILURE = 4;
public static final int UNREACHABLE_HOST = 8;
public static final int CONNECTION_TIMEOUT = 16;
public static final int SERVER_ERROR = 32;
public static final int PROGRESS_STARTED = 0;
public static final int PROGRESS_CLEANED = 1;
public static final int PROGRESS_AUTHED = 2;
private static final int PROGRESS_DONE= 4;
public static final int PROGRESS_RECOVERY_NEEDED= 8;
public static final int PROGRESS_RECOVERY_STARTED= 16;
private static final int PROGRESS_RECOVERY_FAIL_SAFE = 32;
private static final int PROGRESS_RECOVERY_FAIL_BAD = 64;
public static final int PROGRESS_PROCESSING = 128;
public static final int PROGRESS_DOWNLOADING = 256;
/**
* Whether to enable loading this data from a local asset for
* debug/testing.
*
* This flag should never be set to true on a prod build or in VC
* TODO: It should be an error for "debuggable" to be off and this flag
* to be true
*/
private static final boolean DEBUG_LOAD_FROM_LOCAL = false;
private InputStream mDebugStream;
public DataPullTask(String username, String password, String server, Context c) {
this.server = server;
this.username = username;
this.password = password;
this.c = c;
this.taskId = DATA_PULL_TASK_ID;
TAG = DataPullTask.class.getSimpleName();
}
@Override
protected void onCancelled() {
super.onCancelled();
if(wasKeyLoggedIn) {
CommCareApplication._().releaseUserResourcesAndServices();
}
}
@Override
protected Integer doTaskBackground(Void... params) {
// Don't try to sync if logging out is occuring
if (!CommCareSessionService.sessionAliveLock.tryLock()) {
// TODO PLM: once this task is refactored into manageable
// components, it should use the ManagedAsyncTask pattern of
// checking for isCancelled() and aborting at safe places.
return UNKNOWN_FAILURE;
}
// Wrap in a 'try' to enable a 'finally' close that releases the
// sessionAliveLock.
try {
publishProgress(PROGRESS_STARTED);
CommCareApp app = CommCareApplication._().getCurrentApp();
SharedPreferences prefs = app.getAppPreferences();
String keyServer = prefs.getString("key_server", null);
mTotalItems = -1;
mCurrentProgress = -1;
//Whether or not we should be generating the first key
boolean useExternalKeys = !(keyServer == null || keyServer.equals(""));
boolean loginNeeded = true;
boolean useRequestFlags = false;
try {
loginNeeded = !CommCareApplication._().getSession().isActive();
} catch(SessionUnavailableException sue) {
//expected if we aren't initialized.
}
int responseError = UNKNOWN_FAILURE;
//This should be per _user_, not per app
prefs.edit().putLong("last-ota-restore", new Date().getTime()).commit();
HttpRequestGenerator requestor = new HttpRequestGenerator(username, password);
CommCareTransactionParserFactory factory = new CommCareTransactionParserFactory(c, requestor) {
boolean publishedAuth = false;
@Override
public void reportProgress(int progress) {
if(!publishedAuth) {
DataPullTask.this.publishProgress(PROGRESS_AUTHED,progress);
publishedAuth = true;
}
}
};
Logger.log(AndroidLogger.TYPE_USER, "Starting Sync");
long bytesRead = -1;
UserKeyRecord ukr = null;
try {
//This is a dangerous way to do this (the null settings), should revisit later
if(loginNeeded) {
if(!useExternalKeys) {
//Get the key
SecretKey newKey = CryptUtil.generateSemiRandomKey();
if(newKey == null) {
this.publishProgress(PROGRESS_DONE);
return UNKNOWN_FAILURE;
}
String sandboxId = PropertyUtils.genUUID().replace("-", "");
ukr = new UserKeyRecord(username, UserKeyRecord.generatePwdHash(password), CryptUtil.wrapKey(newKey.getEncoded(),password), new Date(), new Date(Long.MAX_VALUE), sandboxId);
} else {
ukr = ManageKeyRecordTask.getCurrentValidRecord(app, username, password, true);
if(ukr == null) {
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Shouldn't be able to not have a valid key record when OTA restoring with a key server");
this.publishProgress(PROGRESS_DONE);
return UNKNOWN_FAILURE;
}
}
//add to transaction parser factory
byte[] wrappedKey = CryptUtil.wrapKey(ukr.getEncryptedKey(),password);
factory.initUserParser(wrappedKey);
} else {
factory.initUserParser(CommCareApplication._().getSession().getLoggedInUser().getWrappedKey());
//Only purge cases if we already had a logged in user. Otherwise we probably can't read the DB.
purgeCases();
useRequestFlags = true;
}
//Either way, don't re-do this step
this.publishProgress(PROGRESS_CLEANED);
int responseCode = -1;
HttpResponse response = null;
//This isn't awesome, but it's hard to work this in in a cleaner way
if(DEBUG_LOAD_FROM_LOCAL) {
try {
mDebugStream = ReferenceManager._().DeriveReference("jr://asset/payload.xml").getStream();
} catch(InvalidReferenceException ire) {
throw new IOException("No payload available at jr://asset/payload.xml");
}
responseCode = 200;
} else {
response = requestor.makeCaseFetchRequest(server, useRequestFlags);
responseCode = response.getStatusLine().getStatusCode();
}
Logger.log(AndroidLogger.TYPE_USER, "Request opened. Response code: " + responseCode);
if(responseCode == 401) {
//If we logged in, we need to drop those credentials
if(loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
Logger.log(AndroidLogger.TYPE_USER, "Bad Auth Request for user!|" + username);
return AUTH_FAILED;
} else if(responseCode >= 200 && responseCode < 300) {
if(loginNeeded) {
//This is necessary (currently) to make sure that data
//is encoded. Probably a better way to do this.
CommCareApplication._().startUserSession(CryptUtil.unWrapKey(ukr.getEncryptedKey(), password), ukr);
wasKeyLoggedIn = true;
}
this.publishProgress(PROGRESS_AUTHED,0);
Logger.log(AndroidLogger.TYPE_USER, "Remote Auth Successful|" + username);
try {
BitCache cache = writeResponseToCache(response);
InputStream cacheIn = cache.retrieveCache();
String syncToken = readInput(cacheIn, factory);
updateUserSyncToken(syncToken);
//record when we last synced
Editor e = prefs.edit();
e.putLong("last-succesful-sync", new Date().getTime());
e.commit();
if(loginNeeded) {
CommCareApplication._().getAppStorage(UserKeyRecord.class).write(ukr);
}
//Let anyone who is listening know!
Intent i = new Intent("org.commcare.dalvik.api.action.data.update");
this.c.sendBroadcast(i);
Logger.log(AndroidLogger.TYPE_USER, "User Sync Successful|" + username);
this.publishProgress(PROGRESS_DONE);
return DOWNLOAD_SUCCESS;
} catch (InvalidStructureException e) {
e.printStackTrace();
//TODO: Dump more details!!!
Logger.log(AndroidLogger.TYPE_USER, "User Sync failed due to bad payload|" + e.getMessage());
return BAD_DATA;
} catch (XmlPullParserException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_USER, "User Sync failed due to bad payload|" + e.getMessage());
return BAD_DATA;
} catch (UnfullfilledRequirementsException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "User sync failed oddly, unfulfilled reqs |" + e.getMessage());
} catch (IllegalStateException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "User sync failed oddly, ISE |" + e.getMessage());
} catch (StorageFullException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Storage Full during user sync |" + e.getMessage());
}
} else if(responseCode == 412) {
//Our local state is bad. We need to do a full restore.
int returnCode = recover(requestor, factory);
if(returnCode == PROGRESS_DONE) {
//All set! Awesome recovery
this.publishProgress(PROGRESS_DONE);
return DOWNLOAD_SUCCESS;
}
else if(returnCode == PROGRESS_RECOVERY_FAIL_SAFE) {
//Things didn't go super well, but they might next time!
//wipe our login if one happened
if(loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
this.publishProgress(PROGRESS_DONE);
return UNKNOWN_FAILURE;
} else if(returnCode == PROGRESS_RECOVERY_FAIL_BAD) {
//WELL! That wasn't so good. TODO: Is there anything
//we can do about this?
//wipe our login if one happened
if(loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
this.publishProgress(PROGRESS_DONE);
return UNKNOWN_FAILURE;
}
if(loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
} else if(responseCode == 500) {
if(loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
Logger.log(AndroidLogger.TYPE_USER, "500 Server Error|" + username);
return SERVER_ERROR;
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Timed out listening to receive data during sync");
responseError = CONNECTION_TIMEOUT;
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Timed out listening to receive data during sync");
responseError = CONNECTION_TIMEOUT;
} catch (ClientProtocolException e) {
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Couldn't sync due network error|" + e.getMessage());
} catch (UnknownHostException e) {
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Couldn't sync due to bad network");
responseError = UNREACHABLE_HOST;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Couldn't sync due to IO Error|" + e.getMessage());
} catch (SessionUnavailableException sue) {
// TODO PLM: eventually take out this catch. These should be
// checked locally
//TODO: Keys were lost somehow.
sue.printStackTrace();
}
if(loginNeeded) {
CommCareApplication._().releaseUserResourcesAndServices();
}
this.publishProgress(PROGRESS_DONE);
return responseError;
} finally {
CommCareSessionService.sessionAliveLock.unlock();
}
}
/**
* Retrieves the HttpResponse stream and writes it to an initialized safe
* local cache. Notifies listeners of progress through the download if its
* size is available.
*
* @throws IOException If there is an issue reading or writing the response.
*/
private BitCache writeResponseToCache(HttpResponse response) throws IOException {
BitCache cache = null;
try {
final long dataSizeGuess = guessDataSize(response);
cache = BitCacheFactory.getCache(c, dataSizeGuess);
cache.initializeCache();
OutputStream cacheOut = cache.getCacheStream();
InputStream input;
if(DEBUG_LOAD_FROM_LOCAL) {
input = this.mDebugStream;
} else {
input = AndroidHttpClient.getUngzippedContent(response.getEntity());
}
Log.i("commcare-network", "Starting network read, expected content size: " + dataSizeGuess + "b");
AndroidStreamUtil.writeFromInputToOutput(new BufferedInputStream(input), cacheOut, new StreamReadObserver() {
long lastOutput = 0;
/** The notification threshold. **/
static final int PERCENT_INCREASE_THRESHOLD = 4;
@Override
public void notifyCurrentCount(long bytesRead) {
boolean notify = false;
//We always wanna notify when we get our first bytes
if(lastOutput == 0) {
Log.i("commcare-network", "First" + bytesRead + " bytes received from network: ");
notify = true;
}
//After, if we don't know how much data to expect, we can't do
//anything useful
if(dataSizeGuess == -1) {
//set this so the first notification up there doesn't keep firing
lastOutput = bytesRead;
return;
}
int percentIncrease = (int)(((bytesRead - lastOutput) * 100) / dataSizeGuess);
//Now see if we're over the reporting threshold
//TODO: Is this actually necessary? In theory this shouldn't
//matter due to android task polling magic?
notify = percentIncrease > PERCENT_INCREASE_THRESHOLD;
if(notify) {
lastOutput = bytesRead;
int totalRead = (int)(((bytesRead) * 100) / dataSizeGuess);
publishProgress(PROGRESS_DOWNLOADING, totalRead);
}
}
});
return cache;
//If something goes wrong while we're reading into the cache
//we may need to free the storage we reserved.
} catch (IOException e) {
if(cache != null) {
cache.release();
}
throw e;
}
}
/**
* Get an estimation of how large the provided response is.
* @return -1 for unknown.
*/
private long guessDataSize(HttpResponse response) {
if(DEBUG_LOAD_FROM_LOCAL) {
try {
//Note: this is really stupid, but apparently you can't
//retrieve the size of Assets due to some bullshit, so
//this is the closest you get.
return this.mDebugStream.available();
} catch (IOException e) {
return -1;
}
}
if(response.containsHeader("Content-Length")) {
String length = response.getFirstHeader("Content-Length").getValue();
try{
return Long.parseLong(length);
} catch(Exception e) {
//Whatever.
}
}
return -1;
}
//TODO: This and the normal sync share a ton of code. It's hard to really... figure out the right way to
private int recover(HttpRequestGenerator requestor, CommCareTransactionParserFactory factory) {
this.publishProgress(PROGRESS_RECOVERY_NEEDED);
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery Triggered");
BitCache cache = null;
//This chunk is the safe field of operations which can all fail in IO in such a way that we can
//just report back that things didn't work and don't need to attempt any recovery or additional
//work
try {
//Make a new request without all of the flags
HttpResponse response = requestor.makeCaseFetchRequest(server, false);
int responseCode = response.getStatusLine().getStatusCode();
//We basically only care about a positive response, here. Anything else would have been caught by the other request.
if(!(responseCode >= 200 && responseCode < 300)) {
return PROGRESS_RECOVERY_FAIL_SAFE;
}
//Grab a cache. The plan is to download the incoming data, wipe (move) the existing db, and then
//restore fresh from the downloaded file
cache = writeResponseToCache(response);
} catch(IOException e) {
e.printStackTrace();
//Ok, well, we're bailing here, but we didn't make any changes
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery Failed due to IOException|" + e.getMessage());
return PROGRESS_RECOVERY_FAIL_SAFE;
}
this.publishProgress(PROGRESS_RECOVERY_STARTED);
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery payload downloaded");
//Ok. Here's where things get real. We now have a stable copy of the fresh data from the
//server, so it's "safe" for us to wipe the casedb copy of it.
//CTS: We're not doing this in a super good way right now, need to be way more fault tolerant.
//this is the temporary implementation of everything past this point
//Wipe storage
//TODO: move table instead. Should be straightforward with sandboxed db's
CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class).removeAll();
String failureReason = "";
try {
//Get new data
String syncToken = readInput(cache.retrieveCache(), factory);
updateUserSyncToken(syncToken);
Logger.log(AndroidLogger.TYPE_USER, "Sync Recovery Succesful");
return PROGRESS_DONE;
} catch (InvalidStructureException e) {
e.printStackTrace();
failureReason = e.getMessage();
} catch (XmlPullParserException e) {
e.printStackTrace();
failureReason = e.getMessage();
} catch (UnfullfilledRequirementsException e) {
e.printStackTrace();
failureReason = e.getMessage();
} catch (StorageFullException e) {
e.printStackTrace();
failureReason = e.getMessage();
}
//These last two aren't a sign that the incoming data is bad, but
//we still can't recover from them usefully
catch (SessionUnavailableException e) {
e.printStackTrace();
failureReason = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
failureReason = e.getMessage();
} finally {
//destroy temp file
cache.release();
}
//OK, so we would have returned success by now if things had worked out, which means that instead we got an error
//while trying to parse everything out. We need to recover from that error here and rollback the changes
//TODO: Roll back changes
Logger.log(AndroidLogger.TYPE_USER, "Sync recovery failed|" + failureReason);
return PROGRESS_RECOVERY_FAIL_BAD;
}
//Utility method for debugging of people need to dump the response b
private void dumpCache(BitCache cache) {
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
AndroidStreamUtil.writeFromInputToOutput(cache.retrieveCache(), baos);
Log.d(TAG, new String(baos.toByteArray()));
} catch(IOException e) {
e.printStackTrace();
}
}
private void updateUserSyncToken(String syncToken) {
SqlStorage<User> storage = CommCareApplication._().getUserStorage(User.class);
try {
User u = storage.getRecordForValue(User.META_USERNAME, username);
u.setSyncToken(syncToken);
storage.write(u);
} catch(NoSuchElementException nsee) {
//TODO: Something here? Maybe figure out if we downloaded a user from the server and attach the data to it?
}
}
private void purgeCases() {
long start = System.currentTimeMillis();
//We need to determine if we're using ownership for purging. For right now, only in sync mode
Vector<String> owners = new Vector<String>();
Vector<String> users = new Vector<String>();
for(IStorageIterator<User> userIterator = CommCareApplication._().getUserStorage(User.class).iterate(); userIterator.hasMore();) {
String id = userIterator.nextRecord().getUniqueId();
owners.addElement(id);
users.addElement(id);
}
//Now add all of the relevant groups
//TODO: Wow. This is.... kind of megasketch
for(String userId : users) {
DataInstance instance = CommCareUtil.loadFixture("user-groups", userId);
if(instance == null) { continue; }
EvaluationContext ec = new EvaluationContext(instance);
for(TreeReference ref : ec.expandReference(XPathReference.getPathExpr("/groups/group/@id").getReference())) {
AbstractTreeElement<AbstractTreeElement> idelement = ec.resolveReference(ref);
if(idelement.getValue() != null) {
owners.addElement(idelement.getValue().uncast().getString());
}
}
}
SqlStorage<ACase> storage = CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class);
CasePurgeFilter filter = new CasePurgeFilter(storage, owners);
int removedCases = storage.removeAll(filter).size();
SqlStorage<Ledger> stockStorage = CommCareApplication._().getUserStorage(Ledger.STORAGE_KEY, Ledger.class);
LedgerPurgeFilter stockFilter = new LedgerPurgeFilter(stockStorage, storage);
int removedLedgers = stockStorage.removeAll(stockFilter).size();
long taken = System.currentTimeMillis() - start;
Logger.log(AndroidLogger.TYPE_MAINTENANCE, String.format("Purged [%d Case, %d Ledger] records in %dms", removedCases, removedLedgers, taken));
}
private String readInput(InputStream stream, CommCareTransactionParserFactory factory) throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException, SessionUnavailableException{
DataModelPullParser parser;
factory.initCaseParser();
factory.initStockParser();
Hashtable<String,String> formNamespaces = new Hashtable<String, String>();
for(String xmlns : CommCareApplication._().getCommCarePlatform().getInstalledForms()) {
Cursor cur = c.getContentResolver().query(CommCareApplication._().getCommCarePlatform().getFormContentUri(xmlns), new String[] {FormsColumns.FORM_FILE_PATH}, null, null, null);
if(cur.moveToFirst()) {
String path = cur.getString(cur.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formNamespaces.put(xmlns, path);
} else {
throw new RuntimeException("No form registered for xmlns at content URI: " + CommCareApplication._().getCommCarePlatform().getFormContentUri(xmlns));
}
cur.close();
}
factory.initFormInstanceParser(formNamespaces);
// SqlIndexedStorageUtility<FormRecord> formRecordStorge = CommCareApplication._().getStorage(FormRecord.STORAGE_KEY, FormRecord.class);
// for(SqlStorageIterator<FormRecord> i = formRecordStorge.iterate(); i.hasNext() ;) {
//this is _really_ coupled, but we'll tolerate it for now because of the absurd performance gains
SQLiteDatabase db = CommCareApplication._().getUserDbHandle();
try {
db.beginTransaction();
parser = new DataModelPullParser(stream, factory, this);
parser.parse();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
//Return the sync token ID
return factory.getSyncToken();
}
//BEGIN - OTA Listener methods below - Note that most of the methods
//below weren't really implemented
@Override
public void onUpdate(int numberCompleted) {
mCurrentProgress = numberCompleted;
int miliSecElapsed = (int)(System.currentTimeMillis() - mSyncStartTime);
this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, miliSecElapsed);
}
@Override
public void setTotalForms(int totalItemCount) {
mTotalItems = totalItemCount;
mCurrentProgress = 0;
mSyncStartTime = System.currentTimeMillis();
this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, 0);
}
@Override
public void statusUpdate(int statusNumber) {}
@Override
public void refreshView() {}
@Override
public void getCredentials() {}
@Override
public void promptRetry(String msg) {}
@Override
public void onSuccess() {}
@Override
public void onFailure(String failMessage) {}
} |
package org.neo4j.server;
import java.io.File;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.configuration.Configuration;
import org.neo4j.server.configuration.Configurator;
import org.neo4j.server.configuration.validation.DatabaseLocationMustBeSpecifiedRule;
import org.neo4j.server.configuration.validation.Validator;
import org.neo4j.server.database.Database;
import org.neo4j.server.logging.Logger;
import org.neo4j.server.startup.healthcheck.ConfigFileMustBePresentRule;
import org.neo4j.server.startup.healthcheck.StartupHealthCheck;
import org.neo4j.server.startup.healthcheck.StartupHealthCheckFailedException;
import org.neo4j.server.web.Jetty6WebServer;
import org.neo4j.server.web.WebServer;
import org.neo4j.server.webadmin.rrd.RrdManager;
import org.neo4j.server.webadmin.rrd.RrdSampler;
import org.tanukisoftware.wrapper.WrapperListener;
/**
* Application entry point for the Neo4j Server.
*/
public class NeoServer implements WrapperListener {
public static final Logger log = Logger.getLogger(NeoServer.class);
public static final String WEBSERVER_PORT_PROPERTY_KEY = "org.neo4j.webserver.port";
public static final String REST_API_SERVICE_NAME = "/db/data";
public static final String REST_API_PACKAGE = "org.neo4j.server.rest.web";
public static final String NEO_CONFIG_FILE_KEY = "org.neo4j.server.properties";
public static final String DEFAULT_NEO_CONFIG_DIR = File.separator + "etc" + File.separator + "neo";
public static final String DATABASE_LOCATION_PROPERTY_KEY = "org.neo4j.database.location";
public static final String WEBADMIN_NAMESPACE_PROPERTY_KEY = "org.neo4j.server.webadmin.";
public static final String WEB_ADMIN_REST_API_SERVICE_NAME = "/db/manage";
static final String WEB_ADMIN_REST_API_PACKAGE = "org.neo4j.server.webadmin.rest";
static final String WEB_ADMIN_PATH = "/webadmin";
private static final String STATIC_CONTENT_LOCATION = "html";
private static final int DEFAULT_WEBSERVER_PORT = 7474;
private static NeoServer theServer;
private Configurator configurator;
private Database database;
private WebServer webServer;
private int webServerPort;
public static final String EXPORT_BASE_PATH = "org.neo4j.export.basepath";
/**
* For test purposes only.
*/
NeoServer(Configurator configurator, Database db, WebServer ws) {
this.configurator = configurator;
this.database = db;
this.webServer = ws;
}
/**
* This only works if the server has been started via NeoServer.main(...)
* @return
*/
public static NeoServer server() {
return theServer;
}
NeoServer() {
StartupHealthCheck healthCheck = new StartupHealthCheck(new ConfigFileMustBePresentRule());
if (!healthCheck.run()) {
throw new StartupHealthCheckFailedException(healthCheck.failedRule());
}
}
/**
* Convenience method which calls start with a null argument
*
* @return
*/
public Integer start() {
return start(null);
}
public Integer start(String[] args) {
try {
this.configurator = new Configurator(new Validator(new DatabaseLocationMustBeSpecifiedRule()), getConfigFile());
webServerPort = configurator.configuration().getInt(WEBSERVER_PORT_PROPERTY_KEY, DEFAULT_WEBSERVER_PORT);
this.database = new Database(configurator.configuration().getString(DATABASE_LOCATION_PROPERTY_KEY));
this.webServer = new Jetty6WebServer();
log.info("Starting Neo Server on port [%s]", webServerPort);
webServer.setPort(webServerPort);
log.info("Mounting webadmin at [%s]", WEB_ADMIN_PATH);
webServer.addStaticContent(STATIC_CONTENT_LOCATION, WEB_ADMIN_PATH);
log.info("Mounting management API at [%s]", WEB_ADMIN_REST_API_SERVICE_NAME);
webServer.addJAXRSPackages(listFrom(new String[] { WEB_ADMIN_REST_API_PACKAGE }), WEB_ADMIN_REST_API_SERVICE_NAME);
log.info("Mounting REST API at [%s]", REST_API_SERVICE_NAME);
webServer.addJAXRSPackages(listFrom(new String[] { REST_API_PACKAGE }), REST_API_SERVICE_NAME);
// RrdSampler.INSTANCE.start();
webServer.start();
log.info("Started Neo Server on port [%s]", restApiUri().getPort());
return null; // This is for the service wrapper, and though it looks weird, it's correct
} catch (Exception e) {
e.printStackTrace();
log.error("Failed to start Neo Server on port [%s]", webServerPort);
e.printStackTrace();
return 1;
}
}
public String baseUri() throws UnknownHostException {
StringBuilder sb = new StringBuilder();
sb.append("http");
if (webServerPort == 443) {
sb.append("s");
}
sb.append(":
sb.append(InetAddress.getLocalHost().getCanonicalHostName());
if (webServerPort != 80) {
sb.append(":");
sb.append(webServerPort);
}
sb.append("/");
return sb.toString();
}
private URI generateUriFor(String serviceName) {
if(serviceName.startsWith("/")) {
serviceName = serviceName.substring(1);
}
StringBuilder sb = new StringBuilder();
try {
sb.append(baseUri());
sb.append(serviceName);
sb.append("/");
return new URI(sb.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public URI managementApiUri() {
return generateUriFor(WEB_ADMIN_REST_API_SERVICE_NAME);
}
public URI restApiUri() {
return generateUriFor(REST_API_SERVICE_NAME);
}
public URI webadminUri() {
return generateUriFor(WEB_ADMIN_PATH);
}
/**
* Convenience method which calls stop with a normal return code
*/
public void stop() {
stop(0);
}
public int stop(int stopArg) {
String location = "unknown";
try {
RrdManager.getRrdDB().close();
RrdSampler.INSTANCE.stop();
if (database != null) {
location = database.getLocation();
database.shutdown();
database = null;
}
if (webServer != null) {
webServer.stop();
webServer = null;
}
configurator = null;
log.info("Successfully shutdown Neo Server on port [%d], database [%s]", webServerPort, location);
return 0;
} catch (Exception e) {
log.error("Failed to cleanly shutdown Neo Server on port [%d], database [%s]. Reason [%s] ", webServerPort, location, e.getMessage());
return 1;
}
}
public static synchronized void shutdown() {
if(theServer != null) {
theServer.stop();
theServer = null;
}
}
public Database database() {
return database;
}
public WebServer webServer() {
return webServer;
}
public Configuration configuration() {
return configurator.configuration();
}
public void controlEvent(int controlArg) {
// Do nothing for now, this is needed by the WrapperListener interface
}
private static File getConfigFile() {
return new File(System.getProperty(NEO_CONFIG_FILE_KEY, DEFAULT_NEO_CONFIG_DIR));
}
private List<String> listFrom(String[] strings) {
ArrayList<String> al = new ArrayList<String>();
if (strings != null) {
for (String str : strings) {
al.add(str);
}
}
return al;
}
public static void main(String args[]) {
theServer = new NeoServer();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log.info("Neo Server shutdown initiated by kill signal");
if(theServer != null) {
theServer.stop();
}
shutdown();
}
});
theServer.start(args);
}
public void reboot() {
stop();
start();
}
} |
package com.lts.ec;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Robert HG (254963746@qq.com) on 5/11/15.
*/
public class EventInfo {
private String topic;
private Map<String, Object> params;
public EventInfo(String topic) {
this.topic = topic;
}
public void setParam(String key, Object value) {
if (params == null) {
params = new HashMap<String, Object>();
}
params.put(key, value);
}
public Object removeParam(String key) {
if (params != null) {
return params.remove(key);
}
return null;
}
public Object getParam(String key) {
if (params != null) {
return params.get(key);
}
return null;
}
public Map<String, Object> getParams() {
return params == null ? new HashMap<String, Object>() : params;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
} |
package in.uncod.android.media.widget;
import java.io.IOException;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class AudioPlayerView extends LinearLayout implements MediaPlayer.OnPreparedListener,
View.OnClickListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener,
SeekBar.OnSeekBarChangeListener {
private MediaPlayer mMediaPlayer;
private ImageButton mPlayPauseButton;
private SeekBar mSeekBar;
private String mMediaLocation;
private PlayerState mPlayerState;
Thread playbackProgressUpdater;
Handler mHandler = new Handler();
int position = -1;
enum PlayerState {
Playing, Paused, Preparing
}
public AudioPlayerView(Context context) {
super(context);
initPlayer();
}
public AudioPlayerView(Context context, AttributeSet attrs) {
super(context, attrs);
initPlayer();
}
public AudioPlayerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPlayer();
}
private void initPlayer() {
mPlayPauseButton = new ImageButton(getContext());
mPlayPauseButton.setOnClickListener(this);
addView(mPlayPauseButton);
updateButtonState(PlayerState.Preparing);
mSeekBar = new SeekBar(getContext());
mSeekBar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
addView(mSeekBar);
mSeekBar.setOnSeekBarChangeListener(this);
setGravity(Gravity.CENTER_VERTICAL);
}
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
updateButtonState(PlayerState.Paused);
if (position > -1) {
mMediaPlayer.start();
mMediaPlayer.seekTo(position);
updateButtonState(PlayerState.Playing);
}
playbackProgressUpdater = new Thread(new ProgressUpdate());
playbackProgressUpdater.start();
}
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
updateButtonState(PlayerState.Paused);
}
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
@Override
public void onClick(View view) {
switch (mPlayerState) {
case Paused:
mMediaPlayer.start();
updateButtonState(PlayerState.Playing);
break;
case Playing:
pausePlaying();
break;
}
}
public void setMediaLocation(String location) {
setMediaLocation(location, -1);
}
public void setMediaLocation(String location, int position) {
this.position = position;
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnErrorListener(this);
mMediaLocation = location;
prepareMediaPlayer();
}
private void prepareMediaPlayer() {
updateButtonState(PlayerState.Preparing);
if (mMediaLocation != null) {
try {
mMediaPlayer.setDataSource(mMediaLocation);
mMediaPlayer.prepareAsync();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
private void updateButtonState(final PlayerState playerState) {
mPlayerState = playerState;
mHandler.post(new Runnable() {
@Override
public void run() {
switch (playerState) {
case Paused:
mPlayPauseButton.setImageResource(android.R.drawable.ic_media_play);
mPlayPauseButton.setEnabled(true);
break;
case Playing:
mPlayPauseButton.setImageResource(android.R.drawable.ic_media_pause);
mPlayPauseButton.setEnabled(true);
break;
case Preparing:
mPlayPauseButton.setImageResource(android.R.drawable.ic_media_play);
mPlayPauseButton.setEnabled(false);
break;
}
}
});
}
private class ProgressUpdate implements Runnable {
public void run() {
while (mMediaPlayer != null) {
double percent = (double) mMediaPlayer.getCurrentPosition() / mMediaPlayer.getDuration();
final int progress = (int) (percent * 100.0);
mHandler.post(new Runnable() {
public void run() {
mSeekBar.setProgress(progress);
mSeekBar.setMax(100);
}
});
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mPlayPauseButton.setEnabled(enabled);
mSeekBar.setProgress(0);
try {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(0);
}
} finally {
// Ignore exception; should only happen when no media has been loaded into the player
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) {
if (fromUser && mMediaPlayer != null) {
int position = (int) (mMediaPlayer.getDuration() * (i / 100.0));
mMediaPlayer.seekTo(position);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
public boolean isPlaying() {
return mMediaPlayer != null && mMediaPlayer.isPlaying();
}
public void pausePlaying() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
updateButtonState(PlayerState.Paused);
}
}
public void stopPlaying() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mMediaPlayer.seekTo(0);
updateButtonState(PlayerState.Paused);
}
}
public int getCurrentPosition() {
if (mMediaPlayer != null) {
try {
return mMediaPlayer.getCurrentPosition();
}
catch (IllegalStateException e) {
}
}
return -1;
}
} |
package UserRegister;
import UserRegister.Repository.UserRepository;
import UserRegister.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserRegisterApplication implements CommandLineRunner{
@Autowired
UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(UserRegisterApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
Student student = new Student();
student.setId(20511091);
student.setName(" ");
userRepository.save(student);
}
} |
package edu.wustl.catissuecore.bizlogic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import net.sf.hibernate.HibernateException;
import edu.wustl.catissuecore.domain.Address;
import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.CellSpecimen;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.DisposalEventParameters;
import edu.wustl.catissuecore.domain.DistributedItem;
import edu.wustl.catissuecore.domain.ExternalIdentifier;
import edu.wustl.catissuecore.domain.FluidSpecimen;
import edu.wustl.catissuecore.domain.MolecularSpecimen;
import edu.wustl.catissuecore.domain.QuantityInCount;
import edu.wustl.catissuecore.domain.QuantityInGram;
import edu.wustl.catissuecore.domain.QuantityInMicrogram;
import edu.wustl.catissuecore.domain.QuantityInMilliliter;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCharacteristics;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.SpecimenEventParameters;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.TissueSpecimen;
import edu.wustl.catissuecore.integration.IntegrationManager;
import edu.wustl.catissuecore.integration.IntegrationManagerFactory;
import edu.wustl.catissuecore.util.ApiSearchUtil;
import edu.wustl.catissuecore.util.StorageContainerUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.dao.DAO;
import edu.wustl.common.dao.DAOFactory;
import edu.wustl.common.dao.JDBCDAO;
import edu.wustl.common.domain.AbstractDomainObject;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.security.SecurityManager;
import edu.wustl.common.security.exceptions.SMException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.logger.Logger;
/**
* NewSpecimenHDAO is used to add new specimen information into the database using Hibernate.
* @author aniruddha_phadnis
*/
public class NewSpecimenBizLogic extends IntegrationBizLogic
{
/**
* Saves the storageType object in the database.
* @param obj The storageType object to be saved.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
if (obj instanceof Map)
{
insertMultipleSpecimen((Map) obj, dao, sessionDataBean);
}
else
{
insertSingleSpecimen((Specimen) obj, dao, sessionDataBean, false);
//Inserting authorization data
Specimen specimen = (Specimen) obj;
Set protectionObjects = new HashSet();
protectionObjects.add(specimen);
if (specimen.getSpecimenCharacteristics() != null)
{
protectionObjects.add(specimen.getSpecimenCharacteristics());
}
try
{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen));
}
catch (SMException e)
{
throw handleSMException(e);
}
}
}
/**
* Insert multiple specimen into the data base.
* @param specimenList
* @param dao
* @param sessionDataBean
* @throws DAOException
* @throws UserNotAuthorizedException
*/
private void insertMultipleSpecimen(Map specimenMap, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
List specimenList = new ArrayList();
Iterator specimenIterator = specimenMap.keySet().iterator();
int count = 0;
while (specimenIterator.hasNext())
{
count++;
Specimen specimen = (Specimen) specimenIterator.next();
ApiSearchUtil.setSpecimenDefault(specimen);
//End:- Change for API Search
Long parentSpecimenId = specimen.getId();
resetId(specimen);
try
{
insertSingleSpecimen(specimen, dao, sessionDataBean, true);
specimenList.add(specimen);
}
catch (DAOException daoException)
{
String message = " (This message is for Specimen number " + count + ")";
daoException.setSupportingMessage(message);
throw daoException;
}
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens == null)
{
continue;
}
//insert derived specimens
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
resetId(derivedSpecimen);
derivedSpecimen.setParentSpecimen(specimen);
derivedSpecimen.setSpecimenCollectionGroup(specimen.getSpecimenCollectionGroup());
try
{
insertSingleSpecimen(derivedSpecimen, dao, sessionDataBean, true);
specimenList.add(derivedSpecimen);
}
catch (DAOException daoException)
{
int j = i + 1;
String message = " (This message is for Derived Specimen " + j + " of Parent Specimen number " + count + ")";
daoException.setSupportingMessage(message);
throw daoException;
}
}
}
//inserting authorization data
Iterator itr = specimenList.iterator();
while (itr.hasNext())
{
Specimen specimen = (Specimen) itr.next();
Set protectionObjects = new HashSet();
protectionObjects.add(specimen);
if (specimen.getSpecimenCharacteristics() != null)
{
protectionObjects.add(specimen.getSpecimenCharacteristics());
}
try
{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen));
}
catch (SMException e)
{
throw handleSMException(e);
}
}
}
/**
* By Rahul Ner
* @param specimen
*/
private void resetId(Specimen specimen)
{
specimen.setId(null);
Iterator childItr = null;
if (specimen.getSpecimenEventCollection() != null)
{
childItr = specimen.getSpecimenEventCollection().iterator();
while (childItr.hasNext())
{
SpecimenEventParameters eventParams = (SpecimenEventParameters) childItr.next();
eventParams.setSpecimen(specimen);
eventParams.setId(null);
}
}
if (specimen.getExternalIdentifierCollection() != null)
{
childItr = specimen.getExternalIdentifierCollection().iterator();
while (childItr.hasNext())
{
ExternalIdentifier externalIdentifier = (ExternalIdentifier) childItr.next();
externalIdentifier.setSpecimen(specimen);
externalIdentifier.setId(null);
}
}
if (specimen.getBiohazardCollection() != null)
{
childItr = specimen.getBiohazardCollection().iterator();
while (childItr.hasNext())
{
Biohazard biohazard = (Biohazard) childItr.next();
//biohazard.setId(null);
}
}
}
/**
* This method gives the error message.
* This method is overrided for customizing error message
* @param ex - DAOException
* @param obj - Object
* @return - error message string
*/
public String getErrorMessage(DAOException daoException, Object obj, String operation)
{
if (obj instanceof HashMap)
{
obj = new Specimen();
}
String supportingMessage = daoException.getSupportingMessage();
String formatedException = formatException(daoException.getWrapException(), obj, operation);
if (supportingMessage != null && formatedException != null)
{
formatedException += supportingMessage;
}
if (formatedException == null)
{
formatedException = daoException.getMessage();
if (supportingMessage != null)
formatedException += supportingMessage;
}
return formatedException;
}
/**
* Insert single specimen into the data base.
* @param specimen
* @param dao
* @param sessionDataBean
* @param partOfMulipleSpecimen
* @throws DAOException
* @throws UserNotAuthorizedException
*/
private void insertSingleSpecimen(Specimen specimen, DAO dao, SessionDataBean sessionDataBean, boolean partOfMulipleSpecimen)
throws DAOException, UserNotAuthorizedException
{
try
{
ApiSearchUtil.setSpecimenDefault(specimen);
//End:- Change for API Search
Collection externalIdentifierCollection = specimen.getExternalIdentifierCollection();
if (externalIdentifierCollection != null)
{
if (externalIdentifierCollection.isEmpty()) //Dummy entry added for query
{
ExternalIdentifier exId = new ExternalIdentifier();
exId.setName(null);
exId.setValue(null);
exId.setSpecimen(specimen);
externalIdentifierCollection.add(exId);
}
else
{
/**
* Bug 3007 - Santosh
*/
Iterator it = externalIdentifierCollection.iterator();
while (it.hasNext())
{
ExternalIdentifier exId = (ExternalIdentifier) it.next();
exId.setSpecimen(specimen);
// dao.insert(exId, sessionDataBean, true, true);
}
}
}
else
{
//Dummy entry added for query.
externalIdentifierCollection = new HashSet();
ExternalIdentifier exId = new ExternalIdentifier();
exId.setName(null);
exId.setValue(null);
exId.setSpecimen(specimen);
externalIdentifierCollection.add(exId);
specimen.setExternalIdentifierCollection(externalIdentifierCollection);
}
//Set protectionObjects = new HashSet();
specimen.setLineage(Constants.NEW_SPECIMEN);
setSpecimenAttributes(dao, specimen, sessionDataBean, partOfMulipleSpecimen);
dao.insert(specimen.getSpecimenCharacteristics(), sessionDataBean, true, true);
dao.insert(specimen, sessionDataBean, true, true);
//protectionObjects.add(specimen);
/*if (specimen.getSpecimenCharacteristics() != null)
{
protectionObjects.add(specimen.getSpecimenCharacteristics());
}*/
//Mandar : 17-july-06 : autoevents start
// Collection specimenEventsCollection = specimen.getSpecimenEventCollection();
// Iterator specimenEventsCollectionIterator = specimenEventsCollection.iterator();
// while (specimenEventsCollectionIterator.hasNext())
// Object eventObject = specimenEventsCollectionIterator.next();
// if (eventObject instanceof CollectionEventParameters)
// CollectionEventParameters collectionEventParameters = (CollectionEventParameters) eventObject;
// collectionEventParameters.setSpecimen(specimen);
// //collectionEventParameters.setId(null);
// dao.insert(collectionEventParameters, sessionDataBean, true, true);
// else if (eventObject instanceof ReceivedEventParameters)
// ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) eventObject;
// receivedEventParameters.setSpecimen(specimen);
// //receivedEventParameters.setId(null);
// dao.insert(receivedEventParameters, sessionDataBean, true, true);
//Mandar : 17-july-06 : autoevents end
//Inserting data for Authorization
//SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen));
}
catch (SMException e)
{
throw handleSMException(e);
}
}
public void postInsert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
Map containerMap = null;
try
{
containerMap = StorageContainerUtil.getContainerMapFromCache();
}
catch (Exception e)
{
e.printStackTrace();
}
if (obj instanceof HashMap)
{
HashMap specimenMap = (HashMap) obj;
Iterator specimenIterator = specimenMap.keySet().iterator();
while (specimenIterator.hasNext())
{
Specimen specimen = (Specimen) specimenIterator.next();
updateStorageLocations((TreeMap) containerMap, specimen);
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens != null)
{
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
updateStorageLocations((TreeMap) containerMap, derivedSpecimen);
}
}
}
}
else
{
updateStorageLocations((TreeMap) containerMap, (Specimen) obj);
}
}
/**
* This method gets called after update method. Any logic after updating into database can be included here.
* @param dao the dao object
* @param currentObj The object to be updated.
* @param oldObj The old object.
* @param sessionDataBean session specific data
* @throws DAOException
* @throws UserNotAuthorizedException
* */
protected void postUpdate(DAO dao, Object currentObj, Object oldObj, SessionDataBean sessionDataBean) throws BizLogicException,
UserNotAuthorizedException
{
/**
* Bug 3094 --> This jdbc query updates all the aliquots of a specimen, saperate query is written to improve the performance
*/
Specimen currentSpecimen = (Specimen) currentObj;
Specimen oldSpecimen = (Specimen) oldObj;
String type = currentSpecimen.getType();
String pathologicalStatus = currentSpecimen.getPathologicalStatus();
String id = currentSpecimen.getId().toString();
if(!currentSpecimen.getPathologicalStatus().equals(oldSpecimen.getPathologicalStatus())||!currentSpecimen.getType().equals(oldSpecimen.getType()))
{
try
{
JDBCDAO jdbcDao = (JDBCDAO) DAOFactory.getInstance().getDAO(Constants.JDBC_DAO);
jdbcDao.openSession(null);
String queryStr = "UPDATE CATISSUE_SPECIMEN SET TYPE = '" + type + "',PATHOLOGICAL_STATUS = '" + pathologicalStatus
+ "' WHERE LINEAGE = 'ALIQUOT' AND PARENT_SPECIMEN_ID ='" + id + "';";
jdbcDao.executeUpdate(queryStr);
jdbcDao.closeSession();
}
catch (Exception e)
{
Logger.out.debug("Exception occured while updating aliquots");
}
}
}
void updateStorageLocations(TreeMap containerMap, Specimen specimen)
{
try
{
if (specimen.getStorageContainer() != null)
{
StorageContainerUtil.deleteSinglePositionInContainerMap(specimen.getStorageContainer(), containerMap, specimen
.getPositionDimensionOne().intValue(), specimen.getPositionDimensionTwo().intValue());
}
}
catch (Exception e)
{
}
}
protected String[] getDynamicGroups(AbstractDomainObject obj) throws SMException
{
Specimen specimen = (Specimen) obj;
String[] dynamicGroups = new String[1];
dynamicGroups[0] = SecurityManager.getInstance(this.getClass()).getProtectionGroupByName(specimen.getSpecimenCollectionGroup(),
Constants.getCollectionProtocolPGName(null));
Logger.out.debug("Dynamic Group name: " + dynamicGroups[0]);
return dynamicGroups;
}
protected void chkContainerValidForSpecimen(StorageContainer container, Specimen specimen, DAO dao) throws DAOException
{
boolean aa = container.getHoldsSpecimenClassCollection().contains(specimen.getClassName());
boolean bb = container.getCollectionProtocolCollection().contains(
specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol());
if (!container.getHoldsSpecimenClassCollection().contains(specimen.getClassName())
|| (!container.getCollectionProtocolCollection().contains(
specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol()) && container
.getCollectionProtocolCollection().size() != 0))
{
throw new DAOException("This Storage Container not valid for Specimen");
}
}
private SpecimenCollectionGroup loadSpecimenCollectionGroup(Long specimenID, DAO dao) throws DAOException
{
//get list of Participant's names
String sourceObjectName = Specimen.class.getName();
String[] selectedColumn = {"specimenCollectionGroup." + Constants.SYSTEM_IDENTIFIER};
String whereColumnName[] = {Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object whereColumnValue[] = {specimenID};
String joinCondition = Constants.AND_JOIN_CONDITION;
List list = dao.retrieve(sourceObjectName, selectedColumn, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (!list.isEmpty())
{
Long specimenCollectionGroupId = (Long) list.get(0);
SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
specimenCollectionGroup.setId(specimenCollectionGroupId);
return specimenCollectionGroup;
}
return null;
}
private SpecimenCharacteristics loadSpecimenCharacteristics(Long specimenID, DAO dao) throws DAOException
{
//get list of Participant's names
String sourceObjectName = Specimen.class.getName();
String[] selectedColumn = {"specimenCharacteristics." + Constants.SYSTEM_IDENTIFIER};
String whereColumnName[] = {Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object whereColumnValue[] = {specimenID};
String joinCondition = Constants.AND_JOIN_CONDITION;
List list = dao.retrieve(sourceObjectName, selectedColumn, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (!list.isEmpty())
{
Long specimenCharacteristicsId = (Long) list.get(0);
SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics();
specimenCharacteristics.setId(specimenCharacteristicsId);
return specimenCharacteristics;
//return (SpecimenCharacteristics)list.get(0);
}
return null;
}
private void setAvailableQuantity(Specimen obj, Specimen oldObj) throws DAOException
{
if (obj instanceof TissueSpecimen)
{
Logger.out.debug("In TissueSpecimen");
TissueSpecimen tissueSpecimenObj = (TissueSpecimen) obj;
TissueSpecimen tissueSpecimenOldObj = (TissueSpecimen) oldObj;
// get new qunatity modifed by user
double newQty = Double.parseDouble(tissueSpecimenObj.getQuantity().toString());//tissueSpecimenObj.getQuantityInGram().doubleValue();
// get old qunatity from database
double oldQty = Double.parseDouble(tissueSpecimenOldObj.getQuantity().toString());//tissueSpecimenOldObj.getQuantityInGram().doubleValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
double oldAvailableQty = Double.parseDouble(tissueSpecimenOldObj.getAvailableQuantity().toString());//tissueSpecimenOldObj.getAvailableQuantityInGram().doubleValue();
double distQty = 0;
double newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
// set new available quantity
tissueSpecimenObj.setAvailableQuantity(new QuantityInGram(newAvailableQty));//tissueSpecimenObj.setAvailableQuantityInGram(new Double(newAvailableQty));
}
}
else if (obj instanceof MolecularSpecimen)
{
Logger.out.debug("In MolecularSpecimen");
MolecularSpecimen molecularSpecimenObj = (MolecularSpecimen) obj;
MolecularSpecimen molecularSpecimenOldObj = (MolecularSpecimen) oldObj;
// get new qunatity modifed by user
double newQty = Double.parseDouble(molecularSpecimenObj.getQuantity().toString());//molecularSpecimenObj.getQuantityInMicrogram().doubleValue();
// get old qunatity from database
double oldQty = Double.parseDouble(molecularSpecimenOldObj.getQuantity().toString());//molecularSpecimenOldObj.getQuantityInMicrogram().doubleValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
double oldAvailableQty = Double.parseDouble(molecularSpecimenOldObj.getAvailableQuantity().toString());//molecularSpecimenOldObj.getAvailableQuantityInMicrogram().doubleValue();
double distQty = 0;
double newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
// set new available quantity
molecularSpecimenObj.setAvailableQuantity(new QuantityInMicrogram(newAvailableQty));//molecularSpecimenObj.setAvailableQuantityInMicrogram(new Double(newAvailableQty));
}
}
else if (obj instanceof CellSpecimen)
{
Logger.out.debug("In CellSpecimen");
CellSpecimen cellSpecimenObj = (CellSpecimen) obj;
CellSpecimen cellSpecimenOldObj = (CellSpecimen) oldObj;
// get new qunatity modifed by user
long newQty = (long) Double.parseDouble(cellSpecimenObj.getQuantity().toString());//cellSpecimenObj.getQuantityInCellCount().intValue();
// get old qunatity from database
long oldQty = (long) Double.parseDouble(cellSpecimenOldObj.getQuantity().toString());//cellSpecimenOldObj.getQuantityInCellCount().intValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
long oldAvailableQty = (long) Double.parseDouble(cellSpecimenOldObj.getAvailableQuantity().toString());//cellSpecimenOldObj.getAvailableQuantityInCellCount().intValue();
long distQty = 0;
long newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
// set new available quantity
cellSpecimenObj.setAvailableQuantity(new QuantityInCount(newAvailableQty));//cellSpecimenObj.setAvailableQuantityInCellCount(new Integer(newAvailableQty));
}
}
else if (obj instanceof FluidSpecimen)
{
Logger.out.debug("In FluidSpecimen");
FluidSpecimen fluidSpecimenObj = (FluidSpecimen) obj;
FluidSpecimen fluidSpecimenOldObj = (FluidSpecimen) oldObj;
// get new qunatity modifed by user
double newQty = Double.parseDouble(fluidSpecimenObj.getQuantity().toString());//fluidSpecimenObj.getQuantityInMilliliter().doubleValue();
// get old qunatity from database
double oldQty = Double.parseDouble(fluidSpecimenOldObj.getQuantity().toString());//fluidSpecimenOldObj.getQuantityInMilliliter().doubleValue();
Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty);
// get Available qty
double oldAvailableQty = Double.parseDouble(fluidSpecimenOldObj.getAvailableQuantity().toString());//fluidSpecimenOldObj.getAvailableQuantityInMilliliter().doubleValue();
double distQty = 0;
double newAvailableQty = 0;
// Distributed Qty = Old_Qty - Old_Available_Qty
distQty = oldQty - oldAvailableQty;
// New_Available_Qty = New_Qty - Distributed_Qty
newAvailableQty = newQty - distQty;
Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty);
if (newAvailableQty < 0)
{
throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty
+ "'");
}
else
{
fluidSpecimenObj.setAvailableQuantity(new QuantityInMilliliter(newAvailableQty));//fluidSpecimenObj.setAvailableQuantityInMilliliter(new Double(newAvailableQty));
}
}
}
/**
* Updates the persistent object in the database.
* @param obj The object to be updated.
* @param session The session in which the object is saved.
* @throws DAOException
* @throws HibernateException Exception thrown during hibernate operations.
*/
public void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
Specimen specimen = (Specimen) obj;
Specimen specimenOld = (Specimen) oldObj;
ApiSearchUtil.setSpecimenDefault(specimen);
//Added for api Search
if (isStoragePositionChanged(specimenOld, specimen))
{
throw new DAOException("Storage Position should not be changed while updating the specimen");
}
if (!specimenOld.getLineage().equals(specimen.getLineage()))
{
throw new DAOException("Lineage should not be changed while updating the specimen");
}
if (!specimenOld.getClassName().equals(specimen.getClassName()))
{
throw new DAOException("Class should not be changed while updating the specimen");
}
// if(specimenOld.getAvailableQuantity().getValue().longValue() != specimen.getAvailableQuantity().getValue().longValue())
// throw new DAOException("Available Quantity should not be changed while updating the specimen");
//End:- Change for API Search
setAvailableQuantity(specimen, specimenOld);
if (specimen.isParentChanged())
{
//Check whether continer is moved to one of its sub container.
if (isUnderSubSpecimen(specimen, specimen.getParentSpecimen().getId()))
{
throw new DAOException(ApplicationProperties.getValue("errors.specimen.under.subspecimen"));
}
Logger.out.debug("Loading ParentSpecimen: " + specimen.getParentSpecimen().getId());
// check for closed ParentSpecimen
checkStatus(dao, specimen.getParentSpecimen(), "Parent Specimen");
SpecimenCollectionGroup scg = loadSpecimenCollectionGroup(specimen.getParentSpecimen().getId(), dao);
specimen.setSpecimenCollectionGroup(scg);
SpecimenCharacteristics sc = loadSpecimenCharacteristics(specimen.getParentSpecimen().getId(), dao);
if (!Constants.ALIQUOT.equals(specimen.getLineage()))//specimen instanceof OriginalSpecimen)
{
specimen.setSpecimenCharacteristics(sc);
}
}
//check for closed Specimen Collection Group
if (!specimen.getSpecimenCollectionGroup().getId().equals(specimenOld.getSpecimenCollectionGroup().getId()))
checkStatus(dao, specimen.getSpecimenCollectionGroup(), "Specimen Collection Group");
setSpecimenGroupForSubSpecimen(specimen, specimen.getSpecimenCollectionGroup(), specimen.getSpecimenCharacteristics());
if (!Constants.ALIQUOT.equals(specimen.getLineage()))//specimen instanceof OriginalSpecimen)
{
dao.update(specimen.getSpecimenCharacteristics(), sessionDataBean, true, true, false);
}
dao.update(specimen, sessionDataBean, true, false, false);//dao.update(specimen, sessionDataBean, true, true, false);
//Audit of Specimen.
dao.audit(obj, oldObj, sessionDataBean, true);
//Audit of Specimen Characteristics.
dao.audit(specimen.getSpecimenCharacteristics(), specimenOld.getSpecimenCharacteristics(), sessionDataBean, true);
Collection oldExternalIdentifierCollection = specimenOld.getExternalIdentifierCollection();
Collection externalIdentifierCollection = specimen.getExternalIdentifierCollection();
if (externalIdentifierCollection != null)
{
Iterator it = externalIdentifierCollection.iterator();
while (it.hasNext())
{
ExternalIdentifier exId = (ExternalIdentifier) it.next();
exId.setSpecimen(specimen);
dao.update(exId, sessionDataBean, true, true, false);
ExternalIdentifier oldExId = (ExternalIdentifier) getCorrespondingOldObject(oldExternalIdentifierCollection, exId.getId());
dao.audit(exId, oldExId, sessionDataBean, true);
}
}
//Disable functionality
Logger.out.debug("specimen.getActivityStatus() " + specimen.getActivityStatus());
if (specimen.getActivityStatus().equals(Constants.ACTIVITY_STATUS_DISABLED))
{
// check for disabling a specimen
boolean disposalEventPresent = false;
Collection eventCollection = specimen.getSpecimenEventCollection();
Iterator itr = eventCollection.iterator();
while (itr.hasNext())
{
Object eventObject = itr.next();
if (eventObject instanceof DisposalEventParameters)
{
disposalEventPresent = true;
break;
}
}
if (!disposalEventPresent)
{
throw new DAOException(ApplicationProperties.getValue("errors.specimen.not.disabled.no.disposalevent"));
}
setDisableToSubSpecimen(specimen);
Logger.out.debug("specimen.getActivityStatus() " + specimen.getActivityStatus());
Long specimenIDArr[] = new Long[1];
specimenIDArr[0] = specimen.getId();
disableSubSpecimens(dao, specimenIDArr);
}
}
private boolean isUnderSubSpecimen(Specimen specimen, Long parentSpecimenID)
{
if (specimen != null)
{
Iterator iterator = specimen.getChildrenSpecimen().iterator();
while (iterator.hasNext())
{
Specimen childSpecimen = (Specimen) iterator.next();
//Logger.out.debug("SUB CONTINER container "+parentContainerID.longValue()+" "+container.getId().longValue()+" "+(parentContainerID.longValue()==container.getId().longValue()));
if (parentSpecimenID.longValue() == childSpecimen.getId().longValue())
return true;
if (isUnderSubSpecimen(childSpecimen, parentSpecimenID))
return true;
}
}
return false;
}
private void setSpecimenGroupForSubSpecimen(Specimen specimen, SpecimenCollectionGroup specimenCollectionGroup,
SpecimenCharacteristics specimenCharacteristics)
{
if (specimen != null)
{
Logger.out.debug("specimen() " + specimen.getId());
Logger.out.debug("specimen.getChildrenContainerCollection() " + specimen.getChildrenSpecimen().size());
Iterator iterator = specimen.getChildrenSpecimen().iterator();
while (iterator.hasNext())
{
Specimen childSpecimen = (Specimen) iterator.next();
childSpecimen.setSpecimenCollectionGroup(specimenCollectionGroup);
//((OriginalSpecimen)childSpecimen).setSpecimenCharacteristics(specimenCharacteristics);
setSpecimenGroupForSubSpecimen(childSpecimen, specimenCollectionGroup, specimenCharacteristics);
}
}
}
// TODO TO BE REMOVED
private void setDisableToSubSpecimen(Specimen specimen)
{
if (specimen != null)
{
Iterator iterator = specimen.getChildrenSpecimen().iterator();
while (iterator.hasNext())
{
Specimen childSpecimen = (Specimen) iterator.next();
childSpecimen.setActivityStatus(Constants.ACTIVITY_STATUS_DISABLED);
setDisableToSubSpecimen(childSpecimen);
}
}
}
private void setSpecimenAttributes(DAO dao, Specimen specimen, SessionDataBean sessionDataBean, boolean partOfMultipleSpecimen)
throws DAOException, SMException
{
specimen.setActivityStatus(Constants.ACTIVITY_STATUS_ACTIVE);
// set barcode to null in case it is blank
if (specimen.getBarcode() != null && specimen.getBarcode().trim().equals(""))
{
specimen.setBarcode(null);
}
// TODO
//Load & set Specimen Collection Group if present
if (specimen.getSpecimenCollectionGroup() != null)
{
SpecimenCollectionGroup specimenCollectionGroupObj = null;
if (partOfMultipleSpecimen)
{
/*String sourceObjectName = SpecimenCollectionGroup.class.getName();
String[] selectColumnName = {"id"};
String[] whereColumnName = {"name"};
String[] whereColumnCondition = {"="};
Object[] whereColumnValue = {specimen.getSpecimenCollectionGroup().getName()};
String joinCondition = null;
List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
specimenCollectionGroupObj = new SpecimenCollectionGroup();
specimenCollectionGroupObj.setId((Long)list.get(0));*/
List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName());
specimenCollectionGroupObj = (SpecimenCollectionGroup) spgList.get(0);
}
else
{
specimenCollectionGroupObj = new SpecimenCollectionGroup();
specimenCollectionGroupObj.setId(specimen.getSpecimenCollectionGroup().getId());
}
if (specimenCollectionGroupObj != null)
{
/*if (specimenCollectionGroupObj.getActivityStatus().equals(Constants.ACTIVITY_STATUS_CLOSED))
{
throw new DAOException("Specimen Collection Group " + ApplicationProperties.getValue("error.object.closed"));
}*/
checkStatus(dao, specimenCollectionGroupObj, "Specimen Collection Group");
specimen.setSpecimenCollectionGroup(specimenCollectionGroupObj);
}
}
//Load & set Parent Specimen if present
if (specimen.getParentSpecimen() != null)
{
// Object parentSpecimenObj = dao.retrieve(Specimen.class.getName(), specimen.getParentSpecimen().getId());
// if (parentSpecimenObj != null)
Specimen parentSpecimen = new Specimen();
parentSpecimen.setId(specimen.getParentSpecimen().getId());
// check for closed Parent Specimen
checkStatus(dao, parentSpecimen, "Parent Specimen");
specimen.setLineage(Constants.DERIVED_SPECIMEN);
// set parent specimen event parameters -- added by Ashwin for bug id# 2476
specimen.setSpecimenEventCollection(populateDeriveSpecimenEventCollection(specimen.getParentSpecimen(), specimen));
}
//Load & set Storage Container
if (specimen.getStorageContainer() != null)
{
if (specimen.getStorageContainer().getId() != null)
{
// Object containerObj = dao.retrieve(StorageContainer.class.getName(), specimen.getStorageContainer().getId());
// if (containerObj != null)
// StorageContainer container = (StorageContainer) containerObj;
StorageContainer storageContainerObj = new StorageContainer();
storageContainerObj.setId(specimen.getStorageContainer().getId());
String sourceObjectName = StorageContainer.class.getName();
String[] selectColumnName = {"name"};
String[] whereColumnName = {"id"}; //"storageContainer."+Constants.SYSTEM_IDENTIFIER
String[] whereColumnCondition = {"="};
Object[] whereColumnValue = {specimen.getStorageContainer().getId()};
String joinCondition = null;
List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (!list.isEmpty())
{
storageContainerObj.setName((String) list.get(0));
}
// check for closed Storage Container
checkStatus(dao, storageContainerObj, "Storage Container");
StorageContainerBizLogic storageContainerBizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.STORAGE_CONTAINER_FORM_ID);
storageContainerBizLogic.checkContainer(dao, storageContainerObj.getId().toString(), specimen.getPositionDimensionOne().toString(),
specimen.getPositionDimensionTwo().toString(), sessionDataBean, partOfMultipleSpecimen);
// chkContainerValidForSpecimen(specimen.getStorageContainer(), specimen,dao);
specimen.setStorageContainer(storageContainerObj);
// else
// throw new DAOException(ApplicationProperties.getValue("errors.storageContainerExist"));
}
}
//Setting the Biohazard Collection
Set set = new HashSet();
Collection biohazardCollection = specimen.getBiohazardCollection();
if (biohazardCollection != null)
{
Iterator it = biohazardCollection.iterator();
while (it.hasNext())
{
Biohazard hazard = (Biohazard) it.next();
Logger.out.debug("hazard.getId() " + hazard.getId());
Object bioObj = dao.retrieve(Biohazard.class.getName(), hazard.getId());
if (bioObj != null)
{
Biohazard hazardObj = (Biohazard) bioObj;
set.add(hazardObj);
}
}
}
specimen.setBiohazardCollection(set);
}
public void disableRelatedObjectsForSpecimenCollectionGroup(DAO dao, Long specimenCollectionGroupArr[]) throws DAOException
{
Logger.out.debug("disableRelatedObjects NewSpecimenBizLogic");
List listOfSpecimenId = super.disableObjects(dao, Specimen.class, "specimenCollectionGroup", "CATISSUE_SPECIMEN",
"SPECIMEN_COLLECTION_GROUP_ID", specimenCollectionGroupArr);
if (!listOfSpecimenId.isEmpty())
{
disableSubSpecimens(dao, Utility.toLongArray(listOfSpecimenId));
}
}
// public void disableRelatedObjectsForStorageContainer(DAO dao, Long storageContainerIdArr[])throws DAOException
// Logger.out.debug("disableRelatedObjectsForStorageContainer NewSpecimenBizLogic");
// List listOfSpecimenId = super.disableObjects(dao, Specimen.class, "storageContainer",
// "CATISSUE_SPECIMEN", "STORAGE_CONTAINER_IDENTIFIER", storageContainerIdArr);
// if(!listOfSpecimenId.isEmpty())
// disableSubSpecimens(dao,Utility.toLongArray(listOfSpecimenId));
private void disableSubSpecimens(DAO dao, Long speIDArr[]) throws DAOException
{
List listOfSubElement = super.disableObjects(dao, Specimen.class, "parentSpecimen", "CATISSUE_SPECIMEN", "PARENT_SPECIMEN_ID", speIDArr);
if (listOfSubElement.isEmpty())
return;
disableSubSpecimens(dao, Utility.toLongArray(listOfSubElement));
}
/**
* @param dao
* @param privilegeName
* @param longs
* @param userId
* @throws DAOException
* @throws SMException
*/
public void assignPrivilegeToRelatedObjectsForSCG(DAO dao, String privilegeName, Long[] specimenCollectionGroupArr, Long userId, String roleId,
boolean assignToUser, boolean assignOperation) throws SMException, DAOException
{
Logger.out.debug("assignPrivilegeToRelatedObjectsForSCG NewSpecimenBizLogic");
List listOfSpecimenId = super.getRelatedObjects(dao, Specimen.class, "specimenCollectionGroup", specimenCollectionGroupArr);
if (!listOfSpecimenId.isEmpty())
{
super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSpecimenId), userId, roleId, assignToUser,
assignOperation);
List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics."
+ Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, Utility.toLongArray(listOfSpecimenId));
super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser,
assignOperation);
assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSpecimenId), userId, roleId, assignToUser,
assignOperation);
}
}
/**
* @param dao
* @param privilegeName
* @param class1
* @param longs
* @param userId
* @throws DAOException
* @throws SMException
*/
private void assignPrivilegeToSubSpecimens(DAO dao, String privilegeName, Class class1, Long[] speIDArr, Long userId, String roleId,
boolean assignToUser, boolean assignOperation) throws SMException, DAOException
{
List listOfSubElement = super.getRelatedObjects(dao, Specimen.class, "parentSpecimen", speIDArr);
if (listOfSubElement.isEmpty())
return;
super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser, assignOperation);
List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics."
+ Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, Utility.toLongArray(listOfSubElement));
super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser,
assignOperation);
assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser,
assignOperation);
}
public void setPrivilege(DAO dao, String privilegeName, Class objectType, Long[] objectIds, Long userId, String roleId, boolean assignToUser,
boolean assignOperation) throws SMException, DAOException
{
super.setPrivilege(dao, privilegeName, objectType, objectIds, userId, roleId, assignToUser, assignOperation);
List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics."
+ Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, objectIds);
super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser,
assignOperation);
assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, objectIds, userId, roleId, assignToUser, assignOperation);
}
// validation code here
/**
* @see edu.wustl.common.bizlogic.IBizLogic#setPrivilege(DAO, String, Class, Long[], Long, String, boolean)
* @param dao
* @param privilegeName
* @param objectIds
* @param userId
* @param roleId
* @param assignToUser
* @throws SMException
* @throws DAOException
*/
public void assignPrivilegeToRelatedObjectsForDistributedItem(DAO dao, String privilegeName, Long[] objectIds, Long userId, String roleId,
boolean assignToUser, boolean assignOperation) throws SMException, DAOException
{
String[] selectColumnNames = {"specimen.id"};
String[] whereColumnNames = {"id"};
List listOfSubElement = super.getRelatedObjects(dao, DistributedItem.class, selectColumnNames, whereColumnNames, objectIds);
if (!listOfSubElement.isEmpty())
{
super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser,
assignOperation);
}
}
/**
* Overriding the parent class's method to validate the enumerated attribute values
*/
protected boolean validate(Object obj, DAO dao, String operation) throws DAOException
{
boolean result;
if (obj instanceof Map)
{
//validation on multiple specimens are performed in MultipleSpecimenValidationUtil, so dont require to perform the bizlogic validations.
return true;
//result = validateMultipleSpecimen((Map) obj, dao, operation);
}
else
{
result = validateSingleSpecimen((Specimen) obj, dao, operation, false);
}
return result;
}
/**
* validates single specimen.
*/
private boolean validateSingleSpecimen(Specimen specimen, DAO dao, String operation, boolean partOfMulipleSpecimen) throws DAOException
{
//Added by Ashish
//Logger.out.debug("Start-Inside validate method of specimen bizlogic");
if (specimen == null)
{
throw new DAOException(ApplicationProperties.getValue("domain.object.null.err.msg", "Specimen"));
}
Validator validator = new Validator();
if (specimen.getSpecimenCollectionGroup() == null || specimen.getSpecimenCollectionGroup().getId() == null
|| specimen.getSpecimenCollectionGroup().getId().equals("-1"))
{
String message = ApplicationProperties.getValue("specimen.specimenCollectionGroup");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (specimen.getParentSpecimen() != null
&& (specimen.getParentSpecimen().getId() == null || validator.isEmpty(specimen.getParentSpecimen().getId().toString())))
{
String message = ApplicationProperties.getValue("createSpecimen.parent");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (validator.isEmpty(specimen.getLabel()))
{
String message = ApplicationProperties.getValue("specimen.label");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (validator.isEmpty(specimen.getClassName()))
{
String message = ApplicationProperties.getValue("specimen.type");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (validator.isEmpty(specimen.getType()))
{
String message = ApplicationProperties.getValue("specimen.subType");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (specimen.getStorageContainer() != null
&& (specimen.getStorageContainer().getId() == null && specimen.getStorageContainer().getName() == null))
{
String message = ApplicationProperties.getValue("specimen.storageContainer");
throw new DAOException(ApplicationProperties.getValue("errors.invalid", message));
}
if (specimen.getStorageContainer() != null && specimen.getStorageContainer().getName() != null)
{
StorageContainer storageContainerObj = specimen.getStorageContainer();
String sourceObjectName = StorageContainer.class.getName();
String[] selectColumnName = {"id"};
String[] whereColumnName = {"name"};
String[] whereColumnCondition = {"="};
Object[] whereColumnValue = {specimen.getStorageContainer().getName()};
String joinCondition = null;
List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (!list.isEmpty())
{
storageContainerObj.setId((Long) list.get(0));
specimen.setStorageContainer(storageContainerObj);
}
else
{
String message = ApplicationProperties.getValue("specimen.storageContainer");
throw new DAOException(ApplicationProperties.getValue("errors.invalid", message));
}
}
if (specimen.getSpecimenEventCollection() != null)
{
Iterator specimenEventCollectionIterator = specimen.getSpecimenEventCollection().iterator();
while (specimenEventCollectionIterator.hasNext())
{
//CollectionEvent validation.
Object eventObject = specimenEventCollectionIterator.next();
if (eventObject instanceof CollectionEventParameters)
{
CollectionEventParameters collectionEventParameters = (CollectionEventParameters) eventObject;
collectionEventParameters.getUser();
if (collectionEventParameters.getUser() == null || collectionEventParameters.getUser().getId() == null)
{
String message = ApplicationProperties.getValue("specimen.collection.event.user");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (!validator.checkDate(Utility.parseDateToString(collectionEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY)))
{
String message = ApplicationProperties.getValue("specimen.collection.event.date");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
// checks the collectionProcedure
if (!validator.isValidOption(collectionEventParameters.getCollectionProcedure()))
{
String message = ApplicationProperties.getValue("collectioneventparameters.collectionprocedure");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
if (!Validator.isEnumeratedValue(procedureList, collectionEventParameters.getCollectionProcedure()))
{
throw new DAOException(ApplicationProperties.getValue("events.collectionProcedure.errMsg"));
}
if (!validator.isValidOption(collectionEventParameters.getContainer()))
{
String message = ApplicationProperties.getValue("collectioneventparameters.container");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null);
if (!Validator.isEnumeratedValue(containerList, collectionEventParameters.getContainer()))
{
throw new DAOException(ApplicationProperties.getValue("events.container.errMsg"));
}
}
//ReceivedEvent validation
else if (eventObject instanceof ReceivedEventParameters)
{
ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) eventObject;
if (receivedEventParameters.getUser() == null || receivedEventParameters.getUser().getId() == null)
{
String message = ApplicationProperties.getValue("specimen.recieved.event.user");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
if (!validator.checkDate(Utility.parseDateToString(receivedEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY)))
{
String message = ApplicationProperties.getValue("specimen.recieved.event.date");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
// checks the collectionProcedure
if (!validator.isValidOption(receivedEventParameters.getReceivedQuality()))
{
String message = ApplicationProperties.getValue("collectioneventparameters.receivedquality");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", message));
}
List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null);
if (!Validator.isEnumeratedValue(qualityList, receivedEventParameters.getReceivedQuality()))
{
throw new DAOException(ApplicationProperties.getValue("events.receivedQuality.errMsg"));
}
}
}
}
//Validations for Biohazard Add-More Block
Collection bioHazardCollection = specimen.getBiohazardCollection();
Biohazard biohazard = null;
if (bioHazardCollection != null && !bioHazardCollection.isEmpty())
{
Iterator itr = bioHazardCollection.iterator();
while (itr.hasNext())
{
biohazard = (Biohazard) itr.next();
if (!validator.isValidOption(biohazard.getType()))
{
String message = ApplicationProperties.getValue("newSpecimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message));
}
if (biohazard.getId() == null)
{
String message = ApplicationProperties.getValue("newSpecimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message));
}
}
}
//validations for external identifiers
Collection extIdentifierCollection = specimen.getExternalIdentifierCollection();
ExternalIdentifier extIdentifier = null;
if (extIdentifierCollection != null && !extIdentifierCollection.isEmpty())
{
Iterator itr = extIdentifierCollection.iterator();
while (itr.hasNext())
{
extIdentifier = (ExternalIdentifier) itr.next();
if (validator.isEmpty(extIdentifier.getName()))
{
String message = ApplicationProperties.getValue("specimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message));
}
if (validator.isEmpty(extIdentifier.getValue()))
{
String message = ApplicationProperties.getValue("specimen.msg");
throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message));
}
}
}
//End Ashish
if (Constants.ALIQUOT.equals(specimen.getLineage()))
{
//return true;
}
validateFields(specimen, dao, operation, partOfMulipleSpecimen);
List specimenClassList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_SPECIMEN_CLASS, null);
String specimenClass = Utility.getSpecimenClassName(specimen);
if (!Validator.isEnumeratedValue(specimenClassList, specimenClass))
{
throw new DAOException(ApplicationProperties.getValue("protocol.class.errMsg"));
}
if (!Validator.isEnumeratedValue(Utility.getSpecimenTypes(specimenClass), specimen.getType()))
{
throw new DAOException(ApplicationProperties.getValue("protocol.type.errMsg"));
}
SpecimenCharacteristics characters = specimen.getSpecimenCharacteristics();
if (characters == null)
{
throw new DAOException(ApplicationProperties.getValue("specimen.characteristics.errMsg"));
}
else
{
if (specimen.getSpecimenCollectionGroup() != null)
{
// NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED);
List tissueSiteList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SITE, null);
if (!Validator.isEnumeratedValue(tissueSiteList, characters.getTissueSite()))
{
throw new DAOException(ApplicationProperties.getValue("protocol.tissueSite.errMsg"));
}
// NameValueBean unknownVal = new NameValueBean(Constants.UNKNOWN,Constants.UNKNOWN);
List tissueSideList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SIDE, null);
if (!Validator.isEnumeratedValue(tissueSideList, characters.getTissueSide()))
{
throw new DAOException(ApplicationProperties.getValue("specimen.tissueSide.errMsg"));
}
List pathologicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_PATHOLOGICAL_STATUS, null);
if (!Validator.isEnumeratedValue(pathologicalStatusList, specimen.getPathologicalStatus()))
{
throw new DAOException(ApplicationProperties.getValue("protocol.pathologyStatus.errMsg"));
}
}
}
if (operation.equals(Constants.ADD))
{
if (!specimen.getAvailable().booleanValue())
{
throw new DAOException(ApplicationProperties.getValue("specimen.available.errMsg"));
}
if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(specimen.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.active.errMsg"));
}
}
else
{
if (!Validator.isEnumeratedValue(Constants.ACTIVITY_STATUS_VALUES, specimen.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg"));
}
}
//Logger.out.debug("End-Inside validate method of specimen bizlogic");
return true;
}
private void validateFields(Specimen specimen, DAO dao, String operation, boolean partOfMulipleSpecimen) throws DAOException
{
Validator validator = new Validator();
if (partOfMulipleSpecimen)
{
if (specimen.getSpecimenCollectionGroup() == null || validator.isEmpty(specimen.getSpecimenCollectionGroup().getName()))
{
String quantityString = ApplicationProperties.getValue("specimen.specimenCollectionGroup");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString));
}
List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName());
if (spgList.size() == 0)
{
throw new DAOException(ApplicationProperties.getValue("errors.item.unknown", "Specimen Collection Group "
+ specimen.getSpecimenCollectionGroup().getName()));
}
}
if (validator.isEmpty(specimen.getLabel()))
{
String labelString = ApplicationProperties.getValue("specimen.label");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", labelString));
}
if (specimen.getQuantity() == null || specimen.getQuantity().getValue() == null)
{
String quantityString = ApplicationProperties.getValue("specimen.quantity");
throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString));
}
/**
* This method gives first valid storage position to a specimen if it is not given.
* If storage position is given it validates the storage position
**/
StorageContainerUtil.validateStorageLocationForSpecimen(specimen);
}
/**
* validates multiple specimen. Internally it for each specimen it innvokes validateSingleSpecimen.
* @throws DAOException
* @throws DAOException
private boolean validateMultipleSpecimen(Map specimenMap, DAO dao, String operation) throws DAOException
{
populateStorageLocations(dao, specimenMap);
Iterator specimenIterator = specimenMap.keySet().iterator();
boolean result = true;
while (specimenIterator.hasNext() && result == true)
{
Specimen specimen = (Specimen) specimenIterator.next();
//validate single specimen
*/
/* if (specimenCollectionGroup != null)
{
if (specimenCollectionGroup.getActivityStatus().equals(Constants.ACTIVITY_STATUS_CLOSED))
{
throw new DAOException("Specimen Collection Group " + ApplicationProperties.getValue("error.object.closed"));
}
specimen.setSpecimenCollectionGroup(specimenCollectionGroup);
}
List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName());
if(spgList!=null && !spgList.isEmpty())
{
specimenCollectionGroup = (SpecimenCollectionGroup) spgList.get(0);
}
else if(specimen.getParentSpecimen()!=null)
{
List spList = dao.retrieve(Specimen.class.getName(), Constants.SYSTEM_LABEL, specimen.getParentSpecimen().getLabel());
if (spList != null && !spList.isEmpty())
{
Specimen sp = (Specimen) spList.get(0);
specimenCollectionGroup = sp.getSpecimenCollectionGroup();
}
} */
/*
// TODO uncomment code for label, performance
try
{
result = validateSingleSpecimen(specimen, dao, operation, true);
}
catch (DAOException daoException)
{
String message = daoException.getMessage();
message += " (This message is for Specimen number " + specimen.getId() + ")";
daoException.setMessage(message);
throw daoException;
}
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens == null)
{
continue;
}
//validate derived specimens
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
derivedSpecimen.setSpecimenCharacteristics(specimen.getSpecimenCharacteristics());
derivedSpecimen.setSpecimenCollectionGroup(specimen.getSpecimenCollectionGroup());
derivedSpecimen.setPathologicalStatus(specimen.getPathologicalStatus());
try
{
result = validateSingleSpecimen(derivedSpecimen, dao, operation, false);
}
catch (DAOException daoException)
{
int j = i + 1;
String message = daoException.getMessage();
message += " (This message is for Derived Specimen " + j + " of Parent Specimen number " + specimen.getId() + ")";
daoException.setMessage(message);
throw daoException;
}
if (!result)
{
break;
}
}
}
return result;
}
*/
/**
*
* Start --> Code added for auto populating storage locations in case of multiple specimen
*/
/**
* This method populates SCG Id and storage locations for Multiple Specimen
* @param dao
* @param specimenMap
* @throws DAOException
private void populateStorageLocations(DAO dao, Map specimenMap) throws DAOException
{
final String saperator = "$";
Map tempSpecimenMap = new HashMap();
Iterator specimenIterator = specimenMap.keySet().iterator();
while (specimenIterator.hasNext())
{
Specimen specimen = (Specimen) specimenIterator.next();
//validate single specimen
if (specimen.getSpecimenCollectionGroup() != null)
{
String[] selectColumnName = {"collectionProtocolRegistration.id"};
String[] whereColumnName = {Constants.NAME};
String[] whereColumnCondition = {"="};
String[] whereColumnValue = {specimen.getSpecimenCollectionGroup().getName()};
List spCollGroupList = dao.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName, whereColumnCondition,
whereColumnValue, null);
// TODO saperate calls for SCG - ID and cpid
// SCG - ID will be needed before populateStorageLocations
// TODO test
if (!spCollGroupList.isEmpty())
{
//Object idList[] = (Object[]) spCollGroupList.get(0); // Move up + here
long cpId = ((Long) spCollGroupList.get(0)).longValue();
//Long scgId = (Long) idList[0]; // Move up
//long cpId = ((Long) idList[0]).longValue();//here
//specimen.getSpecimenCollectionGroup().setId(scgId); // Move up
List tempListOfSpecimen = (ArrayList) tempSpecimenMap.get(cpId + saperator + specimen.getClassName());
if (tempListOfSpecimen == null)
{
tempListOfSpecimen = new ArrayList();
}
int i = 0;
for (; i < tempListOfSpecimen.size(); i++)
{
Specimen sp = (Specimen) tempListOfSpecimen.get(i);
if ((sp.getId() != null) && (specimen.getId().longValue() < sp.getId().longValue()))
break;
}
tempListOfSpecimen.add(i, specimen);
tempSpecimenMap.put(cpId + saperator + specimen.getClassName(), tempListOfSpecimen);
List listOfDerivedSpecimen = (ArrayList) specimenMap.get(specimen);
// TODO
if (listOfDerivedSpecimen != null)
{
for (int j = 0; j < listOfDerivedSpecimen.size(); j++)
{
Specimen tempDerivedSpecimen = (Specimen) listOfDerivedSpecimen.get(j);
String derivedKey = cpId + saperator + tempDerivedSpecimen.getClassName();
List listOfSpecimen = (ArrayList) tempSpecimenMap.get(derivedKey);
if (listOfSpecimen == null)
{
listOfSpecimen = new ArrayList();
}
listOfSpecimen.add(tempDerivedSpecimen);
tempSpecimenMap.put(derivedKey, listOfSpecimen);
}
}
}
}
}
Iterator keyIterator = tempSpecimenMap.keySet().iterator();
while (keyIterator.hasNext())
{
String key = (String) keyIterator.next();
StorageContainerBizLogic scbizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.STORAGE_CONTAINER_FORM_ID);
String split[] = key.split("[$]");
// TODO when moved to acion pass true
TreeMap containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen((Long.parseLong(split[0])), split[1], 0, "", false);
List listOfSpecimens = (ArrayList) tempSpecimenMap.get(key);
allocatePositionToSpecimensList(specimenMap, listOfSpecimens, containerMap);
}
}
*/
/**
* This function gets the default positions for list of specimens
* @param specimenMap
* @param listOfSpecimens
* @param containerMap
private void allocatePositionToSpecimensList(Map specimenMap, List listOfSpecimens, Map containerMap)
{
List newListOfSpecimen = new ArrayList();
*/
/* for (int i = 0; i < listOfSpecimens.size(); i++)
{
Specimen tempSpecimen = (Specimen) listOfSpecimens.get(i);
newListOfSpecimen.add(tempSpecimen);
List listOfDerivedSpecimen = (ArrayList) specimenMap.get(tempSpecimen);
// TODO
if (listOfDerivedSpecimen != null)
{
for (int j = 0; j < listOfDerivedSpecimen.size(); j++)
{
Specimen tempDerivedSpecimen = (Specimen) listOfDerivedSpecimen.get(j);
newListOfSpecimen.add(tempDerivedSpecimen);
}
}
}
*/
/*
Iterator iterator = containerMap.keySet().iterator();
int i = 0;
while (iterator.hasNext())
{
NameValueBean nvb = (NameValueBean) iterator.next();
Map tempMap = (Map) containerMap.get(nvb);
if (tempMap.size() > 0)
{
boolean result = false;
for (; i < newListOfSpecimen.size(); i++)
{
Specimen tempSpecimen = (Specimen) newListOfSpecimen.get(i);
result = allocatePositionToSingleSpecimen(specimenMap, tempSpecimen, tempMap, nvb);
if (result == false) // container is exhausted
break;
}
if (result == true)
break;
}
}
}
*/
/**
* This function gets the default position specimen,the position should not be used by any other specimen in specimenMap
* This is required because we might have given the same position to another specimen.
* @param specimenMap
* @param tempSpecimen
* @param tempMap
* @param nvb
* @return
private boolean allocatePositionToSingleSpecimen(Map specimenMap, Specimen tempSpecimen, Map tempMap, NameValueBean nvbForContainer)
{
Iterator itr = tempMap.keySet().iterator();
String containerId = nvbForContainer.getValue(), xPos, yPos;
while (itr.hasNext())
{
NameValueBean nvb = (NameValueBean) itr.next();
xPos = nvb.getValue();
List list = (List) tempMap.get(nvb);
for (int i = 0; i < list.size(); i++)
{
nvb = (NameValueBean) list.get(i);
yPos = nvb.getValue();
boolean result = checkPositionValidForSpecimen(containerId, xPos, yPos, specimenMap);
if (result == true)
{
StorageContainer tempStorageContainer = new StorageContainer();
tempStorageContainer.setId(new Long(Long.parseLong(containerId)));
tempSpecimen.setPositionDimensionOne(new Integer(Integer.parseInt(xPos)));
tempSpecimen.setPositionDimensionTwo(new Integer(Integer.parseInt(yPos)));
tempSpecimen.setStorageContainer(tempStorageContainer);
return true;
}
}
}
return false;
}
*/
/**
* This method checks whether the given parameters match with parameters in specimen Map
* @param containerId
* @param pos
* @param pos2
* @param specimenMap
* @return
private boolean checkPositionValidForSpecimen(String containerId, String xpos, String ypos, Map specimenMap)
{
// TODO can be optimised by passing list
Iterator specimenIterator = specimenMap.keySet().iterator();
while (specimenIterator.hasNext())
{
Specimen specimen = (Specimen) specimenIterator.next();
boolean matchFound = checkMatchingPosition(containerId, xpos, ypos, specimen);
if (matchFound == true)
return false;
List derivedSpecimens = (List) specimenMap.get(specimen);
if (derivedSpecimens != null)
{
for (int i = 0; i < derivedSpecimens.size(); i++)
{
Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i);
matchFound = checkMatchingPosition(containerId, xpos, ypos, derivedSpecimen);
if (matchFound == true)
return false;
}
}
}
return true;
}
*/
/**
* This method checks whether the given parameters match with parameters of the specimen
* @param containerId
* @param pos
* @param pos2
* @param specimen
* @return
private boolean checkMatchingPosition(String containerId, String xpos, String ypos, Specimen specimen)
{
String storageContainerId = "";
if (specimen.getStorageContainer() != null && specimen.getStorageContainer().getId() != null)
storageContainerId += specimen.getStorageContainer().getId();
else
return false;
String pos1 = specimen.getPositionDimensionOne() + "";
String pos2 = specimen.getPositionDimensionTwo() + "";
if (storageContainerId.equals(containerId) && xpos.equals(pos1) && ypos.equals(pos2))
return true;
return false;
}
*/
/**
*
* End --> Code added for auto populating storage locations in case of multiple specimen
*/
/* This function checks whether the storage position of a specimen is changed or not
* & returns the status accordingly.
*/
private boolean isStoragePositionChanged(Specimen oldSpecimen, Specimen newSpecimen)
{
StorageContainer oldContainer = oldSpecimen.getStorageContainer();
StorageContainer newContainer = newSpecimen.getStorageContainer();
//Added for api: Jitendra
if ((oldContainer == null && newContainer != null) || (oldContainer != null && newContainer == null))
{
return true;
}
if (oldContainer != null && newContainer != null)
{
if (oldContainer.getId().longValue() == newContainer.getId().longValue())
{
if (oldSpecimen.getPositionDimensionOne().intValue() == newSpecimen.getPositionDimensionOne().intValue())
{
if (oldSpecimen.getPositionDimensionTwo().intValue() == newSpecimen.getPositionDimensionTwo().intValue())
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
return false;
}
}
/**
* This method fetches linked data from integrated application i.e. CAE/caTies.
*/
public List getLinkedAppData(Long id, String applicationID)
{
Logger.out.debug("In getIntegrationData() of SpecimenBizLogic ");
Logger.out.debug("ApplicationName in getIntegrationData() of SCGBizLogic==>" + applicationID);
long identifiedPathologyReportId = 0;
try
{
//JDBC call to get matching identifier from database
Class.forName("org.gjt.mm.mysql.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/catissuecore", "catissue_core", "catissue_core");
Statement stmt = connection.createStatement();
String specimenCollectionGroupQuery = "select SPECIMEN_COLLECTION_GROUP_ID from CATISSUE_SPECIMEN where IDENTIFIER=" + id;
ResultSet specimenCollectionGroupResultSet = stmt.executeQuery(specimenCollectionGroupQuery);
long specimenCollectionGroupId = 0;
while (specimenCollectionGroupResultSet.next())
{
specimenCollectionGroupId = specimenCollectionGroupResultSet.getLong(1);
break;
}
Logger.out.debug("SpecimenCollectionGroupId==>" + specimenCollectionGroupId);
if (specimenCollectionGroupId == 0)
{
List exception = new ArrayList();
exception.add("SpecimenCollectionGroupId is not available for Specimen");
return exception;
}
String clinicalReportQuery = "select CLINICAL_REPORT_ID from CATISSUE_SPECIMEN_COLL_GROUP where IDENTIFIER=" + specimenCollectionGroupId;
ResultSet clinicalReportResultSet = stmt.executeQuery(clinicalReportQuery);
long clinicalReportId = 0;
while (clinicalReportResultSet.next())
{
clinicalReportId = clinicalReportResultSet.getLong(1);
break;
}
Logger.out.debug("ClinicalReportId==>" + clinicalReportId);
clinicalReportResultSet.close();
if (clinicalReportId == 0)
{
List exception = new ArrayList();
exception.add("ClinicalReportId is not available for SpecimenCollectionGroup");
return exception;
}
String identifiedPathologyReportIdQuery = "select IDENTIFIER from CATISSUE_IDENTIFIED_PATHOLOGY_REPORT where CLINICAL_REPORT_ID="
+ clinicalReportId;
ResultSet identifiedPathologyReportResultSet = stmt.executeQuery(identifiedPathologyReportIdQuery);
while (identifiedPathologyReportResultSet.next())
{
identifiedPathologyReportId = identifiedPathologyReportResultSet.getLong(1);
break;
}
Logger.out.debug("IdentifiedPathologyReportId==>" + identifiedPathologyReportId);
identifiedPathologyReportResultSet.close();
if (identifiedPathologyReportId == 0)
{
List exception = new ArrayList();
exception.add("IdentifiedPathologyReportId is not available for linked ClinicalReportId");
return exception;
}
stmt.close();
connection.close();
}
catch (Exception e)
{
Logger.out.debug("JDBC Exception==>" + e.getMessage());
}
IntegrationManager integrationManager = IntegrationManagerFactory.getIntegrationManager(applicationID);
return integrationManager.getLinkedAppData(new Specimen(), new Long(identifiedPathologyReportId));
}
public String getPageToShow()
{
return new String();
}
public List getMatchingObjects()
{
return new ArrayList();
}
// added by Ashwin for bug id# 2476
/**
* Set event parameters from parent specimen to derived specimen
* @param parentSpecimen specimen
* @return set
*/
private Set populateDeriveSpecimenEventCollection(Specimen parentSpecimen, Specimen deriveSpecimen)
{
Set deriveEventCollection = new HashSet();
Set parentSpecimeneventCollection = (Set) parentSpecimen.getSpecimenEventCollection();
SpecimenEventParameters specimenEventParameters = null;
SpecimenEventParameters deriveSpecimenEventParameters = null;
try
{
if (parentSpecimeneventCollection != null)
{
for (Iterator iter = parentSpecimeneventCollection.iterator(); iter.hasNext();)
{
specimenEventParameters = (SpecimenEventParameters) iter.next();
deriveSpecimenEventParameters = (SpecimenEventParameters) specimenEventParameters.clone();
deriveSpecimenEventParameters.setId(null);
deriveSpecimenEventParameters.setSpecimen(deriveSpecimen);
deriveEventCollection.add(deriveSpecimenEventParameters);
}
}
}
catch (CloneNotSupportedException exception)
{
exception.printStackTrace();
}
return deriveEventCollection;
}
} |
package com.technicolor.eloyente;
import hudson.Extension;
import hudson.model.AbstractItem;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.model.Items;
import hudson.model.Project;
import hudson.model.TopLevelItem;
import hudson.tasks.Builder;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.FormValidation;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.packet.DiscoverItems;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
/**
* @author Juan Luis Pardo Gonzalez
* @author Isabel Fernandez Diaz
*/
public class ElOyente extends Trigger<Project> {
private String server;
private String user;
private String password;
private static Item project;
/**
* Constructor for elOyente.
*
* It uses the Descriptor to set the fields required later on. The
* Descriptor will bring the information set in the main configuration to
* the particular job.
*/
@DataBoundConstructor
public ElOyente(Item project) {
super();
server = this.getDescriptor().server;
user = this.getDescriptor().user;
password = this.getDescriptor().password;
ElOyente.project = project;
}
/**
* Method used for starting a job.
*
* This method is called when the Save button is pressed in a job
* configuration in case this plugin is activated.
*
* It checks if there is all the information required for an XMPP connection
* in the main configuration and creates the connection.
*
* @param project
* @param newInstance
*/
@Override
public void start(Project project, boolean newInstance) {
server = this.getDescriptor().server;
user = this.getDescriptor().user;
password = this.getDescriptor().password;
if (server != null || user != null || password != null) {
ConnectionConfiguration config = new ConnectionConfiguration(server);
Connection con = new XMPPConnection(config);
con.disconnect(new Presence(Presence.Type.unavailable));
}
if (server != null && !server.isEmpty() && user != null && !user.isEmpty() && password != null && !password.isEmpty()) {
try {
ConnectionConfiguration config = new ConnectionConfiguration(server);
Connection con = new XMPPConnection(config);
con.connect();
if (con.isConnected()) {
try {
con.login(user, password, project.getName());
} catch (XMPPException ex) {
System.err.println("Login error");
ex.printStackTrace(System.err);
}
}
} catch (XMPPException ex) {
System.err.println("Couldn't establish the connection, or already connected");
ex.printStackTrace(System.err);
}
}
}
@Override
public void run() {
if (!project.getAllJobs().isEmpty()) {
Iterator iterator = project.getAllJobs().iterator();
while (iterator.hasNext()) {
((Project) iterator.next()).scheduleBuild(null);
}
}
//super.run();
}
/**
* Retrieves the descriptor for the plugin elOyente.
*
* Used by the plugin to set and work with the main configuration.
*
* @return DescriptorImpl
*/
@Override
public final DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
* <tt>src/main/resources/hudson/plugins/eloyente/elOyente/*.jelly</tt> for
* the actual HTML fragment for the configuration screen.
*/
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends TriggerDescriptor {
/**
* To persist global configuration information, simply store it in a
* field and call save().
*
* <p> If you don't want fields to be persisted, use <tt>transient</tt>.
*/
private String server, oldserver;
private String user, olduser;
private String password, oldpassword;
/**
* Brings the persisted configuration in the main configuration.
*
* Brings the persisted configuration in the main configuration.
*/
public DescriptorImpl() {
load();
oldserver = this.getServer();
olduser = this.getUser();
oldpassword = this.getPassword();
}
/**
* Used to persist the global configuration.
*
*
* This method is used to set the field for the checkbox that activates
* the plugin in the job configuration.
*
* @return boolean
* @param item
*/
@Override
public boolean isApplicable(Item item) {
return true;
}
/**
* Used to persist the global configuration.
*
*
* This method is used to set the field for the checkbox that activates
* the plugin in the job configuration.
*
* @return String
*/
@Override
public String getDisplayName() {
return "XMPP triggered plugin";
}
/**
* Used to persist the global configuration.
*
*
* global.jelly calls this method to obtain the value of field server.
*
* @param req
* @param formData
* @return boolean
* @throws Descriptor.FormException
*/
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws Descriptor.FormException {
// To persist global configuration information,
// set that to properties and call save().
server = formData.getString("server");
user = formData.getString("user");
password = formData.getString("password");
// ^Can also use req.bindJSON(this, formData);
// (easier when there are many fields; need set* methods for this)
//report();
save();
if (!server.equals(oldserver) || !user.equals(olduser) || !password.equals(oldpassword)) {
try {
AbstractItem item = (AbstractItem) Jenkins.getInstance().getItem("Prueba1");
File directoryConfigXml = item.getConfigFile().getFile().getParentFile();
System.out.println(Items.load(item.getParent(), directoryConfigXml));
} catch (IOException ex) {
Logger.getLogger(ElOyente.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("NO EXISTE EL JOB PRUEBA1");
}
}
return super.configure(req, formData);
}
/**
* Used for logging to the log file.
*
* This method reports information related to XMPP events like
* "Available Nodes", connection information, etc. It creates a
* connection to take the required data for reporting and it closes it
* after. It is used in the main configuration every time the Save or
* Apply buttons are pressed.
*
*/
// public void report() {
// Logger logger = Logger.getLogger("com.technicolor.eloyente");
// //Logger loger = Logger.getLogger(ElOyente.class.getName());
// if (server != null && !server.isEmpty() && user != null && !user.isEmpty() && password != null && !password.isEmpty()) {
// try {
// //Connection
// ConnectionConfiguration config = new ConnectionConfiguration(server);
// PubSubManager mgr;
// Connection con = new XMPPConnection(config);
// con.connect();
// logger.log(Level.INFO, "Connection established");
// if (con.isConnected()) {
// //Login
// con.login(user, password, "Global");
// logger.log(Level.INFO, "JID: {0}", con.getUser());
// logger.log(Level.INFO, "{0} has been logged to openfire!", user);
// //Log the availables nodes
// mgr = new PubSubManager(con);
// DiscoverItems items = mgr.discoverNodes(null);
// Iterator<DiscoverItems.Item> iter = items.getItems();
// while (iter.hasNext()) {
// DiscoverItems.Item i = iter.next();
// logger.log(Level.INFO, "Node: {0}", i.getNode());
// System.out.println("Node: " + i.toXML());
// System.out.println("NodeName: " + i.getNode());
// //Disconnection
// con.disconnect();
// } catch (XMPPException ex) {
// System.err.println(ex.getXMPPError().getMessage());
/**
* This method returns the URL of the XMPP server.
*
*
* global.jelly calls this method to obtain the value of field server.
*
* @return server
*/
public String getServer() {
return server;
}
/**
* This method returns the username for the XMPP connection.
*
*
* global.jelly calls this method to obtain the value of field user.
*
* @return user
*/
public String getUser() {
return user;
}
/**
* This method returns the password for the XMPP connection.
*
*
* global.jelly calls this method to obtain the value of field password.
*
* @return password
*/
public String getPassword() {
return password;
}
/**
* Performs on-the-fly validation of the form field 'server'.
*
* This method checks if the connection to the XMPP server specified is
* available. It shows a notification describing the status of the
* server connection.
*
* @param server
*/
public FormValidation doCheckServer(@QueryParameter String server) {
try {
ConnectionConfiguration config = new ConnectionConfiguration(server);
Connection con = new XMPPConnection(config);
if (server.isEmpty()) {
return FormValidation.warningWithMarkup("No server specified");
}
con.connect();
if (con.isConnected()) {
con.disconnect();
return FormValidation.okWithMarkup("Connection available");
}
return FormValidation.errorWithMarkup("Couldn't connect");
} catch (XMPPException ex) {
return FormValidation.errorWithMarkup("Couldn't connect");
}
}
/**
* Performs on-the-fly validation of the form fields 'user' and
* 'password'.
*
* This method checks if the user and password of the XMPP server
* specified are correct and valid. It shows a notification describing
* the status of the login.
*
* @param user
* @param password
*/
public FormValidation doCheckPassword(@QueryParameter String user, @QueryParameter String password, @QueryParameter String server) {
ConnectionConfiguration config = new ConnectionConfiguration(server);
Connection con = new XMPPConnection(config);
if ((user.isEmpty() || password.isEmpty()) || server.isEmpty()) {
return FormValidation.warningWithMarkup("Not authenticated");
}
try {
con.connect();
con.login(user, password);
if (con.isAuthenticated()) {
con.disconnect();
return FormValidation.okWithMarkup("Authentication succed");
}
return FormValidation.warningWithMarkup("Not authenticated");
} catch (XMPPException ex) {
return FormValidation.errorWithMarkup("Authentication failed");
}
}
}
} |
package org.teiid.query.optimizer;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.core.types.DataTypeManager;
import org.teiid.metadata.Column;
import org.teiid.metadata.MetadataStore;
import org.teiid.metadata.Schema;
import org.teiid.metadata.Table;
import org.teiid.query.mapping.relational.QueryNode;
import org.teiid.query.metadata.TransformationMetadata;
import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
import org.teiid.query.optimizer.TestOptimizer.DependentProjectNode;
import org.teiid.query.optimizer.TestOptimizer.DependentSelectNode;
import org.teiid.query.optimizer.TestOptimizer.DupRemoveNode;
import org.teiid.query.optimizer.TestOptimizer.DupRemoveSortNode;
import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
import org.teiid.query.processor.FakeDataManager;
import org.teiid.query.processor.ProcessorPlan;
import org.teiid.query.processor.TestProcessor;
import org.teiid.query.processor.relational.*;
import org.teiid.query.unittest.RealMetadataFactory;
@SuppressWarnings("nls")
public class TestLimit {
private static final int[] FULL_PUSHDOWN = new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
0, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
0 // UnionAll
};
public static final Class<?>[] NODE_TYPES = new Class[] {
AccessNode.class,
DependentAccessNode.class,
DependentSelectNode.class,
DependentProjectNode.class,
DupRemoveNode.class,
GroupingNode.class,
LimitNode.class,
NestedLoopJoinStrategy.class,
MergeJoinStrategy.class,
NullNode.class,
PlanExecutionNode.class,
ProjectNode.class,
SelectNode.class,
SortNode.class,
UnionAllNode.class
};
private static TransformationMetadata exampleMetadata() {
MetadataStore metadataStore = new MetadataStore();
// Create models
Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
Schema vm1 = RealMetadataFactory.createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
// Create physical groups
Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
Table pm1g2 = RealMetadataFactory.createPhysicalGroup("g2", pm1); //$NON-NLS-1$
Table pm1g3 = RealMetadataFactory.createPhysicalGroup("g3", pm1); //$NON-NLS-1$
Table pm1g4 = RealMetadataFactory.createPhysicalGroup("g4", pm1); //$NON-NLS-1$
Table pm1g5 = RealMetadataFactory.createPhysicalGroup("g5", pm1); //$NON-NLS-1$
Table pm1g6 = RealMetadataFactory.createPhysicalGroup("g6", pm1); //$NON-NLS-1$
// Create physical elements
RealMetadataFactory.createElements(pm1g1,
new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
RealMetadataFactory.createElements(pm1g2,
new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
RealMetadataFactory.createElements(pm1g3,
new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
List<Column> pm1g4e = RealMetadataFactory.createElements(pm1g4,
new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
pm1g4e.get(1).setSelectable(false);
pm1g4e.get(3).setSelectable(false);
List<Column> pm1g5e = RealMetadataFactory.createElements(pm1g5,
new String[] { "e1" }, //$NON-NLS-1$
new String[] { DataTypeManager.DefaultDataTypes.STRING });
pm1g5e.get(0).setSelectable(false);
RealMetadataFactory.createElements(pm1g6,
new String[] { "in", "in3" }, //$NON-NLS-1$ //$NON-NLS-2$
new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
// Create virtual groups
QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1 LIMIT 100"); //$NON-NLS-1$ //$NON-NLS-2$
Table vm1g1 = RealMetadataFactory.createVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
// Create virtual elements
RealMetadataFactory.createElements(vm1g1,
new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
QueryNode vm1g2n1 = new QueryNode("SELECT * FROM vm1.g1 ORDER BY e1"); //$NON-NLS-1$ //$NON-NLS-2$
Table vm1g2 = RealMetadataFactory.createVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
// Create virtual elements
RealMetadataFactory.createElements(vm1g2,
new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
}
@Test public void testLimit() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 limit 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitPushdown() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 limit 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 100" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
}
@Test public void testLimitWithOffset() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testPushedLimitWithOffset() throws Exception {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 150" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitWithOffsetFullyPushed() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 50, 100" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
}
@Test public void testSort() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 order by e1 limit 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
1, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testSortPushed() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
// pm3 model supports order by
capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm3.g1 order by e1 limit 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 ORDER BY pm3.g1.e1" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testSortPushedWithLimit() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
// pm3 model supports order by
capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm3.g1 order by e1 limit 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 ORDER BY pm3.g1.e1 LIMIT 100" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
}
@Test public void testSortUnderLimitNotRemoved() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
// pm3 model supports order by
capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
String sql = "SELECT * FROM (SELECT * FROM pm3.g1 order by e1 limit 100) AS V1 ORDER BY v1.e2";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
0, // Select
2, // Sort
0 // UnionAll
}, NODE_TYPES);
}
//TODO: there is a redundent project node here
@Test public void testSortAboveLimitNotPushed() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM vm1.g2 order by e1";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 100" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, exampleMetadata(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
0, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
0, // Select
1, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitNotPushedWithUnion() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 UNION SELECT * FROM PM1.g2 LIMIT 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM PM1.g2" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
1, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
1 // UnionAll
}, NODE_TYPES);
}
@Test public void testStrictLimitWithUnion() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM (select e2 from pm1.g1 where e1 = 'a') x UNION ALL SELECT e2 FROM PM1.g2 LIMIT 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g2.e2 FROM pm1.g2 LIMIT 100", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
2, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
1, // Select
0, // Sort
1 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitNotPushedWithDupRemove() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT distinct * FROM pm1.g1 LIMIT 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
1, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitPushedWithUnionAll() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 UNION ALL SELECT * FROM PM1.g2 LIMIT 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM PM1.g2 LIMIT 100", "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 100" //$NON-NLS-1$ //$NON-NLS-2$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
1 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitWithOffsetPushedWithUnion() throws Exception {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 UNION ALL SELECT * FROM PM1.g2 LIMIT 50, 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1 AS c_0, pm1.g1.e2 AS c_1, pm1.g1.e3 AS c_2, pm1.g1.e4 AS c_3 FROM pm1.g1 LIMIT 150", "SELECT pm1.g2.e1 AS c_0, pm1.g2.e2 AS c_1, pm1.g2.e3 AS c_2, pm1.g2.e4 AS c_3 FROM pm1.g2 LIMIT 150" //$NON-NLS-1$ //$NON-NLS-2$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
1 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitNotPushedWithUnionOrderBy() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * FROM pm1.g1 UNION SELECT * FROM PM1.g2 ORDER BY e1 LIMIT 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM PM1.g2", "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$ //$NON-NLS-2$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
1 // UnionAll
}, NODE_TYPES);
TestOptimizer.checkNodeTypes(plan, new int[] {1}, new Class[]{DupRemoveSortNode.class});
}
@Test public void testCombinedLimits() throws Exception {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * from (SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 10, 100) x LIMIT 20, 75";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1 AS c_0 FROM pm1.g1 LIMIT 105" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
0, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testCombinedLimitsWithOffset() throws Exception {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
// pm1 model supports order by
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT * from (SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 10, 100) x LIMIT 40, 75";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm1.g1.e1 AS c_0 FROM pm1.g1 LIMIT 10, 60" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
}
@Test public void testInlineView() throws TeiidComponentException, TeiidProcessingException {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
//caps.setCapabilitySupport(SourceCapabilities.QUERY_ORDERBY, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
// pm3 model supports order by
capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
String sql = "SELECT * FROM (SELECT * FROM pm3.g1) as v1 limit 100";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT g_0.e1 AS c_0, g_0.e2 AS c_1, g_0.e3 AS c_2, g_0.e4 AS c_3 FROM pm3.g1 AS g_0 LIMIT 100" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, ComparisonMode.EXACT_COMMAND_STRING);
TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
}
/**
* This turns out to be an important test for LIMIT: there are several nodes
* (e.g. grouping, inline views, aggregates, sorting, joins, etc) that should not be pushed
* down (because they change row order or row count) if there is already a limit node in that plan branch,
* which can only be placed above LIMIT with an inline view. This test acts as a gatekeeper for avoiding
* several of those pushdowns.
* @throws TeiidProcessingException
* @throws TeiidComponentException
*
* @since 4.3
*/
@Test public void testInlineViewAboveLimitNotMerged() throws TeiidComponentException, TeiidProcessingException {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
// pm3 model supports order by
capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
String sql = "SELECT * FROM (SELECT * FROM pm3.g1 limit 100) as v1 order by e1";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT v_0.c_0, v_0.c_1, v_0.c_2, v_0.c_3 FROM (SELECT g_0.e1 AS c_0, g_0.e2 AS c_1, g_0.e3 AS c_2, g_0.e4 AS c_3 FROM pm3.g1 AS g_0 LIMIT 100) AS v_0 ORDER BY c_0" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, ComparisonMode.EXACT_COMMAND_STRING);
TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
}
/**
* since there is no order by with the nested limit, the criteria can be pushed through
*
*/
@Test public void testCriteriaPushedUnderLimit() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
// pm3 model supports order by
capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
String sql = "SELECT * FROM (SELECT * FROM pm3.g1 /*+ non_strict */ limit 100) as v1 where v1.e1 = 1";//$NON-NLS-1$
String[] expectedSql = new String[] {
"SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 WHERE pm3.g1.e1 = '1' LIMIT 100" //$NON-NLS-1$
};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
}
@Test public void testInlineViewJoin() throws TeiidComponentException, TeiidProcessingException {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.QUERY_UNION, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "SELECT x FROM ((SELECT e1 as x FROM pm1.g1 LIMIT 700) c INNER JOIN (SELECT e1 FROM pm1.g2) d ON d.e1 = c.x) order by x LIMIT 5";//$NON-NLS-1$
String[] expectedSql = new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 LIMIT 700", "SELECT g_0.e1 FROM pm1.g2 AS g_0"};//$NON-NLS-1$ //$NON-NLS-2$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, ComparisonMode.EXACT_COMMAND_STRING);
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
1, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
0, // Select
1, // Sort
0 // UnionAll
}, NODE_TYPES);
//test to ensure that the unnecessary inline view removal is done properly
FakeDataManager fdm = new FakeDataManager();
TestProcessor.sampleData1(fdm);
TestProcessor.helpProcess(plan, fdm, new List[] {
Arrays.asList("a"), //$NON-NLS-1$
Arrays.asList("a"), //$NON-NLS-1$
Arrays.asList("a"), //$NON-NLS-1$
Arrays.asList("a"), //$NON-NLS-1$
Arrays.asList("a"), //$NON-NLS-1$
});
}
@Test public void testDontPushSelectWithOrderedLimit() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "select * from (SELECT e1 as x FROM pm1.g1 order by x LIMIT 700) y where x = 1";//$NON-NLS-1$
String[] expectedSql = new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0"};//$NON-NLS-1$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
1, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testDontPushSelectWithOrderedLimit1() {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String sql = "select * from (SELECT e1 as x FROM pm1.g1 order by x LIMIT 10, 700) y where x = 1";//$NON-NLS-1$
String[] expectedSql = new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0"};//$NON-NLS-1$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
1, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testLimitWithNoAccessNode() {
String sql = "select 1 limit 1";//$NON-NLS-1$
String[] expectedSql = new String[] {};
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), expectedSql);
TestOptimizer.checkNodeTypes(plan, new int[] {
0, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
/**
* Note here that the criteria made it to the having clause
*/
@Test public void testAggregateCriteriaOverUnSortedLimit() {
String sql = "select a from (SELECT MAX(e2) as a FROM pm1.g1 GROUP BY e2 /*+ non_strict */ LIMIT 1) x where a = 0"; //$NON-NLS-1$
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
String[] expectedSql = new String[] {"SELECT MAX(e2) FROM pm1.g1 GROUP BY e2 HAVING MAX(e2) = 0 LIMIT 1"};//$NON-NLS-1$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, expectedSql, true);
TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
}
@Test public void testSortWithLimitInlineView() {
String sql = "select e1 from (select pm1.g1.e1, pm1.g1.e2 from pm1.g1 order by pm1.g1.e1, pm1.g1.e2 limit 1) x"; //$NON-NLS-1$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0, g_0.e2"}); //$NON-NLS-1$
TestOptimizer.checkNodeTypes(plan, new int[] {
1, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testCrossJoinLimit() throws Exception {
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
DefaultCapabilitiesFinder capFinder = new DefaultCapabilitiesFinder(caps);
String sql = "select pm1.g1.e1, pm1.g1.e2 from pm1.g1, pm2.g1 limit 5, 5"; //$NON-NLS-1$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT pm2.g1.e1 FROM pm2.g1 LIMIT 10", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 LIMIT 10"}, capFinder, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
1, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
/**
* Note that the limit is not pushed below the select nodes under the join
*/
@Test public void testEffectivelyCrossJoinLimit() throws Exception {
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
DefaultCapabilitiesFinder capFinder = new DefaultCapabilitiesFinder(caps);
String sql = "select pm1.g1.e1, pm1.g1.e2 from pm1.g1, pm2.g1 where pm1.g1.e1 = pm2.g1.e1 and pm1.g1.e1 = 2 limit 5"; //$NON-NLS-1$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT pm2.g1.e1 FROM pm2.g1", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, capFinder, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
3, // Limit
1, // NestedLoopJoinStrategy
0, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
2, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
@Test public void testOuterJoinLimit() throws Exception {
BasicSourceCapabilities caps = new BasicSourceCapabilities();
caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
DefaultCapabilitiesFinder capFinder = new DefaultCapabilitiesFinder(caps);
String sql = "select pm1.g1.e1, pm1.g1.e2 from pm1.g1 left outer join pm2.g1 on pm1.g1.e1 = pm2.g1.e1 limit 5"; //$NON-NLS-1$
ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT pm2.g1.e1 FROM pm2.g1", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 LIMIT 5"}, capFinder, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
TestOptimizer.checkNodeTypes(plan, new int[] {
2, // Access
0, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
0, // Grouping
1, // Limit
0, // NestedLoopJoinStrategy
1, // MergeJoinStrategy
0, // Null
0, // PlanExecution
1, // Project
0, // Select
0, // Sort
0 // UnionAll
}, NODE_TYPES);
}
} |
package erogenousbeef.bigreactors.gui.controls;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import erogenousbeef.bigreactors.client.gui.BeefGuiBase;
import erogenousbeef.bigreactors.common.interfaces.IReactorFuelInfo;
import erogenousbeef.bigreactors.gui.IBeefTooltipControl;
public class BeefGuiFuelMixBar extends BeefGuiVerticalProgressBar implements
IBeefTooltipControl {
IReactorFuelInfo entity;
protected double fuelLeftU = 0.25;
protected double fuelRightU = 0.4999;
protected double wasteLeftU = 0.5;
protected double wasteRightU = 0.7499;
public BeefGuiFuelMixBar(BeefGuiBase container, int x, int y, IReactorFuelInfo entity) {
super(container, x, y);
this.entity = entity;
}
@Override
protected double getBackgroundLeftU() { return 0; }
@Override
protected double getBackgroundRightU() { return 0.2499; }
@Override
protected String getBackgroundTexture() { return "controls/FuelMixBar.png"; }
private final static double maxV = 63.0/64.0;
private final static double minV = 1.0/64.0;
@Override
protected void drawProgressBar(Tessellator tessellator,
TextureManager renderEngine, int barMinX, int barMaxX, int barMinY,
int barMaxY, int zLevel) {
int barMaxHeight = this.height - 1;
int barHeight = Math.max(1, Math.round(getProgress() * barMaxHeight));
double fullness = (double)(entity.getFuelAmount() + entity.getWasteAmount()) / (double)entity.getCapacity();
double fuelProportion = (double)entity.getFuelAmount() / (double)(entity.getFuelAmount() + entity.getWasteAmount());
double wasteProportion = (double)entity.getWasteAmount() / (double)(entity.getFuelAmount() + entity.getWasteAmount());
renderEngine.bindTexture(controlResource);
if(fuelProportion > 0) {
double fuelMinV = 1.0 - fullness*maxV;
double fuelMaxV = maxV;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(this.absoluteX, this.absoluteY + this.height - 1, zLevel, fuelLeftU, fuelMaxV);
tessellator.addVertexWithUV(this.absoluteX + this.width, this.absoluteY + this.height - 1, zLevel, fuelRightU, fuelMaxV);
tessellator.addVertexWithUV(this.absoluteX + this.width, this.absoluteY + this.height - barHeight, zLevel, fuelRightU, fuelMinV);
tessellator.addVertexWithUV(this.absoluteX, this.absoluteY + this.height - barHeight, zLevel, fuelLeftU, fuelMinV);
tessellator.draw();
}
if(wasteProportion > 0) {
double wasteMinV = 1.0 - fullness * wasteProportion * maxV;
double wasteMaxV = maxV;
double wasteHeight = Math.round(barHeight * wasteProportion);
if(wasteHeight > 0) {
double wasteTop = this.absoluteY + this.height - 1 - wasteHeight;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(this.absoluteX, this.absoluteY + this.height - 1, zLevel+1, wasteLeftU, wasteMaxV);
tessellator.addVertexWithUV(this.absoluteX + this.width, this.absoluteY + this.height - 1, zLevel+1, wasteRightU, wasteMaxV);
tessellator.addVertexWithUV(this.absoluteX + this.width, wasteTop, zLevel+1, wasteRightU, wasteMinV);
tessellator.addVertexWithUV(this.absoluteX, wasteTop, zLevel+1, wasteLeftU, wasteMinV);
tessellator.draw();
}
}
}
@Override
public String[] getTooltip() {
float fullness = getProgress() * 100f;
float richness;
if(entity.getFuelAmount() + entity.getWasteAmount() == 0) {
richness = 0f;
}
else {
richness = ((float)entity.getFuelAmount() / (float)(entity.getFuelAmount() + entity.getWasteAmount())) * 100f;
}
return new String[] {
"Reactor Fuel Rods",
String.format(" %2.1f%% full", fullness),
String.format(" %2.1f%% enriched", richness)
};
}
@Override
protected float getProgress() {
return (float)(entity.getFuelAmount() + entity.getWasteAmount()) / (float)entity.getCapacity();
}
} |
// modification, are permitted provided that the following conditions
// are met:
// provided with the distribution.
// * Neither the name of the OWASP nor the names of its
// contributors may be used to endorse or promote products
// derived from this software without specific prior written
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
package org.owasp.encoder.esapi;
import java.io.IOException;
import java.net.URI;
import org.owasp.encoder.Encode;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.codecs.Codec;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.reference.DefaultEncoder;
/**
* ESAPIEncoder is a singleton implementation of the ESAPI Encoder API. It
* is meant to allow quick and easy drop-in replacement of the default
* encoder included with the ESAPI library, as the Encoder libraries are
* faster and use less memory thus cause fewer garbage collections.
*
* <p>Please note that the OWASP Java Encoders does not implement all
* the encodings of the ESAPI Encoder API. In such situations this
* implementation will fallback onto the default reference implementation
* included with ESAPI. Thus you should see the performance benefit from
* the methods included in the Encoder, but still maintain compatibility
* with all methods from ESAPI Encoder.</p>
*
* <p>For clarity, the reason the OWASP Java Encoders do not include some
* of the ESAPI library is that the Encoders library is specifically focused
* on <i>encoding</i>, and thus does not include:</p>
*
* <ul>
* <li>Input validation/normalization methods:
* {@link org.owasp.esapi.Encoder#canonicalize(String)},
* {@link org.owasp.esapi.Encoder#canonicalize(String, boolean)},
* {@link org.owasp.esapi.Encoder#canonicalize(String, boolean, boolean)}
* {@link org.owasp.esapi.Encoder#getCanonicalizedURI(URI)}</li>
*
* <li>Decoding methods:
* {@link org.owasp.esapi.Encoder#decodeForHTML(String)},
* {@link org.owasp.esapi.Encoder#decodeFromURL(String)}</li>
*
* <li>Binary-to-text/text-to-binary:
* {@link org.owasp.esapi.Encoder#encodeForBase64(byte[], boolean)},
* {@link org.owasp.esapi.Encoder#decodeFromBase64(String)}.</li>
*
* <li>Bind-able APIs (such as {@link java.sql.PreparedStatement}:
* {@link org.owasp.esapi.Encoder#encodeForSQL(org.owasp.esapi.codecs.Codec, String)},
* {@link org.owasp.esapi.Encoder#encodeForXPath(String)},
* {@link org.owasp.esapi.Encoder#encodeForOS(org.owasp.esapi.codecs.Codec, String)}</li>
*
* <li>Rarely-used or alternate compatible encoding:
* {@link org.owasp.esapi.Encoder#encodeForVBScript(String)},
* {@link org.owasp.esapi.Encoder#encodeForLDAP(String)},
* {@link org.owasp.esapi.Encoder#encodeForLDAP(String, boolean)},
* {@link org.owasp.esapi.Encoder#encodeForDN(String)}</li>
* </ul>
*
* <p>(Please note that with sufficient feedback from the user base, the above
* mentioned methods may be implemented in future releases of the OWASP
* Java Encoders, if/when that happens, this shim class will be updated to
* call out to the new methods.)</p>
*
* <p>You may notice that this class does not actually implement Encoder
* itself. Instead it simply provides a {@link #getInstance()} method that
* does. This allows the implementation details maximum flexibility by not
* creating a any public API that would restrict changes later</p>
*
* @author jeffi
*/
public final class ESAPIEncoder {
/** No instances. */
private ESAPIEncoder() {}
/**
* Returns an instance of the Encoder. This method is the only supported
* mechanism by which an ESAPIEncoder instance should be obtained. The
* returned implementation is guaranteed to be thread-safe for the methods
* that the OWASP Java Encoders implement (see class documentation).
* Though not a requirement of the ESAPI Encoder API, the returned value
* is also serializable.
*
* @return An encoder implementation that uses the OWASP Java Encoders
* for most of the common encoding methods.
*/
public static Encoder getInstance() {
return Impl.INSTANCE;
}
/**
* This is the private singleton that implements the ESAPI Encoder shim.
* It is implemented as a single-value enum to get all the "free" singleton
* properties associated with enums--such as serialization, and on-demand
* initialization.
*
* <p>The implementation is intentionally private to avoid any API baggage.
* The instance should be obtained using
* {@link org.owasp.encoder.esapi.ESAPIEncoder#getInstance()}.</p>
*/
private enum Impl implements Encoder {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The reference encoder from ESAPI. Any ESAPI method without an
* OWASP Java Encoder equivalent is delegated to this instance.
*/
private final Encoder _referenceEncoder = DefaultEncoder.getInstance();
/** {@inheritDoc} */
public String canonicalize(String s) {
return _referenceEncoder.canonicalize(s);
}
/** {@inheritDoc} */
public String canonicalize(String s, boolean strict) {
return _referenceEncoder.canonicalize(s, strict);
}
/** {@inheritDoc} */
public String canonicalize(String s, boolean restrictMultiple, boolean restrictMixed) {
return _referenceEncoder.canonicalize(s, restrictMultiple, restrictMixed);
}
/** {@inheritDoc} */
public String getCanonicalizedURI(URI dirtyUri) {
return _referenceEncoder.getCanonicalizedURI(dirtyUri);
}
/** {@inheritDoc} */
public String encodeForCSS(String s) {
return Encode.forCssString(s);
}
/** {@inheritDoc} */
public String encodeForHTML(String s) {
return Encode.forHtml(s);
}
/** {@inheritDoc} */
public String decodeForHTML(String s) {
return _referenceEncoder.decodeForHTML(s);
}
/** {@inheritDoc} */
public String encodeForHTMLAttribute(String s) {
return Encode.forHtmlAttribute(s);
}
/** {@inheritDoc} */
public String encodeForJavaScript(String s) {
return Encode.forJavaScript(s);
}
/** {@inheritDoc} */
public String encodeForVBScript(String s) {
return _referenceEncoder.encodeForVBScript(s);
}
/** {@inheritDoc} */
public String encodeForSQL(Codec codec, String s) {
return _referenceEncoder.encodeForSQL(codec, s);
}
/** {@inheritDoc} */
public String encodeForOS(Codec codec, String s) {
return _referenceEncoder.encodeForOS(codec, s);
}
/** {@inheritDoc} */
public String encodeForLDAP(String s) {
return _referenceEncoder.encodeForLDAP(s);
}
/** {@inheritDoc} */
public String encodeForLDAP(String s, boolean b) {
return _referenceEncoder.encodeForLDAP(s, b);
}
/** {@inheritDoc} */
public String encodeForDN(String s) {
return _referenceEncoder.encodeForDN(s);
}
/** {@inheritDoc} */
public String encodeForXPath(String s) {
return _referenceEncoder.encodeForXPath(s);
}
/** {@inheritDoc} */
public String encodeForXML(String s) {
return Encode.forXml(s);
}
/** {@inheritDoc} */
public String encodeForXMLAttribute(String s) {
return Encode.forXmlAttribute(s);
}
/** {@inheritDoc} */
public String encodeForURL(String s) throws EncodingException {
return Encode.forUri(s);
}
/** {@inheritDoc} */
public String decodeFromURL(String s) throws EncodingException {
return _referenceEncoder.decodeFromURL(s);
}
/** {@inheritDoc} */
public String encodeForBase64(byte[] bytes, boolean wrap) {
return _referenceEncoder.encodeForBase64(bytes, wrap);
}
/** {@inheritDoc} */
public byte[] decodeFromBase64(String s) throws IOException {
return _referenceEncoder.decodeFromBase64(s);
}
}
} |
package com.firoj.shabnaz;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import com.firoj.shabnaz.database.Repo;
import com.firoj.shabnaz.database.model.Shabnaz;
import com.firoj.shabnaz.ui.MainActivity;
import com.firoj.shabnaz.ui.SessionManager;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class MySentSmsHandler extends ContentObserver {
private Context mContext;
private String LastsmsID;
public MySentSmsHandler(Context applicationContext){
super(null);
mContext = applicationContext;
}
public void onChange(boolean selfChange){
Cursor cursor = mContext.getContentResolver().query(
Uri.parse("content://sms/sent"), null, null, null, null);
assert cursor != null;
Repo repoObject;
repoObject = MainActivity.getRepo();
if (cursor.moveToNext()) {
long lastId = cursor.getLong(cursor.getColumnIndex("_id"));
SessionManager session = new SessionManager(mContext);
HashMap<String, String> Radious = session.getLastID();
if(Radious!= null)
{
LastsmsID = Radious.get(SessionManager.KEY_LastID);
}
else {
LastsmsID = "0";
}
String ab = Long.toString(lastId);
if(!LastsmsID.equals(Long.toString(lastId)))
{
String protocol = cursor.getString(cursor.getColumnIndex("protocol"));
int type = cursor.getInt(cursor.getColumnIndex("type"));
// Only processing outgoing sms event & only when it
// is sent successfully (available in SENT box).
if (protocol != null || type != 2) {
return;
}
int dateColumn = cursor.getColumnIndex("date");
int bodyColumn = cursor.getColumnIndex("body");
int addressColumn = cursor.getColumnIndex("address");
String from = "9603988968";
String to = cursor.getString(addressColumn);
Date now = new Date(cursor.getLong(dateColumn));
String message = cursor.getString(bodyColumn);
// List<Shabnaz> bb = repoObject.rShabnaz.getAllByAssetsID((int) lastId);
// if(bb != null)
// Shabnaz aa = bb.get(0);
// if(aa.getLastId() != (int) lastId) {
Shabnaz mShabnaz;
mShabnaz = new Shabnaz();
mShabnaz.setMessage(message);
mShabnaz.setSenderNum(to);
mShabnaz.setShabnazID(0);
// mShabnaz.setLastId((int) lastId);
repoObject.rShabnaz.save(mShabnaz);
session.createLastID(Long.toString(lastId));
// List<Shabnaz> aa = repoObject.rShabnaz.getAllWorkOrders(0);
// Shabnaz ShabnazObj = aa.get(0);
// String a = ShabnazObj.getMessage();
// long lastId = cursor.getLong(cursor.getColumnIndex("_id"));
// if (lastId == cursor.getLong(cursor.getColumnIndex("_id")))
// return;
}
}
}
} |
package edu.cmu.neuron2;
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.annotation.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.logging.*;
import java.util.logging.Formatter;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.common.IoSession;
import org.apache.mina.transport.socket.nio.DatagramAcceptor;
import org.apache.mina.transport.socket.nio.DatagramAcceptorConfig;
import edu.cmu.neuron2.RonTest.RunMode;
class LabelFilter implements Filter {
private final HashSet<String> suppressedLabels;
private final boolean suppressAll;
public LabelFilter(HashSet<String> suppressedLabels) {
this.suppressedLabels = suppressedLabels;
this.suppressAll = suppressedLabels.contains("all");
}
public boolean isLoggable(LogRecord record) {
if (suppressAll) return false;
String[] parts = record.getLoggerName().split("\\.", 2);
return parts.length == 1
|| !suppressedLabels.contains(parts[1]);
}
}
public class NeuRonNode extends Thread {
private final ExecutorService executor;
private final ScheduledExecutorService scheduler;
public short myNid;
private final boolean isCoordinator;
private final String coordinatorHost;
private final int basePort;
private final AtomicBoolean doQuit = new AtomicBoolean();
private Logger logger;
/**
* maps node id's to nodestates. this is the primary container.
*/
private final Hashtable<Short, NodeState> nodes = new Hashtable<Short, NodeState>();
/**
* neighbors = rendesvousServers union rendezvousClients. we send our
* routes to all servers in this set.
*/
/**
* maps nid to {the set of rendezvous servers to that nid}
*/
private final Hashtable<Short, HashSet<NodeState>> rendezvousServers = new Hashtable<Short, HashSet<NodeState>>();
/**
* the set of nodes that are relying us to get to someone.
*
* this is needed during route computation. i need to know who to calculate
* routes among, and we want to include rendezvousclients in this set.
*/
private final SortedSet<NodeState> rendezvousClients = new TreeSet<NodeState>();
private NodeState[][] grid;
private Hashtable<NodeState, Short> gridRow = new Hashtable<NodeState, Short>();
private Hashtable<NodeState, Short> gridColumn = new Hashtable<NodeState, Short>();
private short numCols, numRows;
private final Hashtable<InetAddress, Short> addr2id = new Hashtable<InetAddress, Short>();
private final Hashtable<Short, HashSet<NodeState>> defaultRendezvousServers =
new Hashtable<Short, HashSet<NodeState>>();
private short currentStateVersion;
public final int neighborBroadcastPeriod;
public final int probePeriod;
public final int gcPeriod;
private final NodeInfo coordNode;
private final DatagramSocket sendSocket;
private final RunMode mode;
private final short numNodesHint;
private final Semaphore semAllJoined;
private final Random rand = new Random();
private final InetAddress myCachedAddr;
private ArrayList<Short> cachedMemberNids = new ArrayList<Short>(); // sorted list of members
private short cachedMemberNidsVersion;
private final boolean blockJoins;
private final boolean capJoins;
private final int joinRetries; // seconds
private final boolean enableSubpings;
private final int subpingPeriod; // seconds
private final int dumpPeriod;
private final FileHandler fh;
private final short origNid;
private final short sessionId;
private final int linkTimeout;
private final int membershipBroadcastPeriod;
private static final String defaultLabelSet = "subprobe send.Ping recv.Ping stale.Ping send.Pong recv.Pong send.Subprobe recv.Subprobe stale.Pong send.Measurements send.RoutingRecs subprobe";
private final Hashtable<Short,Long> lastSentMbr = new Hashtable<Short,Long>();
private final double smoothingFactor;
private final short resetLatency = Short.MAX_VALUE;
private final Hashtable<Short, NodeInfo> coordNodes = new Hashtable<Short, NodeInfo>();
private final ArrayList<Short> memberNids = new ArrayList<Short>();
private final ArrayList<NodeState> otherNodes = new ArrayList<NodeState>();
private final ArrayList<NodeState> lastRendezvousServers = new ArrayList<NodeState>();
// TODO discard
private final HashSet<NodeState> allDefaultServers = new HashSet<NodeState>();
private Runnable safeRun(final Runnable r) {
return new Runnable() {
public void run() {
try {
synchronized (NeuRonNode.this) {
r.run();
}
} catch (Throwable ex) {
err(ex);
}
}
};
}
private void createLabelFilter(Properties props, String labelSet, Handler handler) {
String[] labels = props.getProperty(labelSet, defaultLabelSet).split(" ");
final HashSet<String> suppressedLabels = new HashSet<String>(Arrays.asList(labels));
handler.setFilter(new LabelFilter(suppressedLabels));
}
private final int joinDelay;
public NeuRonNode(short id, ExecutorService executor, ScheduledExecutorService scheduler,
Properties props, short numNodes, Semaphore semJoined,
InetAddress myAddr, String coordinatorHost, NodeInfo coordNode) {
joinDelay = rand.nextInt(Integer.parseInt(props.getProperty("joinDelayRange", "1")));
if ((coordNode == null) || (coordNode.addr == null)){
throw new RuntimeException("coordNode is null!");
}
dumpPeriod = Integer.parseInt(props.getProperty("dumpPeriod", "60"));
myNid = id;
origNid = id;
cachedMemberNidsVersion = (short)-1;
joinRetries = Integer.parseInt(props.getProperty("joinRetries", "10")); // wait up to 10 secs by default for coord to be available
membershipBroadcastPeriod = Integer.parseInt(props.getProperty("membershipBroadcastPeriod", "0"));
// NOTE note that you'll probably want to set this, always!
sessionId = Short.parseShort(props.getProperty("sessionId", "0"));
blockJoins = Boolean.valueOf(props.getProperty("blockJoins", "true"));
capJoins = Boolean.valueOf(props.getProperty("capJoins", "true"));
this.coordinatorHost = coordinatorHost;
this.coordNode = coordNode;
mode = RunMode.valueOf(props.getProperty("mode", "sim").toUpperCase());
basePort = coordNode.port;
neighborBroadcastPeriod = Integer.parseInt(props.getProperty("neighborBroadcastPeriod", "30"));
gcPeriod = Integer.parseInt(props.getProperty("gcPeriod", neighborBroadcastPeriod + ""));
enableSubpings = Boolean.valueOf(props.getProperty("enableSubpings", "true"));
// for simulations we can safely reduce the probing frequency, or even turn it off
//if (mode == RunMode.SIM) {
//probePeriod = Integer.parseInt(props.getProperty("probePeriod", "60"));
//} else {
probePeriod = Integer.parseInt(props.getProperty("probePeriod", "10"));
subpingPeriod = Integer.parseInt(props.getProperty("subpingPeriod", "" + probePeriod));
membershipTimeout = Integer.parseInt(props.getProperty("timeout", "" + probePeriod * 3));
linkTimeout = Integer.parseInt(props.getProperty("failoverTimeout", "" + membershipTimeout));
scheme = RoutingScheme.valueOf(props.getProperty("scheme", "SQRT").toUpperCase());
smoothingFactor = Double.parseDouble(props.getProperty("smoothingFactor", "0.1"));
Formatter minfmt = new Formatter() {
public String format(LogRecord record) {
StringBuilder buf = new StringBuilder();
buf.append(record.getMillis()).append(' ')/*.append(new Date(record.getMillis())).append(" ").append(
record.getLevel()).append(" ")*/.append(
record.getLoggerName()).append(": ").append(
record.getMessage()).append("\n");
return buf.toString();
}
};
Formatter fmt = new Formatter() {
public String format(LogRecord record) {
StringBuilder buf = new StringBuilder();
buf.append(record.getMillis()).append(' ').append(new Date(record.getMillis())).append(" ").append(
record.getLevel()).append(" ").append(
record.getLoggerName()).append(": ").append(
record.getMessage()).append("\n");
return buf.toString();
}
};
Logger rootLogger = Logger.getLogger("");
rootLogger.getHandlers()[0].setFormatter(fmt);
logger = Logger.getLogger("node" + myNid);
createLabelFilter(props, "consoleLogFilter", rootLogger.getHandlers()[0]);
try {
String logFileBase = props.getProperty("logFileBase", "%t/scaleron-log-");
fh = new FileHandler(logFileBase + myNid, true);
fh.setFormatter(fmt);
createLabelFilter(props, "fileLogFilter", fh);
logger.addHandler(fh);
sendSocket = new DatagramSocket();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
this.executor = executor;
this.scheduler = scheduler;
grid = null;
numCols = numRows = 0;
isCoordinator = myNid == 0;
currentStateVersion = (short) (isCoordinator ? 0 : -1);
numNodesHint = Short.parseShort(props.getProperty("numNodesHint", "" + numNodes));
semAllJoined = semJoined;
if (myAddr == null) {
try {
myCachedAddr = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
throw new RuntimeException(ex);
}
}
else {
myCachedAddr = myAddr;
}
myPort = basePort + myNid;
clientTimeout = Integer.parseInt(props.getProperty("clientTimeout", "" + 3 * neighborBroadcastPeriod));
}
private final int myPort;
private void handleInit(Init im) {
if (im.id == -1) {
throw new PlannedException("network is full; aborting");
}
System.out.println("Had nodeId = " + myNid + ". New nodeId = " + im.id);
myNid = im.id;
logger = Logger.getLogger("node_" + myNid);
if (logger.getHandlers().length == 0) {
logger.addHandler(fh);
}
currentStateVersion = im.version;
log("got from coord => Init version " + im.version);
updateMembers(im.members);
}
private String bytes2string(byte[] buf) {
String s = "[ ";
for (byte b : buf) {
s += b + " ";
}
s += "]";
return s;
}
private void log(String msg) {
logger.info(msg);
}
private void warn(String msg) {
logger.warning(msg);
}
private void err(String msg) {
logger.severe(msg);
}
private void err(Throwable ex) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
ex.printStackTrace(p);
err(s.toString());
}
/**
* Used for logging data, such as neighbor lists.
*
* @param name - the name of the data, e.g.: "neighbors", "info"
* @param value
*/
private void log(String name, Object value) {
Logger.getLogger(logger.getName() + "." + name).info(value.toString());
}
public static final class PlannedException extends RuntimeException {
public PlannedException(String msg) {
super(msg);
}
}
public final AtomicReference<Exception> failure = new AtomicReference<Exception>();
public void run() {
try {
run3();
} catch (PlannedException ex) {
warn(ex.getMessage());
failure.set(ex);
if (semAllJoined != null) semAllJoined.release();
} catch (Exception ex) {
err(ex);
failure.set(ex);
if (semAllJoined != null) semAllJoined.release();
}
}
/**
* Similar to fixed-rate scheduling, but doesn't try to make up multiple
* overdue items, but rather allows us to skip over them. This should deal
* better with PLab's overloaded hosts.
*
* @param r The runnable task.
* @param initialDelay The initial delay in seconds.
* @param period The period in seconds.
*/
private ScheduledFuture<?> safeSchedule(final Runnable r, long initialDelay, final long period) {
final long bufferTime = 1000; // TODO parameterize
return scheduler.schedule(new Runnable() {
private long scheduledTime = -1;
public void run() {
if (scheduledTime < 0) scheduledTime = System.currentTimeMillis();
r.run();
long now = System.currentTimeMillis();
scheduledTime = Math.max(scheduledTime + period * 1000, now + bufferTime);
scheduler.schedule(this, scheduledTime - now, TimeUnit.MILLISECONDS);
}
}, initialDelay, TimeUnit.SECONDS);
}
private boolean hasJoined = false;
public void run3() {
if (isCoordinator) {
try {
safeSchedule(safeRun(new Runnable() {
public void run() {
log("checkpoint: " + coordNodes.size() + " nodes");
printMembers();
//printGrid();
}
}), dumpPeriod, dumpPeriod);
new DatagramAcceptor().bind(new InetSocketAddress(InetAddress
.getLocalHost(), basePort), new CoordReceiver());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
try {
final Receiver receiver = new Receiver();
new DatagramAcceptor().bind(new InetSocketAddress(myCachedAddr, myPort),
receiver);
log("server started on " + myCachedAddr + ":" + (basePort + myNid));
safeSchedule(safeRun(new Runnable() {
public void run() {
if (hasJoined) {
pingAll();
}
}
}), 1, probePeriod);
safeSchedule(safeRun(new Runnable() {
public void run() {
if (hasJoined) {
/*
* path-finding and rendezvous finding is
* interdependent. the fact that we do the path-finding
* first before the rendezvous servers is arbitrary.
*/
Pair<Integer, Integer> p = findPathsForAllNodes();
log(p.first
+ " live nodes, "
+ p.second
+ " avg paths, "
+ nodes.get(myNid).latencies.keySet()
.size() + " direct paths");
ArrayList<NodeState> measRecips = scheme == RoutingScheme.SIMPLE ? getAllReachableNodes()
: getAllRendezvousServers();
broadcastMeasurements(measRecips);
if (scheme != RoutingScheme.SIMPLE) {
broadcastRecommendations();
}
}
}
}), 7, neighborBroadcastPeriod);
if (enableSubpings) {
safeSchedule(safeRun(new Runnable() {
public void run() {
subping();
}
}), 5, subpingPeriod);
// TODO should these initial offsets be constants?
}
safeSchedule(new Runnable() {
public void run() {
System.gc();
}
}, 3, gcPeriod);
final InetAddress coordAddr = InetAddress.getByName(coordinatorHost);
scheduler.schedule(safeRun(new Runnable() {
private int count = 0;
public void run() {
if (count > joinRetries) {
warn("exceeded max tries!");
System.exit(0);
} else if (!hasJoined) {
log("sending join to coordinator at "
+ coordinatorHost + ":" + basePort
+ " (try " + count++ + ")");
Join msg = new Join();
msg.addr = myCachedAddr;
msg.src = myNid; // informs coord of orig id
msg.port = myPort;
sendObject(msg, coordAddr, basePort, (short)-1);
log("waiting for InitMsg");
scheduler.schedule(this, 10, TimeUnit.SECONDS);
}
}
}), joinDelay, TimeUnit.SECONDS);
if (semAllJoined != null) semAllJoined.release();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private final HashSet<Short> ignored = new HashSet<Short>();
public synchronized void ignore(short nid) {
if (nid != myNid) {
log("ignoring " + nid);
ignored.add(nid);
}
}
public synchronized void unignore(short nid) {
if (nid != myNid) {
log("unignoring " + nid);
ignored.remove(nid);
}
}
private ArrayList<NodeState> getAllReachableNodes() {
ArrayList<NodeState> nbrs = new ArrayList<NodeState>();
for (NodeState n : otherNodes)
if (n.isReachable)
nbrs.add(n);
return nbrs;
}
private static final byte SUBPING = 0, SUBPING_FWD = 1, SUBPONG = 2,
SUBPONG_FWD = 3;
private Subprobe subprobe(short nid, long time, byte type) {
Subprobe p = new Subprobe();
p.nid = nid;
p.time = time;
p.type = type;
return p;
}
private void subping() {
Set<Map.Entry<Short,NodeState>> entries = nodes.entrySet();
List<Short> nids = new ArrayList<Short>();
int bytes = 0;
for (Map.Entry<Short,NodeState> entry : entries) {
short nid = entry.getKey();
short hop = entry.getValue().hop;
long time = System.currentTimeMillis();
if (nid != myNid && hop != 0) {
bytes += sendObject(subprobe(nid, time, SUBPING), hop);
nids.add(nid);
}
}
log("sent subpings " + bytes + " bytes, to " + nids);
}
private void handleSubping(Subprobe p) {
if (p.nid == myNid && nodes.containsKey(p.src)) {
sendObject(subprobe(p.nid, p.time, SUBPONG_FWD), p.src);
log("subprobe", "direct subpong from/to " + p.src);
} else if (nodes.containsKey(p.nid) && nodes.containsKey(p.src)) {
// we also checked for p.src because eventually we'll need to
// forward the subpong back too; if we don't know him, no point in
// sending a subping
sendObject(subprobe(p.src, p.time, SUBPING_FWD), p.nid);
log("subprobe", "subping fwd from " + p.src + " to " + p.nid);
}
}
private void handleSubpingFwd(Subprobe p) {
if (nodes.containsKey(p.src)) {
sendObject(subprobe(p.nid, p.time, SUBPONG), p.src);
log("subprobe", "subpong to " + p.nid + " via " + p.src);
}
}
private void handleSubpong(Subprobe p) {
if (nodes.containsKey(p.nid)) {
sendObject(subprobe(p.src, p.time, SUBPONG_FWD), p.nid);
log("subprobe", "subpong fwd from " + p.src + " to " + p.nid);
}
}
private void handleSubpongFwd(Subprobe p) {
long latency = (System.currentTimeMillis() - p.time) / 2;
log("subpong from " + p.nid + " via " + p.src + ": " + latency + ", time " + p.time);
}
private void pingAll() {
log("pinging");
Ping ping = new Ping();
ping.time = System.currentTimeMillis();
NodeInfo tmp = nodes.get(myNid).info;
ping.info = new NodeInfo();
ping.info.id = origNid; // note that the ping info uses the original id
ping.info.addr = tmp.addr;
ping.info.port = tmp.port;
for (short nid : nodes.keySet())
if (nid != myNid)
sendObject(ping, nid);
/* send ping to the membership server (co-ord) -
this might not be required if everone makes their own local decision.
i.e. each node notices that no other node can reach a node (say X),
then each node sends the co-ord a msg saying that "i think X is dead".
The sending of this msg can be staggered in time so that the co-ord is not flooded with mesgs.
The co-ordinator can then make a decision on keeping or removing node Y from the membership.
On seeing a subsequent msg from the co-ord that X has been removed from the overlay, if a node Y
has not sent its "i think X is dead" msg, it can cancel this event.
*/
sendObject(ping, (short)0);
}
private Msg deserialize(Object o) {
ByteBuffer buf = (ByteBuffer) o;
byte[] bytes = new byte[buf.limit()];
buf.get(bytes);
try {
return (Msg) new Serialization().deserialize(new DataInputStream(new
ByteArrayInputStream(bytes)));
} catch (Exception ex) {
err("deserialization exception: " + ex.getMessage());
return null;
}
}
private Hashtable<Short,Short> id2oid = new Hashtable<Short,Short>();
private Hashtable<Short,String> id2name = new Hashtable<Short,String>();
/**
* coordinator's msg handling loop
*/
public final class CoordReceiver extends IoHandlerAdapter {
/**
* Generates non-repeating random sequence of short IDs, and keeps
* track of how many are emitted.
*/
public final class IdGenerator {
private final Iterator<Short> iter;
private short counter;
public IdGenerator() {
List<Short> list = new ArrayList<Short>();
for (short s = 1; s < Short.MAX_VALUE; s++) {
list.add(s);
}
Collections.shuffle(list);
iter = list.iterator();
}
public short next() {
counter++;
return iter.next();
}
public short count() {
return counter;
}
}
private IdGenerator nidGen = new IdGenerator();
private void sendInit(short nid, Join join) {
Init im = new Init();
im.id = nid;
im.members = getMemberInfos();
sendObject(im, join.addr, join.port, (short)-1);
}
@Override
public void messageReceived(IoSession session, Object obj)
throws Exception {
try {
Msg msg = deserialize(obj);
if (msg == null) return;
synchronized (NeuRonNode.this) {
if (msg.session == sessionId) {
if (msg instanceof Join) {
final Join join = (Join) msg ;
if (id2oid.values().contains(msg.src)) {
// we already added this guy; just resend him the init msg
sendInit(addr2id.get(join.addr), join);
} else {
// need to add this guy and send him the init msg (if there's space)
if (!capJoins || coordNodes.size() < numNodesHint) {
short newNid = nidGen.next();
addMember(newNid, join.addr, join.port, join.src);
if (blockJoins) {
if (coordNodes.size() >= numNodesHint) {
// time to broadcast ims to everyone
ArrayList<NodeInfo> memberList = getMemberInfos();
for (NodeInfo m : memberList) {
Init im = new Init();
im.id = m.id;
im.members = memberList;
sendObject(im, m);
}
}
} else {
sendInit(newNid, join);
broadcastMembershipChange(newNid);
}
if (coordNodes.size() == numNodesHint) {
semAllJoined.release();
}
} else if (capJoins && coordNodes.size() == numNodesHint) {
Init im = new Init();
im.id = -1;
im.members = new ArrayList<NodeInfo>();
sendObject(im, join.addr, join.port, (short)-1);
}
}
} else if (coordNodes.containsKey(msg.src)) {
log("recv." + msg.getClass().getSimpleName(), "from " +
msg.src + " (oid " + id2oid.get(msg.src) + ", "
+ id2name.get(msg.src) + ")");
resetTimeoutAtCoord(msg.src);
if (msg.version < currentStateVersion) {
// this includes joins
log("updating stale membership");
sendMembership(msg.src);
} else if (msg instanceof Ping) {
// ignore the ping
} else {
throw new Exception("can't handle message type here: " + msg.getClass().getName());
}
} else {
if ((!capJoins || coordNodes.size() < numNodesHint) &&
msg instanceof Ping) {
Ping ping = (Ping) msg;
log("dead." + ping.getClass().getSimpleName(),
"from '" + ping.src + "' " + ping.info.addr.getHostName());
Short mappedId = addr2id.get(ping.info.addr);
short nid;
if (mappedId == null) {
nid = nidGen.next();
addMember(nid, ping.info.addr,
ping.info.port, ping.info.id);
broadcastMembershipChange(nid);
} else {
nid = mappedId;
}
Init im = new Init();
im.id = nid;
im.src = myNid;
im.version = currentStateVersion;
im.members = getMemberInfos();
sendObject(im, nid);
} else {
log("dead." + msg.getClass().getSimpleName(), "from '" + msg.src + "'");
}
}
}
}
} catch (Exception ex) {
err(ex);
}
}
}
/**
* receiver's msg handling loop
*/
public final class Receiver extends IoHandlerAdapter {
@Override
public void sessionCreated(IoSession session) throws Exception {
// TODO Auto-generated method stub
super.sessionCreated(session);
}
@Override
public void sessionOpened(IoSession session) throws Exception {
// TODO Auto-generated method stub
super.sessionOpened(session);
}
@Override
public void messageReceived(IoSession session, Object obj)
throws Exception {
try {
Msg msg = deserialize(obj);
if (msg == null) return;
synchronized (NeuRonNode.this) {
if ((msg.src == 0 || nodes.containsKey(msg.src) || msg instanceof Ping)
&& msg.session == sessionId) {
NodeState state = nodes.get(msg.src);
log("recv." + msg.getClass().getSimpleName(), "from "
+ msg.src + " len " + ((ByteBuffer) obj).limit());
// always reply to pings and log pongs
if (msg instanceof Ping) {
Ping ping = ((Ping) msg);
Pong pong = new Pong();
pong.time = ping.time;
sendObject(pong, ping.info);
} else if (msg instanceof Pong) {
Pong pong = (Pong) msg;
long rawRtt = System.currentTimeMillis() - pong.time;
// if the rtt was astronomical, just treat it as a dropped packet
if (rawRtt / 2 < Short.MAX_VALUE) {
// we define "latency" as rtt/2; this should be
// a bigger point near the top of this file
short latency = (short) (rawRtt / 2);
if (state != null) {
resetTimeoutAtNode(pong.src);
NodeState self = nodes.get(myNid);
short oldLatency = self.latencies.get(pong.src);
final short ewma;
if (oldLatency == resetLatency) {
ewma = latency;
} else {
ewma = (short) (smoothingFactor * latency +
(1 - smoothingFactor) * oldLatency);
}
log("latency", pong.src + " = " + latency +
", ewma " + ewma + ", time " +
pong.time);
self.latencies.put(pong.src, ewma);
} else {
log("latency", "some " + pong.src + " = " + latency);
}
}
} else if (msg instanceof Subprobe) {
Subprobe p = (Subprobe) msg;
switch (p.type) {
case SUBPING: handleSubping(p); break;
case SUBPING_FWD: handleSubpingFwd(p); break;
case SUBPONG: handleSubpong(p); break;
case SUBPONG_FWD: handleSubpongFwd(p); break;
default: assert false;
}
}
// for other messages, make sure their state version is
// the same as ours
if (msg.version > currentStateVersion) {
if (msg instanceof Membership && hasJoined) {
currentStateVersion = msg.version;
Membership m = (Membership) msg;
assert myNid == m.yourId;
updateMembers(m.members);
} else if (msg instanceof Init) {
hasJoined = true;
if (semAllJoined != null)
semAllJoined.release();
if (((Init) msg).id == -1)
session.close();
handleInit((Init) msg);
} else {
// i am out of date - wait until i am updated
}
} else if (msg.version == currentStateVersion) {
// from coordinator
if (msg instanceof Membership) {
Membership m = (Membership) msg;
assert myNid == m.yourId;
updateMembers(m.members);
} else if (msg instanceof Measurements) {
resetTimeoutOnRendezvousClient(msg.src);
updateMeasurements((Measurements) msg);
} else if (msg instanceof RoutingRecs) {
RoutingRecs recs = (RoutingRecs) msg;
handleRecommendations(recs);
log("got recs " + routesToString(recs.recs));
} else if (msg instanceof Ping ||
msg instanceof Pong ||
msg instanceof Subprobe ||
msg instanceof Init) {
// nothing to do, already handled above
} else {
throw new Exception("can't handle that message type");
}
} else {
log("stale." + msg.getClass().getSimpleName(),
"from " + msg.src + " version "
+ msg.version + " current "
+ currentStateVersion);
}
} else {
// log("ignored." + msg.getClass().getSimpleName(), "ignored from " + msg.src + " session " + msg.session);
}
}
} catch (Exception ex) {
err(ex);
}
}
}
/**
* If we don't hear from a node for this number of seconds, then consider
* them dead.
*/
private int membershipTimeout;
private Hashtable<Short, ScheduledFuture<?>> timeouts = new Hashtable<Short, ScheduledFuture<?>>();
/**
* a coord-only method
*
* @param nid
*/
private void resetTimeoutAtCoord(final short nid) {
if (coordNodes.containsKey(nid)) {
ScheduledFuture<?> oldFuture = timeouts.get(nid);
if (oldFuture != null) {
oldFuture.cancel(false);
}
ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() {
public void run() {
removeMember(nid);
}
}), membershipTimeout, TimeUnit.SECONDS);
timeouts.put(nid, future);
}
}
private final int clientTimeout;
private final Hashtable<Short, ScheduledFuture<?>> rendezvousClientTimeouts = new Hashtable<Short, ScheduledFuture<?>>();
private void resetTimeoutOnRendezvousClient(final short nid) {
final NodeState node = nodes.get(nid);
if (!node.isReachable) return;
ScheduledFuture<?> oldFuture = rendezvousClientTimeouts.get(nid);
if (oldFuture != null) {
oldFuture.cancel(false);
}
if (rendezvousClients.add(node)) {
log("rendezvous client " + node + " added");
}
ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() {
public void run() {
if (rendezvousClients.remove(node)) {
log("rendezvous client " + node + " removed");
}
}
}), clientTimeout, TimeUnit.SECONDS);
rendezvousClientTimeouts.put(nid, future);
}
private void resetTimeoutAtNode(final short nid) {
if (nodes.containsKey(nid)) {
ScheduledFuture<?> oldFuture = timeouts.get(nid);
if (oldFuture != null) {
oldFuture.cancel(false);
}
final NodeState node = nodes.get(nid);
if (!node.isReachable) {
log(nid + " reachable");
if (node.hop == 0) {
node.isHopRecommended = false;
node.cameUp = true;
node.hop = nid;
}
}
node.isReachable = true;
ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() {
public void run() {
if (nodes.containsKey(nid)) {
log(nid + " unreachable");
node.isReachable = false;
nodes.get(myNid).latencies.remove(nid);
rendezvousClients.remove(node);
findPaths(node, false);
}
}
}), linkTimeout, TimeUnit.SECONDS);
timeouts.put(nid, future);
}
}
/**
* a coordinator-only method
*/
private NodeInfo addMember(short newNid, InetAddress addr, int port, short origId) {
NodeInfo info = new NodeInfo();
info.id = newNid;
info.addr = addr;
info.port = port;
coordNodes.put(newNid, info);
id2oid.put(newNid, origId);
id2name.put(newNid, addr.getHostName());
addr2id.put(addr, newNid);
log("adding new node: " + newNid + " oid " + origId + " name " +
id2name.get(newNid));
currentStateVersion++;
resetTimeoutAtCoord(newNid);
return info;
}
private final AtomicBoolean membersChanged = new AtomicBoolean();
/**
* a coordinator-only method
*
* @param exceptNid - if this is 0, then we must have been called by the
* periodic membership-broadcast daemon thread, so actually send stuff;
* otherwise, we should just signal to the daemon thread a pending change
*/
private void broadcastMembershipChange(short exceptNid) {
if (exceptNid == 0 || membershipBroadcastPeriod == 0) {
for (short nid : coordNodes.keySet()) {
if (nid != exceptNid) {
sendMembership(nid);
}
}
}
}
ArrayList<NodeInfo> getMemberInfos() {
return new ArrayList<NodeInfo>(coordNodes.values());
}
/**
* a coordinator-only method
*
* throttles these messages so they're sent at most once per second
*/
private void sendMembership(short nid) {
Membership msg = new Membership();
msg.yourId = nid;
msg.members = getMemberInfos();
sendObject(msg, coordNodes.get(nid));
}
/**
* a coordinator-only method
*
* NOTE: there is a hack workaround here for sim mode, because addr2id is
* not storing unique host:port combos, only unique hosts.
*
* @param nid
*/
private void removeMember(short nid) {
log("removing dead node " + nid + " oid " + id2oid.get(nid) + " " +
id2name.get(nid));
id2oid.remove(nid);
NodeInfo info = coordNodes.remove(nid);
Short mid = addr2id.remove(info.addr);
if (mode != RunMode.SIM)
assert mid != null;
currentStateVersion++;
broadcastMembershipChange(nid);
}
/**
* updates our member state. modifies data structures as necessary to
* maintain invariants.
*
* @param newNodes
*/
private void updateMembers(List<NodeInfo> newNodes) {
// add new nodes
for (NodeInfo node : newNodes)
if (!nodes.containsKey(node.id)) {
nodes.put(node.id, new NodeState(node));
if (node.id != myNid)
resetTimeoutAtNode(node.id);
}
// remove nodes
HashSet<Short> newNids = new HashSet<Short>();
for (NodeInfo node : newNodes)
newNids.add(node.id);
HashSet<Short> toRemove = new HashSet<Short>();
for (Short nid : nodes.keySet())
if (!newNids.contains(nid))
toRemove.add(nid);
for (Short nid : toRemove)
nodes.remove(nid);
// consistency cleanups: check that all nid references are still valid nid's
for (NodeState state : nodes.values()) {
if (state.hop != 0 && !newNids.contains(state.hop)) {
state.hop = state.info.id;
state.isHopRecommended = false;
}
for (Iterator<Short> i = state.hopOptions.iterator(); i.hasNext();)
if (!newNids.contains(i.next()))
i.remove();
HashSet<Short> garbage = new HashSet<Short>();
for (short nid : state.latencies.keySet())
if (!newNids.contains(nid))
garbage.add(nid);
for (short nid : garbage)
state.latencies.remove(nid);
}
// regenerate alternative views of this data
NodeState self = nodes.get(myNid);
assert self != null;
memberNids.clear();
memberNids.addAll(newNids);
Collections.sort(memberNids);
otherNodes.clear();
otherNodes.addAll(nodes.values());
otherNodes.remove(self);
numCols = (short) Math.ceil(Math.sqrt(nodes.size()));
numRows = (short) Math.ceil((double) nodes.size() / (double) numCols);
grid = new NodeState[numRows][numCols];
gridRow.clear();
gridColumn.clear();
List<Short> nids = memberNids;
for (short i = 0, r = 0; r < numRows; r++)
for (short c = 0; c < numCols; c++) {
grid[r][c] = nodes.get(nids.get(i++ % nids.size()));
gridRow.put(grid[r][c], r);
gridColumn.put(grid[r][c], c);
}
/*
* simply forget about all our neighbors. thus, this forgets all our
* failover clients and servers. since the grid is different. if this
* somehow disrupts route computation, so be it - it'll only last for a
* period.
*
* one worry is that others who miss this member update will continue to
* broadcast to us. this is a non-issue because we ignore stale
* messages, and when they do become updated, they'll forget about us
* too.
*
* this should correctly handle nodes that reappear in the grid.
*/
rendezvousClients.clear();
defaultRendezvousServers.clear();
int rz = gridRow.get(self);
int cz = gridColumn.get(self);
HashSet<NodeState> rendezvousClientRow = new HashSet<NodeState>();
HashSet<NodeState> rendezvousClientCol = new HashSet<NodeState>();
// add this column and row as clients
for (int r1 = 0; r1 < numRows; r1++) {
NodeState cli = grid[r1][cz];
if (cli.isReachable && cli != self)
rendezvousClientCol.add(cli);
}
for (int c1 = 0; c1 < numCols; c1++) {
NodeState cli = grid[rz][c1];
if (cli.isReachable && cli != self)
rendezvousClientRow.add(cli);
}
rendezvousClients.addAll(rendezvousClientRow);
rendezvousClients.addAll(rendezvousClientCol);
// Put timeouts for all new rendezvous clients. If they can never
// reach us, we should stop sending them recommendations.
for (final NodeState clientNode : rendezvousClients) {
ScheduledFuture<?> oldFuture = rendezvousClientTimeouts.get(clientNode.info.id);
if (oldFuture != null) {
oldFuture.cancel(false);
}
ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() {
public void run() {
if (rendezvousClients.remove(clientNode)) {
log("rendezvous client " + clientNode + " removed");
}
}
}), clientTimeout, TimeUnit.SECONDS);
rendezvousClientTimeouts.put(clientNode.info.id, future);
}
// add the rendezvous servers to all nodes
for (int r0 = 0; r0 < numRows; r0++) {
for (int c0 = 0; c0 < numCols; c0++) {
NodeState dst = grid[r0][c0];
HashSet<NodeState> rs = defaultRendezvousServers.get(dst.info.id);
if (rs == null) {
rs = new HashSet<NodeState>();
defaultRendezvousServers.put(dst.info.id, rs);
}
if (r0 != rz && c0 != cz) {
// normally, add the pairs
if (self != grid[rz][c0])
rs.add(grid[rz][c0]);
if (self != grid[r0][cz])
rs.add(grid[r0][cz]);
} else if (c0 == cz) {
/*
* if this is in our col (a neighbor), everyone
* else in that col is in essence a rendezvous
* server between us two
*/
rs.addAll(rendezvousClientCol);
} else if (r0 == rz) {
/*
* ditto for rows
*/
rs.addAll(rendezvousClientRow);
}
}
}
rendezvousServers.clear();
for (Entry<Short, HashSet<NodeState>> entry : defaultRendezvousServers.entrySet()) {
rendezvousServers.put(entry.getKey(), new HashSet<NodeState>());
}
lastRendezvousServers.clear();
allDefaultServers.clear();
allDefaultServers.addAll(rendezvousClients);
for (int r0 = 0; r0 < numRows; r0++) {
for (int c0 = 0; c0 < numCols; c0++) {
NodeState n = grid[r0][c0];
for (int r1 = 0; r1 < numRows; r1++)
n.defaultClients.add(grid[r1][c0]);
for (int c1 = 0; c1 < numCols; c1++)
n.defaultClients.add(grid[r0][c1]);
n.defaultClients.remove(self);
}
}
log("state " + currentStateVersion + ", mbrs " + nids);
}
/**
* @param n
* @param remoteNid
* @return
*/
private boolean isFailedRendezvous(NodeState n, NodeState remote) {
return !n.isReachable || n.remoteFailures.contains(remote);
}
/**
* @return failoverClients `union` nodes in my row and col (wherever i occur)
*/
private ArrayList<NodeState> getAllRendezvousClients() {
ArrayList<NodeState> list = new ArrayList<NodeState>(rendezvousClients);
Collections.sort(list);
return list;
}
private String mkString(HashSet<NodeState> ns, String glue) {
String s = "";
for (NodeState n : ns) {
s += n.info.id + glue;
}
return s;
}
/**
* makes one pass over the metaset of all rendezvous servers, removing any
* failed rendezvous from the individual sets.
*
* for the simple routing scheme, this is the full set of nodes. as a
* result, measurements are broadcast to everyone, as intended. (note that
* there are no routing recommendation messages in this scheme.)
*
* OLD ALGO
*
* for dst
* if dst is not down
* rs = dst's current rendezvous servers
* ds = dst's default rendezvous servers
* if any of ds are working to dst and rs is not ds
* rs = working subset of ds
* if rs = []
* rs += random node from dst's row/col
* else
* rs -= any failed rs
* note that this may leave rs empty for the coming round
* this is what we want bc it will delay failover-finding till the next round
*
* NEW ALGO
*
* // CHANGES START
* build a rowmap (row -&rt; set(rendezvous)) and colmap
* call these F
* // CHANGES END
* for dst
* if dst is not down
* rs = dst's current rendezvous servers
* ds = dst's default rendezvous servers
* if any of ds are working to dst and rs is not ds
* rs = working subset of ds
* if rs = []
* // CHANGES START
* for active failover in dst's row/col (according to F)
* if failover works to dst, choose it as failover for dst as well
* choose rand node from dst's row/col that is not currently in use
* rs += whatever we chose; F += whatever we chose
* // CHANGES END
* else
* rs -= any failed rs
* note that this may leave rs empty for the coming round
* this is what we want bc it will delay failover-finding till the next round
*
* @return the union of all the sets of non-failed rendezvous servers.
*/
private ArrayList<NodeState> getAllRendezvousServers() {
// first, prepare the rowmap and colmap so that we can share/reuse
// rendezvous servers
Hashtable<Integer, HashSet<NodeState>> colmap = new Hashtable<Integer, HashSet<NodeState>>();
Hashtable<Integer, HashSet<NodeState>> rowmap = new Hashtable<Integer, HashSet<NodeState>>();
HashSet<NodeState> allDefaults = new HashSet<NodeState>();
for (HashSet<NodeState> d : defaultRendezvousServers.values()) {
allDefaults.addAll(d);
}
for (int r = 0; r < numRows; r++) {
rowmap.put(r, new HashSet<NodeState>());
}
for (int c = 0; c < numCols; c++) {
colmap.put(c, new HashSet<NodeState>());
}
for (int r = 0; r < numRows; r++) {
for (int c = 0; c < numCols; c++) {
for (NodeState n : rendezvousServers.get(grid[r][c].info.id)) {
// if this is an actual failover
if (!allDefaults.contains(n)) {
// n will be in either row r or column c, not both
rowmap.get(gridRow.get(n)).add(n);
colmap.get(gridColumn.get(n)).add(n);
}
}
}
}
// these are the rendezvous servers that we want to sent our
// measurements to
HashSet<NodeState> servers = new HashSet<NodeState>();
NodeState self = nodes.get(myNid);
for (int r0 = 0; r0 < numRows; r0++) {
for (int c0 = 0; c0 < numCols; c0++) {
NodeState dst = grid[r0][c0];
// if dst is not us and we believe that the node is not down
if (dst != self && dst.hop != 0 &&
!(dst.info.id == grid[0][0].info.id && r0 != 0 && c0 != 0)) {
// this is our current (active) set of rendezvous servers
HashSet<NodeState> rs = rendezvousServers.get(dst.info.id);
// check if any of our default rendezvous servers are once
// more available; if so, add them back
HashSet<NodeState> defaults = defaultRendezvousServers.get(dst.info.id);
// we always want to try talking to our default rendezvous
// servers if we think they're reachable
for (NodeState r : defaults)
if (r.isReachable)
servers.add(r);
// rs consists of either default rendezvous servers or
// non-default rendezvous, but never a mix of both; test
// which type it is
boolean hasDefaultsOnly = rs.isEmpty() ?
true : defaults.contains(rs.iterator().next());
// the following code attempts to add default rendezvous
// servers back into rs
HashSet<NodeState> old = new HashSet<NodeState>(rs);
if (hasDefaultsOnly) {
// if any default rendezvous servers are in use, then
// don't clear rs; simply add any more default servers
// that are working
if (!defaults.equals(rs))
for (NodeState r : defaults)
if (!isFailedRendezvous(r, dst))
rs.add(r);
} else {
// if no default rendezvous servers are in use, then
// try adding any that are working; if any are working,
// we make sure to first clear rs
boolean cleared = false;
for (NodeState r : defaults) {
if (!isFailedRendezvous(r, dst)) {
if (!cleared) {
rs.clear();
cleared = true;
}
rs.add(r);
}
}
}
if (!old.equals(rs)) {
log("restored rendezvous server for " + dst + " from " + old + " to " + rs);
}
if (rs.isEmpty() && scheme != RoutingScheme.SQRT_NOFAILOVER) {
// create debug string
String s = "defaults";
for (NodeState r : defaults) {
s += " " + r.info.id + (
!r.isReachable ? " unreachable" :
" <-/-> " + mkString(r.remoteFailures, ",") );
}
final String report = s;
// look for failovers
HashSet<NodeState> cands = new HashSet<NodeState>();
// first, start by looking at the failovers that are
// currently in use for this col/row, so that we can
// share when possible. that is, if we know that a
// failover works for a destination, keep using it.
HashSet<NodeState> colrowFailovers = new HashSet<NodeState>();
colrowFailovers.addAll(rowmap.get(r0));
colrowFailovers.addAll(colmap.get(c0));
for (NodeState f : colrowFailovers) {
if (!isFailedRendezvous(f, dst)) {
cands.add(f);
}
}
if (cands.isEmpty()) {
// only once we have determined that no current
// failover works for us do we go ahead and randomly
// select a new failover. this is a blind choice;
// we don't have these node's routing recommendations,
// so we could not hope to do better.
// get candidates from col
for (int r1 = 0; r1 < numRows; r1++) {
NodeState cand = grid[r1][c0];
if (cand != self && cand.isReachable)
cands.add(cand);
}
// get candidates from row
for (int c1 = 0; c1 < numCols; c1++) {
NodeState cand = grid[r0][c1];
if (cand != self && cand.isReachable)
cands.add(cand);
}
}
// if any of the candidates are already selected to be in
// 'servers', we want to make sure that we only choose from
// these choices.
HashSet<NodeState> candsInServers = new HashSet<NodeState>();
for (NodeState cand : cands)
if (servers.contains(cand))
candsInServers.add(cand);
// choose candidate uniformly at random
ArrayList<NodeState> candsList = new
ArrayList<NodeState>(candsInServers.isEmpty() ?
cands : candsInServers);
if (candsList.size() == 0) {
log("no failover candidates! giving up; " + report);
} else {
NodeState failover = candsList.get(rand.nextInt(candsList.size()));
log("new failover for " + dst + ": " + failover + ", prev rs = " + rs + "; " + report);
rs.add(failover);
servers.add(failover);
// share this failover in this routing iteration too
if (!allDefaults.contains(failover)) {
rowmap.get(gridRow.get(failover)).add(failover);
colmap.get(gridColumn.get(failover)).add(failover);
}
}
} else {
/*
* when we remove nodes now, don't immediately look
* for failovers. the next period, we will have
* received link states from our neighbors, from
* which we can determine whether dst is just down.
*
* the reason for this is that if a node fails, we
* don't want the entire network to flood the row/col
* of that downed node (no need for failovers period)
*/
for (Iterator<NodeState> i = rs.iterator(); i.hasNext();) {
NodeState r = i.next();
if (isFailedRendezvous(r, dst)) {
i.remove();
} else {
servers.add(r);
}
}
if (rs.isEmpty()) {
log("all rs to " + dst + " failed");
System.out.println("ALL FAILED!");
}
}
}
}
}
ArrayList<NodeState> list = new ArrayList<NodeState>(servers);
Collections.sort(list);
return list;
}
public static enum RoutingScheme { SIMPLE, SQRT, SQRT_NOFAILOVER, SQRT_RC_FAILOVER, SQRT_SPECIAL };
private final RoutingScheme scheme;
private void printMembers() {
String s = "members:";
for (NodeInfo info : coordNodes.values()) {
s += "\n " + info.id + " oid " + id2oid.get(info.id) + " " +
id2name.get(info.id) + " " + info.port;
}
log(s);
}
// PERF
private void printGrid() {
String s = "grid:";
if (grid != null) {
for (int i = 0; i < numRows; i++) {
s += "\n ";
for (int j = 0; j < numCols; j++) {
s += "\t" + grid[i][j];
}
}
}
log(s);
}
/**
* in the sqrt routing scheme: for each neighbor, find for him the min-cost
* hops to all other neighbors, and send this info to him (the intermediate
* node may be one of the endpoints, meaning a direct route is cheapest).
*
* in the sqrt_special routing scheme, we instead find for each neighbor the
* best intermediate other neighbor through which to route to every
* destination. this still needs work, see various todos.
*
* a failed rendezvous wrt some node n is one which we cannot reach
* (proximal failure) or which cannot reach n (remote failure). when all
* current rendezvous to some node n fail, then we find a failover from node
* n's row and col, and include it in our neighbor set. by befault, this
* situation occurs when a row-col rendezvous pair fail. it can also occur
* with any of our current failovers.
*/
private void broadcastRecommendations() {
ArrayList<NodeState> clients = getAllRendezvousClients();
ArrayList<NodeState> dsts = new ArrayList<NodeState>(clients);
dsts.add(nodes.get(myNid));
Collections.sort(dsts);
int totalSize = 0;
for (NodeState src : clients) {
ArrayList<Rec> recs = new ArrayList<Rec>();
// dst <- nbrs, hop <- any
findHops(dsts, memberNids, src, recs);
/*
* TODO: need to additionally send back info about *how good* the
* best hop is, so that the receiver can decide which of the many
* recommendations to accept
*/
if (scheme == RoutingScheme.SQRT_SPECIAL) {
// dst <- any, hop <- nbrs
findHopsAlt(memberNids, dsts, src, recs);
}
RoutingRecs msg = new RoutingRecs();
msg.recs = recs;
totalSize += sendObject(msg, src.info.id);
}
log("sent recs, " + totalSize + " bytes, to " + clients);
}
/**
* Given the src, find for each dst in dsts the ideal hop from hops,
* storing these into recs. This may choose the dst itself as the hop.
*/
private void findHops(ArrayList<NodeState> dsts,
ArrayList<Short> hops, NodeState src, ArrayList<Rec> recs) {
for (NodeState dst : dsts) {
if (src != dst) {
short min = resetLatency;
short minhop = -1;
for (short hop : hops) {
if (hop != src.info.id) {
int src2hop = src.latencies.get(hop);
int dst2hop = dst.latencies.get(hop);
int latency = src2hop + dst2hop;
// DEBUG
// log(src + "->" + hop + " is " + src2hop + ", " + hop +
// "->" + dst + " is " + dst2hop + ", sum " +
// latency);
if (latency < min) {
min = (short) latency;
minhop = hop;
}
}
}
// it's possible for us to have not found an ideal hop. this
// may be counter-intuitive, since even if src<->dst is broken,
// the fact that both are our clients means we should be able
// to serve as a hop. however it may be that either one of them
// was, or we were, recently added as a member to the network,
// so they never had a chance to ping us yet (and hence we're
// missing from their measurements). (TODO also is it possible
// that we're missing their measurement entirely? are all
// clients necessarily added on demand by measurement packets?)
// what we can do is to try finding our own latency to the hop
// (perhaps we've had a chance to ping them), and failing that,
// estimating the latency (only if one of us was newly added).
// however, these errors are transient anyway - by the next
// routing period, several pings will have taken place that
// would guarantee (or there was a failure, and eventually one
// of {src,dst} will fall out of our client set).
if (minhop != -1) {
// DEBUG
// log("recommending " + src + "->" + minhop + "->" + dst +
// " latency " + min);
Rec rec = new Rec();
rec.dst = dst.info.id;
rec.via = minhop;
recs.add(rec);
}
}
}
}
private void findHopsAlt(ArrayList<Short> dsts,
ArrayList<NodeState> hops, NodeState src, ArrayList<Rec> recs) {
for (short dst : dsts) {
if (src.info.id != dst && nodes.get(dst).isReachable) {
short min = resetLatency;
short minhop = -1;
for (NodeState hop : hops) {
if (hop != src) {
short src2hop = src.latencies.get(hop.info.id);
short dst2hop = hop.latencies.get(dst);
short latency = (short) (src2hop + dst2hop);
if (latency < min) {
min = latency;
minhop = hop.info.id;
}
}
}
assert minhop != -1;
Rec rec = new Rec();
rec.dst = dst;
rec.via = minhop;
recs.add(rec);
}
}
}
private String routesToString(ArrayList<Rec> recs) {
String s = "";
for (Rec rec : recs)
s += rec.via + "->" + rec.dst + " ";
return s;
}
private Serialization senderSer = new Serialization();
private int sendObject(final Msg o, InetAddress addr, int port, short nid) {
o.src = myNid;
o.version = currentStateVersion;
o.session = sessionId;
try {
/*
* note that it's unsafe to re-use these output streams - at
* least, i don't know how (reset() is insufficient)
*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
senderSer.serialize(o, new DataOutputStream(baos));
byte[] buf = baos.toByteArray();
String who = nid >= 0 ? "" + nid : (addr + ":" + port);
log("send." + o.getClass().getSimpleName(),
"to " + who + " len " + buf.length);
if (!ignored.contains(nid)) {
sendSocket.send(new DatagramPacket(buf, buf.length, addr, port));
} else {
log("droppng packet sent to " + who);
}
return buf.length;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private int sendObject(final Msg o, NodeInfo info, short nid) {
return sendObject(o, info.addr, info.port, nid);
}
private int sendObject(final Msg o, NodeInfo info) {
return sendObject(o, info, (short)-1);
}
private int sendObject(final Msg o, short nid) {
return nid != myNid ?
sendObject(o,
nid == 0 ? coordNode : (myNid == 0 ?
coordNodes.get(nid) : nodes.get(nid).info),
nid) : 0;
}
private void broadcastMeasurements(ArrayList<NodeState> servers) {
ShortShortMap latencies = nodes.get(myNid).latencies;
Measurements rm = new Measurements();
rm.probeTable = new short[memberNids.size()];
for (int i = 0; i < rm.probeTable.length; i++)
rm.probeTable[i] = latencies.get(memberNids.get(i));
rm.inflation = new byte[rm.probeTable.length];
int totalSize = 0;
for (NodeState nbr : servers) {
totalSize += sendObject(rm, nbr.info.id);
}
log("sent measurements, " + totalSize + " bytes, to " + servers);
}
private void updateMeasurements(Measurements m) {
NodeState src = nodes.get(m.src);
for (int i = 0; i < m.probeTable.length; i++)
src.latencies.put(memberNids.get(i), m.probeTable[i]);
// NOTE we aren't setting node.{hop,cameUp,isHopRecommended=false}...
}
private void handleRecommendations(RoutingRecs msg) {
ArrayList<Rec> recs = msg.recs;
NodeState r = nodes.get(msg.src);
r.dstsPresent.clear();
r.remoteFailures.clear();
for (Rec rec : recs) {
r.dstsPresent.add(rec.dst);
if (nodes.get(rec.via).isReachable) {
if (scheme == RoutingScheme.SQRT_SPECIAL) {
/*
* TODO: add in support for processing sqrt_special
* recommendations. first we need to add in the actual cost of
* the route to these recommendations (see
* broadcastRecommndations), then we need to compare all of
* these and see which ones were better. a complication is that
* routing recommendation broadcasts are not synchronized, so
* while older messages may appear to have better routes, there
* must be some threshold in time past which we disregard old
* latencies. must keep some history
*/
} else {
// blindly trust the recommendations
NodeState node = nodes.get(rec.dst);
if (node.hop == 0)
node.cameUp = true;
node.isHopRecommended = true;
node.hop = rec.via;
}
}
}
if (scheme != RoutingScheme.SQRT_SPECIAL) {
/*
* get the full set of dsts that we depend on this node for. note
* that the set of nodes it's actually serving may be different.
*/
for (NodeState dst : r.defaultClients) {
if (!r.dstsPresent.contains(dst.info.id)) {
/*
* there was a comm failure between this rendezvous and the
* dst for which this rendezvous did not provide a
* recommendation. consider this a rendezvous failure, so that if
* necessary during the next phase, we will find failovers.
*/
r.remoteFailures.add(dst);
}
}
}
}
/**
* counts the number of nodes that we can reach - either directly, through a
* hop, or through any rendezvous client.
*
* @return
*/
private int countReachableNodes() {
/*
* TODO need to fix up hopOptions so that it actually gets updated
* correctly, since currently things are *never* removed from it (they
* need to expire)
*/
NodeState myState = nodes.get(myNid);
int count = 0;
for (NodeState node : otherNodes) {
count += node.hop != 0 ? 1 : 0;
}
return count;
}
/**
* Counts the number of paths to a particular node.
*
* Note that this does not get run whenever nodes become reachable, only
* when they become unreachable (and also in batch periodically).
* Furthermore, we do not run this whenever we get a measurement packet.
* The reason for these infelicities is one of performance.
*
* The logic among hop, isHopRecommended, and cameUp is tricky.
*/
private int findPaths(NodeState node, boolean batch) {
ArrayList<NodeState> clients = getAllRendezvousClients();
ArrayList<NodeState> servers = lastRendezvousServers;
HashSet<NodeState> options = new HashSet<NodeState>();
short min = resetLatency;
short nid = node.info.id;
boolean wasDead = node.hop == 0;
NodeState self = nodes.get(myNid);
// we would like to keep recommended nodes (they should be the best
// choice, but also we have no ping data). but if it was not obtained
// via recommendation (i.e., a previous findPaths() got this hop), then
// we should feel free to update it.
if (node.hop == 0) {
node.isHopRecommended = false;
} else {
// we are not adding the hop
if (!node.isHopRecommended) {
node.hop = 0;
}
}
// direct hop
if (node.isReachable) {
options.add(node);
if (!node.isHopRecommended) {
node.hop = node.info.id;
min = self.latencies.get(node.info.id);
}
}
// find best rendezvous client. (`clients` are all reachable.)
for (NodeState client : clients) {
int val = client.latencies.get(nid);
if (val != resetLatency) {
options.add(client);
val += self.latencies.get(client.info.id);
if (!node.isHopRecommended && val < min) {
node.hop = client.info.id;
min = (short) val;
}
}
}
// see if a rendezvous server can serve as the hop. (can't just iterate
// through hopOptions, because that doesn't tell us which server to go
// through.) using the heuristic of just our latency to the server
for (NodeState server : servers) {
if (server.dstsPresent.contains(nid)) {
options.add(server);
short val = self.latencies.get(server.info.id);
if (node.hop == 0 && val < min) {
node.hop = server.info.id;
min = val;
}
}
}
boolean isDead = node.hop == 0;
// seems that (!isDead && wasDead) can be true, if a hop is found here
// from a measurement (from a rclient).
boolean cameUp = !isDead && wasDead || node.cameUp;
boolean wentDown = isDead && !wasDead;
// reset node.cameUp
node.cameUp = false;
// we always print something in non-batch mode. we also print stuff if
// there was a change in the node's up/down status. if a node is reachable
// then findPaths(node,) will only be called during batch processing, and
// so wasDead will have been set either by the last unreachable call or by
// the previous batch call. thus, the first batch call after a node goes
// up, the "up" message will be printed.
if (!batch || cameUp || wentDown) {
String stateChange = cameUp ? " up" : (wentDown ? " down" : "");
log("node " + node + stateChange + " hop " + node.hop + " total "
+ options.size());
}
return options.size();
}
/**
* counts the avg number of one-hop or direct paths available to nodes
* @return
*/
private Pair<Integer, Integer> findPathsForAllNodes() {
NodeState myState = nodes.get(myNid);
int count = 0;
int numNodesReachable = 0;
for (NodeState node : otherNodes) {
int d = findPaths(node, true);
count += d;
numNodesReachable += d > 0 ? 1 : 0;
}
if (numNodesReachable > 0)
count /= numNodesReachable;
return Pair.of(numNodesReachable, count);
}
public void quit() {
doQuit.set(true);
}
private class NodeState implements Comparable<NodeState> {
public String toString() {
return "" + info.id;
}
/**
* not null
*/
public final NodeInfo info;
/**
* updated in resetTimeoutAtNode(). if hop == 0, this must be false; if
* hop == the nid, this must be true.
*
* this should also be made to correspond with the appropriate latencies in myNid
*/
public boolean isReachable = true;
/**
* the last known latencies to all other nodes. missing entry implies
* resetLatency. this is populated/valid for rendezvous clients.
*
* invariants:
* - keyset is a subset of current members (memberNids); enforced in
* updateMembers()
* - keyset contains only live nodes; enforced in resetTimeoutAtNode()
* - values are not resetLatency
* - undefined if not a rendezvous client
*/
public final ShortShortMap latencies = new ShortShortMap(resetLatency);
/**
* the recommended intermediate hop for us to get to this node, or 0 if
* no way we know of to get to that node, and thus believe the node is
* down.
*
* invariants:
* - always refers to a member or 0; enforced in updateMembers()
* - never refers to dead node; enforced in resetTimeoutAtNode()
* - may be nid (may be dst)
* - initially defaults to dst (since we don't know hops to it)
* - never refers to the owning neuronnode (never is src)
* - cannot be nid if !isReachable
*/
public short hop;
/**
* this is set at certain places where we determine that a node is
* alive, and reset in the next findPaths(). the only reason we need
* this is to help produce the correct logging output for the
* effectiveness timing analysis.
*/
public boolean cameUp;
/**
* this indicates how we got this hop. this is set in
* handleRecommendations(), reset in resetTimeoutAtNode(), and
* read/reset from batch-mode findPaths(). if it was recommended to
* us, then we will want to keep it; otherwise, it was just something
* we found in failover mode, so are free to wipe it out. this var has
* no meaning when hop == 0.
*/
public boolean isHopRecommended;
/**
* remote failures. applies only if this nodestate is of a rendezvous
* node. contains nids of all nodes for which this rendezvous cannot
* recommend routes.
*
* invariants:
* - undefined if this is not a rendezvous node
* - empty
*/
public final HashSet<NodeState> remoteFailures = new HashSet<NodeState>();
/**
* dstsPresent, the complement of remoteFailures (in defaultClients).
*/
public final HashSet<Short> dstsPresent = new HashSet<Short>();
/**
* basically, his row/col. (all the nodes that he's responsible for).
*/
public final HashSet<NodeState> defaultClients = new HashSet<NodeState>();
/**
* this is unused at the moment. still need to re-design.
*/
public final HashSet<Short> hopOptions = new HashSet<Short>();
public NodeState(NodeInfo info) {
this.info = info;
this.hop = info.id;
latencies.put(info.id, (short) 0);
}
public int compareTo(NodeState o) {
return new Short(info.id).compareTo(o.info.id);
}
}
}
class ShortShortMap {
private final Hashtable<Short,Short> table = new Hashtable<Short, Short>();
private final short defaultValue;
public ShortShortMap(short defaultValue) {
this.defaultValue = defaultValue;
}
public Set<Short> keySet() {
return table.keySet();
}
public boolean containsKey(short key) {
return table.containsKey(key);
}
public void remove(short key) {
table.remove(key);
}
public short get(short key) {
Short value = table.get(key);
return value != null ? value : defaultValue;
}
public void put(short key, short value) {
if (value == defaultValue)
table.remove(key);
else
table.put(key, value);
}
}
// welcome to my
// DEATH MACHINE,
// interloper!!!!!!!11
class NodeInfo {
short id;
int port;
InetAddress addr;
}
class Rec {
short dst;
short via;
}
class Msg {
short src;
short version;
short session;
}
class Join extends Msg {
InetAddress addr;
int port;
}
class Init extends Msg {
short id;
ArrayList<NodeInfo> members;
}
class Membership extends Msg {
ArrayList<NodeInfo> members;
short numNodes;
short yourId;
}
class RoutingRecs extends Msg {
ArrayList<Rec> recs;
}
class Ping extends Msg {
long time;
NodeInfo info;
}
class Pong extends Msg {
long time;
}
class Subprobe extends Msg {
long time;
short nid;
byte type;
}
class Measurements extends Msg {
short[] probeTable;
byte[] inflation;
}
class MemberPoll extends Msg {
}
class PeeringRequest extends Msg {
}
class Serialization {
public void serialize(Object obj, DataOutputStream out) throws IOException {
if (false) {}
else if (obj.getClass() == NodeInfo.class) {
NodeInfo casted = (NodeInfo) obj; out.writeInt(0);
out.writeShort(casted.id);
out.writeInt(casted.port);
byte[] buf = casted.addr.getAddress();out.writeInt(buf.length);out.write(buf);
}
else if (obj.getClass() == Rec.class) {
Rec casted = (Rec) obj; out.writeInt(1);
out.writeShort(casted.dst);
out.writeShort(casted.via);
}
else if (obj.getClass() == Msg.class) {
Msg casted = (Msg) obj; out.writeInt(2);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == Join.class) {
Join casted = (Join) obj; out.writeInt(3);
byte[] buf = casted.addr.getAddress();out.writeInt(buf.length);out.write(buf);
out.writeInt(casted.port);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == Init.class) {
Init casted = (Init) obj; out.writeInt(4);
out.writeShort(casted.id);
out.writeInt(casted.members.size());
for (int i = 0; i < casted.members.size(); i++) {
out.writeShort(casted.members.get(i).id);
out.writeInt(casted.members.get(i).port);
byte[] buf = casted.members.get(i).addr.getAddress();out.writeInt(buf.length);out.write(buf);
}
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == Membership.class) {
Membership casted = (Membership) obj; out.writeInt(5);
out.writeInt(casted.members.size());
for (int i = 0; i < casted.members.size(); i++) {
out.writeShort(casted.members.get(i).id);
out.writeInt(casted.members.get(i).port);
byte[] buf = casted.members.get(i).addr.getAddress();out.writeInt(buf.length);out.write(buf);
}
out.writeShort(casted.numNodes);
out.writeShort(casted.yourId);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == RoutingRecs.class) {
RoutingRecs casted = (RoutingRecs) obj; out.writeInt(6);
out.writeInt(casted.recs.size());
for (int i = 0; i < casted.recs.size(); i++) {
out.writeShort(casted.recs.get(i).dst);
out.writeShort(casted.recs.get(i).via);
}
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == Ping.class) {
Ping casted = (Ping) obj; out.writeInt(7);
out.writeLong(casted.time);
out.writeShort(casted.info.id);
out.writeInt(casted.info.port);
byte[] buf = casted.info.addr.getAddress();out.writeInt(buf.length);out.write(buf);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == Pong.class) {
Pong casted = (Pong) obj; out.writeInt(8);
out.writeLong(casted.time);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == Subprobe.class) {
Subprobe casted = (Subprobe) obj; out.writeInt(9);
out.writeLong(casted.time);
out.writeShort(casted.nid);
out.writeByte(casted.type);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == Measurements.class) {
Measurements casted = (Measurements) obj; out.writeInt(10);
out.writeInt(casted.probeTable.length);
for (int i = 0; i < casted.probeTable.length; i++) {
out.writeShort(casted.probeTable[i]);
}
out.writeInt(casted.inflation.length);out.write(casted.inflation);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == MemberPoll.class) {
MemberPoll casted = (MemberPoll) obj; out.writeInt(11);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
else if (obj.getClass() == PeeringRequest.class) {
PeeringRequest casted = (PeeringRequest) obj; out.writeInt(12);
out.writeShort(casted.src);
out.writeShort(casted.version);
out.writeShort(casted.session);
}
}
public Object deserialize(DataInputStream in) throws IOException {
switch (readInt(in)) {
case 0: { // NodeInfo
NodeInfo obj;
{
obj = new NodeInfo();
{
obj.id = in.readShort();
}
{
obj.port = readInt(in);
}
{
byte[] buf;
{
buf = new byte[readInt(in)];
in.read(buf);
}
obj.addr = InetAddress.getByAddress(buf);
}
}
return obj;}
case 1: { // Rec
Rec obj;
{
obj = new Rec();
{
obj.dst = in.readShort();
}
{
obj.via = in.readShort();
}
}
return obj;}
case 2: { // Msg
Msg obj;
{
obj = new Msg();
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
return obj;}
case 3: { // Join
Join obj;
{
obj = new Join();
{
byte[] buf;
{
buf = new byte[readInt(in)];
in.read(buf);
}
obj.addr = InetAddress.getByAddress(buf);
}
{
obj.port = readInt(in);
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 4: { // Init
Init obj;
{
obj = new Init();
{
obj.id = in.readShort();
}
{
obj.members = new ArrayList<NodeInfo>();
for (int i = 0, len = readInt(in); i < len; i++) {
NodeInfo x;
{
x = new NodeInfo();
{
x.id = in.readShort();
}
{
x.port = readInt(in);
}
{
byte[] buf;
{
buf = new byte[readInt(in)];
in.read(buf);
}
x.addr = InetAddress.getByAddress(buf);
}
}
obj.members.add(x);
}
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 5: { // Membership
Membership obj;
{
obj = new Membership();
{
obj.members = new ArrayList<NodeInfo>();
for (int i = 0, len = readInt(in); i < len; i++) {
NodeInfo x;
{
x = new NodeInfo();
{
x.id = in.readShort();
}
{
x.port = readInt(in);
}
{
byte[] buf;
{
buf = new byte[readInt(in)];
in.read(buf);
}
x.addr = InetAddress.getByAddress(buf);
}
}
obj.members.add(x);
}
}
{
obj.numNodes = in.readShort();
}
{
obj.yourId = in.readShort();
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 6: { // RoutingRecs
RoutingRecs obj;
{
obj = new RoutingRecs();
{
obj.recs = new ArrayList<Rec>();
for (int i = 0, len = readInt(in); i < len; i++) {
Rec x;
{
x = new Rec();
{
x.dst = in.readShort();
}
{
x.via = in.readShort();
}
}
obj.recs.add(x);
}
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 7: { // Ping
Ping obj;
{
obj = new Ping();
{
obj.time = in.readLong();
}
{
obj.info = new NodeInfo();
{
obj.info.id = in.readShort();
}
{
obj.info.port = readInt(in);
}
{
byte[] buf;
{
buf = new byte[readInt(in)];
in.read(buf);
}
obj.info.addr = InetAddress.getByAddress(buf);
}
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 8: { // Pong
Pong obj;
{
obj = new Pong();
{
obj.time = in.readLong();
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 9: { // Subprobe
Subprobe obj;
{
obj = new Subprobe();
{
obj.time = in.readLong();
}
{
obj.nid = in.readShort();
}
{
obj.type = in.readByte();
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 10: { // Measurements
Measurements obj;
{
obj = new Measurements();
{
obj.probeTable = new short[readInt(in)];
for (int i = 0; i < obj.probeTable.length; i++) {
{
obj.probeTable[i] = in.readShort();
}
}
}
{
obj.inflation = new byte[readInt(in)];
in.read(obj.inflation);
}
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 11: { // MemberPoll
MemberPoll obj;
{
obj = new MemberPoll();
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
case 12: { // PeeringRequest
PeeringRequest obj;
{
obj = new PeeringRequest();
{
{
obj.src = in.readShort();
}
{
obj.version = in.readShort();
}
{
obj.session = in.readShort();
}
}
}
return obj;}
default:throw new RuntimeException("unknown obj type");}}
private byte[] readBuffer = new byte[4];
public int readInt(DataInputStream dis) throws IOException {
dis.readFully(readBuffer, 0, 4);
return (
((int)(readBuffer[0] & 255) << 24) +
((readBuffer[1] & 255) << 16) +
((readBuffer[2] & 255) << 8) +
((readBuffer[3] & 255) << 0));
}
/*
public static void main(String[] args) throws IOException {
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
Pong pong = new Pong();
pong.src = 2;
pong.version = 3;
pong.time = 4;
serialize(pong, out);
byte[] buf = baos.toByteArray();
System.out.println(buf.length);
Object obj = deserialize(new DataInputStream(new ByteArrayInputStream(buf)));
System.out.println(obj);
}
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
Measurements m = new Measurements();
m.src = 2;
m.version = 3;
m.membershipList = new ArrayList<Integer>();
m.membershipList.add(4);
m.membershipList.add(5);
m.membershipList.add(6);
m.ProbeTable = new long[5];
m.ProbeTable[1] = 7;
m.ProbeTable[2] = 8;
m.ProbeTable[3] = 9;
serialize(m, out);
byte[] buf = baos.toByteArray();
System.out.println(buf.length);
Object obj = deserialize(new DataInputStream(new ByteArrayInputStream(buf)));
System.out.println(obj);
}
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
Membership m = new Membership();
m.src = 2;
m.version = 3;
m.members = new ArrayList<NodeInfo>();
NodeInfo n1 = new NodeInfo();
n1.addr = InetAddress.getLocalHost();
n1.port = 4;
n1.id = 5;
m.members.add(n1);
NodeInfo n2 = new NodeInfo();
n2.addr = InetAddress.getByName("google.com");
n2.port = 6;
n2.id = 7;
m.members.add(n2);
m.numNodes = 8;
serialize(m, out);
byte[] buf = baos.toByteArray();
System.out.println(buf.length);
Object obj = deserialize(new DataInputStream(
new ByteArrayInputStream(buf)));
System.out.println(obj);
}
}*/
} |
import com.sun.star.uno.UnoRuntime;
import drafts.com.sun.star.accessibility.XAccessibleContext;
import drafts.com.sun.star.accessibility.XAccessibleImage;
class AccessibleImageHandler extends NodeHandler
{
public NodeHandler createHandler (XAccessibleContext xContext)
{
XAccessibleImage xImage =
(XAccessibleImage) UnoRuntime.queryInterface (
XAccessibleImage.class, xContext);
if (xImage != null)
return new AccessibleImageHandler (xImage);
else
return null;
}
public AccessibleImageHandler ()
{
}
public AccessibleImageHandler (XAccessibleImage xImage)
{
if (xImage != null)
maChildList.setSize (1);
}
protected static XAccessibleImage getImage (AccTreeNode aNode)
{
return (XAccessibleImage) UnoRuntime.queryInterface (
XAccessibleImage.class, aNode.getContext());
}
public AccessibleTreeNode createChild (AccessibleTreeNode aParent, int nIndex)
{
if (aParent instanceof AccTreeNode)
{
XAccessibleImage xImage = getImage ((AccTreeNode)aParent);
if (xImage != null)
return new StringNode (
"Image: " +
xImage.getAccessibleImageDescription() + " (" +
xImage.getAccessibleImageWidth() + "x" +
xImage.getAccessibleImageHeight() + ")",
aParent);
}
return null;
}
} |
package gui.editionView;
import entity.Model;
import gui.AbstractComponentPanel;
import gui.Lang;
import gui.MainFrame;
import gui.State;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ListIterator;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import solution.SolverExecutionException;
import solution.SolverTestSAT4J;
import translation.TranslationError;
import translation.TranslatorSAT;
/**
*
* @author Skander
*/
public class ParentEditionPanel extends AbstractComponentPanel {
private Thread testThread;
/**
* Creates new form FormulasPanel
*/
public ParentEditionPanel(MainFrame parent) {
super(parent);
initComponents();
testThread = new Thread();
editorPanelFormulas.initPalette(PalettePanel.PaletteType.FORMULA);
editorPanelSets.initPalette(PalettePanel.PaletteType.SET);
jFileChooser1.setCurrentDirectory(new File(".."));
jLabelErrorMessage.setText("");
}
/**
* 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() {
jFileChooser1 = new javax.swing.JFileChooser();
jOptionPane1 = new javax.swing.JOptionPane();
jTabbedPane1 = new javax.swing.JTabbedPane();
editorPanelFormulas = new gui.editionView.EditionPanel(parent);
editorPanelSets = new gui.editionView.EditionPanel(parent);
testButton = new javax.swing.JButton();
importButton = new javax.swing.JButton();
jLabelErrorMessage = new javax.swing.JLabel();
jLabelCaretPosition = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
exportButton = new javax.swing.JButton();
jFileChooser1.setFileSelectionMode(JFileChooser.FILES_ONLY);
jFileChooser1.addChoosableFileFilter(new FileNameExtensionFilter("Touistl files(touistl)","touistl"));
jFileChooser1.setToolTipText(""); // TODO
jTabbedPane1.setToolTipText("");
jTabbedPane1.addTab(getFrame().getLang().getWord("ParentEditionPanel.editorPanelFormulas.TabConstraints.tabTitle"), editorPanelFormulas);
editorPanelFormulas.setToolTipText("ParentEditionPanel.editorPanelFormulas.TabConstraints.tabTooltip");
jTabbedPane1.addTab(getFrame().getLang().getWord("ParentEditionPanel.editorPanelSets.TabConstraints.tabTitle"), editorPanelSets);
editorPanelSets.setToolTipText(getFrame().getLang().getWord("ParentEditionPanel.editorPanelSets.TabConstraints.tabTooltip"));
testButton.setText(getFrame().getLang().getWord("ParentEditionPanel.testButton.text"));
testButton.setToolTipText(getFrame().getLang().getWord("ParentEditionPanel.testButton.tooltip"));
testButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
testButtonActionPerformed(evt);
}
});
importButton.setText(getFrame().getLang().getWord("ParentEditionPanel.importButton.text"));
importButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
importButtonActionPerformed(evt);
}
});
jLabelErrorMessage.setForeground(new java.awt.Color(255, 0, 0));
jLabelErrorMessage.setText("<Error message>");
jLabelCaretPosition.setText("1:1");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SAT", "SMT" }));
exportButton.setText(getFrame().getLang().getWord("ParentEditionPanel.exportButton.text"));
exportButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exportButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 992, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelCaretPosition)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelErrorMessage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(exportButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(importButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(testButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(testButton)
.addComponent(importButton)
.addComponent(jLabelCaretPosition)
.addComponent(jLabelErrorMessage)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(exportButton))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void importButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importButtonActionPerformed
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
setState(State.EDITION);
importHandler();
break;
case EDITION_ERROR :
setState(State.EDITION_ERROR);
importHandler();
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + getState());
}
}//GEN-LAST:event_importButtonActionPerformed
/**
* For Java RE 6 compatibility (p.isAlive() is JavaRE7)
*/
private boolean isAlive(Process process) {
try {
process.exitValue();
return false;
} catch (Exception e) {
return true;
}
}
private boolean isStopInsteadOfTest = false;
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButtonActionPerformed
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
jLabelErrorMessage.setText("");
this.testButton.setText(isStopInsteadOfTest
?getFrame().getLang().getWord("ParentEditionPanel.testButton.text")
:getFrame().getLang().getWord("ParentEditionPanel.stopButton.text"));
isStopInsteadOfTest = (isStopInsteadOfTest)?false:true;
if(testThread.isAlive()) {
testThread.interrupt();
}
Process p = getFrame().getTranslator().getP();
if(p != null && isAlive(p)){
p.destroy();
}
if(!isStopInsteadOfTest)
break;
Runnable r = new Runnable() {
public void run() {
State state = initResultView();
if (state != State.EDITION) {
setState(state);
getFrame().setViewToResults();
testButton.setText(getFrame().getLang().getWord("ParentEditionPanel.testButton.text"));
}
}
};
testThread = new Thread(r);
testThread.start();
break;
case EDITION_ERROR :
// interdit
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + getState());
}
}//GEN-LAST:event_testButtonActionPerformed
private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
setState(State.EDITION);
exportHandler();
break;
case EDITION_ERROR :
setState(State.EDITION_ERROR);
exportHandler();
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + getState());
} }//GEN-LAST:event_exportButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private gui.editionView.EditionPanel editorPanelFormulas;
private gui.editionView.EditionPanel editorPanelSets;
private javax.swing.JButton exportButton;
private javax.swing.JButton importButton;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JFileChooser jFileChooser1;
private javax.swing.JLabel jLabelCaretPosition;
private javax.swing.JLabel jLabelErrorMessage;
private javax.swing.JOptionPane jOptionPane1;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JButton testButton;
// End of variables declaration//GEN-END:variables
public void importHandler() {
String path = "";
int returnVal;
getFrame().getClause().setFormules("");
getFrame().getClause().setSets("");
returnVal = jFileChooser1.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION && jFileChooser1.getSelectedFile() != null) {
path = jFileChooser1.getSelectedFile().getPath();
try {
getFrame().getClause().uploadFile(path);
} catch(Exception e) {
//TODO handle error message
System.out.println("Error : Failed to load the file : " + path);
e.printStackTrace();
}
String text = getFrame().getClause().getFormules();
editorPanelFormulas.setText(text);
text = getFrame().getClause().getSets();
editorPanelSets.setText(text);
}
}
public void exportHandler() {
getFrame().getClause().setFormules("");
getFrame().getClause().setSets("");
getFrame().getClause().addFormules(editorPanelFormulas.getText());
getFrame().getClause().addSets(editorPanelSets.getText());
int returnVal = jFileChooser1.showDialog(this,getFrame().getLang().getWord(Lang.EDITION_FILE_CHOOSER));
try {
if(returnVal == JFileChooser.APPROVE_OPTION){
getFrame().getClause().saveToFile(jFileChooser1.getSelectedFile().getPath());
}
} catch (IOException e) {
String warningWindowTitle = getFrame().getLang().getWord(Lang.EDITION_EXPORT_FAILURE_TITLE);
String warningWindowText = getFrame().getLang().getWord(Lang.EDITION_EXPORT_FAILURE_TEXT);
JOptionPane.showMessageDialog(this,warningWindowText,warningWindowTitle,JOptionPane.ERROR_MESSAGE);
}
}
private void showErrorMessage(String message, String title) {
jOptionPane1.showMessageDialog(getParent(),
message,
title,
JOptionPane.ERROR_MESSAGE);
}
private void showErrorMessage(Exception e, String message, String title) {
showErrorMessage(message, title);
FileWriter writer = null;
String texte = String.valueOf(e.getStackTrace()) + "\n" + "
try{
writer = new FileWriter("log.txt", true);
writer.write(texte,0,texte.length());
}catch(IOException ex){
ex.printStackTrace();
}finally{
if(writer != null){
try {
writer.close();
} catch (IOException ex) {
e.printStackTrace();
}
}
}
}
private TranslationError guiTranslationErrorAdapter(TranslationError error) {
TranslatorSAT t = new TranslatorSAT("");
TranslationError adaptedError;
int row = error.getRowInCode();
String sets = getFrame().getClause().getSets();
int nbRowsInSets = 1;
int setShift = (getFrame().getClause().getSets().isEmpty()) ? 0 : -1; // -1 pour tenir compte de "begin sets";
int formulasShift = (getFrame().getClause().getSets().isEmpty()) ? 0 : -3; // -3 pour tenir compte de "begin sets", "end sets" et "begin formulas"
for (int i=0; i<sets.length(); i++) {
if (sets.charAt(i) == '\n') {
nbRowsInSets++;
}
}
if (row < nbRowsInSets) {
// l'erreur est dans les sets
adaptedError = new TranslationError(row - setShift,
error.getColumnInCode(),
error.getErrorMessage() + getFrame().getLang().getWord(Lang.ERROR_TRADUCTION_IN_SETS));
} else {
// l'erreur est dans les formules
adaptedError = new TranslationError(row-nbRowsInSets - formulasShift,
error.getColumnInCode(),
error.getErrorMessage() + getFrame().getLang().getWord(Lang.ERROR_TRADUCTION_IN_FORMULAS));
}
return adaptedError;
}
private State initResultView() {
// Initialisation de BaseDeClause
getFrame().getClause().setFormules("");
getFrame().getClause().setSets("");
getFrame().getClause().addFormules(editorPanelFormulas.getText());
getFrame().getClause().addSets(editorPanelSets.getText());
String bigAndFilePath = "temp.touistl";
String errorMessage;
try {
getFrame().getClause().saveToFile(bigAndFilePath);
} catch (IOException ex) {
ex.printStackTrace();
errorMessage = "Couldn't create file '" + bigAndFilePath + "'";
showErrorMessage(errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
System.exit(0);
return State.EDITION;
}
try {
if(! getFrame().getTranslator().translate(bigAndFilePath)) {
errorMessage = "";
for(int i=0; i<getFrame().getTranslator().getErrors().size(); i++) {
TranslationError error = guiTranslationErrorAdapter(getFrame().getTranslator().getErrors().get(i));
errorMessage += error + "\n";
}
jLabelErrorMessage.setText(errorMessage);
System.out.println("Traduction error : " + "\n" + errorMessage + "\n");
showErrorMessage(errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
return State.EDITION;
}
File f = new File(bigAndFilePath);
f.deleteOnExit();
} catch (IOException ex) {
ex.printStackTrace();
errorMessage = "The translator returned an IOException: \n"+ex.getMessage();
showErrorMessage(ex, errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
return State.EDITION;
} catch (InterruptedException ex) {
ex.printStackTrace();
errorMessage = "Translator has been interrupted.";
showErrorMessage(ex, errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
return State.EDITION;
}
//Add CurrentPath/dimacsFile
String translatedFilePath = getFrame().getTranslator().getDimacsFilePath();
Map<Integer, String> literalsMap = getFrame().getTranslator().getLiteralsMap();
getFrame().setSolver(new SolverTestSAT4J(translatedFilePath, literalsMap));
try {
getFrame().getSolver().launch();
} catch (IOException ex) {
ex.printStackTrace();
errorMessage = "Couldn't launch solver.";
showErrorMessage(ex, errorMessage, "Solver error");
return State.EDITION;
}
// Si il y a au moins un model
try {
ListIterator<Model> iter = getFrame().getSolver().getModelList().iterator();
if(!iter.hasNext()) {
System.out.println("This problem is unsatisfiable");
errorMessage = "There is no solution";
showErrorMessage(errorMessage, "Solver error");
return State.EDITION;
}
getFrame().updateResultsPanelIterator(iter);
if (iter.hasNext()) {
getFrame().setResultView(iter.next());
if (iter.hasNext()) {
//iter.previous();
return State.FIRST_RESULT;
} else {
//iter.previous();
return State.SINGLE_RESULT;
}
} else {
return State.SINGLE_RESULT;
}
} catch (SolverExecutionException ex) {
ex.printStackTrace();
errorMessage = "The solver encountered a problem.";
showErrorMessage(ex, errorMessage, "Solver error");
return State.EDITION;
}
//return State.NO_RESULT;
}
public void setJLabelCaretPositionText(String text) {
jLabelCaretPosition.setText(text);
}
@Override
public void updateLanguage() {
importButton.setText(getFrame().getLang().getWord(Lang.EDITION_IMPORT));
exportButton.setText(getFrame().getLang().getWord(Lang.EDITION_EXPORT));
testButton.setText(getFrame().getLang().getWord(Lang.EDITION_TEST));
editorPanelFormulas.updateLanguage();
editorPanelSets.updateLanguage();
jTabbedPane1.setTitleAt(0, getFrame().getLang().getWord(Lang.EDITION_TAB_FORMULAS));
jTabbedPane1.setTitleAt(1, getFrame().getLang().getWord(Lang.EDITION_TAB_SETS));
updateUI();
}
} |
package com.adyen.v6.facades;
import java.io.IOException;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import com.adyen.Util.HMACValidator;
import com.adyen.Util.Util;
import com.adyen.constants.HPPConstants;
import com.adyen.model.Amount;
import com.adyen.model.Card;
import com.adyen.model.PaymentResult;
import com.adyen.model.checkout.PaymentMethod;
import com.adyen.model.checkout.PaymentsResponse;
import com.adyen.model.nexo.ErrorConditionType;
import com.adyen.model.nexo.ResultType;
import com.adyen.model.recurring.Recurring;
import com.adyen.model.recurring.RecurringDetail;
import com.adyen.model.terminal.TerminalAPIResponse;
import com.adyen.service.exception.ApiException;
import com.adyen.v6.converters.PaymentsResponseConverter;
import com.adyen.v6.converters.PosPaymentResponseConverter;
import com.adyen.v6.enums.RecurringContractMode;
import com.adyen.v6.exceptions.AdyenNonAuthorizedPaymentException;
import com.adyen.v6.factory.AdyenPaymentServiceFactory;
import com.adyen.v6.forms.AdyenPaymentForm;
import com.adyen.v6.forms.validation.AdyenPaymentFormValidator;
import com.adyen.v6.model.RequestInfo;
import com.adyen.v6.repository.OrderRepository;
import com.adyen.v6.service.AdyenOrderService;
import com.adyen.v6.service.AdyenPaymentService;
import com.adyen.v6.service.AdyenTransactionService;
import com.adyen.v6.util.TerminalAPIUtil;
import com.google.gson.Gson;
import de.hybris.platform.commercefacades.i18n.I18NFacade;
import de.hybris.platform.commercefacades.order.CheckoutFacade;
import de.hybris.platform.commercefacades.order.OrderFacade;
import de.hybris.platform.commercefacades.order.data.CartData;
import de.hybris.platform.commercefacades.order.data.OrderData;
import de.hybris.platform.commercefacades.user.data.AddressData;
import de.hybris.platform.commercefacades.user.data.CountryData;
import de.hybris.platform.commercefacades.user.data.RegionData;
import de.hybris.platform.commerceservices.strategies.CheckoutCustomerStrategy;
import de.hybris.platform.commercewebservicescommons.dto.order.PaymentDetailsListWsDTO;
import de.hybris.platform.commercewebservicescommons.dto.order.PaymentDetailsWsDTO;
import de.hybris.platform.core.model.order.CartModel;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.core.model.order.payment.PaymentInfoModel;
import de.hybris.platform.core.model.user.AddressModel;
import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.core.model.user.TitleModel;
import de.hybris.platform.order.CartService;
import de.hybris.platform.order.InvalidCartException;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import de.hybris.platform.servicelayer.i18n.CommonI18NService;
import de.hybris.platform.servicelayer.keygenerator.KeyGenerator;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import de.hybris.platform.servicelayer.session.SessionService;
import de.hybris.platform.store.BaseStoreModel;
import de.hybris.platform.store.services.BaseStoreService;
import static com.adyen.constants.ApiConstants.Redirect.Data.MD;
import static com.adyen.constants.ApiConstants.ThreeDS2Property.CHALLENGE_RESULT;
import static com.adyen.constants.ApiConstants.ThreeDS2Property.FINGERPRINT_RESULT;
import static com.adyen.constants.ApiConstants.ThreeDS2Property.THREEDS2_CHALLENGE_TOKEN;
import static com.adyen.constants.ApiConstants.ThreeDS2Property.THREEDS2_FINGERPRINT_TOKEN;
import static com.adyen.constants.BrandCodes.PAYPAL_ECS;
import static com.adyen.constants.HPPConstants.Fields.BRAND_CODE;
import static com.adyen.constants.HPPConstants.Fields.COUNTRY_CODE;
import static com.adyen.constants.HPPConstants.Fields.CURRENCY_CODE;
import static com.adyen.constants.HPPConstants.Fields.ISSUER_ID;
import static com.adyen.constants.HPPConstants.Fields.MERCHANT_ACCOUNT;
import static com.adyen.constants.HPPConstants.Fields.MERCHANT_REFERENCE;
import static com.adyen.constants.HPPConstants.Fields.MERCHANT_SIG;
import static com.adyen.constants.HPPConstants.Fields.PAYMENT_AMOUNT;
import static com.adyen.constants.HPPConstants.Fields.RES_URL;
import static com.adyen.constants.HPPConstants.Fields.SESSION_VALIDITY;
import static com.adyen.constants.HPPConstants.Fields.SHIP_BEFORE_DATE;
import static com.adyen.constants.HPPConstants.Fields.SKIN_CODE;
import static com.adyen.constants.HPPConstants.Response.SHOPPER_LOCALE;
import static com.adyen.v6.constants.Adyenv6coreConstants.KLARNA;
import static com.adyen.v6.constants.Adyenv6coreConstants.OPENINVOICE_METHODS_ALLOW_SOCIAL_SECURITY_NUMBER;
import static com.adyen.v6.constants.Adyenv6coreConstants.OPENINVOICE_METHODS_API;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_IDEAL;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK;
import static com.adyen.v6.constants.Adyenv6coreConstants.RATEPAY;
import static de.hybris.platform.order.impl.DefaultCartService.SESSION_CART_PARAMETER_NAME;
/**
* Adyen Checkout Facade for initiating payments using CC or APM
*/
public class DefaultAdyenCheckoutFacade implements AdyenCheckoutFacade {
private BaseStoreService baseStoreService;
private SessionService sessionService;
private CartService cartService;
private OrderFacade orderFacade;
private CheckoutFacade checkoutFacade;
private AdyenTransactionService adyenTransactionService;
private OrderRepository orderRepository;
private AdyenOrderService adyenOrderService;
private CheckoutCustomerStrategy checkoutCustomerStrategy;
private HMACValidator hmacValidator;
private AdyenPaymentServiceFactory adyenPaymentServiceFactory;
private ModelService modelService;
private CommonI18NService commonI18NService;
private KeyGenerator keyGenerator;
private PaymentsResponseConverter paymentsResponseConverter;
private FlexibleSearchService flexibleSearchService;
private Converter<AddressData, AddressModel> addressReverseConverter;
private PosPaymentResponseConverter posPaymentResponseConverter;
@Resource(name = "i18NFacade")
private I18NFacade i18NFacade;
public static final Logger LOGGER = Logger.getLogger(DefaultAdyenCheckoutFacade.class);
public static final String SESSION_LOCKED_CART = "adyen_cart";
public static final String SESSION_MD = "adyen_md";
public static final String SESSION_CSE_TOKEN = "adyen_cse_token";
public static final String SESSION_SF_CARD_NUMBER = "encryptedCardNumber";
public static final String SESSION_SF_EXPIRY_MONTH = "encryptedExpiryMonth";
public static final String SESSION_SF_EXPIRY_YEAR = "encryptedExpiryYear";
public static final String SESSION_SF_SECURITY_CODE = "encryptedSecurityCode";
public static final String SESSION_CARD_BRAND = "cardBrand";
public static final String THREE_D_MD = "MD";
public static final String THREE_D_PARES = "PaRes";
public static final String SESSION_PAYMENT_DATA = "adyen_payment_data";
public static final String MODEL_SELECTED_PAYMENT_METHOD = "selectedPaymentMethod";
public static final String MODEL_PAYMENT_METHODS = "paymentMethods";
public static final String MODEL_ALLOWED_CARDS = "allowedCards";
public static final String MODEL_REMEMBER_DETAILS = "showRememberTheseDetails";
public static final String MODEL_STORED_CARDS = "storedCards";
public static final String MODEL_DF_URL = "dfUrl";
public static final String MODEL_ORIGIN_KEY = "originKey";
public static final String MODEL_CHECKOUT_SHOPPER_HOST = "checkoutShopperHost";
public static final String DF_VALUE = "dfValue";
public static final String MODEL_OPEN_INVOICE_METHODS = "openInvoiceMethods";
public static final String MODEL_SHOW_SOCIAL_SECURITY_NUMBER = "showSocialSecurityNumber";
public static final String MODEL_SHOW_BOLETO = "showBoleto";
public static final String MODEL_SHOW_POS = "showPos";
public static final String CHECKOUT_SHOPPER_HOST_TEST = "checkoutshopper-test.adyen.com";
public static final String CHECKOUT_SHOPPER_HOST_LIVE = "checkoutshopper-live.adyen.com";
public static final String MODEL_IDEAL_ISSUER_LIST = "iDealissuerList";
public static final String MODEL_CONNECTED_TERMINAL_LIST = "connectedTerminalList";
public static final String MODEL_ENVIRONMENT_MODE = "environmentMode";
protected static final Set<String> HPP_RESPONSE_PARAMETERS = new HashSet<>(Arrays.asList(HPPConstants.Response.MERCHANT_REFERENCE,
HPPConstants.Response.SKIN_CODE,
HPPConstants.Response.SHOPPER_LOCALE,
HPPConstants.Response.PAYMENT_METHOD,
HPPConstants.Response.AUTH_RESULT,
HPPConstants.Response.PSP_REFERENCE,
HPPConstants.Response.MERCHANT_RETURN_DATA));
public DefaultAdyenCheckoutFacade() {
hmacValidator = new HMACValidator();
}
@Override
public void validateHPPResponse(SortedMap<String, String> hppResponseData, String merchantSig) throws SignatureException {
BaseStoreModel baseStore = getBaseStoreService().getCurrentBaseStore();
String hmacKey = baseStore.getAdyenSkinHMAC();
if (StringUtils.isEmpty(hmacKey)) {
LOGGER.error("Empty HMAC Key");
throw new SignatureException("Empty HMAC Key");
}
String dataToSign = getHmacValidator().getDataToSign(hppResponseData);
String calculatedMerchantSig = getHmacValidator().calculateHMAC(dataToSign, hmacKey);
LOGGER.debug("Calculated signature: " + calculatedMerchantSig + " from data: " + dataToSign);
if (StringUtils.isEmpty(calculatedMerchantSig) || ! calculatedMerchantSig.equals(merchantSig)) {
LOGGER.error("Signature does not match!");
throw new SignatureException("Signatures doesn't match");
}
}
@Override
public void validateHPPResponse(final HttpServletRequest request) throws SignatureException {
SortedMap<String, String> hppResponseData = getQueryParameters(request);
LOGGER.debug("Received HPP response: " + hppResponseData);
String merchantSig = request.getParameter(HPPConstants.Response.MERCHANT_SIG);
if (StringUtils.isEmpty(merchantSig)) {
LOGGER.error("MerchantSig was not provided");
throw new SignatureException("MerchantSig was not provided");
}
validateHPPResponse(hppResponseData, merchantSig);
}
@Override
public String getOriginKey(HttpServletRequest request) throws IOException, ApiException {
return getAdyenPaymentService().getOriginKey(getBaseURL(request));
}
public String getBaseURL(HttpServletRequest request) {
String currentRequestURL = request.getRequestURL().toString();
int requestUrlLength = currentRequestURL.length();
int requestUriLength = request.getRequestURI().length();
return currentRequestURL.substring(0, requestUrlLength - requestUriLength);
}
@Override
public String getCheckoutShopperHost() {
BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
if (baseStore.getAdyenTestMode()) {
return CHECKOUT_SHOPPER_HOST_TEST;
}
return CHECKOUT_SHOPPER_HOST_LIVE;
}
@Override
public String getEnvironmentMode() {
if (baseStoreService.getCurrentBaseStore().getAdyenTestMode()) {
return "test";
}
return "live";
}
@Override
public String getHppUrl() {
return getAdyenPaymentService().getHppEndpoint() + "/details.shtml";
}
@Override
public void lockSessionCart() {
getSessionService().setAttribute(SESSION_LOCKED_CART, cartService.getSessionCart());
getSessionService().removeAttribute(SESSION_CART_PARAMETER_NAME);
//Refresh session for registered users
if (! getCheckoutCustomerStrategy().isAnonymousCheckout()) {
getCartService().getSessionCart();
}
}
@Override
public CartModel restoreSessionCart() throws InvalidCartException {
CartModel cartModel = getSessionService().getAttribute(SESSION_LOCKED_CART);
if (cartModel == null) {
throw new InvalidCartException("Cart does not exist!");
}
getCartService().setSessionCart(cartModel);
getSessionService().removeAttribute(SESSION_LOCKED_CART);
getSessionService().removeAttribute(SESSION_PAYMENT_DATA);
getSessionService().removeAttribute(THREEDS2_FINGERPRINT_TOKEN);
getSessionService().removeAttribute(THREEDS2_CHALLENGE_TOKEN);
getSessionService().removeAttribute(PAYMENT_METHOD);
return cartModel;
}
@Override
public OrderData handleHPPResponse(final HttpServletRequest request) throws SignatureException {
validateHPPResponse(request);
String merchantReference = request.getParameter(HPPConstants.Response.MERCHANT_REFERENCE);
String authResult = request.getParameter(HPPConstants.Response.AUTH_RESULT);
OrderData orderData = null;
//Restore the cart or find the created order
try {
restoreSessionCart();
CartData cartData = getCheckoutFacade().getCheckoutCart();
if (! cartData.getCode().equals(merchantReference)) {
throw new InvalidCartException("Merchant reference doesn't match cart's code");
}
if (HPPConstants.Response.AUTH_RESULT_AUTHORISED.equals(authResult) || HPPConstants.Response.AUTH_RESULT_PENDING.equals(authResult)) {
orderData = getCheckoutFacade().placeOrder();
}
} catch (InvalidCartException e) {
LOGGER.warn("InvalidCartException", e);
//Cart does not exist, retrieve order
orderData = getOrderFacade().getOrderDetailsForCode(merchantReference);
}
return orderData;
}
@Override
public OrderData authorisePayment(final CartData cartData) throws Exception {
CustomerModel customer = null;
if (! getCheckoutCustomerStrategy().isAnonymousCheckout()) {
customer = getCheckoutCustomerStrategy().getCurrentUserForCheckout();
}
PaymentsResponse paymentsResponse = getAdyenPaymentService().authorisePayment(cartData, RequestInfo.empty(), customer);
//In case of Authorized: create order and authorize it
if (PaymentsResponse.ResultCodeEnum.AUTHORISED == paymentsResponse.getResultCode()) {
return createAuthorizedOrder(paymentsResponse);
}
//In case of Received: create order
if (PaymentsResponse.ResultCodeEnum.RECEIVED == paymentsResponse.getResultCode()) {
return createOrderFromPaymentsResponse(paymentsResponse);
}
if (PaymentsResponse.ResultCodeEnum.PRESENTTOSHOPPER == paymentsResponse.getResultCode()) {
return createOrderFromPaymentsResponse(paymentsResponse);
}
throw new AdyenNonAuthorizedPaymentException(paymentsResponse);
}
@Override
public PaymentDetailsWsDTO addPaymentDetails(PaymentDetailsWsDTO paymentDetails) {
CartModel cartModel = cartService.getSessionCart();
final AddressModel billingAddress = createBillingAddress(paymentDetails);
PaymentInfoModel paymentInfo = createPaymentInfo(cartModel, paymentDetails);
paymentInfo.setBillingAddress(billingAddress);
billingAddress.setOwner(paymentInfo);
modelService.save(paymentInfo);
cartModel.setPaymentInfo(paymentInfo);
modelService.save(cartModel);
return paymentDetails;
}
private AddressModel createBillingAddress(PaymentDetailsWsDTO paymentDetails) {
String titleCode = paymentDetails.getBillingAddress().getTitleCode();
final AddressModel billingAddress = getModelService().create(AddressModel.class);
if (StringUtils.isNotBlank(titleCode)) {
final TitleModel title = new TitleModel();
title.setCode(titleCode);
billingAddress.setTitle(getFlexibleSearchService().getModelByExample(title));
}
billingAddress.setFirstname(paymentDetails.getBillingAddress().getFirstName());
billingAddress.setLastname(paymentDetails.getBillingAddress().getLastName());
billingAddress.setLine1(paymentDetails.getBillingAddress().getLine1());
billingAddress.setLine2(paymentDetails.getBillingAddress().getLine2());
billingAddress.setTown(paymentDetails.getBillingAddress().getTown());
billingAddress.setPostalcode(paymentDetails.getBillingAddress().getPostalCode());
billingAddress.setCountry(getCommonI18NService().getCountry(paymentDetails.getBillingAddress().getCountry().getIsocode()));
final AddressData addressData = new AddressData();
addressData.setTitleCode(paymentDetails.getBillingAddress().getTitleCode());
addressData.setFirstName(billingAddress.getFirstname());
addressData.setLastName(billingAddress.getLastname());
addressData.setLine1(billingAddress.getLine1());
addressData.setLine2(billingAddress.getLine2());
addressData.setTown(billingAddress.getTown());
addressData.setPostalCode(billingAddress.getPostalcode());
addressData.setBillingAddress(true);
if (paymentDetails.getBillingAddress().getCountry() != null) {
final CountryData countryData = getI18NFacade().getCountryForIsocode(paymentDetails.getBillingAddress().getCountry().getIsocode());
addressData.setCountry(countryData);
}
if (paymentDetails.getBillingAddress().getRegion().getIsocode() != null) {
final RegionData regionData = getI18NFacade().getRegion(paymentDetails.getBillingAddress().getCountry().getIsocode(), paymentDetails.getBillingAddress().getRegion().getIsocode());
addressData.setRegion(regionData);
}
getAddressReverseConverter().convert(addressData, billingAddress);
return billingAddress;
}
@Override
public PaymentsResponse handleRedirectPayload(HashMap<String, String> details) {
try {
PaymentsResponse response;
String paymentMethod = getSessionService().getAttribute(PAYMENT_METHOD);
if (paymentMethod != null && paymentMethod.startsWith(KLARNA)) {
response = getAdyenPaymentService().getPaymentDetailsFromPayload(details, getSessionService().getAttribute(SESSION_PAYMENT_DATA));
} else {
response = getAdyenPaymentService().getPaymentDetailsFromPayload(details);
}
restoreSessionCart();
CartData cartData = getCheckoutFacade().getCheckoutCart();
if (! cartData.getCode().equals(response.getMerchantReference())) {
throw new InvalidCartException("Merchant reference doesn't match cart's code");
}
if (PaymentsResponse.ResultCodeEnum.RECEIVED == response.getResultCode() || PaymentsResponse.ResultCodeEnum.AUTHORISED == response.getResultCode()) {
getCheckoutFacade().placeOrder();
}
return response;
} catch (Exception e) {
LOGGER.warn(e);
}
throw new IllegalArgumentException("Invalid payload");
}
@Override
public OrderData authorisePayment(final HttpServletRequest request, final CartData cartData) throws Exception {
CustomerModel customer = null;
if (! getCheckoutCustomerStrategy().isAnonymousCheckout()) {
customer = getCheckoutCustomerStrategy().getCurrentUserForCheckout();
}
updateCartWithSessionData(cartData);
String adyenPaymentMethod = cartData.getAdyenPaymentMethod();
if (adyenPaymentMethod.equals(PAYPAL_ECS) || adyenPaymentMethod.startsWith(RATEPAY)) {
PaymentResult paymentResult = getAdyenPaymentService().authorise(cartData, request, customer);
if (PaymentResult.ResultCodeEnum.AUTHORISED == paymentResult.getResultCode()) {
return createAuthorizedOrder(paymentResult);
}
if (PaymentResult.ResultCodeEnum.RECEIVED == paymentResult.getResultCode()) {
return createOrderFromPaymentResult(paymentResult);
}
throw new AdyenNonAuthorizedPaymentException(paymentResult);
}
RequestInfo requestInfo = new RequestInfo(request);
requestInfo.setShopperLocale(getShopperLocale());
PaymentsResponse paymentsResponse = getAdyenPaymentService().authorisePayment(cartData, requestInfo, customer);
if (PaymentsResponse.ResultCodeEnum.AUTHORISED == paymentsResponse.getResultCode()) {
return createAuthorizedOrder(paymentsResponse);
}
if (PaymentsResponse.ResultCodeEnum.RECEIVED == paymentsResponse.getResultCode()) {
return createOrderFromPaymentsResponse(paymentsResponse);
}
if (PaymentsResponse.ResultCodeEnum.PRESENTTOSHOPPER == paymentsResponse.getResultCode()) {
return createOrderFromPaymentsResponse(paymentsResponse);
}
if (PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER == paymentsResponse.getResultCode()) {
if (PAYMENT_METHOD_CC.equals(adyenPaymentMethod) || adyenPaymentMethod.indexOf(PAYMENT_METHOD_ONECLICK) == 0) {
getSessionService().setAttribute(SESSION_MD, paymentsResponse.getRedirect().getData().get(MD));
getSessionService().setAttribute(SESSION_PAYMENT_DATA, paymentsResponse.getPaymentData());
}
if (adyenPaymentMethod.startsWith(KLARNA)) {
getSessionService().setAttribute(PAYMENT_METHOD, adyenPaymentMethod);
getSessionService().setAttribute(SESSION_PAYMENT_DATA, paymentsResponse.getPaymentData());
}
lockSessionCart();
}
if (PaymentsResponse.ResultCodeEnum.IDENTIFYSHOPPER.equals(paymentsResponse.getResultCode())) {
if (PAYMENT_METHOD_CC.equals(adyenPaymentMethod) || adyenPaymentMethod.indexOf(PAYMENT_METHOD_ONECLICK) == 0) {
getSessionService().setAttribute(THREEDS2_FINGERPRINT_TOKEN, paymentsResponse.getAuthentication().get(THREEDS2_FINGERPRINT_TOKEN));
getSessionService().setAttribute(SESSION_PAYMENT_DATA, paymentsResponse.getPaymentData());
}
lockSessionCart();
}
if (PaymentsResponse.ResultCodeEnum.CHALLENGESHOPPER.equals(paymentsResponse.getResultCode())) {
if (PAYMENT_METHOD_CC.equals(adyenPaymentMethod) || adyenPaymentMethod.indexOf(PAYMENT_METHOD_ONECLICK) == 0) {
getSessionService().setAttribute(THREEDS2_CHALLENGE_TOKEN, paymentsResponse.getAuthentication().get(THREEDS2_CHALLENGE_TOKEN));
getSessionService().setAttribute(SESSION_PAYMENT_DATA, paymentsResponse.getPaymentData());
}
lockSessionCart();
}
throw new AdyenNonAuthorizedPaymentException(paymentsResponse);
}
private void updateCartWithSessionData(CartData cartData) {
cartData.setAdyenCseToken(getSessionService().getAttribute(SESSION_CSE_TOKEN));
cartData.setAdyenEncryptedCardNumber(getSessionService().getAttribute(SESSION_SF_CARD_NUMBER));
cartData.setAdyenEncryptedExpiryMonth(getSessionService().getAttribute(SESSION_SF_EXPIRY_MONTH));
cartData.setAdyenEncryptedExpiryYear(getSessionService().getAttribute(SESSION_SF_EXPIRY_YEAR));
cartData.setAdyenEncryptedSecurityCode(getSessionService().getAttribute(SESSION_SF_SECURITY_CODE));
cartData.setAdyenCardBrand(getSessionService().getAttribute(SESSION_CARD_BRAND));
getSessionService().removeAttribute(SESSION_CSE_TOKEN);
getSessionService().removeAttribute(SESSION_SF_CARD_NUMBER);
getSessionService().removeAttribute(SESSION_SF_EXPIRY_MONTH);
getSessionService().removeAttribute(SESSION_SF_EXPIRY_YEAR);
getSessionService().removeAttribute(SESSION_SF_SECURITY_CODE);
getSessionService().removeAttribute(SESSION_CARD_BRAND);
getSessionService().removeAttribute(PAYMENT_METHOD);
getSessionService().removeAttribute(SESSION_PAYMENT_DATA);
}
@Override
public OrderData handle3DResponse(final HttpServletRequest request) throws Exception {
String paRes = request.getParameter(THREE_D_PARES);
String md = request.getParameter(THREE_D_MD);
String sessionMd = getSessionService().getAttribute(SESSION_MD);
String sessionPaymentData = getSessionService().getAttribute(SESSION_PAYMENT_DATA);
try {
//Check if MD matches in order to avoid authorizing wrong order
if (sessionMd != null && ! sessionMd.equals(md)) {
throw new SignatureException("MD does not match!");
}
restoreSessionCart();
PaymentsResponse paymentsResponse = getAdyenPaymentService().authorise3DPayment(sessionPaymentData, paRes, md);
if (PaymentsResponse.ResultCodeEnum.AUTHORISED == paymentsResponse.getResultCode()) {
return createAuthorizedOrder(paymentsResponse);
}
throw new AdyenNonAuthorizedPaymentException(paymentsResponse);
} catch (ApiException e) {
throw e;
}
}
@Override
public OrderData handle3DS2Response(final HttpServletRequest request) throws Exception {
String fingerprintResult = request.getParameter(FINGERPRINT_RESULT);
String challengeResult = request.getParameter(CHALLENGE_RESULT);
String paymentData = getSessionService().getAttribute(SESSION_PAYMENT_DATA);
String type = "";
String token = "";
if (challengeResult != null && ! challengeResult.isEmpty()) {
type = "challenge";
token = challengeResult;
} else if (fingerprintResult != null && ! fingerprintResult.isEmpty()) {
type = "fingerprint";
token = fingerprintResult;
}
try {
PaymentsResponse paymentsResponse = getAdyenPaymentService().authorise3DS2Payment(paymentData, token, type);
if (paymentsResponse.getResultCode() != PaymentsResponse.ResultCodeEnum.IDENTIFYSHOPPER && paymentsResponse.getResultCode() != PaymentsResponse.ResultCodeEnum.CHALLENGESHOPPER) {
restoreSessionCart();
}
if (PaymentsResponse.ResultCodeEnum.AUTHORISED == paymentsResponse.getResultCode()) {
return createAuthorizedOrder(paymentsResponse);
}
throw new AdyenNonAuthorizedPaymentException(paymentsResponse);
} catch (ApiException e) {
if (type.equals("challenge")) {
LOGGER.debug("Restoring cart because ApiException occurred after challengeResult ");
restoreSessionCart();
}
throw e;
}
}
@Override
public Map<String, String> initializeHostedPayment(final CartData cartData, final String redirectUrl) throws SignatureException, InvalidCartException {
final String sessionValidity = Util.calculateSessionValidity();
final SortedMap<String, String> hppFormData = new TreeMap<>();
BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
String merchantAccount = baseStore.getAdyenMerchantAccount();
String skinCode = baseStore.getAdyenSkinCode();
String hmacKey = baseStore.getAdyenSkinHMAC();
Assert.notNull(merchantAccount);
Assert.notNull(skinCode);
Assert.notNull(hmacKey);
Amount amount = Util.createAmount(cartData.getTotalPrice().getValue(), cartData.getTotalPrice().getCurrencyIso());
//Identify country code based on shopper's delivery address
String countryCode = "";
AddressData deliveryAddress = cartData.getDeliveryAddress();
if (deliveryAddress != null) {
CountryData deliveryCountry = deliveryAddress.getCountry();
if (deliveryCountry != null) {
countryCode = deliveryCountry.getIsocode();
}
}
CartModel cartModel = regenerateCartCode();
String merchantReference = cartModel.getCode();
hppFormData.put(PAYMENT_AMOUNT, String.valueOf(amount.getValue()));
hppFormData.put(CURRENCY_CODE, cartData.getTotalPrice().getCurrencyIso());
hppFormData.put(SHIP_BEFORE_DATE, sessionValidity);
hppFormData.put(MERCHANT_REFERENCE, merchantReference);
hppFormData.put(SKIN_CODE, skinCode);
hppFormData.put(MERCHANT_ACCOUNT, merchantAccount);
hppFormData.put(SESSION_VALIDITY, sessionValidity);
hppFormData.put(BRAND_CODE, cartData.getAdyenPaymentMethod());
hppFormData.put(ISSUER_ID, cartData.getAdyenIssuerId());
hppFormData.put(COUNTRY_CODE, countryCode);
hppFormData.put(RES_URL, redirectUrl);
hppFormData.put(DF_VALUE, cartData.getAdyenDfValue());
if (! StringUtils.isEmpty(getShopperLocale())) {
hppFormData.put(SHOPPER_LOCALE, getShopperLocale());
}
String dataToSign = getHmacValidator().getDataToSign(hppFormData);
String merchantSig = getHmacValidator().calculateHMAC(dataToSign, hmacKey);
hppFormData.put(MERCHANT_SIG, merchantSig);
//Lock the cart
lockSessionCart();
return hppFormData;
}
private CartModel regenerateCartCode() {
final CartModel cartModel = cartService.getSessionCart();
cartModel.setCode(String.valueOf(keyGenerator.generate()));
cartService.saveOrder(cartModel);
return cartModel;
}
/**
* Create order and authorized TX
*/
private OrderData createAuthorizedOrder(final PaymentsResponse paymentsResponse) throws InvalidCartException {
final CartModel cartModel = cartService.getSessionCart();
final String merchantTransactionCode = cartModel.getCode();
//First save the transactions to the CartModel < AbstractOrderModel
getAdyenTransactionService().authorizeOrderModel(cartModel, merchantTransactionCode, paymentsResponse.getPspReference());
return createOrderFromPaymentsResponse(paymentsResponse);
}
/**
* Create order and authorized TX
*/
private OrderData createAuthorizedOrder(final PaymentResult paymentResult) throws InvalidCartException {
PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult);
return createAuthorizedOrder(paymentsResponse);
}
/**
* Create order
*/
private OrderData createOrderFromPaymentsResponse(final PaymentsResponse paymentsResponse) throws InvalidCartException {
LOGGER.debug("Create order from paymentsResponse: " + paymentsResponse.getPspReference());
OrderData orderData = getCheckoutFacade().placeOrder();
OrderModel orderModel = orderRepository.getOrderModel(orderData.getCode());
updateOrder(orderModel, paymentsResponse);
orderData.setAdyenBoletoUrl(paymentsResponse.getBoletoUrl());
orderData.setAdyenBoletoData(paymentsResponse.getBoletoData());
orderData.setAdyenBoletoBarCodeReference(paymentsResponse.getBoletoBarCodeReference());
orderData.setAdyenBoletoExpirationDate(paymentsResponse.getBoletoExpirationDate());
orderData.setAdyenBoletoDueDate(paymentsResponse.getBoletoDueDate());
orderData.setAdyenMultibancoEntity(paymentsResponse.getMultibancoEntity());
orderData.setAdyenMultibancoAmount(paymentsResponse.getMultibancoAmount());
orderData.setAdyenMultibancoDeadline(paymentsResponse.getMultibancoDeadline());
orderData.setAdyenMultibancoReference(paymentsResponse.getMultibancoReference());
if (paymentsResponse.getAdditionalData() != null) {
orderData.setAdyenPosReceipt(paymentsResponse.getAdditionalData().get("pos.receipt"));
}
return orderData;
}
/**
* Create order
*/
private OrderData createOrderFromPaymentResult(final PaymentResult paymentResult) throws InvalidCartException {
PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult);
return createOrderFromPaymentsResponse(paymentsResponse);
}
private void updateOrder(final OrderModel orderModel, final PaymentsResponse paymentsResponse) {
try {
adyenOrderService.updateOrderFromPaymentsResponse(orderModel, paymentsResponse);
} catch (Exception e) {
LOGGER.error(e);
}
}
@Override
public void initializeCheckoutData(Model model) {
final CartData cartData = getCheckoutFacade().getCheckoutCart();
AdyenPaymentService adyenPaymentService = getAdyenPaymentService();
//Set APMs from Adyen HPP Directory Lookup
List<PaymentMethod> alternativePaymentMethods = new ArrayList<>();
String iDealissuerList = null;
List<String> connectedTerminalList = null;
try {
alternativePaymentMethods = adyenPaymentService.getPaymentMethods(cartData.getTotalPrice().getValue(),
cartData.getTotalPrice().getCurrencyIso(),
cartData.getDeliveryAddress().getCountry().getIsocode(),
getShopperLocale(),
null);
PaymentMethod idealPaymentMethod = alternativePaymentMethods.stream()
.filter(paymentMethod -> ! paymentMethod.getType().isEmpty() && PAYMENT_METHOD_IDEAL.equals(paymentMethod.getType()))
.findFirst()
.orElse(null);
if (showPos()) {
connectedTerminalList = adyenPaymentService.getConnectedTerminals().getUniqueTerminalIds();
}
if (idealPaymentMethod != null) {
Gson gson = new Gson();
iDealissuerList = gson.toJson(idealPaymentMethod.getDetails());
}
//Exclude cards, boleto, bcmc and bcmc_mobile_QR and iDeal
alternativePaymentMethods = alternativePaymentMethods.stream()
.filter(paymentMethod -> ! paymentMethod.getType().isEmpty() && ! isHiddenPaymentMethod(paymentMethod))
.collect(Collectors.toList());
} catch (ApiException | IOException e) {
LOGGER.error(ExceptionUtils.getStackTrace(e));
}
//Set allowed cards from BaseStore configuration
BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
List<RecurringDetail> storedCards = new ArrayList<>();
boolean showRememberTheseDetails = showRememberDetails();
if (showRememberTheseDetails) {
//Include stored cards
CustomerModel customerModel = getCheckoutCustomerStrategy().getCurrentUserForCheckout();
try {
storedCards = adyenPaymentService.getStoredCards(customerModel.getCustomerID());
} catch (ApiException e) {
LOGGER.error("API Exception", e);
} catch (Exception e) {
LOGGER.error(ExceptionUtils.getStackTrace(e));
}
}
// current selected PaymentMethod
model.addAttribute(MODEL_SELECTED_PAYMENT_METHOD, cartData.getAdyenPaymentMethod());
//Set HPP payment methods
model.addAttribute(MODEL_PAYMENT_METHODS, alternativePaymentMethods);
//Set allowed Credit Cards
model.addAttribute(MODEL_ALLOWED_CARDS, baseStore.getAdyenAllowedCards());
model.addAttribute(MODEL_REMEMBER_DETAILS, showRememberTheseDetails);
model.addAttribute(MODEL_STORED_CARDS, storedCards);
model.addAttribute(MODEL_DF_URL, adyenPaymentService.getDeviceFingerprintUrl());
model.addAttribute(MODEL_CHECKOUT_SHOPPER_HOST, getCheckoutShopperHost());
model.addAttribute(MODEL_ENVIRONMENT_MODE, getEnvironmentMode());
model.addAttribute(SHOPPER_LOCALE, getShopperLocale());
Set<String> recurringDetailReferences = new HashSet<>();
if (storedCards != null) {
recurringDetailReferences = storedCards.stream().map(RecurringDetail::getRecurringDetailReference).collect(Collectors.toSet());
}
//Set stored cards to model
CartModel cartModel = cartService.getSessionCart();
cartModel.setAdyenStoredCards(recurringDetailReferences);
// OpenInvoice Methods
model.addAttribute(MODEL_OPEN_INVOICE_METHODS, OPENINVOICE_METHODS_API);
// retrieve shipping Country to define if social security number needs to be shown or date of birth field for openinvoice methods
model.addAttribute(MODEL_SHOW_SOCIAL_SECURITY_NUMBER, showSocialSecurityNumber());
//Include Boleto banks
model.addAttribute(MODEL_SHOW_BOLETO, showBoleto());
//Include POS Enable configuration
model.addAttribute(MODEL_SHOW_POS, showPos());
//Include connnected terminal List for POS
model.addAttribute(MODEL_CONNECTED_TERMINAL_LIST, connectedTerminalList);
//Include Issuer List for iDEAL
model.addAttribute(MODEL_IDEAL_ISSUER_LIST, iDealissuerList);
modelService.save(cartModel);
}
private boolean isHiddenPaymentMethod(PaymentMethod paymentMethod) {
String paymentMethodType = paymentMethod.getType();
if (paymentMethodType == null
|| paymentMethodType.isEmpty()
|| paymentMethodType.equals("scheme")
|| paymentMethodType.equals("bcmc")
|| paymentMethodType.equals("bcmc_mobile_QR")
|| paymentMethodType.equals(PAYMENT_METHOD_IDEAL)
|| (paymentMethodType.contains("wechatpay") && ! paymentMethodType.equals("wechatpayWeb"))
|| paymentMethodType.startsWith(PAYMENT_METHOD_BOLETO)) {
return true;
}
return false;
}
@Override
public boolean showBoleto() {
BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
//Check base store settings
if (baseStore.getAdyenBoleto() == null || ! baseStore.getAdyenBoleto()) {
return false;
}
CartData cartData = getCheckoutFacade().getCheckoutCart();
String currency = cartData.getTotalPrice().getCurrencyIso();
String country = cartData.getDeliveryAddress().getCountry().getIsocode();
//Show only on Brasil with BRL
return "BRL".equals(currency) && "BR".equals(country);
}
@Override
public boolean showPos() {
BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
//Check base store settings for POS Enabled or not.
if (baseStore.getAdyenPosEnabled() == null || ! baseStore.getAdyenPosEnabled()) {
return false;
}
return true;
}
@Override
public boolean showRememberDetails() {
BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
/*
* The show remember me checkout should only be shown as the
* user is logged in and the recurirng mode is set to ONECLICK or ONECLICK,RECURRING
*/
RecurringContractMode recurringContractMode = baseStore.getAdyenRecurringContractMode();
if (! getCheckoutCustomerStrategy().isAnonymousCheckout()) {
if (Recurring.ContractEnum.ONECLICK_RECURRING.name().equals(recurringContractMode.getCode()) || Recurring.ContractEnum.ONECLICK.name().equals(recurringContractMode.getCode())) {
return true;
}
}
return false;
}
@Override
public boolean showSocialSecurityNumber() {
Boolean showSocialSecurityNumber = false;
CartData cart = getCheckoutFacade().getCheckoutCart();
final AddressData deliveryAddress = cart.getDeliveryAddress();
String countryCode = deliveryAddress.getCountry().getIsocode();
if (RATEPAY.equals(cart.getAdyenPaymentMethod()) && OPENINVOICE_METHODS_ALLOW_SOCIAL_SECURITY_NUMBER.contains(countryCode)) {
showSocialSecurityNumber = true;
}
return showSocialSecurityNumber;
}
@Override
public PaymentInfoModel createPaymentInfo(final CartModel cartModel, AdyenPaymentForm adyenPaymentForm) {
final PaymentInfoModel paymentInfo = modelService.create(PaymentInfoModel.class);
paymentInfo.setUser(cartModel.getUser());
paymentInfo.setSaved(false);
paymentInfo.setCode(generateCcPaymentInfoCode(cartModel));
// Clone DeliveryAdress to BillingAddress
final AddressModel clonedAddress = modelService.clone(cartModel.getDeliveryAddress());
clonedAddress.setBillingAddress(true);
clonedAddress.setOwner(paymentInfo);
paymentInfo.setBillingAddress(clonedAddress);
paymentInfo.setAdyenPaymentMethod(adyenPaymentForm.getPaymentMethod());
paymentInfo.setAdyenIssuerId(adyenPaymentForm.getIssuerId());
paymentInfo.setAdyenRememberTheseDetails(adyenPaymentForm.getRememberTheseDetails());
paymentInfo.setAdyenSelectedReference(adyenPaymentForm.getSelectedReference());
// openinvoice fields
paymentInfo.setAdyenDob(adyenPaymentForm.getDob());
paymentInfo.setAdyenSocialSecurityNumber(adyenPaymentForm.getSocialSecurityNumber());
// Boleto fields
paymentInfo.setAdyenFirstName(adyenPaymentForm.getFirstName());
paymentInfo.setAdyenLastName(adyenPaymentForm.getLastName());
paymentInfo.setAdyenCardHolder(adyenPaymentForm.getCardHolder());
//required for 3DS2
paymentInfo.setAdyenBrowserInfo(adyenPaymentForm.getBrowserInfo());
//pos field(s)
paymentInfo.setAdyenTerminalId(adyenPaymentForm.getTerminalId());
modelService.save(paymentInfo);
return paymentInfo;
}
public PaymentInfoModel createPaymentInfo(final CartModel cartModel, PaymentDetailsWsDTO paymentDetails) {
final PaymentInfoModel paymentInfo = modelService.create(PaymentInfoModel.class);
paymentInfo.setUser(cartModel.getUser());
paymentInfo.setSaved(false);
paymentInfo.setCode(generateCcPaymentInfoCode(cartModel));
paymentInfo.setAdyenIssuerId(paymentDetails.getIssueNumber());
paymentInfo.setAdyenCardHolder(paymentDetails.getAccountHolderName());
paymentInfo.setEncryptedCardNumber(paymentDetails.getEncryptedCardNumber());
paymentInfo.setEncryptedExpiryMonth(paymentDetails.getEncryptedExpiryMonth());
paymentInfo.setEncryptedExpiryYear(paymentDetails.getEncryptedExpiryYear());
paymentInfo.setEncryptedSecurityCode(paymentDetails.getEncryptedSecurityCode());
paymentInfo.setAdyenRememberTheseDetails(paymentDetails.getSaveCardData());
paymentInfo.setAdyenPaymentMethod(paymentDetails.getAdyenPaymentMethod());
paymentInfo.setAdyenSelectedReference(paymentDetails.getAdyenSelectedReference());
paymentInfo.setAdyenSocialSecurityNumber(paymentDetails.getAdyenSocialSecurityNumber());
paymentInfo.setAdyenFirstName(paymentDetails.getAdyenFirstName());
paymentInfo.setAdyenLastName(paymentDetails.getAdyenLastName());
paymentInfo.setOwner(cartModel.getOwner());
paymentInfo.setAdyenTerminalId(paymentDetails.getTerminalId());
paymentInfo.setAdyenInstallments(paymentDetails.getInstallments());
return paymentInfo;
}
@Override
public void handlePaymentForm(AdyenPaymentForm adyenPaymentForm, BindingResult bindingResult) {
//Validate form
CartModel cartModel = cartService.getSessionCart();
boolean showRememberDetails = showRememberDetails();
boolean showSocialSecurityNumber = showSocialSecurityNumber();
AdyenPaymentFormValidator adyenPaymentFormValidator = new AdyenPaymentFormValidator(cartModel.getAdyenStoredCards(), showRememberDetails, showSocialSecurityNumber);
adyenPaymentFormValidator.validate(adyenPaymentForm, bindingResult);
if (bindingResult.hasErrors()) {
return;
}
//Put encrypted data to session
if (! StringUtils.isEmpty(adyenPaymentForm.getCseToken())) {
getSessionService().setAttribute(SESSION_CSE_TOKEN, adyenPaymentForm.getCseToken());
}
if (! StringUtils.isEmpty(adyenPaymentForm.getEncryptedCardNumber())) {
getSessionService().setAttribute(SESSION_SF_CARD_NUMBER, adyenPaymentForm.getEncryptedCardNumber());
}
if (! StringUtils.isEmpty(adyenPaymentForm.getEncryptedExpiryMonth())) {
getSessionService().setAttribute(SESSION_SF_EXPIRY_MONTH, adyenPaymentForm.getEncryptedExpiryMonth());
}
if (! StringUtils.isEmpty(adyenPaymentForm.getEncryptedExpiryYear())) {
getSessionService().setAttribute(SESSION_SF_EXPIRY_YEAR, adyenPaymentForm.getEncryptedExpiryYear());
}
if (! StringUtils.isEmpty(adyenPaymentForm.getEncryptedSecurityCode())) {
getSessionService().setAttribute(SESSION_SF_SECURITY_CODE, adyenPaymentForm.getEncryptedSecurityCode());
}
if (! StringUtils.isEmpty(adyenPaymentForm.getCardBrand())) {
getSessionService().setAttribute(SESSION_CARD_BRAND, adyenPaymentForm.getCardBrand());
}
//Update CartModel
cartModel.setAdyenDfValue(adyenPaymentForm.getDfValue());
//Create payment info
PaymentInfoModel paymentInfo = createPaymentInfo(cartModel, adyenPaymentForm);
cartModel.setPaymentInfo(paymentInfo);
modelService.save(cartModel);
}
@Override
public PaymentDetailsListWsDTO getPaymentDetails(String userId) throws IOException, ApiException {
CustomerModel customer = getCheckoutCustomerStrategy().getCurrentUserForCheckout();
List<RecurringDetail> recurringDetails = getAdyenPaymentService().getStoredCards(customer.getCustomerID());
PaymentDetailsListWsDTO paymentDetailsListWsDTO = new PaymentDetailsListWsDTO();
paymentDetailsListWsDTO.setPayments(toPaymentDetails(recurringDetails));
return paymentDetailsListWsDTO;
}
private List<PaymentDetailsWsDTO> toPaymentDetails(List<RecurringDetail> recurringDetails) {
return recurringDetails.stream().map(r -> toPaymentDetail(r)).collect(Collectors.toList());
}
private PaymentDetailsWsDTO toPaymentDetail(RecurringDetail recurringDetail) {
PaymentDetailsWsDTO paymentDetailsWsDTO = new PaymentDetailsWsDTO();
Card card = recurringDetail.getCard();
if (card == null) {
throw new RuntimeException("Card information not found");
}
paymentDetailsWsDTO.setAccountHolderName(card.getHolderName());
paymentDetailsWsDTO.setCardNumber("**** **** **** " + card.getNumber());
paymentDetailsWsDTO.setExpiryMonth(card.getExpiryMonth());
paymentDetailsWsDTO.setExpiryYear(card.getExpiryYear());
paymentDetailsWsDTO.setSubscriptionId(recurringDetail.getRecurringDetailReference());
return paymentDetailsWsDTO;
}
@Override
public String getShopperLocale() {
if (commonI18NService.getCurrentLanguage() != null) {
return commonI18NService.getCurrentLanguage().getIsocode();
}
return null;
}
/**
* Helper function for retrieving only GET parameters (of querystring)
*
* @param request HttpServletRequest request object
* @return Sorted map with parameters
*/
private static SortedMap<String, String> getQueryParameters(HttpServletRequest request) {
SortedMap<String, String> queryParameters = new TreeMap<>();
String queryString = request.getQueryString();
if (StringUtils.isEmpty(queryString)) {
return queryParameters;
}
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String key = keyValuePair[0];
String value = request.getParameter(key);
// Add only HPP parameters for signature calculation
if (HPP_RESPONSE_PARAMETERS.contains(key) || key.startsWith("additionalData.")) {
queryParameters.put(key, value);
}
}
return queryParameters;
}
protected String generateCcPaymentInfoCode(final CartModel cartModel) {
return cartModel.getCode() + "_" + UUID.randomUUID();
}
public AdyenPaymentService getAdyenPaymentService() {
return adyenPaymentServiceFactory.createFromBaseStore(baseStoreService.getCurrentBaseStore());
}
/**
* Initiate POS Payment using Adyen Terminal API
*/
@Override
public OrderData initiatePosPayment(HttpServletRequest request, CartData cartData) throws Exception {
CustomerModel customer = null;
if (! getCheckoutCustomerStrategy().isAnonymousCheckout()) {
customer = getCheckoutCustomerStrategy().getCurrentUserForCheckout();
}
//This will be used to check status later
String serviceId = request.getAttribute("originalServiceId").toString();
TerminalAPIResponse terminalApiResponse = getAdyenPaymentService().sendSyncPosPaymentRequest(cartData, customer, serviceId);
ResultType resultType = TerminalAPIUtil.getPaymentResultFromStatusOrPaymentResponse(terminalApiResponse);
if (ResultType.SUCCESS == resultType) {
PaymentsResponse paymentsResponse = getPosPaymentResponseConverter().convert(terminalApiResponse.getSaleToPOIResponse());
String posReceipt = TerminalAPIUtil.getReceiptFromPaymentResponse(terminalApiResponse);
if (StringUtils.isNotEmpty(posReceipt)) {
paymentsResponse.putAdditionalDataItem("pos.receipt", posReceipt);
}
return createAuthorizedOrder(paymentsResponse);
}
throw new AdyenNonAuthorizedPaymentException(terminalApiResponse);
}
/**
* Check POS Payment Status using Adyen Terminal API
*/
@Override
public OrderData checkPosPaymentStatus(HttpServletRequest request, CartData cartData) throws Exception {
String originalServiceId = request.getAttribute("originalServiceId").toString();
TerminalAPIResponse terminalApiResponse = getAdyenPaymentService().sendSyncPosStatusRequest(cartData, originalServiceId);
ResultType statusResult = TerminalAPIUtil.getStatusResultFromStatusResponse(terminalApiResponse);
if (statusResult != null) {
if (statusResult == ResultType.SUCCESS) {
//this will be success even if payment is failed. because this belongs to status call not payment call
ResultType paymentResult = TerminalAPIUtil.getPaymentResultFromStatusOrPaymentResponse(terminalApiResponse);
if (paymentResult == ResultType.SUCCESS) {
PaymentsResponse paymentsResponse = getPosPaymentResponseConverter().convert(terminalApiResponse.getSaleToPOIResponse());
String posReceipt = TerminalAPIUtil.getReceiptFromStatusResponse(terminalApiResponse);
if (StringUtils.isNotEmpty(posReceipt)) {
paymentsResponse.putAdditionalDataItem("pos.receipt", posReceipt);
}
return createAuthorizedOrder(paymentsResponse);
} else {
throw new AdyenNonAuthorizedPaymentException(terminalApiResponse);
}
} else {
ErrorConditionType errorCondition = TerminalAPIUtil.getErrorConditionForStatusFromStatusResponse(terminalApiResponse);
//If transaction is still in progress, keep retrying in 5 seconds.
if (errorCondition == ErrorConditionType.IN_PROGRESS) {
TimeUnit.SECONDS.sleep(5);
if (isPosTimedOut(request)) {
throw new AdyenNonAuthorizedPaymentException(terminalApiResponse);
} else {
return checkPosPaymentStatus(request, cartData);
}
} else {
throw new AdyenNonAuthorizedPaymentException(terminalApiResponse);
}
}
}
//probably returned SaleToPOIRequest, that means terminal unreachable, return the response as error
throw new AdyenNonAuthorizedPaymentException(terminalApiResponse);
}
private boolean isPosTimedOut(HttpServletRequest request) {
long currentTime = System.currentTimeMillis();
long processStartTime = (long) request.getAttribute("paymentStartTime");
int totalTimeout = ((int) request.getAttribute("totalTimeout")) * 1000;
long timeDiff = currentTime - processStartTime;
if (timeDiff >= totalTimeout) {
return true;
} else {
return false;
}
}
public BaseStoreService getBaseStoreService() {
return baseStoreService;
}
public void setBaseStoreService(BaseStoreService baseStoreService) {
this.baseStoreService = baseStoreService;
}
public SessionService getSessionService() {
return sessionService;
}
public void setSessionService(SessionService sessionService) {
this.sessionService = sessionService;
}
public CartService getCartService() {
return cartService;
}
public void setCartService(CartService cartService) {
this.cartService = cartService;
}
public OrderFacade getOrderFacade() {
return orderFacade;
}
public void setOrderFacade(OrderFacade orderFacade) {
this.orderFacade = orderFacade;
}
public CheckoutFacade getCheckoutFacade() {
return checkoutFacade;
}
public void setCheckoutFacade(CheckoutFacade checkoutFacade) {
this.checkoutFacade = checkoutFacade;
}
public AdyenTransactionService getAdyenTransactionService() {
return adyenTransactionService;
}
public void setAdyenTransactionService(AdyenTransactionService adyenTransactionService) {
this.adyenTransactionService = adyenTransactionService;
}
public OrderRepository getOrderRepository() {
return orderRepository;
}
public void setOrderRepository(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
public AdyenOrderService getAdyenOrderService() {
return adyenOrderService;
}
public void setAdyenOrderService(AdyenOrderService adyenOrderService) {
this.adyenOrderService = adyenOrderService;
}
public CheckoutCustomerStrategy getCheckoutCustomerStrategy() {
return checkoutCustomerStrategy;
}
public void setCheckoutCustomerStrategy(CheckoutCustomerStrategy checkoutCustomerStrategy) {
this.checkoutCustomerStrategy = checkoutCustomerStrategy;
}
public HMACValidator getHmacValidator() {
return hmacValidator;
}
public void setHmacValidator(HMACValidator hmacValidator) {
this.hmacValidator = hmacValidator;
}
public AdyenPaymentServiceFactory getAdyenPaymentServiceFactory() {
return adyenPaymentServiceFactory;
}
public void setAdyenPaymentServiceFactory(AdyenPaymentServiceFactory adyenPaymentServiceFactory) {
this.adyenPaymentServiceFactory = adyenPaymentServiceFactory;
}
public ModelService getModelService() {
return modelService;
}
public void setModelService(ModelService modelService) {
this.modelService = modelService;
}
public CommonI18NService getCommonI18NService() {
return commonI18NService;
}
public void setCommonI18NService(CommonI18NService commonI18NService) {
this.commonI18NService = commonI18NService;
}
public KeyGenerator getKeyGenerator() {
return keyGenerator;
}
public void setKeyGenerator(KeyGenerator keyGenerator) {
this.keyGenerator = keyGenerator;
}
public PaymentsResponseConverter getPaymentsResponseConverter() {
return paymentsResponseConverter;
}
public void setPaymentsResponseConverter(PaymentsResponseConverter paymentsResponseConverter) {
this.paymentsResponseConverter = paymentsResponseConverter;
}
public FlexibleSearchService getFlexibleSearchService() {
return flexibleSearchService;
}
public void setFlexibleSearchService(FlexibleSearchService flexibleSearchService) {
this.flexibleSearchService = flexibleSearchService;
}
public Converter<AddressData, AddressModel> getAddressReverseConverter() {
return addressReverseConverter;
}
public void setAddressReverseConverter(Converter<AddressData, AddressModel> addressReverseConverter) {
this.addressReverseConverter = addressReverseConverter;
}
public I18NFacade getI18NFacade() {
return i18NFacade;
}
public void setI18NFacade(I18NFacade i18NFacade) {
this.i18NFacade = i18NFacade;
}
public PosPaymentResponseConverter getPosPaymentResponseConverter() {
return posPaymentResponseConverter;
}
public void setPosPaymentResponseConverter(PosPaymentResponseConverter posPaymentResponseConverter) {
this.posPaymentResponseConverter = posPaymentResponseConverter;
}
} |
package lucee.runtime.op;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.sql.Blob;
import java.sql.Clob;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Pattern;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import lucee.commons.date.DateTimeUtil;
import lucee.commons.i18n.FormatUtil;
import lucee.commons.lang.CFTypes;
import lucee.commons.lang.StringUtil;
import lucee.runtime.Component;
import lucee.runtime.PageContext;
import lucee.runtime.coder.Base64Util;
import lucee.runtime.converter.WDDXConverter;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.ext.function.Function;
import lucee.runtime.image.ImageUtil;
import lucee.runtime.java.JavaObject;
import lucee.runtime.net.mail.MailUtil;
import lucee.runtime.op.date.DateCaster;
import lucee.runtime.op.validators.ValidateCreditCard;
import lucee.runtime.text.xml.XMLCaster;
import lucee.runtime.text.xml.XMLUtil;
import lucee.runtime.text.xml.struct.XMLStruct;
import lucee.runtime.type.Array;
import lucee.runtime.type.Closure;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.Lambda;
import lucee.runtime.type.ObjectWrap;
import lucee.runtime.type.Objects;
import lucee.runtime.type.Pojo;
import lucee.runtime.type.Query;
import lucee.runtime.type.QueryColumn;
import lucee.runtime.type.Struct;
import lucee.runtime.type.UDF;
import lucee.runtime.type.dt.DateTime;
/**
* Object to test if an Object is a specific type
*/
public final class Decision {
private static final String STRING_DEFAULT_VALUE = "this is a unique string";
private static Pattern ssnPattern;
private static Pattern phonePattern;
private static Pattern zipPattern;
/**
* tests if value is a simple value (Number,String,Boolean,Date,Printable)
*
* @param value value to test
* @return is value a simple value
*/
public static boolean isSimpleValue(Object value) {
return (value instanceof Number) || (value instanceof Locale) || (value instanceof TimeZone) || (value instanceof String) || (value instanceof Boolean)
|| (value instanceof Date) || ((value instanceof Castable) && !(value instanceof Objects) && !(value instanceof Collection));
}
public static boolean isSimpleValueLimited(Object value) {
return (value instanceof Number) || (value instanceof Locale) || (value instanceof TimeZone) || (value instanceof String) || (value instanceof Boolean)
|| (value instanceof Date);
}
/**
* tests if value is Numeric
*
* @param value value to test
* @return is value numeric
*/
public static boolean isNumber(Object value) {
if (value instanceof Number) return true;
else if (value instanceof CharSequence || value instanceof Character) {
return isNumber(value.toString());
}
else return false;
}
public static boolean isCastableToNumeric(Object o) {
if (isNumber(o)) return true;
else if (isBoolean(o)) return true;
else if (isDateSimple(o, false)) return true;
else if (o == null) return true;
else if (o instanceof ObjectWrap) return isCastableToNumeric(((ObjectWrap) o).getEmbededObject("notanumber"));
else if (o instanceof Castable) {
return Decision.isValid(((Castable) o).castToDoubleValue(Double.NaN));
}
return false;
}
public static boolean isCastableToDate(Object o) {
if (isDateAdvanced(o, true)) return true;
else if (isBoolean(o)) return true;
else if (o instanceof ObjectWrap) return isCastableToDate(((ObjectWrap) o).getEmbededObject("notadate"));
else if (o instanceof Castable) {
return ((Castable) o).castToDateTime(null) != null;
}
return false;
}
/**
* tests if value is Numeric
*
* @param value value to test
* @return is value numeric
*/
public static boolean isNumber(Object value, boolean alsoBooleans) {
if (alsoBooleans && isBoolean(value)) return true;
return isNumber(value);
}
/**
* tests if String value is Numeric
*
* @param str value to test
* @return is value numeric
*/
public static boolean isNumber(String str) {
if (str == null) return false;
str = str.trim();
int pos = 0;
int len = str.length();
if (len == 0) return false;
char curr = str.charAt(pos);
if (curr == '+' || curr == '-') {
if (len == ++pos) return false;
curr = str.charAt(pos);
}
boolean hasDot = false;
boolean hasExp = false;
for (; pos < len; pos++) {
curr = str.charAt(pos);
if (curr < '0') {
if (curr == '.') {
if (pos + 1 >= len || hasDot) return false;
hasDot = true;
}
else return false;
}
else if (curr > '9') {
if (curr == 'e' || curr == 'E') {
if (pos + 1 >= len || hasExp) return false;
hasExp = true;
hasDot = true;
}
else return false;
}
}
if (hasExp) {
try {
if (Double.isInfinite(Double.parseDouble(str))) return false;
return true;
}
catch (NumberFormatException e) {
return false;
}
}
return true;
}
public static boolean isInteger(Object value) {
return isInteger(value, false);
}
public static boolean isInteger(Object value, boolean alsoBooleans) {
if (!alsoBooleans && value instanceof Boolean) return false;
double dbl = Caster.toDoubleValue(value, false, Double.NaN);
if (!Decision.isValid(dbl)) return false;
int i = (int) dbl;
return i == dbl;
}
/**
* tests if String value is Hex Value
*
* @param str value to test
* @return is value numeric
*/
public static boolean isHex(String str) {
if (str == null || str.length() == 0) return false;
for (int i = str.length() - 1; i >= 0; i
char c = str.charAt(i);
if (!(c >= '0' && c <= '9')) {
c = Character.toLowerCase(c);
if (!(c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')) return false;
}
}
return true;
}
/**
* tests if String value is UUID Value
*
* @param obj value to test
* @return is value numeric
*/
public static boolean isUUId(Object obj) {
String str = Caster.toString(obj, null);
if (str == null) return false;
if (str.length() == 35) {
return Decision.isHex(str.substring(0, 8)) && str.charAt(8) == '-' && Decision.isHex(str.substring(9, 13)) && str.charAt(13) == '-'
&& Decision.isHex(str.substring(14, 18)) && str.charAt(18) == '-' && Decision.isHex(str.substring(19));
}
else if (str.length() == 32) return Decision.isHex(str);
return false;
}
public static boolean isGUId(Object obj) {
String str = Caster.toString(obj, null);
if (str == null) return false;
// GUID
if (str.length() == 36) {
return Decision.isHex(str.substring(0, 8)) && str.charAt(8) == '-' && Decision.isHex(str.substring(9, 13)) && str.charAt(13) == '-'
&& Decision.isHex(str.substring(14, 18)) && str.charAt(18) == '-' && Decision.isHex(str.substring(19, 23)) && str.charAt(23) == '-'
&& Decision.isHex(str.substring(24));
}
return false;
}
public static boolean isGUIdSimple(Object obj) {
String str = Caster.toString(obj, null);
if (str == null) return false;
// GUID
if (str.length() == 36) {
return str.charAt(8) == '-' && str.charAt(13) == '-' && str.charAt(18) == '-' && str.charAt(23) == '-';
}
return false;
}
/**
* tests if value is a Boolean (Numbers are not acctepeted)
*
* @param value value to test
* @return is value boolean
*/
public static boolean isBoolean(Object value) {
if (value instanceof Boolean) return true;
else if (value instanceof String) {
return isBoolean(value.toString());
}
else if (value instanceof ObjectWrap) return isBoolean(((ObjectWrap) value).getEmbededObject(null));
else return false;
}
public static boolean isCastableToBoolean(Object value) {
if (value instanceof Boolean) return true;
if (value instanceof Number) return true;
else if (value instanceof String) {
String str = (String) value;
return isBoolean(str) || isNumber(str);
}
else if (value instanceof Castable) {
return ((Castable) value).castToBoolean(null) != null;
}
else if (value instanceof ObjectWrap) return isCastableToBoolean(((ObjectWrap) value).getEmbededObject(null));
else return false;
}
public static boolean isBoolean(Object value, boolean alsoNumbers) {
if (isBoolean(value)) return true;
else if (alsoNumbers) return isNumber(value);
else return false;
}
/**
* tests if value is a Boolean
*
* @param str value to test
* @return is value boolean
*/
public static boolean isBoolean(String str) {
// str=str.trim();
if (str.length() < 2) return false;
switch (str.charAt(0)) {
case 't':
case 'T':
return str.equalsIgnoreCase("true");
case 'f':
case 'F':
return str.equalsIgnoreCase("false");
case 'y':
case 'Y':
return str.equalsIgnoreCase("yes");
case 'n':
case 'N':
return str.equalsIgnoreCase("no");
}
return false;
}
/**
* tests if value is DateTime Object
*
* @param value value to test
* @param alsoNumbers interpret also a number as date
* @return is value a DateTime Object
*/
public static boolean isDate(Object value, boolean alsoNumbers) {
return isDateSimple(value, alsoNumbers);
}
public static boolean isDateSimple(Object value, boolean alsoNumbers) {
return isDateSimple(value, alsoNumbers, false);
}
public static boolean isDateSimple(Object value, boolean alsoNumbers, boolean alsoMonthString) {
// return DateCaster.toDateEL(value)!=null;
if (value instanceof DateTime) return true;
else if (value instanceof Date) return true;
// wrong timezone but this isent importend because date will not be importend
else if (value instanceof String) return DateCaster.toDateSimple(value.toString(), alsoNumbers ? DateCaster.CONVERTING_TYPE_OFFSET : DateCaster.CONVERTING_TYPE_NONE,
alsoMonthString, TimeZone.getDefault(), null) != null;
else if (value instanceof ObjectWrap) {
return isDateSimple(((ObjectWrap) value).getEmbededObject(null), alsoNumbers);
}
else if (value instanceof Castable) {
return ((Castable) value).castToDateTime(null) != null;
}
else if (alsoNumbers && value instanceof Number) return true;
else if (value instanceof Calendar) return true;
return false;
}
public static boolean isDateAdvanced(Object value, boolean alsoNumbers) {
// return DateCaster.toDateEL(value)!=null;
if (value instanceof Date) return true;
// wrong timezone but this isent importend because date will not be importend
else if (value instanceof String) return DateCaster.toDateAdvanced(value.toString(), alsoNumbers ? DateCaster.CONVERTING_TYPE_OFFSET : DateCaster.CONVERTING_TYPE_NONE,
TimeZone.getDefault(), null) != null;
else if (value instanceof Castable) {
return ((Castable) value).castToDateTime(null) != null;
}
else if (alsoNumbers && value instanceof Number) return true;
else if (value instanceof ObjectWrap) {
return isDateAdvanced(((ObjectWrap) value).getEmbededObject(null), alsoNumbers);
}
else if (value instanceof Calendar) return true;
return false;
}
private static char[] DATE_DEL = new char[] { '.', '/', '-' };
public static boolean isUSDate(Object value) {
String str = Caster.toString(value, "");
return isUSorEuroDateEuro(str, false);
}
public static boolean isUSDate(String str) {
return isUSorEuroDateEuro(str, false);
}
public static boolean isEuroDate(Object value) {
String str = Caster.toString(value, "");
return isUSorEuroDateEuro(str, true);
}
public static boolean isEuroDate(String str) {
return isUSorEuroDateEuro(str, true);
}
private static boolean isUSorEuroDateEuro(String str, boolean isEuro) {
if (StringUtil.isEmpty(str)) return false;
for (int i = 0; i < DATE_DEL.length; i++) {
Array arr = lucee.runtime.type.util.ListUtil.listToArrayRemoveEmpty(str, DATE_DEL[i]);
if (arr.size() != 3) continue;
int month = Caster.toIntValue(arr.get(isEuro ? 2 : 1, Constants.INTEGER_0), Integer.MIN_VALUE);
int day = Caster.toIntValue(arr.get(isEuro ? 1 : 2, Constants.INTEGER_0), Integer.MIN_VALUE);
int year = Caster.toIntValue(arr.get(3, Constants.INTEGER_0), Integer.MIN_VALUE);
if (month == Integer.MIN_VALUE) continue;
if (month > 12) continue;
if (day == Integer.MIN_VALUE) continue;
if (day > 31) continue;
if (year == Integer.MIN_VALUE) continue;
if (DateTimeUtil.getInstance().toTime(null, year, month, day, 0, 0, 0, 0, Long.MIN_VALUE) == Long.MIN_VALUE) continue;
return true;
}
return false;
}
public static boolean isCastableToStruct(Object o) {
if (isStruct(o)) return true;
if (o == null) return false;
else if (o instanceof ObjectWrap) {
if (o instanceof JavaObject) return true;
return isCastableToStruct(((ObjectWrap) o).getEmbededObject(null));
}
if (Decision.isSimpleValue(o)) {
return false;
}
// if(isArray(o) || isQuery(o)) return false;
return false;
}
/**
* tests if object is a struct
*
* @param o
* @return is struct or not
*/
public static boolean isStruct(Object o) {
if (o instanceof Struct) return true;
else if (o instanceof Map) return true;
else if (o instanceof Node) return true;
return false;
}
/**
* can this type be casted to an array
*
* @param o
* @return
* @throws PageException
*/
public static boolean isCastableToArray(Object o) {
if (isArray(o)) return true;
else if (o instanceof Set) return true;
else if (o instanceof Struct) {
Struct sct = (Struct) o;
Iterator<Key> it = sct.keyIterator();
while (it.hasNext()) {
if (!isInteger(it.next(), false)) return false;
}
return true;
}
return false;
}
/**
* tests if object is an array
*
* @param o
* @return is array or not
*/
public static boolean isArray(Object o) {
if (o instanceof Array) return true;
if (o instanceof List) return true;
if (isNativeArray(o)) return true;
if (o instanceof ObjectWrap) {
return isArray(((ObjectWrap) o).getEmbededObject(null));
}
return false;
}
/**
* tests if object is a native java array
*
* @param o
* @return is a native (java) array
*/
public static boolean isNativeArray(Object o) {
// return o.getClass().isArray();
if (o instanceof Object[]) return true;
else if (o instanceof boolean[]) return true;
else if (o instanceof byte[]) return true;
else if (o instanceof char[]) return true;
else if (o instanceof short[]) return true;
else if (o instanceof int[]) return true;
else if (o instanceof long[]) return true;
else if (o instanceof float[]) return true;
else if (o instanceof double[]) return true;
return false;
}
/**
* tests if object is catable to a binary
*
* @param object
* @return boolean
*/
public static boolean isCastableToBinary(Object object, boolean checkBase64String) {
if (isBinary(object)) return true;
if (object instanceof InputStream) return true;
if (object instanceof ByteArrayOutputStream) return true;
if (object instanceof Blob) return true;
// Base64 String
if (!checkBase64String) return false;
String str = Caster.toString(object, null);
if (str == null) return false;
return Base64Util.isBase64(str);
}
/**
* tests if object is a binary
*
* @param object
* @return boolean
*/
public static boolean isBinary(Object object) {
if (object instanceof byte[]) return true;
if (object instanceof ObjectWrap) return isBinary(((ObjectWrap) object).getEmbededObject(""));
return false;
}
/**
* tests if object is a Component
*
* @param object
* @return boolean
*/
public static boolean isComponent(Object object) {
return object instanceof Component;
}
/**
* tests if object is a Query
*
* @param object
* @return boolean
*/
public static boolean isQuery(Object object) {
if (object instanceof Query) return true;
else if (object instanceof ObjectWrap) {
return isQuery(((ObjectWrap) object).getEmbededObject(null));
}
return false;
}
public static boolean isQueryColumn(Object object) {
if (object instanceof QueryColumn) return true;
else if (object instanceof ObjectWrap) {
return isQueryColumn(((ObjectWrap) object).getEmbededObject(null));
}
return false;
}
/**
* tests if object is a binary
*
* @param object
* @return boolean
*/
public static boolean isUserDefinedFunction(Object object) {
return object instanceof UDF;
}
/**
* tests if year is a leap year
*
* @param year year to check
* @return boolean
*/
public static final boolean isLeapYear(int year) {
return DateTimeUtil.getInstance().isLeapYear(year);
// return new GregorianCalendar().isLeapYear(year);
}
/**
* tests if object is a WDDX Object
*
* @param o Object to check
* @return boolean
*/
public static boolean isWddx(Object o) {
if (!(o instanceof String)) return false;
String str = o.toString();
if (!(str.indexOf("wddxPacket") > 0)) return false;
// wrong timezone but this isent importend because date will not be used
WDDXConverter converter = new WDDXConverter(TimeZone.getDefault(), false, true);
try {
converter.deserialize(Caster.toString(o), true);
}
catch (Exception e) {
return false;
}
return true;
}
/**
* tests if object is a XML Object
*
* @param o Object to check
* @return boolean
*/
public static boolean isXML(Object o) {
if (o instanceof Node || o instanceof NodeList) return true;
if (o instanceof ObjectWrap) {
return isXML(((ObjectWrap) o).getEmbededObject(null));
}
try {
XMLCaster.toXMLStruct(XMLUtil.parse(XMLUtil.toInputSource(null, o), null, false), false);
return true;
}
catch (Exception outer) {
return false;
}
}
public static boolean isVoid(Object o) {
if (o == null) return true;
else if (o instanceof String) return o.toString().length() == 0;
else if (o instanceof Number) return ((Number) o).intValue() == 0;
else if (o instanceof Boolean) return ((Boolean) o).booleanValue() == false;
else if (o instanceof ObjectWrap) return isVoid(((ObjectWrap) o).getEmbededObject(("isnotnull")));
return false;
}
/**
* tests if object is a XML Element Object
*
* @param o Object to check
* @return boolean
*/
public static boolean isXMLElement(Object o) {
return o instanceof Element;
}
/**
* tests if object is a XML Document Object
*
* @param o Object to check
* @return boolean
*/
public static boolean isXMLDocument(Object o) {
return o instanceof Document;
}
/**
* tests if object is a XML Root Element Object
*
* @param o Object to check
* @return boolean
*/
public static boolean isXMLRootElement(Object o) {
if (o instanceof Node) {
Node n = (Node) o;
if (n instanceof XMLStruct) n = ((XMLStruct) n).toNode();
return XMLUtil.getDocument(n) != null && XMLUtil.getDocument(n).getDocumentElement() == n;
}
return false;
}
/**
* @param obj
* @return returns if string represent a variable name
*/
public static boolean isVariableName(Object obj) {
if (obj instanceof String) return isVariableName((String) obj);
return false;
}
public static boolean isFunction(Object obj) {
if (obj instanceof UDF) return true;
else if (obj instanceof ObjectWrap) {
return isFunction(((ObjectWrap) obj).getEmbededObject(null));
}
return false;
}
public static boolean isClosure(Object obj) {
if (obj instanceof Closure) return true;
else if (obj instanceof ObjectWrap) {
return isClosure(((ObjectWrap) obj).getEmbededObject(null));
}
return false;
}
public static boolean isLambda(Object obj) {
if (obj instanceof Lambda) return true;
else if (obj instanceof ObjectWrap) {
return isLambda(((ObjectWrap) obj).getEmbededObject(null));
}
return false;
}
/**
* @param string
* @return returns if string represent a variable name
*/
public static boolean isVariableName(String string) {
if (string.length() == 0) return false;
int len = string.length();
int pos = 0;
while (pos < len) {
char first = string.charAt(pos);
if (!((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z') || (first == '_'))) return false;
pos++;
for (; pos < len; pos++) {
char c = string.charAt(pos);
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '_'))) break;
}
if (pos == len) return true;
if (string.charAt(pos) == '.') pos++;
}
return false;
}
/**
* @param string
* @return returns if string represent a variable name
*/
public static boolean isSimpleVariableName(String string) {
if (string.length() == 0) return false;
char first = string.charAt(0);
if (!((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z') || (first == '_'))) return false;
for (int i = string.length() - 1; i > 0; i
char c = string.charAt(i);
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '_'))) return false;
}
return true;
}
/**
* @param key
* @return returns if string represent a variable name
*/
public static boolean isSimpleVariableName(Collection.Key key) {
String strKey = key.getLowerString();
if (strKey.length() == 0) return false;
char first = strKey.charAt(0);
if (!((first >= 'a' && first <= 'z') || (first == '_'))) return false;
for (int i = strKey.length() - 1; i > 0; i
char c = strKey.charAt(i);
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_'))) return false;
}
return true;
}
/**
* returns if object is a CFML object
*
* @param o Object to check
* @return is or not
*/
public static boolean isObject(Object o) {
return isComponent(o)
|| (!isArray(o) && !isQuery(o) && !isSimpleValue(o) && !isStruct(o) && !isUserDefinedFunction(o) && !isXML(o));
}
/**
* @param obj
* @return return if a String is "Empty", that means NULL or String with length 0 (whitespaces will
* not counted)
*/
public static boolean isEmpty(Object obj) {
if (obj instanceof String) return StringUtil.isEmpty((String) obj);
return obj == null;
}
/**
* @deprecated use instead <code>StringUtil.isEmpty(String)</code>
* @param str
* @return return if a String is "Empty", that means NULL or String with length 0 (whitespaces will
* not counted)
*/
@Deprecated
public static boolean isEmpty(String str) {
return StringUtil.isEmpty(str);
}
/**
* @deprecated use instead <code>StringUtil.isEmpty(String)</code>
* @param str
* @param trim
* @return return if a String is "Empty", that means NULL or String with length 0 (whitespaces will
* not counted)
*/
@Deprecated
public static boolean isEmpty(String str, boolean trim) {
return StringUtil.isEmpty(str, trim);
}
/**
* returns if a value is a credit card
*
* @param value
* @return is credit card
*/
public static boolean isCreditCard(Object value) {
return ValidateCreditCard.isValid(Caster.toString(value, "0"));
}
/**
* returns if given object is an email
*
* @param value
* @return
*/
public static boolean isEmail(Object value) {
return MailUtil.isValidEmail(value);
}
/**
* returns if given object is a social security number (usa)
*
* @param value
* @return
*/
public static boolean isSSN(Object value) {
String str = Caster.toString(value, null);
if (str == null) return false;
if (ssnPattern == null) ssnPattern = Pattern.compile("^[0-9]{3}[-|]{1}[0-9]{2}[-|]{1}[0-9]{4}$");
return ssnPattern.matcher(str.trim()).matches();
}
/**
* returns if given object is a phone
*
* @param value
* @return
*/
public static boolean isPhone(Object value) {
String str = Caster.toString(value, null);
if (str == null) return false;
if (phonePattern == null) phonePattern = Pattern
.compile("^(\\+?1?[ \\-\\.]?([\\(]?([1-9][0-9]{2})[\\)]?))?[ ,\\-,\\.]?([^0-1]){1}([0-9]){2}[ ,\\-,\\.]?([0-9]){4}(( )((x){0,1}([0-9]){1,5}){0,1})?$");
return phonePattern.matcher(str.trim()).matches();
}
/**
* returns true if the given object is a valid URL
*
* @param value
* @return
*/
public static boolean isURL(Object value) {
String str = Caster.toString(value, null);
if (str == null) return false;
if (str.indexOf(':') == -1) return false;
str = str.toLowerCase().trim();
if (!str.startsWith("http:
&& !str.startsWith("news:") && !str.startsWith("urn:"))
return false;
try {
URI uri = new URI(str);
String proto = uri.getScheme();
if (proto == null) return false;
if (proto.equals("http") || proto.equals("https") || proto.equals("file") || proto.equals("ftp")) {
if (uri.getHost() == null) return false;
String path = uri.getPath();
if (path != null) {
int len = path.length();
for (int i = 0; i < len; i++) {
if ("?<>*|\"".indexOf(path.charAt(i)) > -1) return false;
}
}
}
return true;
}
catch (Exception ex) {
return false;
}
}
/**
* returns if given object is a zip code
*
* @param value
* @return
*/
public static boolean isZipCode(Object value) {
String str = Caster.toString(value, null);
if (str == null) return false;
if (zipPattern == null) zipPattern = Pattern.compile("([0-9]{5,5})|([0-9]{5,5}[- ]{1}[0-9]{4,4})");
return zipPattern.matcher(str.trim()).matches();
}
public static boolean isString(Object o) {
if (o instanceof String) return true;
else if (o instanceof Boolean) return true;
else if (o instanceof Number) return true;
else if (o instanceof Date) return true;
else if (o instanceof Castable) {
return ((Castable) o).castToString(STRING_DEFAULT_VALUE) != STRING_DEFAULT_VALUE;
}
else if (o instanceof Clob) return true;
else if (o instanceof Node) return true;
else if (o instanceof Map || o instanceof List || o instanceof Function) return false;
else if (o == null) return true;
else if (o instanceof ObjectWrap) return isString(((ObjectWrap) o).getEmbededObject(""));
return true;
}
public static boolean isCastableToString(Object o) {
return isString(o);
}
public static boolean isValid(String type, Object value) throws ExpressionException {
type = StringUtil.toLowerCase(type.trim());
char first = type.charAt(0);
switch (first) {
case 'a':
if ("any".equals(type)) return true;// isSimpleValue(value);
if ("array".equals(type)) return isArray(value);
break;
case 'b':
if ("binary".equals(type)) return isBinary(value);
if ("boolean".equals(type)) return isBoolean(value, true);
break;
case 'c':
if ("creditcard".equals(type)) return isCreditCard(value);
if ("component".equals(type)) return isComponent(value);
if ("cfc".equals(type)) return isComponent(value);
if ("class".equals(type)) return isComponent(value);
if ("closure".equals(type)) return isClosure(value);
break;
case 'd':
if ("date".equals(type)) return isDateAdvanced(value, true); // ist zwar nicht logisch aber ident. zu Neo
if ("datetime".equals(type)) return isDateAdvanced(value, true); // ist zwar nicht logisch aber ident. zu Neo
if ("double".equals(type)) return isCastableToNumeric(value);
break;
case 'e':
if ("eurodate".equals(type)) return isEuroDate(value);
if ("email".equals(type)) return isEmail(value);
break;
case 'f':
if ("float".equals(type)) return isNumber(value, true);
if ("function".equals(type)) return isFunction(value);
break;
case 'g':
if ("guid".equals(type)) return isGUId(value);
break;
case 'i':
if ("integer".equals(type)) return isInteger(value, false);
if ("image".equals(type)) return ImageUtil.isImage(value);
break;
case 'l':
if ("lambda".equals(type)) return isLambda(value);
break;
case 'n':
if ("numeric".equals(type)) return isCastableToNumeric(value);
if ("number".equals(type)) return isCastableToNumeric(value);
if ("node".equals(type)) return isXML(value);
break;
case 'p':
if ("phone".equals(type)) return isPhone(value);
break;
case 'q':
if ("query".equals(type)) return isQuery(value);
break;
case 's':
if ("simple".equals(type)) return isSimpleValue(value);
if ("struct".equals(type)) return isStruct(value);
if ("ssn".equals(type)) return isSSN(value);
if ("social_security_number".equals(type)) return isSSN(value);
if ("string".equals(type)) return isString(value);
break;
case 't':
if ("telephone".equals(type)) return isPhone(value);
if ("time".equals(type)) return isDateAdvanced(value, false);
break;
case 'u':
if ("usdate".equals(type)) return isUSDate(value);
if ("uuid".equals(type)) return isUUId(value);
if ("url".equals(type)) return isURL(value);
break;
case 'v':
if ("variablename".equals(type)) return isVariableName(Caster.toString(value, ""));
break;
case 'x':
if ("xml".equals(type)) return isXML(value); // DIFF 23
break;
case 'z':
if ("zip".equals(type)) return isZipCode(value);
if ("zipcode".equals(type)) return isZipCode(value);
break;
}
throw new ExpressionException("invalid type [" + type
+ "], valid types are [any,array,binary,boolean,component,creditcard,date,time,email,eurodate,float,numeric,guid,integer,query,simple,ssn,string,struct,telephone,URL,UUID,USdate,variableName,zipcode]");
}
/**
* checks if a value is castable to a certain type
*
* @param type any,array,boolean,binary, ...
* @param o value to check
* @param alsoPattern also check patterns like creditcards,email,phone ...
* @param maxlength only used for email,url, string, ignored otherwise
* @return
*/
public static boolean isCastableTo(String type, Object o, boolean alsoAlias, boolean alsoPattern, int maxlength) {
type = StringUtil.toLowerCase(type).trim();
if (type.length() > 2) {
char first = type.charAt(0);
switch (first) {
case 'a':
if (type.equals("any")) {
return true;
}
else if (type.equals("array")) {
return isCastableToArray(o);
}
break;
case 'b':
if (type.equals("boolean") || (alsoAlias && type.equals("bool"))) {
return isCastableToBoolean(o);
}
else if (type.equals("binary")) {
return isCastableToBinary(o, true);
}
else if (alsoAlias && type.equals("bigint")) {
return isCastableToNumeric(o);
}
else if (type.equals("base64")) {
return Caster.toBase64(o, null, null) != null;
}
break;
case 'c':
if (alsoPattern && type.equals("creditcard")) {
return Caster.toCreditCard(o, null) != null;
}
if (alsoPattern && type.equals("char")) {
if (maxlength > -1) {
String str = Caster.toString(o, null);
if (str == null) return false;
return str.length() <= maxlength;
}
return isCastableToString(o);
}
break;
case 'd':
if (type.equals("date")) {
return isDateAdvanced(o, true);
}
else if (type.equals("datetime")) {
return isDateAdvanced(o, true);
}
else if (alsoAlias && type.equals("double")) {
return isCastableToNumeric(o);
}
else if (alsoAlias && type.equals("decimal")) {
return Caster.toDecimal(o, true, null) != null;
}
break;
case 'e':
if (alsoAlias && type.equals("eurodate")) {
return isDateAdvanced(o, true);
}
else if (alsoPattern && type.equals("email")) {
if (maxlength > -1) {
String str = Caster.toEmail(o, null);
if (str == null) return false;
return str.length() <= maxlength;
}
return Caster.toEmail(o, null) != null;
}
break;
case 'f':
if (alsoAlias && type.equals("float")) {
return isCastableToNumeric(o);
}
if (type.equals("function")) {
return isFunction(o);
}
break;
case 'g':
if (type.equals("guid")) {
return isGUId(o);
}
break;
case 'i':
if (alsoAlias && (type.equals("integer") || type.equals("int"))) {
return isCastableToNumeric(o);
}
break;
case 'l':
if (alsoAlias && type.equals("long")) {
return isCastableToNumeric(o);
}
break;
case 'n':
if (type.equals("numeric")) {
return isCastableToNumeric(o);
}
else if (type.equals("number")) {
return isCastableToNumeric(o);
}
if (alsoAlias) {
if (type.equals("node")) return isXML(o);
else if (type.equals("nvarchar") || type.equals("nchar")) {
if (maxlength > -1) {
String str = Caster.toString(o, null);
if (str == null) return false;
return str.length() <= maxlength;
}
return isCastableToString(o);
}
}
break;
case 'o':
if (type.equals("object")) {
return true;
}
else if (alsoAlias && type.equals("other")) {
return true;
}
break;
case 'p':
if (alsoPattern && type.equals("phone")) {
return Caster.toPhone(o, null) != null;
}
break;
case 'q':
if (type.equals("query")) {
return isQuery(o);
}
if (type.equals("querycolumn")) return isQueryColumn(o);
break;
case 's':
if (type.equals("string")) {
if (maxlength > -1) {
String str = Caster.toString(o, null);
if (str == null) return false;
return str.length() <= maxlength;
}
return isCastableToString(o);
}
else if (type.equals("struct")) {
return isCastableToStruct(o);
}
else if (alsoAlias && type.equals("short")) {
return isCastableToNumeric(o);
}
else if (alsoPattern && (type.equals("ssn") || type.equals("social_security_number"))) {
return Caster.toSSN(o, null) != null;
}
break;
case 't':
if (type.equals("timespan")) {
return Caster.toTimespan(o, null) != null;
}
if (type.equals("time")) {
return isDateAdvanced(o, true);
}
if (alsoPattern && type.equals("telephone")) {
return Caster.toPhone(o, null) != null;
}
if (alsoAlias && type.equals("timestamp")) return isDateAdvanced(o, true);
if (alsoAlias && type.equals("text")) {
if (maxlength > -1) {
String str = Caster.toString(o, null);
if (str == null) return false;
return str.length() <= maxlength;
}
return isCastableToString(o);
}
case 'u':
if (type.equals("uuid")) {
return isUUId(o);
}
if (alsoAlias && type.equals("usdate")) {
return isDateAdvanced(o, true);
}
if (alsoPattern && type.equals("url")) {
if (maxlength > -1) {
String str = Caster.toURL(o, null);
if (str == null) return false;
return str.length() <= maxlength;
}
return Caster.toURL(o, null) != null;
}
if (alsoAlias && type.equals("udf")) {
return isFunction(o);
}
break;
case 'v':
if (type.equals("variablename")) {
return isVariableName(o);
}
else if (type.equals("void")) {
return isVoid(o);// Caster.toVoid(o,Boolean.TRUE)!=Boolean.TRUE;
}
else if (alsoAlias && type.equals("variable_name")) {
return isVariableName(o);
}
else if (alsoAlias && type.equals("variable-name")) {
return isVariableName(o);
}
if (type.equals("varchar")) {
if (maxlength > -1) {
String str = Caster.toString(o, null);
if (str == null) return false;
return str.length() <= maxlength;
}
return isCastableToString(o);
}
break;
case 'x':
if (type.equals("xml")) {
return isXML(o);
}
break;
case 'z':
if (alsoPattern && (type.equals("zip") || type.equals("zipcode"))) {
return Caster.toZip(o, null) != null;
}
break;
}
}
return _isCastableTo(null, type, o);
}
private static boolean _isCastableTo(PageContext pcMaybeNull, String type, Object o) {
if (o instanceof Component) {
Component comp = ((Component) o);
return comp.instanceOf(type);
}
if (o instanceof Pojo) {
pcMaybeNull = ThreadLocalPageContext.get(pcMaybeNull);
return pcMaybeNull != null && Caster.toComponent(pcMaybeNull, ((Pojo) o), type, null) != null;
}
if (isArrayType(type) && isArray(o)) {
String _strType = type.substring(0, type.length() - 2);
short _type = CFTypes.toShort(_strType, false, (short) -1);
Array arr = Caster.toArray(o, null);
if (arr != null) {
Iterator<Object> it = arr.valueIterator();
while (it.hasNext()) {
Object obj = it.next();
if (!isCastableTo(pcMaybeNull, _type, _strType, obj)) return false;
}
return true;
}
}
return false;
}
private static boolean isArrayType(String type) {
return type.endsWith("[]");
}
public static boolean isCastableTo(PageContext pc, short type, String strType, Object o) {
switch (type) {
case CFTypes.TYPE_ANY:
return true;
case CFTypes.TYPE_STRING:
return isCastableToString(o);
case CFTypes.TYPE_BOOLEAN:
return isCastableToBoolean(o);
case CFTypes.TYPE_NUMERIC:
return isCastableToNumeric(o);
case CFTypes.TYPE_STRUCT:
return isCastableToStruct(o);
case CFTypes.TYPE_ARRAY:
return isCastableToArray(o);
case CFTypes.TYPE_QUERY:
return isQuery(o);
case CFTypes.TYPE_QUERY_COLUMN:
return isQueryColumn(o);
case CFTypes.TYPE_DATETIME:
return isDateAdvanced(o, true);
case CFTypes.TYPE_VOID:
return isVoid(o);// Caster.toVoid(o,Boolean.TRUE)!=Boolean.TRUE;
case CFTypes.TYPE_BINARY:
return isCastableToBinary(o, true);
case CFTypes.TYPE_TIMESPAN:
return Caster.toTimespan(o, null) != null;
case CFTypes.TYPE_UUID:
return isUUId(o);
case CFTypes.TYPE_GUID:
return isGUId(o);
case CFTypes.TYPE_VARIABLE_NAME:
return isVariableName(o);
case CFTypes.TYPE_FUNCTION:
return isFunction(o);
case CFTypes.TYPE_IMAGE:
return ImageUtil.isCastableToImage(pc, o);
case CFTypes.TYPE_XML:
return isXML(o);
}
return _isCastableTo(pc, strType, o);
}
public static boolean isDate(String str, Locale locale, TimeZone tz, boolean lenient) {
str = str.trim();
tz = ThreadLocalPageContext.getTimeZone(tz);
DateFormat[] df;
// get Calendar
// Calendar c=JREDateTimeUtil.getThreadCalendar(locale,tz);
// datetime
ParsePosition pp = new ParsePosition(0);
df = FormatUtil.getDateTimeFormats(locale, tz, false);// dfc[FORMATS_DATE_TIME];
Date d;
for (int i = 0; i < df.length; i++) {
pp.setErrorIndex(-1);
pp.setIndex(0);
df[i].setTimeZone(tz);
d = df[i].parse(str, pp);
if (pp.getIndex() == 0 || d == null || pp.getIndex() < str.length()) continue;
return true;
}
// date
df = FormatUtil.getDateFormats(locale, tz, false);
for (int i = 0; i < df.length; i++) {
pp.setErrorIndex(-1);
pp.setIndex(0);
df[i].setTimeZone(tz);
d = df[i].parse(str, pp);
if (pp.getIndex() == 0 || d == null || pp.getIndex() < str.length()) continue;
return true;
}
// time
df = FormatUtil.getTimeFormats(locale, tz, false);
for (int i = 0; i < df.length; i++) {
pp.setErrorIndex(-1);
pp.setIndex(0);
df[i].setTimeZone(tz);
d = df[i].parse(str, pp);
if (pp.getIndex() == 0 || d == null || pp.getIndex() < str.length()) continue;
return true;
}
if (lenient) return isDateSimple(str, false);
return false;
}
/**
* Checks if number is valid (not infinity or NaN)
*
* @param dbl
* @return
*/
public static boolean isValid(double dbl) {
return !Double.isNaN(dbl) && !Double.isInfinite(dbl);
}
public static boolean isAnyType(String type) {
return StringUtil.isEmpty(type) || type.equalsIgnoreCase("object") || type.equalsIgnoreCase("any");
}
public static boolean isWrapped(Object o) {
return o instanceof JavaObject || o instanceof ObjectWrap;
}
} |
package nu.yona.server;
import java.text.MessageFormat;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
@Service
public class Translator
{
public static final Locale EN_US_LOCALE = Locale.forLanguageTag("en-US");
/** The source for the messages to use */
@Autowired
private MessageSource msgSource;
/**
* This method returns the translated and formatted message for the passed message ID and parameters based on the given locale
*
* @return The actual message based on the default locale.
*/
public String getLocalizedMessage(String messageId, Object... parameters)
{
return getLocalizedMessage(messageId, parameters, null);
}
/**
* This method returns the translated and formatted message for the passed message ID and parameters based on the given locale
*
* @param locale The locale to use for getting the message.
* @return The actual message based on the given locale.
*/
public String getLocalizedMessage(String messageId, Object[] parameters, Locale locale)
{
if (locale == null)
{
locale = LocaleContextHolder.getLocale();
}
return msgSource.getMessage(messageId, parameters, locale);
}
public static String getStandardLocaleString(Locale locale)
{
return locale.toString().replace('_', '-');
}
public static String buildLocaleSpecificResourcePath(String format)
{
return MessageFormat.format(format, determineLocaleInfix());
}
private static Object determineLocaleInfix()
{
Locale locale = LocaleContextHolder.getLocale();
if (locale.equals(EN_US_LOCALE))
{
return "";
}
return "_" + locale.getLanguage();
}
} |
package edu.umd.cs.findbugs.gui2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JComboBox;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.TreePath;
import edu.umd.cs.findbugs.BugDesignation;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugDesignation;
import edu.umd.cs.findbugs.I18N;
import edu.umd.cs.findbugs.annotations.CheckForNull;
/**
* @author pugh
*/
public class CommentsArea {
private JTextArea userCommentsText = new JTextArea();
private Color userCommentsTextUnenabledColor;
private JComboBox designationComboBox;
private ArrayList<String> designationKeys;
LinkedList<String> prevCommentsList = new LinkedList<String>();
final static private int prevCommentsMaxSize = 10;
private JComboBox prevCommentsComboBox = new JComboBox();
private boolean dontShowAnnotationConfirmation = false;
private boolean changed;
final MainFrame frame;
CommentsArea(MainFrame frame) {
this.frame = frame;
}
/**
* Create center panel that holds the user input combo boxes and TextArea.
*/
JPanel createCommentsInputPanel() {
JPanel centerPanel = new JPanel();
BorderLayout centerLayout = new BorderLayout();
centerLayout.setVgap(10);
centerPanel.setLayout(centerLayout);
userCommentsText.getDocument().addDocumentListener(
new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
frame.setProjectChanged(true);
changed = true;
}
public void removeUpdate(DocumentEvent e) {
frame.setProjectChanged(true);
changed = true;
}
public void changedUpdate(DocumentEvent e) {
changed = true;
}
});
userCommentsTextUnenabledColor = centerPanel.getBackground();
userCommentsText.setLineWrap(true);
userCommentsText
.setToolTipText(edu.umd.cs.findbugs.gui.L10N.getLocalString("tooltip.enter_comments", "Enter your comments about this bug here"));
userCommentsText.setWrapStyleWord(true);
userCommentsText.setEnabled(false);
userCommentsText.setBackground(userCommentsTextUnenabledColor);
JScrollPane commentsScrollP = new JScrollPane(userCommentsText);
prevCommentsComboBox.setEnabled(false);
prevCommentsComboBox
.setToolTipText(edu.umd.cs.findbugs.gui.L10N.getLocalString("tooltip.reuse_comments", "Use this to reuse a previous textual comment for this bug"));
prevCommentsComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED
&& prevCommentsComboBox.getSelectedIndex() != 0) {
setCurrentUserCommentsText(getCurrentPrevCommentsSelection());
prevCommentsComboBox.setSelectedIndex(0);
}
}
});
designationComboBox = new JComboBox();
designationKeys = new ArrayList<String>();
designationComboBox.setEnabled(false);
designationComboBox
.setToolTipText(edu.umd.cs.findbugs.gui.L10N.getLocalString("tooltip.select_designation", "Select a user designation for this bug"));
designationComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (frame.userInputEnabled
&& e.getStateChange() == ItemEvent.SELECTED) {
if (frame.currentSelectedBugLeaf == null)
setDesignationNonLeaf(designationComboBox
.getSelectedItem().toString());
else if (!alreadySelected())
setDesignation(designationComboBox.getSelectedItem()
.toString());
}
}
/*
* Checks to see if the designation is already selected as that.
* This was created because it was found the itemStateChanged method
* is called when the combo box is set when a bug is clicked.
*/
private boolean alreadySelected() {
return designationKeys.get(
designationComboBox.getSelectedIndex()).equals(
frame.currentSelectedBugLeaf.getBug()
.getNonnullUserDesignation()
.getDesignationKey());
}
});
designationKeys.add("");
designationComboBox.addItem("");
for (String s : I18N.instance().getUserDesignationKeys(true)) {
designationKeys.add(s);
designationComboBox.addItem(Sortables.DESIGNATION.formatValue(s));
}
setUnknownDesignation();
centerPanel.add(designationComboBox, BorderLayout.NORTH);
centerPanel.add(commentsScrollP, BorderLayout.CENTER);
centerPanel.add(prevCommentsComboBox, BorderLayout.SOUTH);
return centerPanel;
}
void setUnknownDesignation() {
designationComboBox.setSelectedIndex(0); // WARNING: this is hard
// coded in here.
}
/**
* Sets the user comment panel to whether or not it is enabled. If isEnabled
* is false will clear the user comments text pane.
*
* @param isEnabled
*/
void setUserCommentInputEnable(final boolean isEnabled) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setUserCommentInputEnableFromSwingThread(isEnabled);
}
});
}
/**
* Sets the user comment panel to whether or not it is enabled. If isEnabled
* is false will clear the user comments text pane.
*
* @param isEnabled
*/
void setUserCommentInputEnableFromSwingThread(final boolean isEnabled) {
frame.userInputEnabled = isEnabled;
if (!isEnabled) {
userCommentsText.setText("");
// WARNING: this is hard coded in here, but needed
// so when not enabled shows default setting of designation
setUnknownDesignation();
userCommentsText.setBackground(userCommentsTextUnenabledColor);
} else
userCommentsText.setBackground(Color.WHITE);
userCommentsText.setEnabled(isEnabled);
prevCommentsComboBox.setEnabled(isEnabled);
designationComboBox.setEnabled(isEnabled);
}
/**
* Updates comments tab. Takes node passed and sets the designation and
* comments.
*
* @param node
*/
void updateCommentsFromLeafInformation(final BugLeafNode node) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
BugInstance bug = node.getBug();
setCurrentUserCommentsText(bug.getAnnotationText());
designationComboBox.setSelectedIndex(designationKeys
.indexOf(bug.getNonnullUserDesignation()
.getDesignationKey()));
setUserCommentInputEnableFromSwingThread(true);
changed = false;
}
});
}
void updateCommentsFromNonLeafInformation(final BugAspects theAspects) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateCommentsFromNonLeafInformationFromSwingThread(theAspects);
setUserCommentInputEnableFromSwingThread(true);
changed = false;
}
});
}
/**
* Saves the current comments to the BugLeafNode passed in. If the passed in
* node's annotation is already equal to the current user comment then will
* not do anything so setProjectedChanged is not made true. Will also add
* the comment if it is new to the previous comments list.
*
* @param node
*/
private void saveCommentsToBug(BugLeafNode node) {
if (node == null)
return;
String comments = getCurrentUserCommentsText();
if (node.getBug().getAnnotationText().equals(comments))
return;
node.getBug().setAnnotationText(comments);
setProjectChanged(true);
changed = false;
addToPrevComments(comments);
}
private boolean confirmAnnotation() {
String[] options = { edu.umd.cs.findbugs.gui.L10N.getLocalString("dlg.yes_btn", "Yes"), edu.umd.cs.findbugs.gui.L10N.getLocalString("dlg.no_btn", "No"), edu.umd.cs.findbugs.gui.L10N.getLocalString("dlg.yes_dont_ask_btn", "Yes, and don't ask me this again")};
if (dontShowAnnotationConfirmation)
return true;
int choice = JOptionPane
.showOptionDialog(
frame,
edu.umd.cs.findbugs.gui.L10N.getLocalString("dlg.changing_text_lbl", "Changing this text box will overwrite the annotations associated with all bugs in this folder and subfolders. Are you sure?"),
edu.umd.cs.findbugs.gui.L10N.getLocalString("dlg.annotation_change_ttl", "Annotation Change"), JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
switch (choice) {
case 0:
return true;
case 1:
return false;
case 2:
dontShowAnnotationConfirmation = true;
return true;
default:
return true;
}
}
private void saveCommentsToNonLeaf(BugAspects aspects) {
if (aspects == null)
return;
if (!changed) return;
String newComment = getCurrentUserCommentsText();
if (newComment.equals(getNonLeafCommentsText(aspects)))
return;
else if (confirmAnnotation()) {
BugSet filteredSet = aspects
.getMatchingBugs(BugSet.getMainBugSet());
for (BugLeafNode nextNode : filteredSet) {
saveCommentsToBug(nextNode);
}
}
changed = false;
}
/**
* Saves comments to the current selected bug.
*
*/
public void saveComments() {
saveComments(frame.currentSelectedBugLeaf,
frame.currentSelectedBugAspects);
}
public void saveComments(BugLeafNode theNode, BugAspects theAspects) {
if (theNode != null)
saveCommentsToBug(theNode);
else
saveCommentsToNonLeaf(theAspects);
}
/**
* Deletes the list have already. Then loads from list. Will load from the
* list until run out of room in the prevCommentsList.
*
* @param list
*/
void loadPrevCommentsList(String[] list) {
int count = 0;
for (String str : list) {
if (str.equals(""))
count++;
}
String[] ary = new String[list.length - count];
int j = 0;
for (String str : list) {
if (!str.equals("")) {
ary[j] = str;
j++;
}
}
String[] temp;
prevCommentsList = new LinkedList<String>();
if ((ary.length) > prevCommentsMaxSize) {
temp = new String[prevCommentsMaxSize];
for (int i = 0; i < temp.length && i < ary.length; i++)
temp[i] = ary[i];
} else {
temp = new String[ary.length];
for (int i = 0; i < ary.length; i++)
temp[i] = ary[i];
}
for (String str : temp)
prevCommentsList.add(str);
resetPrevCommentsComboBox();
}
/**
* Adds the comment into the list. If the comment is already in the list
* then simply moves to the front. If the list is too big when adding the
* comment then deletes the last comment on the list.
*
* @param comment
*/
private void addToPrevComments(String comment) {
if (comment.equals(""))
return;
if (prevCommentsList.contains(comment)) {
int index = prevCommentsList.indexOf(comment);
if (index == 0)
return;
prevCommentsList.remove(index);
}
prevCommentsList.addFirst(comment);
while (prevCommentsList.size() > prevCommentsMaxSize)
prevCommentsList.removeLast();
resetPrevCommentsComboBox();
}
/**
* Removes all items in the comboBox for previous comments. Then refills it
* using prevCommentsList.
*
*/
private void resetPrevCommentsComboBox() {
prevCommentsComboBox.removeAllItems();
prevCommentsComboBox.addItem("");
for (String str : prevCommentsList) {
if (str.length() < 20)
prevCommentsComboBox.addItem(str);
else
prevCommentsComboBox.addItem(str.substring(0, 17) + "...");
}
}
/**
* Returns the text in the current user comments textArea.
*
* @return
*/
private String getCurrentUserCommentsText() {
return userCommentsText.getText();
}
/**
* Sets the current user comments text area to comment.
*
* @param comment
*/
private void setCurrentUserCommentsText(String comment) {
changed = true;
userCommentsText.setText(comment);
}
/**
* Returns the current selected previous comments. Returns as an object.
*/
private String getCurrentPrevCommentsSelection() {
return prevCommentsList
.get(prevCommentsComboBox.getSelectedIndex() - 1);
}
void addDesignationItem(JMenu menu, final String menuName, int keyEvent) {
JMenuItem toggleItem = new JMenuItem(menuName);
toggleItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (frame.currentSelectedBugLeaf == null)
setDesignationNonLeaf(menuName);
else
setDesignation(menuName);
}
});
MainFrame.attachAccelaratorKey(toggleItem, keyEvent);
menu.add(toggleItem);
}
void setDesignation(String designationName) {
if (frame.currentSelectedBugLeaf == null)
return;
String designationKey = convertDesignationNameToDesignationKey(designationName);
if (designationKey == null)
return;
if (changeDesignationOfBug(frame.currentSelectedBugLeaf, designationKey))
changed = true;
setDesignationComboBox(designationKey);
}
protected void setDesignationNonLeaf(String designationName) {
String designationKey = convertDesignationNameToDesignationKey(designationName);
if (designationKey == null || frame.currentSelectedBugAspects == null)
return;
BugSet filteredSet = frame.currentSelectedBugAspects
.getMatchingBugs(BugSet.getMainBugSet());
for (BugLeafNode nextNode : filteredSet)
if (changeDesignationOfBug(nextNode, designationKey)) changed = true;
setDesignationComboBox(designationKey);
}
protected boolean changeDesignationOfBug(BugLeafNode theNode, String selection) {
BugDesignation userDesignation = theNode.getBug().getNonnullUserDesignation();
if (userDesignation.getDesignationKey().equals(selection)) return false;
userDesignation.setDesignationKey(selection);
return true;
}
protected void updateDesignationComboBox() {
if (frame.currentSelectedBugLeaf == null)
updateCommentsFromNonLeafInformationFromSwingThread(frame.currentSelectedBugAspects);
else {
int selectedIndex = designationComboBox
.getSelectedIndex();
if (selectedIndex >= 0) setDesignationComboBox(designationKeys.get(selectedIndex));
else
Debug.println("Couldn't find selected index in designationComboBox: " + designationComboBox.getSelectedItem());
}
}
protected void updateCommentsFromNonLeafInformationFromSwingThread(BugAspects theAspects) {
if (theAspects == null)
return;
BugSet filteredSet = theAspects.getMatchingBugs(BugSet.getMainBugSet());
boolean allSame = true;
int first = -1;
for (BugLeafNode nextNode : filteredSet) {
int designationIndex = designationKeys.indexOf(nextNode.getBug()
.getNonnullUserDesignation().getDesignationKey());
if (first == -1) {
first = designationIndex;
} else {
if (designationIndex != first)
allSame = false;
}
}
;
if (allSame) {
designationComboBox.setSelectedIndex(first);
} else {
designationComboBox.setSelectedIndex(0);
}
userCommentsText.setText(getNonLeafCommentsText(theAspects));
changed = false;
// setUserCommentInputEnableFromSwingThread(true);
}
protected String getNonLeafCommentsText(BugAspects theAspects)
{ if (theAspects == null)
return "";
BugSet filteredSet = theAspects.getMatchingBugs(BugSet.getMainBugSet());
Iterator<BugLeafNode> filteredIter = filteredSet.iterator();
boolean allSame = true;
String comments = null;
for (BugLeafNode nextNode : filteredSet) {
String commentsOnThisBug = nextNode.getBug().getAnnotationText();
if (comments == null) {
comments = commentsOnThisBug;
} else {
if (!commentsOnThisBug.equals(comments))
allSame = false;
}
}
if((comments == null) || (allSame == false))
return "";
else return comments;
}
protected void setDesignationComboBox(String designationKey) {
int numItems = designationComboBox.getItemCount();
for (int i = 0; i < numItems; i++) {
String value = designationKeys.get(i);
if (designationKey.equals(value)) {
designationComboBox.setSelectedIndex(i);
return;
}
}
if (MainFrame.DEBUG) System.out.println("Couldn't find combo box for " + designationKey);
}
public void moveNodeAccordingToDesignation(BugLeafNode theNode,
String selection) {
if (!getSorter().getOrder().contains(Sortables.DESIGNATION)) {
// designation not sorted on at all
theNode.getBug().getNonnullUserDesignation().setDesignationKey(
selection);
} else if (getSorter().getOrderBeforeDivider().contains(
Sortables.DESIGNATION)) {
BugTreeModel model = getModel();
TreePath path = model.getPathToBug(theNode.getBug());
if (path == null) {
theNode.getBug().getNonnullUserDesignation().setDesignationKey(
selection);
return;
}
Object[] objPath = path.getParentPath().getPath();
ArrayList<Object> reconstruct = new ArrayList<Object>();
ArrayList<TreePath> listOfNodesToReconstruct = new ArrayList<TreePath>();
for (int x = 0; x < objPath.length; x++) {
Object o = objPath[x];
reconstruct.add(o);
if (o instanceof BugAspects) {
if (((BugAspects) o).getCount() == 1) {
// Debug.println((BugAspects)(o));
break;
}
}
TreePath pathToNode = new TreePath(reconstruct.toArray());
listOfNodesToReconstruct.add(pathToNode);
}
theNode.getBug().getNonnullUserDesignation().setDesignationKey(
selection);
model.suppressBug(path);
TreePath unsuppressPath = model.getPathToBug(theNode.getBug());
if (unsuppressPath != null)// If choosing their designation has not
// moved the bug under any filters
{
model.unsuppressBug(unsuppressPath);
// tree.setSelectionPath(unsuppressPath);
}
for (TreePath pathToNode : listOfNodesToReconstruct) {
model.treeNodeChanged(pathToNode);
}
setProjectChanged(true);
} else if (getSorter().getOrderAfterDivider().contains(
Sortables.DESIGNATION)) {
theNode.getBug().getNonnullUserDesignation().setDesignationKey(
selection);
BugTreeModel model = getModel();
TreePath path = model.getPathToBug(theNode.getBug());
if (path != null)
model.sortBranch(path.getParentPath());
}
}
protected @CheckForNull
String convertDesignationNameToDesignationKey(String name) {
/*
* This converts a designation name from human-readable format ("mostly
* harmless", "critical") to the program's internal format
* ("MOSTLY_HARMLESS", "CRITICAL") etc. This uses the
* DesignationComboBox (this should probably be changed)
*/
int itemCount = designationComboBox.getItemCount();
for (int i = 1; i < itemCount; i++)
if (name.equals(designationComboBox.getItemAt(i)))
return designationKeys.get(i);
return null;
}
private void setProjectChanged(boolean b) {
frame.setProjectChanged(b);
}
/**
* Returns the SorterTableColumnModel of the MainFrame.
*
* @return
*/
SorterTableColumnModel getSorter() {
return frame.getSorter();
}
public void resized() {
resetPrevCommentsComboBox();
userCommentsText.validate();
}
BugTreeModel getModel() {
return (BugTreeModel) frame.tree.getModel();
}
public boolean hasFocus() {
return userCommentsText.hasFocus();
}
} |
package com.yahoo.vespa.flags;
import com.yahoo.vespa.flags.custom.ClusterCapacity;
import com.yahoo.vespa.flags.custom.SharedHost;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definition for permanent feature flags
*
* @author bjorncs
*/
public class PermanentFlags {
static final List<String> OWNERS = List.of();
static final Instant CREATED_AT = Instant.EPOCH;
static final Instant EXPIRES_AT = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant();
public static final UnboundBooleanFlag USE_ALTERNATIVE_ENDPOINT_CERTIFICATE_PROVIDER = defineFeatureFlag(
"use-alternative-endpoint-certificate-provider", false,
"Whether to use an alternative CA when provisioning new certificates",
"Takes effect only on initial application deployment - not on later certificate refreshes!");
public static final UnboundStringFlag JVM_GC_OPTIONS = defineStringFlag(
"jvm-gc-options", "",
"Sets default jvm gc options",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag FLEET_CANARY = defineFeatureFlag(
"fleet-canary", false,
"Whether the host is a fleet canary.",
"Takes effect on next host admin tick.",
HOSTNAME);
public static final UnboundListFlag<ClusterCapacity> PREPROVISION_CAPACITY = defineListFlag(
"preprovision-capacity", List.of(), ClusterCapacity.class,
"Specifies the resources that ought to be immediately available for additional cluster " +
"allocations. If the resources are not available, additional hosts will be provisioned. " +
"Only applies to dynamically provisioned zones.",
"Takes effect on next iteration of DynamicProvisioningMaintainer.");
public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag(
"reboot-interval-in-days", 15,
"No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " +
"scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).",
"Takes effect on next run of NodeRebooter");
public static final UnboundJacksonFlag<SharedHost> SHARED_HOST = defineJacksonFlag(
"shared-host", SharedHost.createDisabled(), SharedHost.class,
"Specifies whether shared hosts can be provisioned, and if so, the advertised " +
"node resources of the host, the maximum number of containers, etc.",
"Takes effect on next iteration of DynamicProvisioningMaintainer.");
public static final UnboundBooleanFlag SKIP_MAINTENANCE_DEPLOYMENT = defineFeatureFlag(
"node-repository-skip-maintenance-deployment", false,
"Whether PeriodicApplicationMaintainer should skip deployment for an application",
"Takes effect at next run of maintainer",
APPLICATION_ID);
public static final UnboundListFlag<String> INACTIVE_MAINTENANCE_JOBS = defineListFlag(
"inactive-maintenance-jobs", List.of(), String.class,
"The list of maintenance jobs that are inactive.",
"Takes effect immediately, but any currently running jobs will run until completion.");
public static final UnboundListFlag<String> OUTBOUND_BLOCKED_IPV4 = defineListFlag(
"container-outbound-blocked-ipv4", List.of(), String.class,
"List of IPs or CIDRs that are blocked for outbound connections",
"Takes effect on next tick");
public static final UnboundListFlag<String> OUTBOUND_BLOCKED_IPV6 = defineListFlag(
"container-outbound-blocked-ipv6", List.of(), String.class,
"List of IPs or CIDRs that are blocked for outbound connections",
"Takes effect on next tick");
public static final UnboundIntFlag TENANT_BUDGET_QUOTA = defineIntFlag(
"tenant-budget-quota", -1,
"The budget in cents/hr a tenant is allowed spend per instance, as calculated by NodeResources",
"Only takes effect on next deployment, if set to a value other than the default for flag!",
TENANT_ID);
public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag(
"container-cpu-cap", 0,
"Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " +
"to cap CPU at 200%, set this to 2, etc. 0 disables the cap to allow unlimited CPU.",
"Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart",
HOSTNAME, APPLICATION_ID, CLUSTER_ID, CLUSTER_TYPE);
public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag(
"disabled-host-admin-tasks", List.of(), String.class,
"List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask), or some node-agent " +
"functionality (see NodeAgentTask), that should be skipped",
"Takes effect on next host admin tick",
HOSTNAME, NODE_TYPE);
public static final UnboundStringFlag DOCKER_IMAGE_REPO = defineStringFlag(
"docker-image-repo", "",
"Override default docker image repo. Docker image version will be Vespa version.",
"Takes effect on next deployment from controller",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag ZOOKEEPER_SERVER_VERSION = defineStringFlag(
"zookeeper-server-version", "3.6.3",
"ZooKeeper server version, a jar file zookeeper-server-<ZOOKEEPER_SERVER_VERSION>-jar-with-dependencies.jar must exist",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundBooleanFlag ENABLE_PUBLIC_SIGNUP_FLOW = defineFeatureFlag(
"enable-public-signup-flow", false,
"Show the public signup flow for a user in the console",
"takes effect on browser reload of api/user/v1/user",
CONSOLE_USER_EMAIL);
public static final UnboundLongFlag INVALIDATE_CONSOLE_SESSIONS = defineLongFlag(
"invalidate-console-sessions", 0,
"Invalidate console sessions (cookies) issued before this unix timestamp",
"Takes effect on next api request"
);
public static final UnboundBooleanFlag JVM_OMIT_STACK_TRACE_IN_FAST_THROW = defineFeatureFlag(
"jvm-omit-stack-trace-in-fast-throw", true,
"Controls JVM option OmitStackTraceInFastThrow (default feature flag value is true, which is the default JVM option value as well)",
"takes effect on JVM restart",
CLUSTER_TYPE, APPLICATION_ID);
public static final UnboundIntFlag MAX_TRIAL_TENANTS = defineIntFlag(
"max-trial-tenants", -1,
"The maximum nr. of tenants with trial plan, -1 is unlimited",
"Takes effect immediately"
);
public static final UnboundBooleanFlag ALLOW_DISABLE_MTLS = defineFeatureFlag(
"allow-disable-mtls", true,
"Allow application to disable client authentication",
"Takes effect on redeployment",
APPLICATION_ID);
public static final UnboundIntFlag MAX_REBUILDS = defineIntFlag(
"max-host-rebuilds", 10,
"The maximum number of hosts allowed to rebuild at a time",
"Takes effect immediately, but any current excess rebuilds will not be cancelled"
);
public static final UnboundListFlag<String> EXTENDED_TRIAL_TENANTS = defineListFlag(
"extended-trial-tenants", List.of(), String.class,
"Tenants that will not be expired from their trial plan",
"Takes effect immediately, used by the CloudTrialExpirer maintainer",
TENANT_ID
);
public static final UnboundListFlag<String> TLS_CIPHERS_OVERRIDE = defineListFlag(
"tls-ciphers-override", List.of(), String.class,
"Override TLS ciphers enabled for port 4443 on hosted application containers",
"Takes effect on redeployment",
APPLICATION_ID
);
private PermanentFlags() {}
private static UnboundBooleanFlag defineFeatureFlag(
String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return Flags.defineFeatureFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions);
}
private static UnboundStringFlag defineStringFlag(
String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return Flags.defineStringFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions);
}
private static UnboundIntFlag defineIntFlag(
String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return Flags.defineIntFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions);
}
private static UnboundLongFlag defineLongFlag(
String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return Flags.defineLongFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions);
}
private static UnboundDoubleFlag defineDoubleFlag(
String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return Flags.defineDoubleFlag(flagId, defaultValue, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions);
}
private static <T> UnboundJacksonFlag<T> defineJacksonFlag(
String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return Flags.defineJacksonFlag(flagId, defaultValue, jacksonClass, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions);
}
private static <T> UnboundListFlag<T> defineListFlag(
String flagId, List<T> defaultValue, Class<T> elementClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return Flags.defineListFlag(flagId, defaultValue, elementClass, OWNERS, toString(CREATED_AT), toString(EXPIRES_AT), description, modificationEffect, dimensions);
}
private static String toString(Instant instant) { return DateTimeFormatter.ISO_DATE.withZone(ZoneOffset.UTC).format(instant); }
} |
package io.flutter.project;
import com.android.tools.adtui.util.FormScalingUtil;
import com.android.tools.adtui.validation.Validator;
import com.android.tools.adtui.validation.ValidatorPanel;
import com.android.tools.idea.npw.project.NewProjectModel;
import com.android.tools.idea.observable.BindingsManager;
import com.android.tools.idea.observable.ListenerManager;
import com.android.tools.idea.observable.core.*;
import com.android.tools.idea.observable.expressions.Expression;
import com.android.tools.idea.observable.expressions.value.TransformOptionalExpression;
import com.android.tools.idea.observable.ui.SelectedItemProperty;
import com.android.tools.idea.observable.ui.TextProperty;
import com.android.tools.idea.ui.validation.validators.PathValidator;
import com.android.tools.idea.ui.wizard.StudioWizardStepPanel;
import com.android.tools.idea.ui.wizard.WizardUtils;
import com.android.tools.idea.wizard.model.ModelWizardStep;
import com.android.tools.idea.wizard.model.SkippableWizardStep;
import com.google.common.collect.Lists;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.IconLoader;
import com.intellij.ui.ComboboxWithBrowseButton;
import com.intellij.ui.JBProgressBar;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.util.ui.UIUtil;
import io.flutter.FlutterBundle;
import io.flutter.FlutterConstants;
import io.flutter.FlutterUtils;
import io.flutter.module.FlutterProjectType;
import io.flutter.module.InstallSdkAction;
import io.flutter.sdk.FlutterSdkUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Collection;
import java.util.List;
/**
* Configure Flutter project parameters that are common to all types.
*/
public class FlutterProjectStep extends SkippableWizardStep<FlutterProjectModel> implements InstallSdkAction.Model {
private final StudioWizardStepPanel myRootPanel;
private final ValidatorPanel myValidatorPanel;
private final BindingsManager myBindings = new BindingsManager();
private final ListenerManager myListeners = new ListenerManager();
private final InstallSdkAction myInstallSdkAction;
private boolean hasEntered = false;
private OptionalValueProperty<FlutterProjectType> myProjectType;
private StringValueProperty myDownloadErrorMessage = new StringValueProperty();
private InstallSdkAction.CancelActionListener myListener;
private String mySdkPathContent = "";
private JPanel myPanel;
private JTextField myProjectName;
private JTextField myDescription;
private TextFieldWithBrowseButton myProjectLocation;
private ComboboxWithBrowseButton myFlutterSdkPath;
private JLabel myHeading;
private JPanel myLocationPanel;
private LinkLabel myInstallActionLink;
private JBProgressBar myProgressBar;
private JLabel myCancelProgressButton;
private JTextPane myProgressText;
public FlutterProjectStep(FlutterProjectModel model, String title, Icon icon, FlutterProjectType type) {
super(model, title, icon);
myProjectType = new OptionalValueProperty<>(type);
myValidatorPanel = new ValidatorPanel(this, myPanel);
Expression<String> computedLocation = model.projectName().transform(FlutterProjectStep::findProjectLocation);
TextProperty locationText = new TextProperty(myProjectLocation.getChildComponent());
BoolProperty isLocationSynced = new BoolValueProperty(true);
myBindings.bind(locationText, computedLocation, isLocationSynced);
myBindings.bind(model.projectLocation(), locationText);
myListeners.receive(locationText, value -> isLocationSynced.set(value.equals(computedLocation.get())));
myBindings.bindTwoWay(new TextProperty(myProjectName), model.projectName());
myBindings.bind(model.description(), new TextProperty(myDescription));
myFlutterSdkPath.getComboBox().setEditable(true);
myFlutterSdkPath.getButton()
.addActionListener((e) -> myFlutterSdkPath.getComboBox().setSelectedItem(myFlutterSdkPath.getComboBox().getEditor().getItem()));
myBindings.bind(
model.flutterSdk(),
new TransformOptionalExpression<String, String>("", new SelectedItemProperty<>(myFlutterSdkPath.getComboBox())) {
@NotNull
@Override
protected String transform(@NotNull String value) {
return value;
}
});
FlutterSdkUtil.addKnownSDKPathsToCombo(myFlutterSdkPath.getComboBox());
myFlutterSdkPath.addBrowseFolderListener(FlutterBundle.message("flutter.sdk.browse.path.label"), null, null,
FileChooserDescriptorFactory.createSingleFolderDescriptor(),
TextComponentAccessor.STRING_COMBOBOX_WHOLE_TEXT);
myProjectLocation.addBrowseFolderListener(FlutterBundle.message("flutter.sdk.browse.path.label"), null, null,
FileChooserDescriptorFactory.createSingleFolderDescriptor(),
TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT);
myValidatorPanel.registerValidator(model.flutterSdk(), FlutterProjectStep::validateFlutterSdk);
myValidatorPanel.registerValidator(model.projectName(), this::validateFlutterModuleName);
myValidatorPanel.registerMessageSource(myDownloadErrorMessage);
Expression<File> locationFile = model.projectLocation().transform(File::new);
myValidatorPanel.registerValidator(locationFile, PathValidator.createDefault("project location"));
// Initialization of the SDK install UI was copied from FlutterGeneratorPeer.
// Hide pending real content.
myProgressBar.setVisible(false);
myProgressText.setVisible(false);
myCancelProgressButton.setVisible(false);
myInstallSdkAction = new InstallSdkAction(this);
myInstallActionLink.setIcon(myInstallSdkAction.getLinkIcon());
myInstallActionLink.setDisabledIcon(IconLoader.getDisabledIcon(myInstallSdkAction.getLinkIcon()));
myInstallActionLink.setText(myInstallSdkAction.getLinkText());
//noinspection unchecked
myInstallActionLink.setListener((label, linkUrl) -> myInstallSdkAction.actionPerformed(null), null);
myProgressText.setFont(UIUtil.getLabelFont(UIUtil.FontSize.NORMAL).deriveFont(Font.ITALIC));
// Some feedback on hover.
myCancelProgressButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
myCancelProgressButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
myListener.actionCanceled();
}
});
myRootPanel = new StudioWizardStepPanel(myValidatorPanel);
FormScalingUtil.scaleComponentTree(this.getClass(), myRootPanel);
}
@NotNull
private static Validator.Result validateFlutterSdk(String sdkPath) {
if (!sdkPath.isEmpty()) {
final String message = FlutterSdkUtil.getErrorMessageIfWrongSdkRootPath(sdkPath);
if (message != null) {
return Validator.Result.fromNullableMessage(message);
}
return Validator.Result.OK;
}
else {
return Validator.Result.fromNullableMessage("Flutter SDK path not given");
}
}
@NotNull
@SuppressWarnings("Duplicates") // Copied from ConfigureAndroidProjectStep
private static String findProjectLocation(@NotNull String appName) {
String applicationName = NewProjectModel.sanitizeApplicationName(appName);
File baseDirectory = WizardUtils.getProjectLocationParent();
File projectDirectory = new File(baseDirectory, applicationName);
// Try appName, appName2, appName3, ...
int counter = 2;
while (projectDirectory.exists()) {
projectDirectory = new File(baseDirectory, String.format("%s%d", applicationName, counter++));
}
return projectDirectory.getPath();
}
private static Validator.Result errorResult(String message) {
return new Validator.Result(Validator.Severity.ERROR, message);
}
private static void ensureComboModelContainsCurrentItem(@NotNull final JComboBox comboBox) {
final Object currentItem = comboBox.getEditor().getItem();
boolean contains = false;
for (int i = 0; i < comboBox.getModel().getSize(); i++) {
if (currentItem.equals(comboBox.getModel().getElementAt(i))) {
contains = true;
break;
}
}
if (!contains) {
//noinspection unchecked
((DefaultComboBoxModel)comboBox.getModel()).insertElementAt(currentItem, 0);
comboBox.setSelectedItem(currentItem); // to set focus on current item in combo popup
comboBox.getEditor().setItem(currentItem); // to set current item in combo itself
}
}
@NotNull
private Validator.Result validateFlutterModuleName(@NotNull String moduleName) {
if (moduleName.isEmpty()) {
return errorResult("Please enter a name for the project");
}
if (!FlutterUtils.isValidPackageName(moduleName)) {
return errorResult(
"Invalid module name: '" + moduleName + "' - must be a valid Dart package name (lower_case_with_underscores).");
}
if (FlutterUtils.isDartKeword(moduleName)) {
return errorResult("Invalid module name: '" + moduleName + "' - must not be a Dart keyword.");
}
if (!FlutterUtils.isValidDartIdentifier(moduleName)) {
return errorResult("Invalid module name: '" + moduleName + "' - must be a valid Dart identifier.");
}
if (FlutterConstants.FLUTTER_PACKAGE_DEPENDENCIES.contains(moduleName)) {
return errorResult("Invalid module name: '" + moduleName + "' - this will conflict with Flutter package dependencies.");
}
if (moduleName.length() > FlutterConstants.MAX_MODULE_NAME_LENGTH) {
return errorResult("Invalid module name - must be less than " +
FlutterConstants.MAX_MODULE_NAME_LENGTH +
" characters.");
}
if (getModel().project().get().isPresent()) {
Project project = getModel().project().getValue();
Module module;
ProjectStructureConfigurable fromConfigurable = ProjectStructureConfigurable.getInstance(project);
if (fromConfigurable != null) {
module = fromConfigurable.getModulesConfig().getModule(moduleName);
}
else {
module = ModuleManager.getInstance(project).findModuleByName(moduleName);
}
if (module != null) {
return errorResult("A module with that name already exists in the project.");
}
}
return Validator.Result.OK;
}
protected void hideLocation() {
myLocationPanel.setVisible(false);
}
@Override
public void dispose() {
myBindings.releaseAll();
myListeners.releaseAll();
}
@NotNull
@Override
protected JComponent getComponent() {
return myRootPanel;
}
@Nullable
@Override
protected JComponent getPreferredFocusComponent() {
return myProjectName;
}
@NotNull
@Override
protected ObservableBool canGoForward() {
return myValidatorPanel.hasErrors().not();
}
@Override
protected void onEntering() {
getModel().projectType().set(myProjectType);
if (hasEntered) {
return;
}
String heading = "";
switch (myProjectType.getValue()) {
case APP:
heading = FlutterBundle.message("module.wizard.app_step_body");
break;
case PACKAGE:
heading = FlutterBundle.message("module.wizard.package_step_body");
break;
case PLUGIN:
heading = FlutterBundle.message("module.wizard.plugin_step_body");
break;
}
myHeading.setText(heading);
myDownloadErrorMessage.set("");
mySdkPathContent = (String)myFlutterSdkPath.getComboBox().getEditor().getItem();
// Set default values for text fields, but only do so the first time the page is shown.
String descrText = "";
String name = "";
switch (myProjectType.getValue()) {
case APP:
name = FlutterBundle.message("module.wizard.app_name");
descrText = FlutterBundle.message("module.wizard.app_text");
break;
case PACKAGE:
name = FlutterBundle.message("module.wizard.package_name");
descrText = FlutterBundle.message("module.wizard.package_text");
break;
case PLUGIN:
name = FlutterBundle.message("module.wizard.plugin_name");
descrText = FlutterBundle.message("module.wizard.plugin_text");
break;
}
myDescription.setText(descrText);
myProjectName.setText(name);
hasEntered = true;
}
@NotNull
@Override
protected Collection<? extends ModelWizardStep> createDependentSteps() {
List<ModelWizardStep> allSteps = Lists.newArrayList();
if (myProjectType.getValue() == FlutterProjectType.PACKAGE) {
return allSteps;
}
allSteps.add(new FlutterSettingsStep(getModel(), getTitle(), getIcon()));
return allSteps;
}
@Override
public void setSdkPath(String path) {
mySdkPathContent = (String)myFlutterSdkPath.getComboBox().getEditor().getItem();
myFlutterSdkPath.getComboBox().getEditor().setItem(path);
myDownloadErrorMessage.set("");
}
@Override
public boolean validate() {
setSdkPath(mySdkPathContent);
ensureComboModelContainsCurrentItem(myFlutterSdkPath.getComboBox());
return false;
}
@Override
public void requestNextStep() {
// Called when the download process completes.
ensureComboModelContainsCurrentItem(myFlutterSdkPath.getComboBox());
}
@Override
public void setErrorDetails(String details) {
// Setting this doesn't do much since the first validation error encountered is displayed, not the most recent.
myDownloadErrorMessage.set(details == null ? "" : details);
}
@Override
public ComboboxWithBrowseButton getSdkComboBox() {
return myFlutterSdkPath;
}
@Override
public void addCancelActionListener(InstallSdkAction.CancelActionListener listener) {
myListener = listener;
}
@Override
public JBProgressBar getProgressBar() {
return myProgressBar;
}
@Override
public LinkLabel getInstallActionLink() {
return myInstallActionLink;
}
@Override
public JTextPane getProgressText() {
return myProgressText;
}
@Override
public JLabel getCancelProgressButton() {
return myCancelProgressButton;
}
} |
package brooklyn.util.net;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.annotation.Nullable;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
public class Urls {
public static Function<String,URI> stringToUriFunction() {
return StringToUri.INSTANCE;
}
public static Function<String,URL> stringToUrlFunction() {
return StringToUrl.INSTANCE;
}
private static enum StringToUri implements Function<String,URI> {
INSTANCE;
@Override public URI apply(@Nullable String input) {
return toUri(input);
}
@Override
public String toString() {
return "StringToUri";
}
}
private static enum StringToUrl implements Function<String,URL> {
INSTANCE;
@Override public URL apply(@Nullable String input) {
return toUrl(input);
}
@Override
public String toString() {
return "StringToUrl";
}
}
/** creates a URL, preserving null and propagating exceptions *unchecked* */
public static final URL toUrl(@Nullable String url) {
if (url==null) return null;
try {
return new URL(url);
} catch (MalformedURLException e) {
// FOAD
throw Throwables.propagate(e);
}
}
/** creates a URL, preserving null and propagating exceptions *unchecked* */
public static final URL toUrl(@Nullable URI uri) {
if (uri==null) return null;
try {
return uri.toURL();
} catch (MalformedURLException e) {
// FOAD
throw Throwables.propagate(e);
}
}
/** creates a URI, preserving null and propagating exceptions *unchecked* */
public static final URI toUri(@Nullable String uri) {
if (uri==null) return null;
return URI.create(uri);
}
/** creates a URI, preserving null and propagating exceptions *unchecked* */
public static final URI toUri(@Nullable URL url) {
if (url==null) return null;
try {
return url.toURI();
} catch (URISyntaxException e) {
// FOAD
throw Throwables.propagate(e);
}
}
/** returns the items with exactly one "/" between items (whether or not the individual items start or end with /),
* except where character before the / is a : (url syntax) in which case it will permit multiple (will not remove any) */
public static String mergePaths(String ...items) {
StringBuilder result = new StringBuilder();
for (String item: items) {
boolean trimThisMerge = result.length()>0 && !result.toString().endsWith("://") && !result.toString().endsWith(":///") && !result.toString().endsWith(":");
if (trimThisMerge) {
while (result.charAt(result.length()-1)=='/')
result.deleteCharAt(result.length()-1);
result.append('/');
}
int i = result.length();
result.append(item);
if (trimThisMerge) {
while (result.length()>i && result.charAt(i)=='/')
result.deleteCharAt(i);
}
}
return result.toString();
}
} |
package io.spacedog.utils;
import java.util.Arrays;
import java.util.Base64;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Sets;
// ignore deprecated fields still in elastic data
@JsonIgnoreProperties(ignoreUnknown = true)
// only map to fields
@JsonAutoDetect(fieldVisibility = Visibility.ANY,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE)
public class Credentials {
public static enum Level {
KEY, USER, ADMIN, SUPER_ADMIN, SUPERDOG;
public Level[] lowerOrEqual() {
return Arrays.copyOf(values(), ordinal() + 1);
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE)
public static class Session {
private String accessToken;
private DateTime accessTokenExpiresAt;
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Session))
return false;
Session other = (Session) obj;
if (accessToken == other.accessToken)
return true;
return accessToken.equals(other.accessToken);
}
@Override
public int hashCode() {
return accessToken == null ? super.hashCode() : accessToken.hashCode();
}
public long expiresIn() {
if (accessTokenExpiresAt == null)
return 0;
long expiresIn = accessTokenExpiresAt.getMillis() - DateTime.now().getMillis();
if (expiresIn < 0)
return 0;
// expiresIn must be converted and rounded up to seconds
return (long) Math.ceil(expiresIn / 1000.0);
}
public static Session newSession(long lifetime) {
String token = new String(Base64.getEncoder().encode(
UUID.randomUUID().toString().getBytes(Utils.UTF8)));
return newSession(token, lifetime);
}
public static Session newSession(String accessToken, long lifetime) {
Session session = new Session();
session.accessToken = accessToken;
// lifetime in seconds is converted to milliseconds
session.accessTokenExpiresAt = DateTime.now().plus(lifetime * 1000);
return session;
}
}
private String backendId;
private String username;
private String email;
private Level level;
private boolean enabled = true;
private Set<String> roles;
private Set<Session> sessions;
private String passwordResetCode;
private String hashedPassword;
private String createdAt;
private String updatedAt;
@JsonIgnore
private Session currentSession;
@JsonIgnore
private boolean passwordChecked;
@JsonIgnore
private String id;
@JsonIgnore
private long version;
public Credentials() {
}
public Credentials(String backendId) {
this.backendId = backendId;
this.level = Level.KEY;
}
public Credentials(String backendId, String name, Level level) {
this.backendId = backendId;
this.username = name;
this.level = level;
}
public boolean isSuperDog() {
return Level.SUPERDOG.equals(level);
}
public boolean isAtLeastSuperAdmin() {
return level.ordinal() >= Level.SUPER_ADMIN.ordinal();
}
public boolean isAtMostSuperAdmin() {
return level.ordinal() <= Level.SUPER_ADMIN.ordinal();
}
public boolean isAtLeastAdmin() {
return level.ordinal() >= Level.ADMIN.ordinal();
}
public boolean isAtMostAdmin() {
return level.ordinal() <= Level.ADMIN.ordinal();
}
public boolean isAtLeastUser() {
return level.ordinal() >= Level.USER.ordinal();
}
public boolean isAtMostUser() {
return level.ordinal() <= Level.USER.ordinal();
}
public String backendId() {
return this.backendId;
}
public String id() {
return id;
}
public void id(String id) {
this.id = id;
}
public long version() {
return version;
}
public void version(long version) {
this.version = version;
}
public void backendId(String backendId) {
this.backendId = backendId;
}
public String name() {
return username == null ? "default" : username;
}
public void name(String name) {
this.username = name;
}
public Optional<String> email() {
return Optional.ofNullable(email);
}
public void email(String value) {
this.email = value;
}
public Level level() {
return level;
}
public void level(Level value) {
this.level = value;
}
public String accessToken() {
return currentSession == null ? null : currentSession.accessToken;
}
public long accessTokenExpiresIn() {
return currentSession == null ? 0 : currentSession.expiresIn();
}
public boolean isPasswordChecked() {
return passwordChecked;
}
public String passwordResetCode() {
return passwordResetCode;
}
public void newPasswordResetCode() {
passwordResetCode = UUID.randomUUID().toString();
}
public boolean enabled() {
return this.enabled;
}
public void enabled(boolean enabled) {
this.enabled = enabled;
}
public Set<String> roles() {
if (roles == null)
roles = Sets.newHashSet();
roles.add(defaultRole());
return roles;
}
public void roles(Set<String> value) {
roles = value;
}
public void checkRoles(String... authorizedRoles) {
if (authorizedRoles != null) {
Set<String> thisCredentialsRoles = roles();
for (String authorizedRole : authorizedRoles)
if (thisCredentialsRoles.contains(authorizedRole))
return;
}
throw Exceptions.insufficientCredentials(this);
}
public String createdAt() {
return createdAt;
}
public void createdAt(String value) {
createdAt = value;
}
public String updatedAt() {
return updatedAt;
}
public void updatedAt(String value) {
updatedAt = value;
}
public boolean isBrandNew() {
return updatedAt == null ? true : updatedAt.equals(createdAt);
}
public boolean isRootBackend() {
return Backends.ROOT_API.equals(backendId);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((backendId == null) ? 0 : backendId.hashCode());
result = prime * result + ((username == null) ? 0 : username.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;
Credentials other = (Credentials) obj;
if (backendId == null) {
if (other.backendId != null)
return false;
} else if (!backendId.equals(other.backendId))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
// Business logic
public boolean checkPassword(String passwordToCheck) {
if (hashedPassword == null)
return false;
String hashedPasswordToCheck = Passwords.hash(passwordToCheck);
if (hashedPassword.equals(hashedPasswordToCheck)) {
passwordChecked = true;
return true;
}
return false;
}
public void clearPasswordAndTokens() {
hashedPassword = null;
passwordResetCode = null;
currentSession = null;
if (sessions != null)
sessions.clear();
}
public void setPassword(String password, String passwordResetCode, Optional<String> regex) {
Check.notNullOrEmpty(password, "password");
Check.notNullOrEmpty(passwordResetCode, "passwordResetCode");
if (hashedPassword != null || passwordResetCode == null)
throw Exceptions.illegalArgument(
"credentials [%s] password must be deleted before reset", username);
if (!this.passwordResetCode.equals(passwordResetCode))
throw Exceptions.illegalArgument(
"password reset code [%s] invalid", passwordResetCode);
setPassword(password, regex);
}
public boolean setPassword(String password, Optional<String> regex) {
hashedPassword = Passwords.checkAndHash(password, regex);
passwordChecked = true;
passwordResetCode = null;
return true;
}
// Sessions and Access Tokens
public void setSession(String accessToken) {
for (Session session : sessions) {
if (session.expiresIn() == 0)
sessions.remove(session);
else if (accessToken.equals(session.accessToken))
currentSession = session;
}
}
public void setSession(Session session) {
currentSession = session;
if (sessions == null)
sessions = Sets.newHashSet();
sessions.add(currentSession);
}
public void deleteSession() {
if (currentSession != null) {
if (sessions != null)
sessions.remove(currentSession);
currentSession = null;
}
}
public ObjectNode toJson() {
return Json.object(
SpaceFieldNames.ID, id(),
SpaceFieldNames.BACKEND_ID, backendId(),
SpaceFieldNames.USERNAME, name(),
SpaceFieldNames.EMAIL, email().get(),
SpaceFieldNames.ENABLED, enabled(),
SpaceFieldNames.CREDENTIALS_LEVEL, level().name(),
SpaceFieldNames.ROLES, roles(),
SpaceFieldNames.CREATED_AT, createdAt(),
SpaceFieldNames.UPDATED_AT, updatedAt());
}
// implementation
private String defaultRole() {
if (Level.USER.equals(level))
return "user";
if (Level.ADMIN.equals(level))
return "admin";
if (Level.SUPER_ADMIN.equals(level))
return "admin";
if (Level.SUPERDOG.equals(level))
return "admin";
return "key";
}
public void setLegacyId() {
this.id = toLegacyId(backendId, username);
}
public static String[] fromLegacyId(String id) {
return id.split("-", 2);
}
public static String toLegacyId(String backendId, String username) {
return String.join("-", backendId, username);
}
} |
package mods.railcraft.api.tracks;
import mods.railcraft.api.core.items.IToolCrowbar;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRailBase;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.MathHelper;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static net.minecraft.block.BlockRailBase.EnumRailDirection.*;
public abstract class TrackInstanceBase implements ITrackInstance {
public TileEntity tileEntity;
private BlockRailBase getBlock() {
return (BlockRailBase) tileEntity.getBlockType();
}
@Override
public void setTile(TileEntity tile) {
tileEntity = tile;
}
@Override
public TileEntity getTile() {
return tileEntity;
}
@Override
public IBlockState getActualState(IBlockState state) {
return state;
}
@Override
public List<ItemStack> getDrops(int fortune) {
List<ItemStack> drops = new ArrayList<ItemStack>();
drops.add(getTrackSpec().getItem());
return drops;
}
@Override
public BlockRailBase.EnumRailDirection getRailDirection(IBlockState state, EntityMinecart cart) {
return getRailDirection(state);
}
protected final BlockRailBase.EnumRailDirection getRailDirection() {
IBlockState state = getWorld().getBlockState(getPos());
return getRailDirection(state);
}
protected static BlockRailBase.EnumRailDirection getRailDirection(IBlockState state) {
if (state.getBlock() instanceof BlockRailBase)
return state.getValue(((BlockRailBase) state.getBlock()).getShapeProperty());
return NORTH_SOUTH;
}
@Override
public void onMinecartPass(EntityMinecart cart) {
}
@Override
public boolean blockActivated(EntityPlayer player) {
if (this instanceof ITrackReversible) {
ItemStack current = player.getCurrentEquippedItem();
if (current != null && current.getItem() instanceof IToolCrowbar) {
IToolCrowbar crowbar = (IToolCrowbar) current.getItem();
if (crowbar.canWhack(player, current, getPos())) {
ITrackReversible track = (ITrackReversible) this;
track.setReversed(!track.isReversed());
markBlockNeedsUpdate();
crowbar.onWhack(player, current, getPos());
return true;
}
}
}
return false;
}
@Override
public void onBlockPlacedBy(IBlockState state, EntityLivingBase placer, ItemStack stack) {
if (placer == null)
return;
if (this instanceof ITrackReversible) {
int dir = MathHelper.floor_double((double) ((placer.rotationYaw * 4F) / 360F) + 0.5D) & 3;
((ITrackReversible) this).setReversed(dir == 0 || dir == 1);
}
switchTrack(state, true);
testPower(state);
markBlockNeedsUpdate();
}
@Override
public void onBlockRemoved() {
}
public void sendUpdateToClient() {
((ITrackTile) tileEntity).sendUpdateToClient();
}
public void markBlockNeedsUpdate() {
getWorld().markBlockForUpdate(tileEntity.getPos());
}
@SuppressWarnings("WeakerAccess")
protected boolean isRailValid(World world, BlockPos pos, BlockRailBase.EnumRailDirection dir) {
boolean valid = true;
if (!world.isSideSolid(pos.down(), EnumFacing.UP))
valid = false;
if (dir == ASCENDING_EAST && !world.isSideSolid(pos.east(), EnumFacing.UP))
valid = false;
else if (dir == ASCENDING_WEST && !world.isSideSolid(pos.west(), EnumFacing.UP))
valid = false;
else if (dir == ASCENDING_NORTH && !world.isSideSolid(pos.north(), EnumFacing.UP))
valid = false;
else if (dir == ASCENDING_SOUTH && !world.isSideSolid(pos.south(), EnumFacing.UP))
valid = false;
return valid;
}
@Override
public void onNeighborBlockChange(IBlockState state, Block neighborBlock) {
boolean valid = isRailValid(getWorld(), getPos(), state.getValue(((BlockRailBase) state.getBlock()).getShapeProperty()));
if (!valid) {
Block blockTrack = getBlock();
blockTrack.dropBlockAsItem(getWorld(), getPos(), state, 0);
getWorld().setBlockToAir(getPos());
return;
}
if (neighborBlock != null && neighborBlock.canProvidePower()
&& isFlexibleRail() && TrackToolsAPI.countAdjacentTracks(getWorld(), getPos()) == 3)
switchTrack(state, false);
testPower(state);
}
private void switchTrack(IBlockState state, boolean flag) {
BlockPos pos = tileEntity.getPos();
BlockRailBase blockTrack = getBlock();
blockTrack.new Rail(getWorld(), pos, state).func_180364_a(getWorld().isBlockPowered(pos), flag);
}
protected final void testPower(IBlockState state) {
if (!(this instanceof ITrackPowered))
return;
ITrackPowered r = (ITrackPowered) this;
boolean powered = getWorld().isBlockIndirectlyGettingPowered(getPos()) > 0 || testPowerPropagation(getWorld(), getPos(), getTrackSpec(), state, r.getPowerPropagation());
if (powered != r.isPowered()) {
r.setPowered(powered);
Block blockTrack = getBlock();
getWorld().notifyNeighborsOfStateChange(getPos(), blockTrack);
getWorld().notifyNeighborsOfStateChange(getPos().down(), blockTrack);
BlockRailBase.EnumRailDirection railDirection = state.getValue(((BlockRailBase) state.getBlock()).getShapeProperty());
if (railDirection.isAscending())
getWorld().notifyNeighborsOfStateChange(getPos().up(), blockTrack);
sendUpdateToClient();
// System.out.println("Setting power [" + i + ", " + j + ", " + k + "]");
}
}
private boolean testPowerPropagation(World world, BlockPos pos, TrackSpec baseSpec, IBlockState state, int maxDist) {
return isConnectedRailPowered(world, pos, baseSpec, state, true, 0, maxDist) || isConnectedRailPowered(world, pos, baseSpec, state, false, 0, maxDist);
}
private boolean isConnectedRailPowered(World world, BlockPos pos, TrackSpec baseSpec, IBlockState state, boolean dir, int dist, int maxDist) {
if (dist >= maxDist)
return false;
boolean powered = true;
int x = pos.getX();
int y = pos.getY();
int z = pos.getZ();
BlockRailBase.EnumRailDirection railDirection = state.getValue(getBlock().getShapeProperty());
switch (railDirection) {
case NORTH_SOUTH:
if (dir)
z++;
else
z
break;
case EAST_WEST: // '\001'
if (dir)
x
else
x++;
break;
case ASCENDING_EAST: // '\002'
if (dir)
x
else {
x++;
y++;
powered = false;
}
railDirection = EAST_WEST;
break;
case ASCENDING_WEST: // '\003'
if (dir) {
x
y++;
powered = false;
} else
x++;
railDirection = EAST_WEST;
break;
case ASCENDING_NORTH: // '\004'
if (dir)
z++;
else {
z
y++;
powered = false;
}
railDirection = NORTH_SOUTH;
break;
case ASCENDING_SOUTH: // '\005'
if (dir) {
z++;
y++;
powered = false;
} else
z
railDirection = NORTH_SOUTH;
break;
}
pos = new BlockPos(x, y, z);
return testPowered(world, pos, baseSpec, dir, dist, maxDist, railDirection) || (powered && testPowered(world, pos.down(), baseSpec, dir, dist, maxDist, railDirection));
}
private boolean testPowered(World world, BlockPos nextPos, TrackSpec baseSpec, boolean dir, int dist, int maxDist, BlockRailBase.EnumRailDirection prevOrientation) {
// System.out.println("Testing Power at <" + nextPos + ">");
IBlockState nextBlockState = world.getBlockState(nextPos);
if (nextBlockState.getBlock() == getBlock()) {
BlockRailBase.EnumRailDirection nextOrientation = nextBlockState.getValue(((BlockRailBase) nextBlockState.getBlock()).getShapeProperty());
TileEntity nextTile = world.getTileEntity(nextPos);
if (nextTile instanceof ITrackTile) {
ITrackInstance nextTrack = ((ITrackTile) nextTile).getTrackInstance();
if (!(nextTrack instanceof ITrackPowered) || nextTrack.getTrackSpec() != baseSpec || !((ITrackPowered) this).canPropagatePowerTo(nextTrack))
return false;
if (prevOrientation == EAST_WEST && (nextOrientation == NORTH_SOUTH || nextOrientation == ASCENDING_NORTH || nextOrientation == ASCENDING_SOUTH))
return false;
if (prevOrientation == NORTH_SOUTH && (nextOrientation == EAST_WEST || nextOrientation == ASCENDING_EAST || nextOrientation == ASCENDING_WEST))
return false;
if (((ITrackPowered) nextTrack).isPowered())
return world.isBlockPowered(nextPos) || world.isBlockPowered(nextPos.up()) || isConnectedRailPowered(world, nextPos, baseSpec, nextBlockState, dir, dist + 1, maxDist);
}
}
return false;
}
@Override
public void writeToNBT(NBTTagCompound data) {
}
@Override
public void readFromNBT(NBTTagCompound data) {
}
@Override
public boolean canUpdate() {
return false;
}
@Override
public void update() {
}
@Override
public float getHardness() {
return 1.05F;
}
@Override
public float getExplosionResistance(Explosion explosion, Entity exploder) {
return 3.5f;
}
@Override
public void writePacketData(DataOutputStream data) throws IOException {
}
@Override
public void readPacketData(DataInputStream data) throws IOException {
}
@Override
public World getWorld() {
return tileEntity.getWorld();
}
@Override
public BlockPos getPos() {
return tileEntity.getPos();
}
/**
* Return true if the rail can make corners. Used by placement logic.
*
* @return true if the rail can make corners.
*/
@Override
public boolean isFlexibleRail() {
return false;
}
/**
* Returns true if the rail can make up and down slopes. Used by placement
* logic.
*
* @return true if the rail can make slopes.
*/
@Override
public boolean canMakeSlopes() {
return true;
}
/**
* Returns the max speed of the rail.
*
* @param cart The cart on the rail, may be null.
* @return The max speed of the current rail.
*/
@Override
public float getRailMaxSpeed(EntityMinecart cart) {
return 0.4f;
}
} |
package edisyn.synth.waldorfblofeld;
import edisyn.*;
import edisyn.gui.*;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.sound.midi.*;
/**
A patch editor for the Waldorf Blofeld. Does not deal with Multi mode, global parameters,
modifying wavetables, or uploading samples. Only Single mode patches.
@author Sean Luke
*/
public class WaldorfBlofeld extends Synth
{
/// Various collections of parameter names for pop-up menus
static final String[] FM_SOURCES = new String[] { "Off", "Osc1", "Osc2", "Osc3", "Noise", "LFO 1", "LFO 2", "LFO 3", "Filter Env", "Amp Env", "Env 3", "Env 4" };
static final String[] MOD_SOURCES = new String[] {"Off", "LFO 1", "LFO1*MW", "LFO 2", "LFO2*Press.", "LFO 3", "Filter Env", "Amp Env", "Env 3", "Env 4", "Keytrack", "Velocity", "Rel. Velo", "Pressure", "Poly Press", "Pitch Bend", "Mod Wheel", "Sustain", "Foot Ctrl", "Breath Ctrl", "Control W", "Control X", "Control Y", "Control Z", "Unisono V.", "Modifier 1", "Modifier 2", "Modifier 3", "Modifier 4", "Minimum", "Maximum" };
static final String[] MOD_DESTINATIONS = new String[] { "Pitch", "O1 Pitch", "O1 FM", "O1 PW/Wave", "O2 Pitch", "O2 FM", "O2 PW/Wave", "O3 Pitch", "O3 FM", "O3 PW", "O1 Level", "O1 Balance", "O2 Level", "O2 Balance", "O3 Level", "O3 Balance", "RMod Level", "RMod Bal.", "Noise Level", "Noise Bal.", "F1 Cutoff", "F1 Reson.", "F1 FM", "F1 Drive", "F1 Pan", "F2 Cutoff", "F2 Reson.", "F2 FM", "F2 Drive", "F2 Pan", "Volume", "LFO1 Speed", "LFO2 Speed", "LFO3 Speed", "FE Attack", "FE Decay", "FE Sustain", "FE Release", "AE Attack", "AE Decay", "AE Sustain", "AE Release", "E3 Attack", "E3 Decay", "E3 Sustain", "E3 Release", "E4 Attack", "E4 Decay", "E4 Sustain", "E4 Release", "M1 Amount", "M2 Amount", "M3 Amount", "M4 Amount" };
static final String[] DRIVE_CURVES = new String[] { "Clipping", "Tube", "Hard", "Medium", "Soft", "Pickup 1", "Pickup 2", "Rectifier", "Square", "Binary", "Overflow", "Sine Shaper", "Osc 1 Mod" };
static final String[] ARPEGGIATOR_SPEEDS = new String[] { "1/96", "1/48", "1/32", "1/16 T", "1/32 .", "1/16", "1/8T", "1/16 .", "1/8", "1/4 T", "1/8 .", "1/4", "1/2 T", "1/4 .", "1/2", "1/1 T", "1/2 .", "1", "1.5", "2", "2.5", "3", "3.5", "4", "5", "6", "7", "8", "9", "10", "12", "14", "16", "18", "20", "24", "28", "32", "36", "40", "48", "56", "64" };
static final String[] ARPEGGIATOR_LENGTHS = new String[] { "1/96", "1/48", "1/32", "1/16 T", "1/32 .", "1/16", "1/8T", "1/16 .", "1/8", "1/4 T", "1/8 .", "1/4", "1/2 T", "1/4 .", "1/2", "1/1 T", "1/2 .", "1", "1.5", "2", "2.5", "3", "3.5", "4", "5", "6", "7", "8", "9", "10", "12", "14", "16", "18", "20", "24", "28", "32", "36", "40", "48", "56", "64", "Legato" };
static final String[] ARPEGGIATOR_MODES = new String[] { "Off", "On", "One Shot", "Hold" };
static final String[] ARPEGGIATOR_DIRECTIONS = new String[] { "Up", "Down", "Alt Up", "Alt Down" };
static final String[] ARPEGGIATOR_SORT_ORDERS = new String[] { "As Played", "Reversed", "Key Lo>Hi", "Key Hi>Lo", "Vel Lo>Hi", "Vel Hi>Lo" };
static final String[] ARPEGGIATOR_VELOCITY_MODES = new String[] { "Each Note", "First Note", "Last Note", "Fix 32", "Fix 64", "Fix 100", "Fix 127" };
static final String[] ARPEGGIATOR_PATTERN_STEPS = new String[] { "Normal", "Pause", "Previous", "First", "Last", "First + Last", "Chord", "Random" };
static final String[] EFFECTS_SHORT = new String[] { "Bypass", "Chorus", "Flanger", "Phaser", "Overdrive", "Triple FX" };
static final String[] EFFECTS_LONG = new String[] { "Bypass", "Chorus", "Flanger", "Phaser", "Overdrive", "Triple FX", "Delay", "Clk. Delay", "Reverb" };
static final String[] MODIFIER_OPERATORS = new String[] { "+", "-", "*", "AND", "OR", "XOR", "MAX", "MIN" };
static final String[] ENVELOPE_TYPES = new String[] { "ADSR", "ADS1DS2R", "One Shot", "Loop S1S2", "Loop All" };
static final String[] LFO_SHAPES = new String[] { "Sine", "Triangle", "Square", "Saw", "Random", "S&H" };
static final String[] LFO_SPEEDS = new String[] { "1280", "1152", "1024", "896", "768", "640", "576", "512",
"448", "384", "320", "288", "256", "224", "192", "160",
"144", "128", "112", "96", "80", "72", "64", "56",
"48", "40", "36", "32", "28", "24", "20", "18",
"16", "14", "12", "10", "9", "8", "7", "6",
"5", "4", "3.5", "3", "2.5", "2", "1.5", "1",
"1/2 .", "1/1 T", "1/2", "1/4 .", "1/2 T", "1/4", "1/8 .", "1/4 T",
"1/8", "1/16 .", "1/8 T", "1/16", "1/32 .", "1/16 T", "1/32", "1/48" };
static final String[] CATEGORIES = new String[] { "Init", "Arp", "Atmo", "Bass", "Drum", "FX", "Keys", "Lead", "Mono", "Pad", "Perc", "Poly", "Seq" };
static final String[] BANKS = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
static final String[] OSCILLATOR_GLIDE_MODES = new String[] { "Portamento", "Fingered P", "Glissando", "Fingered G" };
static final String[] FILTER_TYPES = new String[] { "Bypass", "LP 24dB", "LP 12dB", "BP 24dB", "BP 12dB", "HP 24dB", "HP 12dB", "Notch 24dB", "Notch 12dB", "Comb+", "Comb-", "PPG LP" };
// Note that there is space after "Off". This is to make sure that WAVES_LONG
// Produces a popup menu the same width as WAVES_SHORT
static final String[] WAVES_LONG = new String[] { "Off ", "Pulse", "Saw", "Triangle", "Sine", "Alt 1", "Alt 2", "Resonant", "Resonant2", "MalletSyn",
"Sqr-Sweep", "Bellish", "Pul-Sweep", "Saw-Sweep", "MellowSaw", "Feedback", "Add Harm", "Reso 3 HP",
"Wind Syn", "HighHarm", "Clipper", "OrganSyn", "SquareSaw", "Format1", "Polated", "Transient",
"ElectricP", "Robotic", "StrongHrm", "PercOrgan", "ClipSweep", "ResoHarms", "2 Echoes", "Formant2",
"FmntVocal", "MicroSync", "MicroPWM", "Glassy", "SquareHP", "SawSync1", "SawSync2", "SawSync3",
"PulSync1", "PulSync2", "PulSync3", "SinSync1", "SinSync2", "SinSync3", "PWM Pulse", "PWM Saw",
"Fuzz Wave", "Distorted", "HeavyFuzz", "Fuzz Sync", "K+Strong1", "K+Strong2", "K+Strong3", "1-2-3-4-5",
"19/twenty", "Wavetrip1", "Wavetrip2", "Wavetrip3", "Wavetrip4", "MaleVoice", "Low Piano", "ResoSweep",
"Xmas Bell", "FM Piano", "Fat Organ", "Vibes", "Chorus 2", "True PWM", "UpperWaves", };
// Note that there is space after "Off". This is to make sure that WAVES_SHORT
// Produces a popup menu the same width as WAVES_LONG
static final String[] WAVES_SHORT = new String[] { "Off ", "Pulse", "Saw", "Triangle", "Sine" };
static final String[] OSCILLATOR_OCTAVES = new String[] { "128'", "64'", "32'", "16'", "8'", "4'", "2'", "1'", "1/2'" };
static final String[] SAMPLE_BANKS = new String[] { "None", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" };
public JFrame sprout()
{
JFrame frame = super.sprout();
addBlofeldMenu();
return frame;
}
WaldorfBlofeldWavetable wavetable = new WaldorfBlofeldWavetable();
JCheckBoxMenuItem mpeMenu;
public void addBlofeldMenu()
{
JMenu menu = new JMenu("Blofeld");
menubar.add(menu);
JMenuItem writeWavetableMenu = new JMenuItem("Upload Wavetable...");
writeWavetableMenu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
wavetable.upload(WaldorfBlofeld.this);
}
});
menu.add(writeWavetableMenu);
JMenuItem reviseWavetableNamesMenu = new JMenuItem("Revise User Wavetable Names...");
reviseWavetableNamesMenu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
wavetable.reviseWavetableNames(WaldorfBlofeld.this);
}
});
menu.add(reviseWavetableNamesMenu);
/// FIXME: the Blofeld can't seem to handle this even slowly. It just freaks out and initializes
/// the single patches! So this is cut out for now.
//mpeMenu = new JCheckBoxMenuItem("Write Pseudo-MPE on Batch Download");
//menu.add(mpeMenu);
JMenuItem oneMPEMenu = new JMenuItem("Write Patch as Pseudo-MPE");
oneMPEMenu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JTextField number = new SelectedTextField("" + (model.get("number") + 1), 3);
int n = 0;
String title = "Write Patch as Pseudo-MPE";
while(true)
{
boolean result = showMultiOption(WaldorfBlofeld.this, new String[] { "Patch Number"},
new JComponent[] { number }, title, "Enter the Multimode patch number.");
try { n = Integer.parseInt(number.getText()); }
catch (NumberFormatException ex)
{
showSimpleError(title, "The Patch Number must be an integer 1 ... 128");
continue;
}
if (n < 1 || n > 128)
{
showSimpleError(title, "The Patch Number must be an integer 1 ... 128");
continue;
}
if (result)
break;
if (!result)
return;
}
boolean send = getSendMIDI();
setSendMIDI(true);
tryToSendSysex(getMPEForPatch(model.get("bank", 0), model.get("number"), n - 1, model.get("name", "")));
setSendMIDI(send);
}
});
menu.add(oneMPEMenu);
}
public WaldorfBlofeld()
{
for(int i = 0; i < allParameters.length; i++)
{
allParametersToIndex.put(allParameters[i], Integer.valueOf(i));
}
/// SOUND PANEL
JComponent soundPanel = new SynthPanel(this);
VBox vbox = new VBox();
HBox hbox = new HBox();
hbox.add(addNameGlobal(Style.COLOR_GLOBAL()));
hbox.addLast(addOscillatorGlobal(Style.COLOR_A()));
vbox.add(hbox);
vbox.add(addOscillator(1, Style.COLOR_A()));
vbox.add(addOscillator(2, Style.COLOR_A()));
vbox.add(addOscillator(3, Style.COLOR_A()));
vbox.add(addFilter(1, Style.COLOR_B()));
vbox.add(addFilter(2, Style.COLOR_B()));
soundPanel.add(vbox, BorderLayout.CENTER);
addTab("Oscillators and Filters", soundPanel);
// LFO and ENVELOPE PANEL
JComponent lfoEnvelopePanel = new SynthPanel(this);
vbox = new VBox();
hbox = new HBox();
hbox.add(addLFO(1, Style.COLOR_A()));
hbox.addLast(addLFO(3, Style.COLOR_A()));
vbox.add(hbox);
hbox = new HBox();
hbox.add(addLFO(2, Style.COLOR_A()));
hbox.addLast(addAmplifierGlobal(Style.COLOR_C()));
vbox.add(hbox);
vbox.add(addEnvelope(1, Style.COLOR_B()));
vbox.add(addEnvelope(2, Style.COLOR_B()));
vbox.add(addEnvelope(3, Style.COLOR_B()));
vbox.add(addEnvelope(4, Style.COLOR_B()));
lfoEnvelopePanel.add(vbox, BorderLayout.CENTER);
addTab("LFOs and Envelopes", lfoEnvelopePanel);
// MODULATION PANEL
JComponent modulationPanel = new SynthPanel(this);
vbox = new VBox();
vbox.add(addModulation(Style.COLOR_A()));
vbox.add(addModifiers(Style.COLOR_B()));
vbox.add(addEffect(1, Style.COLOR_C()));
vbox.add(addEffect(2, Style.COLOR_C()));
modulationPanel.add(vbox, BorderLayout.CENTER);
addTab("Modulation and Effects", modulationPanel);
// ARPEGGIATOR PANEL
JComponent arpeggiationPanel = new SynthPanel(this);
vbox = new VBox();
vbox.add(addArpeggiatorGlobal(Style.COLOR_A()));
vbox.add(addArpeggiatorPatterns(Style.COLOR_B()));
arpeggiationPanel.add(vbox, BorderLayout.CENTER);
addTab("Arpeggiator", arpeggiationPanel);
model.set("name", "Init");
model.set("number", 0);
model.set("bank", 0);
loadDefaults();
}
public String getDefaultResourceFileName() { return "WaldorfBlofeld.init"; }
public String getHTMLResourceFileName() { return "WaldorfBlofeld.html"; }
/// ARPEGGIATION
// Adds the Global Arpeggiator category
public JComponent addArpeggiatorGlobal(Color color)
{
Category category = new Category(this, "Arpeggiator", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
params = ARPEGGIATOR_MODES;
comp = new Chooser("Mode", this, "arpeggiatormode", params);
vbox.add(comp);
params = ARPEGGIATOR_DIRECTIONS;
comp = new Chooser("Direction", this, "arpeggiatordirection", params);
vbox.add(comp);
hbox.add(vbox);
vbox = new VBox();
params = ARPEGGIATOR_SORT_ORDERS;
comp = new Chooser("Sort Order", this, "arpeggiatorsortorder", params);
vbox.add(comp);
params = ARPEGGIATOR_VELOCITY_MODES;
comp = new Chooser("Velocity Mode", this, "arpeggiatorvelocitymode", params);
vbox.add(comp);
hbox.add(vbox);
vbox = new VBox();
comp = new CheckBox("Pattern Reset", this, "arpeggiatorpatternreset");
vbox.add(comp);
hbox.add(vbox);
comp = new LabelledDial("Pattern", this, "arpeggiatorpatternlength", color, 0, 16)
{
public String map(int val)
{
return "" + (val + 1);
}
};
((LabelledDial)comp).addAdditionalLabel("Length");
hbox.add(comp);
comp = new LabelledDial("Pattern", this, "arpeggiatorpattern", color, 0, 16)
{
public String map(int val)
{
if (val == 0) return "Off";
else if (val == 1) return "User";
else return "" + (val - 1);
}
};
model.setMetricMin( "arpeggiatorpattern", 2);
hbox.add(comp);
comp = new LabelledDial("Clock", this, "arpeggiatorclock", color, 0, 42)
{
public String map(int val)
{
return ARPEGGIATOR_SPEEDS[val];
}
};
hbox.add(comp);
comp = new LabelledDial("Length", this, "arpeggiatorlength", color, 0, 43)
{
public String map(int val)
{
return ARPEGGIATOR_LENGTHS[val];
}
};
model.setMetricMax( "arpeggiatorlength", 42);
hbox.add(comp);
comp = new LabelledDial("Octave", this, "arpeggiatoroctave", color, 0, 9)
{
public String map(int val)
{
return "" + (val + 1);
}
};
hbox.add(comp);
comp = new LabelledDial("Timing", this, "arpeggiatortimingfactor", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Factor");
hbox.add(comp);
comp = new LabelledDial("Tempo", this, "arpeggiatortempo", color, 0, 127)
{
// 40...300
// BPM 165 and above we jump by 5
// BPM 90 and below we jump by 2
// So 40...90 inclusive is 0...25
// 91 ... 165 is 26 ... 100
// 170 ... 300 is 101 ... 127
public String map(int val)
{
if (val < 25)
return "" + ((val * 2) + 40);
else if (val < 101)
return "" + (val + 65);
else
return "" + (((val - 101) * 5) + 170);
}
public int getDefaultValue() { return 55; } // 120 BPM?
};
hbox.add(comp);
category.add(hbox, BorderLayout.WEST);
return category;
}
// Adds the Arpeggiator Patterns category
public JComponent addArpeggiatorPatterns(Color color)
{
Category category = new Category(this, "Patterns", color);
category.makeDistributable("arp");
JComponent comp;
String[] params;
VBox main = new VBox();
HBox hbox;
VBox vbox;
String[] steps = ARPEGGIATOR_PATTERN_STEPS;
for(int row = 1; row < 17; row += 8)
{
hbox = new HBox();
for(int i = row; i < row + 8; i++)
{
vbox = new VBox();
params = steps;
comp = new Chooser("Step " + i, this, "arp" + (i < 10 ? "0" : "") + i + "step", params);
vbox.add(comp);
comp = new CheckBox("Glide " + i, this, "arp" + (i < 10 ? "0" : "") + i + "glide");
vbox.add(comp);
comp = new LabelledDial("Accent " + i, this, "arp" + (i < 10 ? "0" : "") + i + "accent", color, 0, 7)
{
public double getStartAngle() { return 270 / 7 * 4 + 90; }
public String map(int val)
{
// if 0, it's silent
// if >0 it's -96 ... +96 for 1...7
if (val == 0) return "Rest";
else return "" + (((val - 4) * 96) / 3);
}
public int getDefaultValue() { return 4; }
};
vbox.add(comp);
model.setMetricMin( "arp" + (i < 10 ? "0" : "") + i + "accent", 1);
vbox.add(Strut.makeVerticalStrut(3));
// the little spaces cause Java to not slice off a bit of the last digit
comp = new LabelledDial(" Length " + i + " ", this, "arp" + (i < 10 ? "0" : "") + i + "length", color, 0, 7)
{
public double getStartAngle() { return 270 / 7 * 4 + 90; }
public String map(int val)
{
// if 0, it's legato
// if >0 it's -3 to +3 for 1...7
if (val == 0) return "Legato";
else return "" + (val - 4);
}
public int getDefaultValue() { return 4; }
};
model.setMetricMin( "arp" + (i < 10 ? "0" : "") + i + "length", 1);
vbox.add(comp);
vbox.add(Strut.makeVerticalStrut(3));
// the little spaces cause Java to not slice off a bit of the last digit
comp = new LabelledDial(" Timing " + i + " ", this, "arp" + (i < 10 ? "0" : "") + i + "timing", color, 0, 7)
{
public double getStartAngle() { return 270 / 7 * 4 + 90; }
public String map(int val)
{
// if 0, it's random
// if >0 it's -3 to +3 for 1...7
if (val == 0) return "Rand";
else return "" + (val - 4);
}
public int getDefaultValue() { return 4; }
};
model.setMetricMin( "arp" + (i < 10 ? "0" : "") + i + "timing", 1);
vbox.add(comp);
hbox.add(vbox);
}
main.add(hbox);
}
category.add(main, BorderLayout.WEST);
return category;
}
//// EFFECTS
// Various effect types
public static final int BYPASS = 0;
public static final int CHORUS = 1;
public static final int FLANGER = 2;
public static final int PHASER = 3;
public static final int OVERDRIVE = 4;
public static final int TRIPLEFX = 5;
public static final int DELAY = 6;
public static final int CLKDELAY = 7;
public static final int REVERB = 8;
/** Discards existing parameter widgets and loads new ones according to the
effect type on the given effect number. */
void setupEffect(HBox[] parameters, JComponent[][][] parametersByEffect, int effect, int type)
{
if (parameters[effect - 1] == null) return; // not ready yet
parameters[effect - 1].removeAll();
for(int i = 0; i < parametersByEffect[effect - 1][type].length; i++)
{
parameters[effect - 1].add(parametersByEffect[effect - 1][type][i]);
}
parameters[effect-1].revalidate();
repaint();
}
/** Adds an Effect category. */
public JComponent addEffect(final int effect, Color color)
{
// Effects are problematic because effect parameters are shared, and the same parameter
// doesn't necessarily have the same range from effect type to effect type, grrr.
// Additionally we have to remove and add various dials and other components depending
// on the current effect being displayed, so we need to know the components we can show
// and hide, and the boxes to put them in dynamically.
// The two HBoxes for each effect (#1, #2)
final HBox[/*effect*/] parameters = new HBox[2];
// The various JComponents for different effect parameters
final JComponent[/*effect*/][/*effect type*/][/*parameters*/] parametersByEffect = new JComponent[2][9][];
// The first thing we have to do is build all the effect parameters for all the effect types
// and associate them with each effect type. This is a lot of tedious work.
parametersByEffect[effect - 1][BYPASS] = new JComponent[0];
parametersByEffect[effect - 1][CHORUS] = new JComponent[2];
parametersByEffect[effect - 1][FLANGER] = new JComponent[4];
parametersByEffect[effect - 1][PHASER] = new JComponent[6];
parametersByEffect[effect - 1][OVERDRIVE] = new JComponent[4];
parametersByEffect[effect - 1][TRIPLEFX] = new JComponent[5];
parametersByEffect[effect - 1][DELAY] = new JComponent[5];
parametersByEffect[effect - 1][CLKDELAY] = new JComponent[5];
parametersByEffect[effect - 1][REVERB] = new JComponent[7];
JComponent comp;
String[] params;
comp = new LabelledDial("Speed", this, "effect" + effect + "parameter0", color, 0, 127);
parametersByEffect[effect - 1][CHORUS][0] = comp;
parametersByEffect[effect - 1][FLANGER][0] = comp;
parametersByEffect[effect - 1][PHASER][0] = comp;
parametersByEffect[effect - 1][TRIPLEFX][0] = comp;
comp = new LabelledDial("Size", this, "effect" + effect + "parameter0", color, 0, 127);
parametersByEffect[effect - 1][REVERB][0] = comp;
comp = new LabelledDial("Depth", this, "effect" + effect + "parameter1", color, 0, 127);
parametersByEffect[effect - 1][CHORUS][1] = comp;
parametersByEffect[effect - 1][FLANGER][1] = comp;
parametersByEffect[effect - 1][PHASER][1] = comp;
parametersByEffect[effect - 1][TRIPLEFX][1] = comp;
comp = new LabelledDial("Drive", this, "effect" + effect + "parameter1", color, 0, 127);
parametersByEffect[effect - 1][OVERDRIVE][0] = comp;
comp = new LabelledDial("Shape", this, "effect" + effect + "parameter1", color, 0, 127);
parametersByEffect[effect - 1][REVERB][1] = comp;
comp = new LabelledDial("Post Gain", this, "effect" + effect + "parameter2", color, 0, 127);
parametersByEffect[effect - 1][OVERDRIVE][1] = comp;
comp = new LabelledDial("Decay", this, "effect" + effect + "parameter2", color, 0, 127);
parametersByEffect[effect - 1][REVERB][2] = comp;
comp = new LabelledDial("Chorus Mix", this, "effect" + effect + "parameter3", color, 0, 127);
parametersByEffect[effect - 1][TRIPLEFX][2] = comp;
comp = new LabelledDial("Length", this, "effect" + effect + "parameter3", color, 0, 127);
parametersByEffect[effect - 1][DELAY][0] = comp;
comp = new LabelledDial("Feedback", this, "effect" + effect + "parameter4", color, 0, 127);
parametersByEffect[effect - 1][FLANGER][2] = comp;
parametersByEffect[effect - 1][PHASER][2] = comp;
parametersByEffect[effect - 1][DELAY][1] = comp;
parametersByEffect[effect - 1][CLKDELAY][0] = comp;
comp = new LabelledDial("S&H", this, "effect" + effect + "parameter4", color, 0, 127);
parametersByEffect[effect - 1][TRIPLEFX][3] = comp;
comp = new LabelledDial("Center", this, "effect" + effect + "parameter5", color, 0, 127);
parametersByEffect[effect - 1][PHASER][3] = comp;
comp = new LabelledDial("Cutoff", this, "effect" + effect + "parameter5", color, 0, 127);
parametersByEffect[effect - 1][OVERDRIVE][2] = comp;
parametersByEffect[effect - 1][DELAY][2] = comp;
parametersByEffect[effect - 1][CLKDELAY][1] = comp;
comp = new LabelledDial("Overdrive", this, "effect" + effect + "parameter5", color, 0, 127);
parametersByEffect[effect - 1][TRIPLEFX][4] = comp;
comp = new LabelledDial("Lowpass", this, "effect" + effect + "parameter5", color, 0, 127);
parametersByEffect[effect - 1][REVERB][3] = comp;
comp = new LabelledDial("Spacing", this, "effect" + effect + "parameter6", color, 0, 127);
parametersByEffect[effect - 1][PHASER][4] = comp;
comp = new LabelledDial("Highpass", this, "effect" + effect + "parameter6", color, 0, 127);
parametersByEffect[effect - 1][REVERB][4] = comp;
comp = new LabelledDial("Diffusion", this, "effect" + effect + "parameter7", color, 0, 127);
parametersByEffect[effect - 1][REVERB][5] = comp;
// polarity (0=positive, don't ask why)
VBox vbox = new VBox();
comp = new CheckBox("Negative Polarity", this, "effect" + effect + "parameter8");
vbox.add(comp);
parametersByEffect[effect - 1][FLANGER][3] = vbox;
parametersByEffect[effect - 1][PHASER][5] = vbox;
parametersByEffect[effect - 1][DELAY][4] = vbox;
parametersByEffect[effect - 1][CLKDELAY][4] = vbox;
// we put this AFTER the Negative Polarity checkbox so that it revises the min/max
comp = new LabelledDial("Damping", this, "effect" + effect + "parameter8", color, 0, 127);
parametersByEffect[effect - 1][REVERB][6] = comp;
vbox = new VBox();
params = DRIVE_CURVES;
comp = new Chooser("Curve", this, "effect" + effect + "parameter9", params);
vbox.add(comp);
parametersByEffect[effect - 1][OVERDRIVE][3] = vbox;
// we put this AFTER the Curve pop so that it revises the min/max
comp = new LabelledDial("Spread", this, "effect" + effect + "parameter9", color, 0, 127, 64);
parametersByEffect[effect - 1][DELAY][3] = comp;
parametersByEffect[effect - 1][CLKDELAY][3] = comp;
// A second Length! Gagh
final String[] vals = new String[30];
System.arraycopy(ARPEGGIATOR_SPEEDS, 0, vals, 0, 30); // just the first 30
comp = new LabelledDial("Length", this, "effect" + effect + "parameter10", color, 0, 29)
{
public String map(int val)
{
// it turns out that the WaldorfBlofeld sends "127" when it doesn't have a setting yet for this
// parameter. Dumb dumb dumb. So we have to check for that.
if (val > 29)
val = 0;
return vals[val];
}
};
parametersByEffect[effect - 1][CLKDELAY][2] = comp;
// The Waldorf Blofeld has effects parameters 11....13 even though they're not used. We'll give them min/max values
for(int i = 11; i < 14; i++)
{
model.set("effect" + effect + "parameter" + i, 0);
model.setMin("effect" + effect + "parameter" + i, 0);
model.setMax("effect" + effect + "parameter" + i, 127);
model.setStatus("effect" + effect + "parameter" + i, Model.STATUS_IMMUTABLE);
}
// Now we can set up the category as usual.
Category category = new Category(this, "Effect " + effect, color);
HBox main = new HBox();
vbox = new VBox();
if (effect == 1)
params = EFFECTS_SHORT;
else
params = EFFECTS_LONG;
comp = new Chooser("Type", this, "effect" + effect + "type", params)
{
public void update(String key, Model model)
{
super.update(key, model);
setupEffect(parameters, parametersByEffect, effect, getState());
}
};
vbox.add(comp);
main.add(vbox);
comp = new LabelledDial("Mix", this, "effect" + effect + "mix", color, 0, 127);
main.add(comp);
parameters[effect - 1] = new HBox();
main.add(parameters[effect - 1]);
category.add(main, BorderLayout.WEST);
// category.makePasteable("effect" + effect);
category.makePasteable("effect");
setupEffect(parameters, parametersByEffect, effect, BYPASS);
return category;
}
///// MODULATION
/** Add the Modulation category */
public JComponent addModulation(Color color)
{
Category category = new Category(this, "Modulation", color);
category.makeDistributable("modulation");
JComponent comp;
String[] params;
VBox main = new VBox();
HBox hbox;
VBox vbox;
for(int row = 1; row < 17; row+= 8)
{
hbox = new HBox();
for(int i = row; i < row + 8; i++)
{
vbox = new VBox();
params = MOD_SOURCES;
comp = new Chooser("Source " + i, this, "modulation" + i + "source", params);
vbox.add(comp);
params = MOD_DESTINATIONS;
comp = new Chooser("Destination " + i, this, "modulation" + i + "destination", params);
vbox.add(comp);
comp = new LabelledDial("Level " + i, this, "modulation" + i + "amount", color, 0, 127, 64); // it's Level, not Amount, so we save some horizontal space
vbox.add(comp);
hbox.add(vbox);
}
main.add(hbox);
if (row == 1)
main.add(Strut.makeVerticalStrut(15));
}
category.add(main, BorderLayout.WEST);
return category;
}
/** Add the Modifiers category */
public JComponent addModifiers(Color color)
{
Category category = new Category(this, "Modifiers", color);
category.makeDistributable("modifier");
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox;
for(int i = 1; i < 5; i++)
{
vbox = new VBox();
params = MOD_SOURCES;
comp = new Chooser("A Source " + i, this, "modifier" + i + "sourcea", params);
vbox.add(comp);
// gotta change the first one to "constant" from "off" if we're in Source B
params = new String[MOD_SOURCES.length];
System.arraycopy(MOD_SOURCES, 0, params, 0, MOD_SOURCES.length);
params[0] = "Constant";
comp = new Chooser("B Source " + i, this, "modifier" + i + "sourceb", params);
vbox.add(comp);
params = MODIFIER_OPERATORS;
comp = new Chooser("Operation " + i, this, "modifier" + i + "operation", params);
vbox.add(comp);
// add some space
if (i > 1) // not the first one
{
hbox.add(Strut.makeHorizontalStrut(20));
}
hbox.add(vbox);
comp = new LabelledDial("Constant " + i, this, "modifier" + i + "constant", color, 0, 127, 64);
hbox.add(comp);
}
category.add(hbox, BorderLayout.WEST);
return category;
}
///// ENVELOPES
// Filter envelope is just envelope #1, Amplifier (why not amplitude?) envelope is just envelope #2
public static final int FILTER_ENVELOPE = 1;
public static final int AMPLIFIER_ENVELOPE = 2;
/** Add an Envelope category */
public JComponent addEnvelope(final int envelope, Color color)
{
final EnvelopeDisplay[/*Env Number */][/*Envelope Type */] envelopeDisplays = new EnvelopeDisplay[4][5];
final HBox[/*Env Number*/] envelopeHBoxes = new HBox[4];
Category category;
if (envelope == FILTER_ENVELOPE)
{
category = new Category(this, "Filter Envelope", color);
}
else if (envelope == AMPLIFIER_ENVELOPE)
{
category = new Category(this, "Amplifier Envelope", color);
}
else
{
category = new Category(this, "Envelope " + envelope, color);
}
// category.makePasteable("envelope" + envelope);
category.makePasteable("envelope");
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
params = ENVELOPE_TYPES;
// adding this will call update immediately, but the envelope display's not in the HBox yet so we
// need to wait a bit. The use of a boolean[] rather than a boolean below is a trick to get around
// the requirement that variables outside an anonymous class in Java must be final (a stupid thing
// that better languages with closures don't require).
final boolean[] goAhead = new boolean[] { false };
Chooser comp1 = new Chooser("Mode", this, "envelope" + envelope + "mode", params)
{
public void update(String key, Model model)
{
super.update(key, model);
if (goAhead[0])
{
envelopeHBoxes[envelope - 1].removeLast();
envelopeHBoxes[envelope - 1].addLast(envelopeDisplays[envelope - 1][model.get(key)]);
envelopeHBoxes[envelope - 1].revalidate();
envelopeHBoxes[envelope - 1].repaint();
}
}
};
vbox.add(comp1);
comp = new CheckBox("Single Trigger", this, "envelope" + envelope + "trigger");
vbox.add(comp);
hbox.add(vbox);
comp = new LabelledDial("Attack", this, "envelope" + envelope + "attack", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Attack", this, "envelope" + envelope + "attacklevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Decay", this, "envelope" + envelope + "decay", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Sustain", this, "envelope" + envelope + "sustain", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Decay 2", this, "envelope" + envelope + "decay2", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Sustain 2", this, "envelope" + envelope + "sustain2", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Release", this, "envelope" + envelope + "release", color, 0, 127);
hbox.add(comp);
// ADSR
envelopeDisplays[envelope - 1][0] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", null, "envelope" + envelope + "release" },
new String[] { null, null, "envelope" + envelope + "sustain", "envelope" + envelope + "sustain", null },
new double[] { 0, 0.3333, 0.3333, 0.3333, 0.3333},
new double[] { 0, 1.0, 1.0 / 127.0, 1.0/127.0, 0 },
new double[] { 0, (Math.PI/4/127), (Math.PI/4/127), 0, (Math.PI/4/127)});
/*
envelopeDisplays[envelope - 1][0] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", null, "envelope" + envelope + "release" },
new String[] { null, null, "envelope" + envelope + "sustain", "envelope" + envelope + "sustain", null },
new double[] { 0, 0.25/127.0, 0.25 / 127.0, 0.25, 0.25/127.0},
new double[] { 0, 1.0, 1.0 / 127.0, 1.0/127.0, 0 });
*/
// ADS1DS2R
envelopeDisplays[envelope - 1][1] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", "envelope" + envelope + "decay2", null, "envelope" + envelope + "release" },
new String[] { null, "envelope" + envelope + "attacklevel", "envelope" + envelope + "sustain", "envelope" + envelope + "sustain2", "envelope" + envelope + "sustain2", null },
new double[] { 0, 0.2, 0.2, 0.2, 0.2, 0.2},
new double[] { 0, 1.0/127.0, 1.0 / 127.0, 1.0 / 127.0, 1.0 / 127.0, 0 },
new double[] { 0, Math.PI/4/127, Math.PI/4/127, Math.PI/4/127, 0, Math.PI/4/127 });
/*
envelopeDisplays[envelope - 1][1] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", "envelope" + envelope + "decay2", null, "envelope" + envelope + "release" },
new String[] { null, "envelope" + envelope + "attacklevel", "envelope" + envelope + "sustain", "envelope" + envelope + "sustain2", "envelope" + envelope + "sustain2", null },
new double[] { 0, 0.2/127.0, 0.2 / 127.0, 0.2/127.0, 0.2, 0.2/127.0},
new double[] { 0, 1.0/127.0, 1.0 / 127.0, 1.0 / 127.0, 1.0 / 127.0, 0 });
*/
// One Shot
envelopeDisplays[envelope - 1][2] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", "envelope" + envelope + "decay2", "envelope" + envelope + "release" },
new String[] { null, "envelope" + envelope + "attacklevel", "envelope" + envelope + "sustain", "envelope" + envelope + "sustain2", null },
new double[] { 0, 0.25, 0.25, 0.25, 0.25},
new double[] { 0, 1.0/127.0, 1.0 / 127.0, 1.0 / 127.0, 0 },
new double[] { 0, Math.PI/4/127, Math.PI/4/127, Math.PI/4/127, Math.PI/4/127 });
/*
envelopeDisplays[envelope - 1][2] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", "envelope" + envelope + "release" },
new String[] { null, null, "envelope" + envelope + "sustain", null },
new double[] { 0, 0.5, 0.5, 0.5},
new double[] { 0, 1.0, 1.0 / 127.0, 0 },
new double[] { 0, Math.PI/4/127, Math.PI/4/127, Math.PI/4/127 });
*/
/*
envelopeDisplays[envelope - 1][2] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", "envelope" + envelope + "release" },
new String[] { null, null, "envelope" + envelope + "sustain", null },
new double[] { 0, 0.33333333/127.0, 0.33333333/ 127.0, 0.33333333/127.0},
new double[] { 0, 1.0, 1.0 / 127.0, 0 });
*/
// Loop S1S2
envelopeDisplays[envelope - 1][3] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", "envelope" + envelope + "decay2", "envelope" + envelope + "release" },
new String[] { null, "envelope" + envelope + "attacklevel", "envelope" + envelope + "sustain", "envelope" + envelope + "sustain2", null },
new double[] { 0, 0.25, 0.25, 0.25, 0.25 },
new double[] { 0, 1.0 / 127.0, 1.0 / 127.0, 1.0 / 127.0, 0 },
new double[] { 0, Math.PI/4/127, Math.PI/4/127, Math.PI/4/127, Math.PI/4/127});
/*
envelopeDisplays[envelope - 1][3] = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "envelope" + envelope + "attack", "envelope" + envelope + "decay", "envelope" + envelope + "decay2", "envelope" + envelope + "release" },
new String[] { null, "envelope" + envelope + "attacklevel", "envelope" + envelope + "sustain", "envelope" + envelope + "sustain2", null },
new double[] { 0, 0.25/127.0, 0.25 / 127.0, 0.25/127.0, 0.25/127.0 },
new double[] { 0, 1.0 / 127.0, 1.0 / 127.0, 1.0 / 127.0, 0 });
*/
// Loop All is the same as Loop S1S2
envelopeDisplays[envelope - 1][4] = envelopeDisplays[envelope - 1][3];
comp = envelopeDisplays[envelope - 1][0]; // placeholder
hbox.addLast(comp);
envelopeHBoxes[envelope - 1] = hbox;
// now we re-update the popup
goAhead[0] = true;
comp1.update("envelope" + envelope + "mode", getModel());
category.add(hbox, BorderLayout.CENTER);
return category;
}
///// LFOS
/** Add an LFO category */
public JComponent addLFO(final int lfo, Color color)
{
Category category = new Category(this, "LFO " + lfo, color);
// category.makePasteable("lfo" + lfo);
category.makePasteable("lfo");
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
params = LFO_SHAPES;
comp = new Chooser("Shape", this, "lfo" + lfo + "shape", params);
vbox.add(comp);
comp = new CheckBox("Sync", this, "lfo" + lfo + "sync");
vbox.add(comp);
comp = new CheckBox("Clocked", this, "lfo" + lfo + "clocked");
vbox.add(comp);
hbox.add(vbox);
comp = new LabelledDial("Speed", this, "lfo" + lfo + "speed", color, 0, 127)
{
public String map(int val)
{
// we display this in two different ways depending on whether we're clocked or not
if (model.get("lfo" + lfo + "clocked") == 0)
return "" + val;
else
{
val /= 2; // we map to 0...63
String[] vals = LFO_SPEEDS;
return vals[val];
}
}
};
model.register("lfo" + lfo + "clocked", (LabelledDial)comp); // so we get updated if clocked changes
hbox.add(comp);
comp = new LabelledDial("Start Phase", this, "lfo" + lfo + "startphase", color, 0, 127)
{
public String map(int val)
{
// this one is complex. LFO start phase is 0=off,
// and 1=0 degrees, and .... 127 = 355 degrees
if (val == 0) return "Free";
else return "" + (int)(((val - 1) * 355.0) / 126.0);
}
};
model.setMetricMin( "lfo" + lfo + "startphase", 1);
hbox.add(comp);
comp = new LabelledDial("Delay", this, "lfo" + lfo + "delay", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Fade", this, "lfo" + lfo + "fade", color, 0, 127, 64);
hbox.add(comp);
comp = new LabelledDial("Keytrack", this, "lfo" + lfo + "keytrack", color, 0, 127, 64)
{
public boolean isSymmetric() { return true; }
public String map(int val)
{
return "" + (int)((val - 64) / 64.0 * 200.0) + "%";
}
};
hbox.add(comp);
category.add(hbox, BorderLayout.WEST);
return category;
}
public static final int MAXIMUM_NAME_LENGTH = 16;
public String revisePatchName(String name)
{
name = super.revisePatchName(name); // trim first time
if (name.length() > MAXIMUM_NAME_LENGTH)
name = name.substring(0, MAXIMUM_NAME_LENGTH);
StringBuffer nameb = new StringBuffer(name);
for(int i = 0 ; i < nameb.length(); i++)
{
char c = nameb.charAt(i);
if (c < 32 || c > 127)
nameb.setCharAt(i, ' ');
}
name = nameb.toString();
return super.revisePatchName(name); // trim again
}
///// PATCH INFORMATION
/** Add the global patch category (name, id, number, etc.) */
public JComponent addNameGlobal(Color color)
{
Category globalCategory = new Category(this, "Waldorf Blofeld", color);
//globalCategory.makeUnresettable();
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
HBox hbox2 = new HBox();
comp = new PatchDisplay(this, 4);
hbox2.add(comp);
params = CATEGORIES;
comp = new Chooser("Category", this, "category", params);
model.setStatus("category", Model.STATUS_IMMUTABLE);
hbox2.add(comp);
vbox.add(hbox2);
comp = new StringComponent("Patch Name", this, "name", 16, "Name must be up to 16 ASCII characters.")
{
public String replace(String val)
{
return revisePatchName(val);
}
public void update(String key, Model model)
{
super.update(key, model);
updateTitle();
}
};
vbox.add(comp); // doesn't work right :-(
hbox.add(vbox);
// vbox = new VBox();
globalCategory.add(hbox, BorderLayout.WEST);
return globalCategory;
}
////// VCA
/** Add the Amplifier category. */
public JComponent addAmplifierGlobal(Color color)
{
Category category = new Category(this, "Amplifier", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
params = MOD_SOURCES;
comp = new Chooser("Mod Source", this, "amplifiermodsource", params);
vbox.add(comp);
hbox.add(vbox);
comp = new LabelledDial("Volume", this, "amplifiervolume", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Velocity", this, "amplifiervelocity", color, 0, 127, 64);
hbox.add(comp);
comp = new LabelledDial("Mod", this, "amplifiermodamount", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
category.add(hbox, BorderLayout.WEST);
return category;
}
///// OSCILLATORS
/** Add the Global Oscillator category */
public JComponent addOscillatorGlobal(Color color)
{
Category category = new Category(this, "Oscillators", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
params = OSCILLATOR_GLIDE_MODES;
comp = new Chooser("Glide Mode", this, "oscglidemode", params);
vbox.add(comp);
params = MOD_SOURCES;
comp = new Chooser("Pitch Mod Source", this, "oscpitchsource", params);
vbox.add(comp);
hbox.add(vbox);
comp = new LabelledDial("Glide Rate", this, "oscgliderate", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Unisono", this, "unisono", color, 0, 5)
{
public String map(int val)
{
if (val == 0) return "Off";
else if (val == 1) return "Dual";
else return ("" + (val + 1));
}
};
hbox.add(comp);
comp = new LabelledDial("Unisono", this, "unisonodetune", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Detune");
hbox.add(comp);
comp = new LabelledDial("Noise", this, "noiselevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Noise", this, "noisebalance", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int val)
{
val -= 64;
if (val < 0) return "F1 " + Math.abs(val);
else if (val > 0) return "F2 " + val;
else return "
}
};
((LabelledDial)comp).addAdditionalLabel("Balance");
hbox.add(comp);
comp = new LabelledDial("Noise", this, "noisecolour", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Colour");
hbox.add(comp);
comp = new LabelledDial("Ringmod", this, "ringmodlevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Ringmod", this, "ringmodbalance", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int val)
{
val -= 64;
if (val < 0) return "F1 " + Math.abs(val);
else if (val > 0) return "F2 " + val;
else return "
}
};
((LabelledDial)comp).addAdditionalLabel("Balance");
hbox.add(comp);
comp = new LabelledDial("Pitch Mod", this, "oscpitchamount", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
vbox = new VBox();
comp = new CheckBox("Glide", this, "oscglide");
vbox.add(comp);
comp = new CheckBox("Mono", this, "oscallocation");
vbox.add(comp);
hbox.add(vbox);
category.add(hbox, BorderLayout.WEST);
return category;
}
Chooser choosers[] = new Chooser[3];
// This array stores the previous selected index of the wave table for each wave
int waves[] = { -1, -1, -1 }; // we don't NEED 3, but it keeps me from special-casing osc 3 in buildWavetable
// This array stores the previous selected index of the sample for each wave
int samples[] = { -1, -1, -1 }; // we don't NEED 3, but it keeps me from special-casing osc 3 in buildWavetable
// Changes the wavetable chooser to be either a list of wavetables or
// a list of sample numbers
public void buildWavetable(Chooser chooser, int osc, int bank)
{
// int index = chooser.getIndex();
if (bank == 0)
{
// This is commented out so we guarantee we rebuild, now that we have an option for changing
// the user wavetables
// if (chooser.getNumElements() != 0 && chooser.getElement(0).equals(WAVES_LONG[0]))
// return;
// save old sample index
samples[osc - 1] = chooser.getIndex();
// maybe we can't do this ... checking....
String[] params1 = WAVES_LONG;
String[] params = new String[125];
System.arraycopy(params1, 0, params, 0, 73);
for(int i = 73; i < 86; i++)
params[i] = "Reserved " + (i - 6);
for(int i = 86; i < 125; i++)
{
params[i] = getLastX("WTName" + (i - 86), getSynthNameLocal());
if (params[i] == null) params[i] = "User " + (i - 86);
}
//"User " + (i - 6);
if (osc == 3) params = WAVES_SHORT;
// due to a bug, the chooser's gonna freak here, so we
// turn off its action listener
chooser.setCallActionListener(false);
chooser.setElements("Wave", params);
// restore old wave index
//chooser.setIndex(waves[osc - 1]);
chooser.update("osc" + osc + "shape", model);
chooser.setCallActionListener(true);
}
else
{
if (!(chooser.getNumElements() != 0 && chooser.getElement(0).equals(WAVES_LONG[0])))
{
// maybe change just the label
//chooser.setLabel("Sample Bank " + SAMPLE_BANKS[bank]);
return;
}
// save old wave index
waves[osc - 1] = chooser.getIndex();
String[] params = new String[128];
for(int i = 0; i < 128; i++)
params[i] = "" + (i + 1) + " ";
//chooser.setElements("Sample Bank " + SAMPLE_BANKS[bank], params);
// due to a bug, the chooser's gonna freak here, so we
// turn off its action listener
chooser.setCallActionListener(false);
chooser.setElements("Sample", params);
// restore old sample index
// chooser.setIndex(samples[osc - 1]);
chooser.update("osc" + osc + "shape", model);
chooser.setCallActionListener(true);
}
}
public void rebuildWavetables()
{
buildWavetable(choosers[0], 1, model.get("osc1samplebank"));
buildWavetable(choosers[1], 2, model.get("osc2samplebank"));
buildWavetable(choosers[2], 3, 0);
// now we need to reset them
choosers[0].update("osc1shape", model);
choosers[1].update("osc2shape", model);
choosers[2].update("osc3shape", model);
}
/** Add an Oscillator category */
public JComponent addOscillator(final int osc, Color color)
{
Category category = new Category(this, "Oscillator " + osc, color);
// category.makePasteable("osc" + osc);
category.makePasteable("osc");
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
final Chooser chooser = new Chooser("Wave", this, "osc" + osc + "shape", new String[]{ "Yo Mama" }); // gotta have at least one item as a throwaway and it can't be WAVES_LONG[0]
choosers[osc - 1] = chooser;
comp = chooser;
vbox.add(comp);
buildWavetable(chooser, osc, 0);
// Lock the Wave chooser so it doesn't change size if it gets modified to
// a sample chooser
Dimension d = chooser.getCombo().getPreferredSize();
chooser.getCombo().setPreferredSize(d);
chooser.getCombo().setMinimumSize(d);
chooser.getCombo().setMaximumSize(d);
if (osc != 3)
{
params = SAMPLE_BANKS;
comp = new Chooser("Sample Bank [SL]", this, "osc" + osc + "samplebank", params);
model.setStatus("osc" + osc + "samplebank", Model.STATUS_IMMUTABLE);
model.register("osc" + osc + "samplebank", new Updatable()
{
public void update(String key, Model model)
{
int state = model.get(key);
buildWavetable(chooser, osc, state);
// force an emit
model.set("osc" + osc + "shape", model.get("osc" + osc + "shape"));
}
});
// We do this because it'd be confusing for non-SL people, but
// this has the side-effect of preventing invalid settings to the wave/sample chooser
// during mutation/crossover because there are 128 samples but only, like 124 waves
model.setStatus("osc" + osc + "samplebank", Model.STATUS_IMMUTABLE);
vbox.add(comp);
}
hbox.add(vbox);
vbox = new VBox();
params = FM_SOURCES;
comp = new Chooser("FM Source", this, "osc" + osc + "fmsource", params);
// // model.setSpecial("osc" + osc + "fmsource");
vbox.add(comp);
params = MOD_SOURCES;
comp = new Chooser("PWM Source", this, "osc" + osc + "pwmsource", params);
// // model.setSpecial("osc" + osc + "pwmsource");
vbox.add(comp);
hbox.add(vbox);
comp = new LabelledDial("Octave", this, "osc" + osc + "octave", color, 0, 8)
{
public boolean isSymmetric() { return true; } // so we don't have a weird orientation for no reason
public String map(int val)
{
String[] oct = OSCILLATOR_OCTAVES;
return oct[val];
}
public int getDefaultValue() { return 4; }
};
hbox.add(comp);
comp = new LabelledDial("Semitone", this, "osc" + osc + "semitone", color, 52, 76, 64);
hbox.add(comp);
comp = new LabelledDial("Detune", this, "osc" + osc + "detune", color, 0, 127, 64);
hbox.add(comp);
comp = new LabelledDial("Bend", this, "osc" + osc + "bendrange", color, 40, 88, 64);
((LabelledDial)comp).addAdditionalLabel("Range");
hbox.add(comp);
comp = new LabelledDial("Keytrack", this, "osc" + osc + "keytrack", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int val)
{
return "" + (int)((val - 64) / 64.0 * 200.0) + "%";
}
public int getDefaultValue() { return 96; } // +100%
};
hbox.add(comp);
comp = new LabelledDial("FM", this, "osc" + osc + "fmamount", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
comp = new LabelledDial("Pulsewidth", this, "osc" + osc + "pulsewidth", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("PWM", this, "osc" + osc + "pwmamount", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
comp = new LabelledDial("Brilliance", this, "osc" + osc + "brilliance", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Level", this, "osc" + osc + "level", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Filter", this, "osc" + osc + "balance", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int val)
{
val -= 64;
if (val < 0) return "F1 " + Math.abs(val);
else if (val > 0) return "F2 " + val;
else return "
}
};
((LabelledDial)comp).addAdditionalLabel("Balance");
hbox.add(comp);
vbox = new VBox();
if (osc != 3)
{
// 0 is ON for Limit WT, 1 is OFF. It's flipped relative to other switches
comp = new CheckBox("Limit WT", this, "osc" + osc + "limitwt", true);
vbox.add(comp);
}
if (osc == 2)
{
comp = new CheckBox("Osc3 Sync", this, "osc" + osc + "synctoosc3");
((CheckBox)comp).addToWidth(1);
vbox.add(comp);
}
hbox.add(vbox);
category.add(hbox, BorderLayout.CENTER);
return category;
}
///// FILTERS
/** Add a Filter category */
public JComponent addFilter(int filter, Color color)
{
Category category = new Category(this, "Filter " + filter, color);
// category.makePasteable("filter" + filter);
category.makePasteable("filter");
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
params = FILTER_TYPES;
comp = new Chooser("Type", this, "filter" + filter + "type", params);
// // model.setSpecial("filter" + filter + "type");
vbox.add(comp);
params = DRIVE_CURVES;
comp = new Chooser("Drive Curve", this, "filter" + filter + "drivecurve", params);
vbox.add(comp);
hbox.add(vbox);
vbox = new VBox();
params = MOD_SOURCES;
comp = new Chooser("Mod Source", this, "filter" + filter + "modsource", params);
// // model.setSpecial("filter" + filter + "modsource");
vbox.add(comp);
params = MOD_SOURCES;
comp = new Chooser("Pan Source", this, "filter" + filter + "pansource", params);
// // model.setSpecial("filter" + filter + "pansource");
vbox.add(comp);
hbox.add(vbox);
vbox = new VBox();
params = FM_SOURCES;
comp = new Chooser("FM Source", this, "filter" + filter + "fmsource", params);
// // model.setSpecial("filter" + filter + "fmsource");
vbox.add(comp);
if (filter == 2)
{
comp = new CheckBox("Serial", this, "filterrouting");
vbox.add(comp);
}
hbox.add(vbox);
comp = new LabelledDial("Cutoff", this, "filter" + filter + "cutoff", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Resonance", this, "filter" + filter + "resonance", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Drive", this, "filter" + filter + "drive", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Keytrack", this, "filter" + filter + "keytrack", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int val)
{
return "" + (int)((val - 64) / 64.0 * 200.0) + "%";
}
public int getDefaultValue() { return 64; }
};
hbox.add(comp);
comp = new LabelledDial("Env", this, "filter" + filter + "envamount", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
comp = new LabelledDial("Env", this, "filter" + filter + "envvelocity", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Velocity");
hbox.add(comp);
comp = new LabelledDial("Mod", this, "filter" + filter + "modamount", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
comp = new LabelledDial("FM", this, "filter" + filter + "fmamount", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
comp = new LabelledDial("Pan", this, "filter" + filter + "pan", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int val)
{
val -= 64;
if (val < 0) return "L " + Math.abs(val);
else if (val > 0) return "R " + val;
else return "
}
};
hbox.add(comp);
comp = new LabelledDial("Pan", this, "filter" + filter + "panamount", color, 0, 127, 64);
((LabelledDial)comp).addAdditionalLabel("Amount");
hbox.add(comp);
category.add(hbox, BorderLayout.WEST);
return category;
}
/** Map of parameter -> index in the allParameters array. */
HashMap allParametersToIndex = new HashMap();
/** List of all Waldorf parameters in order. "-" is a reserved (unused and thus unnamed) parameter. */
/// * indicates parameters which must be handled specially due to packing
/// that Waldorf decided to do. :-(
final static String[] allParameters = new String[]
{
"-",
"osc1octave",
"osc1semitone",
"osc1detune",
"osc1bendrange",
"osc1keytrack",
"osc1fmsource",
"osc1fmamount",
"osc1shape",
"osc1pulsewidth",
"osc1pwmsource",
"osc1pwmamount",
"-",
"-",
"osc1limitwt",
"osc1samplebank",
"osc1brilliance",
"osc2octave",
"osc2semitone",
"osc2detune",
"osc2bendrange",
"osc2keytrack",
"osc2fmsource",
"osc2fmamount",
"osc2shape",
"osc2pulsewidth",
"osc2pwmsource",
"osc2pwmamount",
"-",
"-",
"osc2limitwt",
"osc2samplebank",
"osc2brilliance",
"osc3octave",
"osc3semitone",
"osc3detune",
"osc3bendrange",
"osc3keytrack",
"osc3fmsource",
"osc3fmamount",
"osc3shape",
"osc3pulsewidth",
"osc3pwmsource",
"osc3pwmamount",
"-",
"-",
"-",
"-",
"osc3brilliance",
"osc2synctoosc3",
"oscpitchsource",
"oscpitchamount",
"-",
"oscglide",
"-",
"-",
"oscglidemode",
"oscgliderate",
"oscallocation, unisono",
"unisonodetune",
"-",
"osc1level",
"osc1balance",
"osc2level",
"osc2balance",
"osc3level",
"osc3balance",
"noiselevel",
"noisebalance",
"noisecolour",
"-",
"ringmodlevel",
"ringmodbalance",
"-",
"-",
"-",
"-",
"filter1type",
"filter1cutoff",
"-",
"filter1resonance",
"filter1drive",
"filter1drivecurve",
"-",
"-",
"-",
"filter1keytrack",
"filter1envamount",
"filter1envvelocity",
"filter1modsource",
"filter1modamount",
"filter1fmsource",
"filter1fmamount",
"filter1pan",
"filter1pansource",
"filter1panamount",
"-",
"filter2type",
"filter2cutoff",
"-",
"filter2resonance",
"filter2drive",
"filter2drivecurve",
"-",
"-",
"-",
"filter2keytrack",
"filter2envamount",
"filter2envvelocity",
"filter2modsource",
"filter2modamount",
"filter2fmsource",
"filter2fmamount",
"filter2pan",
"filter2pansource",
"filter2panamount",
"-",
"filterrouting",
"-",
"-",
"-",
"amplifiervolume",
"amplifiervelocity",
"amplifiermodsource",
"amplifiermodamount",
"-",
"-",
"-",
"effect1type",
"effect1mix",
// Note that we start at 0 -- this makes things easier in the code
"effect1parameter0",
"effect1parameter1",
"effect1parameter2",
"effect1parameter3",
"effect1parameter4",
"effect1parameter5",
"effect1parameter6",
"effect1parameter7",
"effect1parameter8",
"effect1parameter9",
"effect1parameter10",
"effect1parameter11",
"effect1parameter12",
"effect1parameter13",
"effect2type",
"effect2mix",
// Note that we start at 0 -- this makes things easier in the code
"effect2parameter0",
"effect2parameter1",
"effect2parameter2",
"effect2parameter3",
"effect2parameter4",
"effect2parameter5",
"effect2parameter6",
"effect2parameter7",
"effect2parameter8",
"effect2parameter9",
"effect2parameter10",
"effect2parameter11",
"effect2parameter12",
"effect2parameter13",
"lfo1shape",
"lfo1speed",
"-",
"lfo1sync",
"lfo1clocked",
"lfo1startphase",
"lfo1delay",
"lfo1fade",
"-",
"-",
"lfo1keytrack",
"-",
"lfo2shape",
"lfo2speed",
"-",
"lfo2sync",
"lfo2clocked",
"lfo2startphase",
"lfo2delay",
"lfo2fade",
"-",
"-",
"lfo2keytrack",
"-",
"lfo3shape",
"lfo3speed",
"-",
"lfo3sync",
"lfo3clocked",
"lfo3startphase",
"lfo3delay",
"lfo3fade",
"-",
"-",
"lfo3keytrack",
"-",
"envelope1mode, envelope1trigger",
"-",
"-",
"envelope1attack",
"envelope1attacklevel",
"envelope1decay",
"envelope1sustain",
"envelope1decay2",
"envelope1sustain2",
"envelope1release",
"-",
"-",
"envelope2mode, envelope2trigger",
"-",
"-",
"envelope2attack",
"envelope2attacklevel",
"envelope2decay",
"envelope2sustain",
"envelope2decay2",
"envelope2sustain2",
"envelope2release",
"-",
"-",
"envelope3mode, envelope3trigger",
"-",
"-",
"envelope3attack",
"envelope3attacklevel",
"envelope3decay",
"envelope3sustain",
"envelope3decay2",
"envelope3sustain2",
"envelope3release",
"-",
"-",
"envelope4mode, envelope4trigger",
"-",
"-",
"envelope4attack",
"envelope4attacklevel",
"envelope4decay",
"envelope4sustain",
"envelope4decay2",
"envelope4sustain2",
"envelope4release",
"-",
"-",
"-",
"modifier1sourcea",
"modifier1sourceb",
"modifier1operation",
"modifier1constant",
"modifier2sourcea",
"modifier2sourceb",
"modifier2operation",
"modifier2constant",
"modifier3sourcea",
"modifier3sourceb",
"modifier3operation",
"modifier3constant",
"modifier4sourcea",
"modifier4sourceb",
"modifier4operation",
"modifier4constant",
"modulation1source",
"modulation1destination",
"modulation1amount",
"modulation2source",
"modulation2destination",
"modulation2amount",
"modulation3source",
"modulation3destination",
"modulation3amount",
"modulation4source",
"modulation4destination",
"modulation4amount",
"modulation5source",
"modulation5destination",
"modulation5amount",
"modulation6source",
"modulation6destination",
"modulation6amount",
"modulation7source",
"modulation7destination",
"modulation7amount",
"modulation8source",
"modulation8destination",
"modulation8amount",
"modulation9source",
"modulation9destination",
"modulation9amount",
"modulation10source",
"modulation10destination",
"modulation10amount",
"modulation11source",
"modulation11destination",
"modulation11amount",
"modulation12source",
"modulation12destination",
"modulation12amount",
"modulation13source",
"modulation13destination",
"modulation13amount",
"modulation14source",
"modulation14destination",
"modulation14amount",
"modulation15source",
"modulation15destination",
"modulation15amount",
"modulation16source",
"modulation16destination",
"modulation16amount",
"-",
"-",
"arpeggiatormode",
"arpeggiatorpattern",
"-",
"arpeggiatorclock",
"arpeggiatorlength",
"arpeggiatoroctave",
"arpeggiatordirection",
"arpeggiatorsortorder",
"arpeggiatorvelocitymode",
"arpeggiatortimingfactor",
"-",
"arpeggiatorpatternreset",
"arpeggiatorpatternlength",
"-",
"-",
"arpeggiatortempo",
"arp01step, arp01glide, arp01accent",
"arp02step, arp02glide, arp02accent",
"arp03step, arp03glide, arp03accent",
"arp04step, arp04glide, arp04accent",
"arp05step, arp05glide, arp05accent",
"arp06step, arp06glide, arp06accent",
"arp07step, arp07glide, arp07accent",
"arp08step, arp08glide, arp08accent",
"arp09step, arp09glide, arp09accent",
"arp10step, arp10glide, arp10accent",
"arp11step, arp11glide, arp11accent",
"arp12step, arp12glide, arp12accent",
"arp13step, arp13glide, arp13accent",
"arp14step, arp14glide, arp14accent",
"arp15step, arp15glide, arp15accent",
"arp16step, arp16glide, arp16accent",
"arp01timing, arp01length",
"arp02timing, arp02length",
"arp03timing, arp03length",
"arp04timing, arp04length",
"arp05timing, arp05length",
"arp06timing, arp06length",
"arp07timing, arp07length",
"arp08timing, arp08length",
"arp09timing, arp09length",
"arp10timing, arp10length",
"arp11timing, arp11length",
"arp12timing, arp12length",
"arp13timing, arp13length",
"arp14timing, arp14length",
"arp15timing, arp15length",
"arp16timing, arp16length",
"-",
"-",
"-",
"-",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"name",
"category",
"-",
"-",
"-"
};
////////////// SYNTH ABSTRACT METHOD IMPLEMENTATIONS //////////////////
// READING AND WRITING
public Object[] emitAll(String key)
{
if (!getSendMIDI()) return new Object[0]; // MIDI turned off, don't bother
if (key.equals("bank")) return new Object[0]; // this is not emittable
if (key.equals("number")) return new Object[0]; // this is not emittable
byte DEV = (byte)(getID());
if (key.equals("osc1octave") || key.equals("osc2octave") || key.equals("osc3octave"))
{
int index = ((Integer)(allParametersToIndex.get(key))).intValue();
byte HH = (byte)((index >>> 7) & 127);
byte PP = (byte)(index & 127);
byte XX = (byte)(16 + model.get(key) * 12);
byte[] data = new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x20, 0x00, HH, PP, XX, (byte)0xF7 };
return new Object[] { data };
}
else if (key.equals("oscallocation") || key.equals("unisono"))
{
int index = 58;
byte HH = (byte)((index >>> 7) & 127);
byte PP = (byte)(index & 127);
byte XX = (byte)((model.get("unisono") << 4) | (model.get("oscallocation")));
byte[] data = new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x20, 0x00, HH, PP, XX, (byte)0xF7 };
return new Object[] { data };
}
else if (key.equals("envelope1mode") || key.equals("envelope1trigger") ||
key.equals("envelope2mode") || key.equals("envelope2trigger") ||
key.equals("envelope3mode") || key.equals("envelope3trigger") ||
key.equals("envelope4mode") || key.equals("envelope4trigger"))
{
int i;
try { i = Integer.parseInt(key.substring(8, 9)); }
catch (Exception e) { Synth.handleException(e); return new Object[0]; }
int index = 196 + (i - 1) * 12;
byte HH = (byte)((index >>> 7) & 127);
byte PP = (byte)(index & 127);
byte XX = (byte)((model.get("envelope" + i + "trigger") << 5) | (model.get("envelope" + i + "mode")));
byte[] data = new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x20, 0x00, HH, PP, XX, (byte)0xF7 };
return new Object[] { data };
}
else if (key.startsWith("arp") && !key.startsWith("arpegg"))
{
int i;
try { i = Integer.parseInt(key.substring(3, 5)); }
catch (Exception e) { Synth.handleException(e); return new Object[0]; }
if (key.endsWith("length") || key.endsWith("timing"))
{
int index = i + 342;
byte HH = (byte)((index >>> 7) & 127);
byte PP = (byte)(index & 127);
byte XX = (byte)((model.get("arp" + (i < 10 ? "0" : "") + i + "length") << 4) |
(model.get("arp" + (i < 10 ? "0" : "") + i + "timing")));
byte[] data = new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x20, 0x00, HH, PP, XX, (byte)0xF7 };
return new Object[] { data };
}
else
{
int index = i + 326;
byte HH = (byte)((index >>> 7) & 127);
byte PP = (byte)(index & 127);
byte XX = (byte)((model.get("arp" + (i < 10 ? "0" : "") + i + "step") << 4) |
(model.get("arp" + (i < 10 ? "0" : "") + i + "glide") << 3) |
(model.get("arp" + (i < 10 ? "0" : "") + i + "accent")));
byte[] data = new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x20, 0x00, HH, PP, XX, (byte)0xF7 };
return new Object[] { data };
}
}
else if (key.equals("name"))
{
Object[] data = new Object[16];
String name = model.get(key, "Init") + " ";
for(int i = 0; i < 16; i++)
{
int index = i + 363;
byte HH = (byte)((index >>> 7) & 127);
byte PP = (byte)(index & 127);
byte XX = (byte)(name.charAt(i));
byte[] b = new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x20, 0x00, HH, PP, XX, (byte)0xF7 };
data[i] = b;
}
return data;
}
else
{
int index = ((Integer)(allParametersToIndex.get(key))).intValue();
byte HH = (byte)((index >>> 7) & 127);
byte PP = (byte)(index & 127);
byte XX = (byte)model.get(key);
byte[] data = new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x20, 0x00, HH, PP, XX, (byte)0xF7 };
return new Object[] { data };
}
}
public byte[] emit(Model tempModel, boolean toWorkingMemory, boolean toFile)
{
if (tempModel == null)
tempModel = getModel();
byte DEV = (byte)(getID());
byte BB = (byte) tempModel.get("bank");
byte NN = (byte) tempModel.get("number");
if (toWorkingMemory) { BB = 0x7F; NN = 0x0; }
byte[] bytes = new byte[383];
for(int i = 0; i < 363; i++)
{
String key = allParameters[i];
if (key.equals("-"))
{
bytes[i] = 0;
}
else if (key.equals("osc1octave") || key.equals("osc2octave") || key.equals("osc3octave"))
{
bytes[i] = (byte)(16 + model.get(key) * 12);
}
else if (key.equals("oscallocation, unisono"))
{
bytes[i] = (byte)((model.get("unisono") << 4) | (model.get("oscallocation")));
}
else if (key.equals("envelope1mode, envelope1trigger") ||
key.equals("envelope2mode, envelope2trigger") ||
key.equals("envelope3mode, envelope3trigger") ||
key.equals("envelope4mode, envelope4trigger"))
{
int j;
bytes[i] = 0; // or whatever
try {
j = Integer.parseInt(key.substring(8, 9));
bytes[i] = (byte)((model.get("envelope" + j + "trigger") << 5) | (model.get("envelope" + j + "mode")));
}
catch (Exception e) { Synth.handleException(e); }
}
else if (i >= 327 && i <= 342) // step/glide/accent
{
int j = i - 326;
bytes[i] = (byte)((model.get("arp" + (j < 10 ? "0" : "") + j + "step") << 4) |
(model.get("arp" + (j < 10 ? "0" : "") + j + "glide") << 3) |
(model.get("arp" + (j < 10 ? "0" : "") + j + "accent")));
}
else if (i >= 343 && i <= 358) // timing/length
{
int j = i - 342;
bytes[i] = (byte)((model.get("arp" + (j < 10 ? "0" : "") + j + "length") << 4) |
(model.get("arp" + (j < 10 ? "0" : "") + j + "timing")));
}
else
{
bytes[i] = (byte)(model.get(key));
}
}
String name = model.get("name", "Init") + " "; // has to be 16 long
for(int i = 363; i < 379; i++)
{
bytes[i] = (byte)(name.charAt(i - 363));
}
bytes[379] = (byte)(model.get("category"));
bytes[380] = 0;
bytes[381] = 0;
bytes[382] = 0;
byte[] full = new byte[EXPECTED_SYSEX_LENGTH];
full[0] = (byte)0xF0;
full[1] = 0x3E;
full[2] = 0x13;
full[3] = DEV;
full[4] = 0x10;
full[5] = BB;
full[6] = NN;
System.arraycopy(bytes, 0, full, 7, bytes.length);
full[390] = produceChecksum(bytes);
full[391] = (byte)0xF7;
return full;
}
public void setParameterByIndex(int i, byte b)
{
String key = allParameters[i];
if (key.equals("-"))
{
// do nothing
}
else if (key.equals("osc1octave") || key.equals("osc2octave") || key.equals("osc3octave"))
{
model.set(key, (b - 16) / 12);
}
else if (key.equals("oscallocation, unisono"))
{
model.set("unisono", b >>> 4);
model.set("oscallocation", b & 1);
}
else if (key.equals("envelope1mode, envelope1trigger") ||
key.equals("envelope2mode, envelope2trigger") ||
key.equals("envelope3mode, envelope3trigger") ||
key.equals("envelope4mode, envelope4trigger"))
{
try {
int j = Integer.parseInt(key.substring(8, 9));
model.set("envelope" + j + "trigger", b >>> 5);
model.set("envelope" + j + "mode", b & 7); // even though it's supposed to be 5 bits, only 3 are used!
}
catch (Exception e) { Synth.handleException(e); }
}
else if (i >= 327 && i <= 342) // step/glide/accent
{
int j = i - 326;
model.set("arp" + (j < 10 ? "0" : "") + j + "step", b >>> 4);
model.set("arp" + (j < 10 ? "0" : "") + j + "glide", (b >>> 3) & 1);
model.set("arp" + (j < 10 ? "0" : "") + j + "accent", (b & 7));
}
else if (i >= 343 && i <= 358) // timing/length
{
int j = i - 342;
model.set("arp" + (j < 10 ? "0" : "") + j + "length", b >>> 4);
model.set("arp" + (j < 10 ? "0" : "") + j + "timing", b & 7);
}
else if (i >= 363 && i < 363 + 16) // name
{
try
{
String name = model.get("name", "Init") + " ";
byte[] str = name.getBytes("US-ASCII");
byte[] newstr = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
System.arraycopy(str, 0, newstr, 0, 16);
newstr[i - 363] = b;
model.set("name", new String(newstr, "US-ASCII"));
}
catch (UnsupportedEncodingException e)
{
Synth.handleException(e);
}
}
else
{
model.set(key, b);
}
}
public void parseParameter(byte[] data)
{
int index = -1;
byte b = 0;
// is it a sysex parameter change?
if (data[0] == (byte)0xF0 &&
data[1] == (byte)0x3E &&
data[2] == (byte)0x13 &&
// filter by ID? Presently I'm not
data[4] == (byte)0x20 &&
data[5] == 0x00 && // only Sound Mode Edit Bufer
data.length == 10)
{
int hi = (int)(data[6] & 127);
int lo = (int)(data[7] & 127);
index = (hi << 7) | (lo);
b = (byte)(data[8] & 127);
setParameterByIndex(index, b);
}
else
{
// we'll put CC here later
}
revise();
}
public byte[] getMPEForPatch(int bank, int number, int multinumber, String name)
{
WaldorfBlofeldMulti multi = (WaldorfBlofeldMulti)
instantiate(WaldorfBlofeldMulti.class, true, false, null);
multi.setSendMIDI(false);
multi.getUndo().setWillPush(false);
multi.getModel().setUpdateListeners(false);
multi.getModel().set("number", multinumber);
for(int j = 1; j <= 16; j++)
{
multi.getModel().set("inst" + j + "bank", bank);
multi.getModel().set("inst" + j + "number", number);
}
multi.getModel().set("name", name);
return multi.emit(null, false, false);
}
public int parse(byte[] data, boolean fromFile)
{
boolean retval = true;
if (data[5] < 8) // otherwise it's probably just local patch data. Too bad they do this. :-(
{
model.set("bank", data[5]);
model.set("number", data[6]);
}
else
{
retval = false;
}
for(int i = 0; i < 380; i++)
{
setParameterByIndex(i, data[i + 7]);
}
revise();
if (mpeMenu != null && mpeMenu.isSelected() && isBatchDownloading())
{
// the Blofeld needs a break, or it starts filling up its buffer after about 32 uploads
simplePause(getPauseAfterChangePatch());
boolean send = getSendMIDI();
setSendMIDI(true);
tryToSendSysex(getMPEForPatch(model.get("bank", 0), model.get("number", 0), model.get("number", 0), model.get("name", "")));
setSendMIDI(send);
}
return PARSE_SUCCEEDED;
}
/** Generate a Waldorf checksum of the data bytes */
byte produceChecksum(byte[] bytes)
{
// From the sysex document:
// "Sum of all databytes truncated to 7 bits.
// The addition is done in 8 bit format, the result is
// masked to 7 bits (00h to 7Fh). A checksum of 7Fh is
// always accepted as valid.
// IMPORTANT: the MIDI status-bytes as well as the
// ID's are not used for computing the checksum."
// NOTE: it appears that the WaldorfBlofeld's sysex does NOT include
// the NN or DD data bytes.
byte b = 0; // I *think* signed will work
for(int i = 0; i < bytes.length; i++)
b += bytes[i];
b = (byte)(b & (byte)127);
return b;
}
public int getPauseAfterChangePatch() { return 200; }
public int getPauseAfterWritePatch() { return 75; }
public void changePatch(Model tempModel)
{
byte BB = (byte)tempModel.get("bank");
byte NN = (byte)tempModel.get("number");
try {
// Bank change is CC 32
tryToSendMIDI(new ShortMessage(ShortMessage.CONTROL_CHANGE, getChannelOut(), 32, BB));
// Number change is PC
tryToSendMIDI(new ShortMessage(ShortMessage.PROGRAM_CHANGE, getChannelOut(), NN, 0));
}
catch (Exception e) { Synth.handleException(e); }
}
public byte[] requestDump(Model tempModel)
{
if (tempModel == null)
tempModel = getModel();
byte DEV = (byte)(getID());
byte BB = (byte)tempModel.get("bank");
byte NN = (byte)tempModel.get("number");
return new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x00, BB, NN, 0x00, (byte)0xF7 };
}
public byte[] requestDump(int bank, int number, int id)
{
byte DEV = (byte)id;
byte BB = (byte)bank;
byte NN = (byte)number;
return new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x00, BB, NN, 0x00, (byte)0xF7 };
}
public byte[] requestCurrentDump()
{
byte DEV = (byte)(getID());
return new byte[] { (byte)0xF0, 0x3E, 0x13, DEV, 0x00, 0x7F, 0x00, 0x00, (byte)0xF7 };
}
public static final int EXPECTED_SYSEX_LENGTH = 392;
/////// OTHER ABSTRACT METHODS
public boolean gatherPatchInfo(String title, Model change, boolean writing)
{
JComboBox bank = new JComboBox(BANKS);
bank.setEditable(false);
bank.setMaximumRowCount(32);
bank.setSelectedIndex(model.get("bank"));
JTextField number = new SelectedTextField("" + (model.get("number") + 1), 3);
while(true)
{
boolean result = showMultiOption(this, new String[] { "Bank", "Patch Number"},
new JComponent[] { bank, number }, title, "Enter the Bank and Patch number.");
if (result == false)
return false;
int n;
try { n = Integer.parseInt(number.getText()); }
catch (NumberFormatException e)
{
showSimpleError(title, "The Patch Number must be an integer 1 ... 128");
continue;
}
if (n < 1 || n > 128)
{
showSimpleError(title, "The Patch Number must be an integer 1 ... 128");
continue;
}
change.set("bank", bank.getSelectedIndex());
change.set("number", n - 1);
return true;
}
}
public void revise()
{
// check the easy stuff -- out of range parameters
super.revise();
String nm = model.get("name", "Init");
String newnm = revisePatchName(nm);
if (!nm.equals(newnm))
model.set("name", newnm);
}
public static String getSynthName() { return "Waldorf Blofeld"; }
public String getPatchName(Model model) { return model.get("name", "Init"); }
public byte getID()
{
try
{
byte b = (byte)(Byte.parseByte(tuple.id));
if (b >= 0) return b;
}
catch (NullPointerException e) { } // expected. Happens when tuple's not built yet
catch (NumberFormatException e) { Synth.handleException(e); }
return 0;
}
public String reviseID(String id)
{
try
{
byte b =(byte)(Byte.parseByte(id));
if (b >= 0) return "" + b;
}
catch (NumberFormatException e) { } // expected
return "" + getID();
}
public Model getNextPatchLocation(Model model)
{
int bank = model.get("bank");
int number = model.get("number");
number++;
if (number >= 128)
{
bank++;
number = 0;
if (bank >= 8)
bank = 0;
}
Model newModel = buildModel();
newModel.set("bank", bank);
newModel.set("number", number);
return newModel;
}
public String getPatchLocationName(Model model)
{
// getPatchLocationName() is called from sprout() as a test to see if we should enable
// batch downloading. If we haven't yet created an .init file, then parameters won't exist
// yet and this method will bomb badly. So we return null in this case.
if (!model.exists("number")) return null;
if (!model.exists("bank")) return null;
int number = model.get("number") + 1;
return BANKS[model.get("bank")] +
(number > 99 ? "" : (number > 9 ? "0" : "00")) + number;
}
public static class SubModel extends Model
{
public int reviseMutatedValue(String key, int old, int current)
{
// only standard wavetables are permitted to be mutated
if (key.equals("osc1shape") ||
key.equals("osc2shape"))
{
if (current > 67) // invalid new proposed value
return old;
}
return current;
}
}
public Model buildModel()
{
return new SubModel();
}
public String[] getBankNames() { return BANKS; }
/** Return a list of all patch number names. Default is { "Main" } */
public String[] getPatchNumberNames() { return buildIntegerNames(128, 1); }
/** Return a list whether patches in banks are writeable. Default is { false } */
public boolean[] getWriteableBanks() { return new boolean[] { true, true, true, true, true, true, true, true }; }
/** Return a list whether individual patches can be written. Default is FALSE. */
public boolean getSupportsPatchWrites() { return true; }
public int getPatchNameLength() { return 16; }
} |
package com.jme3.input;
import com.jme3.collision.MotionAllowedListener;
import com.jme3.input.controls.*;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix3f;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
/**
* A first person view camera controller.
* After creation, you must register the camera controller with the
* dispatcher using #registerWithDispatcher().
*
* Controls:
* - Move the mouse to rotate the camera
* - Mouse wheel for zooming in or out
* - WASD keys for moving forward/backward and strafing
* - QZ keys raise or lower the camera
*/
public class FlyByCamera implements AnalogListener, ActionListener {
private static String[] mappings = new String[]{
"FLYCAM_Left",
"FLYCAM_Right",
"FLYCAM_Up",
"FLYCAM_Down",
"FLYCAM_StrafeLeft",
"FLYCAM_StrafeRight",
"FLYCAM_Forward",
"FLYCAM_Backward",
"FLYCAM_ZoomIn",
"FLYCAM_ZoomOut",
"FLYCAM_RotateDrag",
"FLYCAM_Rise",
"FLYCAM_Lower",
"FLYCAM_InvertY"
};
protected Camera cam;
protected Vector3f initialUpVec;
protected float rotationSpeed = 1f;
protected float moveSpeed = 3f;
protected float zoomSpeed = 1f;
protected MotionAllowedListener motionAllowed = null;
protected boolean enabled = true;
protected boolean dragToRotate = false;
protected boolean canRotate = false;
protected boolean invertY = false;
protected InputManager inputManager;
/**
* Creates a new FlyByCamera to control the given Camera object.
* @param cam
*/
public FlyByCamera(Camera cam){
this.cam = cam;
initialUpVec = cam.getUp().clone();
}
/**
* Sets the up vector that should be used for the camera.
* @param upVec
*/
public void setUpVector(Vector3f upVec) {
initialUpVec.set(upVec);
}
public void setMotionAllowedListener(MotionAllowedListener listener){
this.motionAllowed = listener;
}
/**
* Sets the move speed. The speed is given in world units per second.
* @param moveSpeed
*/
public void setMoveSpeed(float moveSpeed){
this.moveSpeed = moveSpeed;
}
/**
* Gets the move speed. The speed is given in world units per second.
* @return moveSpeed
*/
public float getMoveSpeed(){
return moveSpeed;
}
/**
* Sets the rotation speed.
* @param rotationSpeed
*/
public void setRotationSpeed(float rotationSpeed){
this.rotationSpeed = rotationSpeed;
}
/**
* Gets the move speed. The speed is given in world units per second.
* @return rotationSpeed
*/
public float getRotationSpeed(){
return rotationSpeed;
}
/**
* Sets the zoom speed.
* @param zoomSpeed
*/
public void setZoomSpeed(float zoomSpeed) {
this.zoomSpeed = zoomSpeed;
}
/**
* Gets the zoom speed. The speed is a multiplier to increase/decrease
* the zoom rate.
* @return zoomSpeed
*/
public float getZoomSpeed() {
return zoomSpeed;
}
/**
* @param enable If false, the camera will ignore input.
*/
public void setEnabled(boolean enable){
if (enabled && !enable){
if (inputManager!= null && (!dragToRotate || (dragToRotate && canRotate))){
inputManager.setCursorVisible(true);
}
}
enabled = enable;
}
/**
* @return If enabled
* @see FlyByCamera#setEnabled(boolean)
*/
public boolean isEnabled(){
return enabled;
}
/**
* @return If drag to rotate feature is enabled.
*
* @see FlyByCamera#setDragToRotate(boolean)
*/
public boolean isDragToRotate() {
return dragToRotate;
}
/**
* Set if drag to rotate mode is enabled.
*
* When true, the user must hold the mouse button
* and drag over the screen to rotate the camera, and the cursor is
* visible until dragged. Otherwise, the cursor is invisible at all times
* and holding the mouse button is not needed to rotate the camera.
* This feature is disabled by default.
*
* @param dragToRotate True if drag to rotate mode is enabled.
*/
public void setDragToRotate(boolean dragToRotate) {
this.dragToRotate = dragToRotate;
if (inputManager != null) {
inputManager.setCursorVisible(dragToRotate);
}
}
/**
* Registers the FlyByCamera to receive input events from the provided
* Dispatcher.
* @param inputManager
*/
public void registerWithInput(InputManager inputManager){
this.inputManager = inputManager;
// both mouse and button - rotation of cam
inputManager.addMapping("FLYCAM_Left", new MouseAxisTrigger(MouseInput.AXIS_X, true),
new KeyTrigger(KeyInput.KEY_LEFT));
inputManager.addMapping("FLYCAM_Right", new MouseAxisTrigger(MouseInput.AXIS_X, false),
new KeyTrigger(KeyInput.KEY_RIGHT));
inputManager.addMapping("FLYCAM_Up", new MouseAxisTrigger(MouseInput.AXIS_Y, false),
new KeyTrigger(KeyInput.KEY_UP));
inputManager.addMapping("FLYCAM_Down", new MouseAxisTrigger(MouseInput.AXIS_Y, true),
new KeyTrigger(KeyInput.KEY_DOWN));
// mouse only - zoom in/out with wheel, and rotate drag
inputManager.addMapping("FLYCAM_ZoomIn", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false));
inputManager.addMapping("FLYCAM_ZoomOut", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true));
inputManager.addMapping("FLYCAM_RotateDrag", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
// keyboard only WASD for movement and WZ for rise/lower height
inputManager.addMapping("FLYCAM_StrafeLeft", new KeyTrigger(KeyInput.KEY_A));
inputManager.addMapping("FLYCAM_StrafeRight", new KeyTrigger(KeyInput.KEY_D));
inputManager.addMapping("FLYCAM_Forward", new KeyTrigger(KeyInput.KEY_W));
inputManager.addMapping("FLYCAM_Backward", new KeyTrigger(KeyInput.KEY_S));
inputManager.addMapping("FLYCAM_Rise", new KeyTrigger(KeyInput.KEY_Q));
inputManager.addMapping("FLYCAM_Lower", new KeyTrigger(KeyInput.KEY_Z));
inputManager.addListener(this, mappings);
inputManager.setCursorVisible(dragToRotate || !isEnabled());
Joystick[] joysticks = inputManager.getJoysticks();
if (joysticks != null && joysticks.length > 0){
for (Joystick j : joysticks) {
mapJoystick(j);
}
}
}
protected void mapJoystick( Joystick joystick ) {
// Map it differently if there are Z axis
if( joystick.getAxis( JoystickAxis.Z_ROTATION ) != null && joystick.getAxis( JoystickAxis.Z_AXIS ) != null ) {
// Make the left stick move
joystick.getXAxis().assignAxis( "FLYCAM_StrafeRight", "FLYCAM_StrafeLeft" );
joystick.getYAxis().assignAxis( "FLYCAM_Backward", "FLYCAM_Forward" );
// And the right stick control the camera
joystick.getAxis( JoystickAxis.Z_ROTATION ).assignAxis( "FLYCAM_Down", "FLYCAM_Up" );
joystick.getAxis( JoystickAxis.Z_AXIS ).assignAxis( "FLYCAM_Right", "FLYCAM_Left" );
// And let the dpad be up and down
joystick.getPovYAxis().assignAxis("FLYCAM_Rise", "FLYCAM_Lower");
if( joystick.getButton( "Button 8" ) != null ) {
// Let the stanard select button be the y invert toggle
joystick.getButton( "Button 8" ).assignButton( "FLYCAM_InvertY" );
}
} else {
joystick.getPovXAxis().assignAxis("FLYCAM_StrafeRight", "FLYCAM_StrafeLeft");
joystick.getPovYAxis().assignAxis("FLYCAM_Forward", "FLYCAM_Backward");
joystick.getXAxis().assignAxis("FLYCAM_Right", "FLYCAM_Left");
joystick.getYAxis().assignAxis("FLYCAM_Down", "FLYCAM_Up");
}
}
/**
* Registers the FlyByCamera to receive input events from the provided
* Dispatcher.
* @param inputManager
*/
public void unregisterInput(){
if (inputManager == null) {
return;
}
for (String s : mappings) {
if (inputManager.hasMapping(s)) {
inputManager.deleteMapping( s );
}
}
inputManager.removeListener(this);
inputManager.setCursorVisible(!dragToRotate);
Joystick[] joysticks = inputManager.getJoysticks();
if (joysticks != null && joysticks.length > 0){
Joystick joystick = joysticks[0];
// No way to unassing axis
}
}
protected void rotateCamera(float value, Vector3f axis){
if (dragToRotate){
if (canRotate){
// value = -value;
}else{
return;
}
}
Matrix3f mat = new Matrix3f();
mat.fromAngleNormalAxis(rotationSpeed * value, axis);
Vector3f up = cam.getUp();
Vector3f left = cam.getLeft();
Vector3f dir = cam.getDirection();
mat.mult(up, up);
mat.mult(left, left);
mat.mult(dir, dir);
Quaternion q = new Quaternion();
q.fromAxes(left, up, dir);
q.normalizeLocal();
cam.setAxes(q);
}
protected void zoomCamera(float value){
// derive fovY value
float h = cam.getFrustumTop();
float w = cam.getFrustumRight();
float aspect = w / h;
float near = cam.getFrustumNear();
float fovY = FastMath.atan(h / near)
/ (FastMath.DEG_TO_RAD * .5f);
float newFovY = fovY + value * 0.1f * zoomSpeed;
if (newFovY > 0f) {
// Don't let the FOV go zero or negative.
fovY = newFovY;
}
h = FastMath.tan( fovY * FastMath.DEG_TO_RAD * .5f) * near;
w = h * aspect;
cam.setFrustumTop(h);
cam.setFrustumBottom(-h);
cam.setFrustumLeft(-w);
cam.setFrustumRight(w);
}
protected void riseCamera(float value){
Vector3f vel = new Vector3f(0, value * moveSpeed, 0);
Vector3f pos = cam.getLocation().clone();
if (motionAllowed != null)
motionAllowed.checkMotionAllowed(pos, vel);
else
pos.addLocal(vel);
cam.setLocation(pos);
}
protected void moveCamera(float value, boolean sideways){
Vector3f vel = new Vector3f();
Vector3f pos = cam.getLocation().clone();
if (sideways){
cam.getLeft(vel);
}else{
cam.getDirection(vel);
}
vel.multLocal(value * moveSpeed);
if (motionAllowed != null)
motionAllowed.checkMotionAllowed(pos, vel);
else
pos.addLocal(vel);
cam.setLocation(pos);
}
public void onAnalog(String name, float value, float tpf) {
if (!enabled)
return;
if (name.equals("FLYCAM_Left")){
rotateCamera(value, initialUpVec);
}else if (name.equals("FLYCAM_Right")){
rotateCamera(-value, initialUpVec);
}else if (name.equals("FLYCAM_Up")){
rotateCamera(-value * (invertY ? -1 : 1), cam.getLeft());
}else if (name.equals("FLYCAM_Down")){
rotateCamera(value * (invertY ? -1 : 1), cam.getLeft());
}else if (name.equals("FLYCAM_Forward")){
moveCamera(value, false);
}else if (name.equals("FLYCAM_Backward")){
moveCamera(-value, false);
}else if (name.equals("FLYCAM_StrafeLeft")){
moveCamera(value, true);
}else if (name.equals("FLYCAM_StrafeRight")){
moveCamera(-value, true);
}else if (name.equals("FLYCAM_Rise")){
riseCamera(value);
}else if (name.equals("FLYCAM_Lower")){
riseCamera(-value);
}else if (name.equals("FLYCAM_ZoomIn")){
zoomCamera(value);
}else if (name.equals("FLYCAM_ZoomOut")){
zoomCamera(-value);
}
}
public void onAction(String name, boolean value, float tpf) {
if (!enabled)
return;
if (name.equals("FLYCAM_RotateDrag") && dragToRotate){
canRotate = value;
inputManager.setCursorVisible(!value);
} else if (name.equals("FLYCAM_InvertY")) {
// Toggle on the up.
if( !value ) {
invertY = !invertY;
}
}
}
} |
package com.jme3.material;
import com.jme3.asset.TextureKey;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.math.Vector4f;
import com.jme3.renderer.GL1Renderer;
import com.jme3.renderer.Renderer;
import com.jme3.shader.VarType;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
import java.io.IOException;
/**
* Describes a material parameter. This is used for both defining a name and type
* as well as a material parameter value.
*
* @author Kirill Vainer
*/
public class MatParam implements Savable, Cloneable {
protected VarType type;
protected String name;
protected String prefixedName;
protected Object value;
protected FixedFuncBinding ffBinding;
/**
* Create a new material parameter. For internal use only.
*/
public MatParam(VarType type, String name, Object value, FixedFuncBinding ffBinding) {
this.type = type;
this.name = name;
this.prefixedName = "m_" + name;
this.value = value;
this.ffBinding = ffBinding;
}
/**
* Serialization only. Do not use.
*/
public MatParam() {
}
/**
* Returns the fixed function binding.
*
* @return the fixed function binding.
*/
public FixedFuncBinding getFixedFuncBinding() {
return ffBinding;
}
/**
* Returns the material parameter type.
*
* @return the material parameter type.
*/
public VarType getVarType() {
return type;
}
/**
* Returns the name of the material parameter.
* @return the name of the material parameter.
*/
public String getName() {
return name;
}
/**
* Returns the name with "m_" prefixed to it.
*
* @return the name with "m_" prefixed to it
*/
public String getPrefixedName() {
return prefixedName;
}
/**
* Used internally
* @param name
*/
void setName(String name) {
this.name = name;
this.prefixedName = "m_" + name;
}
/**
* Returns the value of this material parameter.
* <p>
* Material parameters that are used for material definitions
* will not have a value, unless there's a default value declared
* in the definition.
*
* @return the value of this material parameter.
*/
public Object getValue() {
return value;
}
/**
* Sets the value of this material parameter.
* <p>
* It is assumed the value is of the same {@link MatParam#getVarType() type}
* as this material parameter.
*
* @param value the value of this material parameter.
*/
public void setValue(Object value) {
this.value = value;
}
void apply(Renderer r, Technique technique) {
TechniqueDef techDef = technique.getDef();
if (techDef.isUsingShaders()) {
technique.updateUniformParam(getPrefixedName(), getVarType(), getValue(), true);
}
if (ffBinding != null && r instanceof GL1Renderer) {
((GL1Renderer) r).setFixedFuncBinding(ffBinding, getValue());
}
}
/**
* Returns the material parameter value as it would appear in a J3M
* file. E.g.<br/>
* <code>
* MaterialParameters {<br/>
* ABC : 1 2 3 4<br/>
* }<br/>
* </code>
* Assuming "ABC" is a Vector4 parameter, then the value
* "1 2 3 4" would be returned by this method.
* <br/><br/>
* @return material parameter value as it would appear in a J3M file.
*/
public String getValueAsString() {
switch (type) {
case Boolean:
case Float:
case Int:
return value.toString();
case Vector2:
Vector2f v2 = (Vector2f) value;
return v2.getX() + " " + v2.getY();
case Vector2Array:
Vector2f[] v2Arr = (Vector2f[]) value;
String v2str = "";
for (int i = 0; i < v2Arr.length ; i++) {
v2str += v2Arr[i].getX() + " " + v2Arr[i].getY() + "\n";
}
return v2str;
case Vector3:
Vector3f v3 = (Vector3f) value;
return v3.getX() + " " + v3.getY() + " " + v3.getZ();
case Vector3Array:
Vector3f[] v3Arr = (Vector3f[]) value;
String v3str = "";
for (int i = 0; i < v3Arr.length ; i++) {
v3str += v3Arr[i].getX() + " "
+ v3Arr[i].getY() + " "
+ v3Arr[i].getZ() + "\n";
}
return v3str;
case Vector4Array:
// can be either ColorRGBA, Vector4f or Quaternion
if (value instanceof Vector4f) {
Vector4f[] v4arr = (Vector4f[]) value;
String v4str = "";
for (int i = 0; i < v4arr.length ; i++) {
v4str += v4arr[i].getX() + " "
+ v4arr[i].getY() + " "
+ v4arr[i].getZ() + " "
+ v4arr[i].getW() + "\n";
}
return v4str;
} else if (value instanceof ColorRGBA) {
ColorRGBA[] colorArr = (ColorRGBA[]) value;
String colStr = "";
for (int i = 0; i < colorArr.length ; i++) {
colStr += colorArr[i].getRed() + " "
+ colorArr[i].getGreen() + " "
+ colorArr[i].getBlue() + " "
+ colorArr[i].getAlpha() + "\n";
}
return colStr;
} else if (value instanceof Quaternion) {
Quaternion[] quatArr = (Quaternion[]) value;
String quatStr = "";
for (int i = 0; i < quatArr.length ; i++) {
quatStr += quatArr[i].getX() + " "
+ quatArr[i].getY() + " "
+ quatArr[i].getZ() + " "
+ quatArr[i].getW() + "\n";
}
return quatStr;
} else {
throw new UnsupportedOperationException("Unexpected Vector4Array type: " + value);
}
case Vector4:
// can be either ColorRGBA, Vector4f or Quaternion
if (value instanceof Vector4f) {
Vector4f v4 = (Vector4f) value;
return v4.getX() + " " + v4.getY() + " "
+ v4.getZ() + " " + v4.getW();
} else if (value instanceof ColorRGBA) {
ColorRGBA color = (ColorRGBA) value;
return color.getRed() + " " + color.getGreen() + " "
+ color.getBlue() + " " + color.getAlpha();
} else if (value instanceof Quaternion) {
Quaternion quat = (Quaternion) value;
return quat.getX() + " " + quat.getY() + " "
+ quat.getZ() + " " + quat.getW();
} else {
throw new UnsupportedOperationException("Unexpected Vector4 type: " + value);
}
case Texture2D:
case Texture3D:
case TextureArray:
case TextureBuffer:
case TextureCubeMap:
Texture texVal = (Texture) value;
TextureKey texKey = (TextureKey) texVal.getKey();
if (texKey == null){
throw new UnsupportedOperationException("The specified MatParam cannot be represented in J3M");
}
String ret = "";
if (texKey.isFlipY()) {
ret += "Flip ";
}
if (texVal.getWrap(Texture.WrapAxis.S) == WrapMode.Repeat) {
ret += "Repeat ";
}
return ret + texKey.getName();
default:
return null; // parameter type not supported in J3M
}
}
@Override
public MatParam clone() {
try {
MatParam param = (MatParam) super.clone();
return param;
} catch (CloneNotSupportedException ex) {
throw new AssertionError();
}
}
public void write(JmeExporter ex) throws IOException {
OutputCapsule oc = ex.getCapsule(this);
oc.write(type, "varType", null);
oc.write(name, "name", null);
oc.write(ffBinding, "ff_binding", null);
if (value instanceof Savable) {
Savable s = (Savable) value;
oc.write(s, "value_savable", null);
} else if (value instanceof Float) {
Float f = (Float) value;
oc.write(f.floatValue(), "value_float", 0f);
} else if (value instanceof Integer) {
Integer i = (Integer) value;
oc.write(i.intValue(), "value_int", 0);
} else if (value instanceof Boolean) {
Boolean b = (Boolean) value;
oc.write(b.booleanValue(), "value_bool", false);
}
}
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
type = ic.readEnum("varType", VarType.class, null);
name = ic.readString("name", null);
ffBinding = ic.readEnum("ff_binding", FixedFuncBinding.class, null);
switch (getVarType()) {
case Boolean:
value = ic.readBoolean("value_bool", false);
break;
case Float:
value = ic.readFloat("value_float", 0f);
break;
case Int:
value = ic.readInt("value_int", 0);
break;
default:
value = ic.readSavable("value_savable", null);
break;
}
}
@Override
public boolean equals(Object other) {
if (!(other instanceof MatParam)) {
return false;
}
MatParam otherParam = (MatParam) other;
return otherParam.type == type
&& otherParam.name.equals(name);
}
@Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + (this.type != null ? this.type.hashCode() : 0);
hash = 17 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
@Override
public String toString() {
return type.name() + " " + name + " : " + getValueAsString();
}
} |
package org.joni.ast;
import java.util.Set;
import org.joni.Config;
import org.joni.WarnCallback;
import org.joni.constants.NodeType;
public abstract class Node implements NodeType {
public Node parent;
public abstract int getType();
public final int getType2Bit() {
return 1 << getType();
}
protected void setChild(Node tgt){} // default definition
protected Node getChild(){return null;}; // default definition
public void swap(Node with) {
Node tmp;
//if (getChild() != null) getChild().parent = with;
//if (with.getChild() != null) with.getChild().parent = this;
//tmp = getChild();
//setChild(with.getChild());
//with.setChild(tmp);
if (parent != null) parent.setChild(with);
if (with.parent != null) with.parent.setChild(this);
tmp = parent;
parent = with.parent;
with.parent = tmp;
}
// overridden by ConsAltNode and CallNode
public void verifyTree(Set<Node> set, WarnCallback warnings) {
if (!set.contains(this) && getChild() != null) {
set.add(this);
if (getChild().parent != this) {
warnings.warn("broken link to child: " + this.getAddressName() + " -> " + getChild().getAddressName());
}
getChild().verifyTree(set, warnings);
}
}
public abstract String getName();
protected abstract String toString(int level);
public String getAddressName() {
return getName() + ":0x" + Integer.toHexString(System.identityHashCode(this));
}
public final String toString() {
StringBuilder s = new StringBuilder();
s.append("<" + getAddressName() + " (" + (parent == null ? "NULL" : parent.getAddressName()) + ")>");
return s + toString(0);
}
protected static String pad(Object value, int level) {
if (value == null) return "NULL";
StringBuilder pad = new StringBuilder(" ");
for (int i=0; i<level; i++) pad.append(pad);
return value.toString().replace("\n", "\n" + pad);
}
public final boolean isSimple() {
return (getType2Bit() & SIMPLE) != 0;
}
} |
package imagej.process;
import java.io.File;
import ij.ImagePlus;
import ij.ImageStack;
import ij.io.FileInfo;
import ij.process.ImageProcessor;
import imagej.SampleInfo.ValueType;
import imagej.io.ImageOpener;
import imagej.process.operation.GetPlaneOperation;
import imagej.process.operation.ImageCopierOperation;
import loci.formats.FormatTools;
import mpicbg.imglib.container.Container;
import mpicbg.imglib.container.ContainerFactory;
import mpicbg.imglib.container.array.Array;
import mpicbg.imglib.container.array.ArrayContainerFactory;
import mpicbg.imglib.container.basictypecontainer.DataAccess;
import mpicbg.imglib.container.basictypecontainer.array.PlanarAccess;
import mpicbg.imglib.cursor.Cursor;
import mpicbg.imglib.cursor.LocalizableByDimCursor;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.image.ImageFactory;
import mpicbg.imglib.type.numeric.RealType;
import mpicbg.imglib.type.numeric.integer.ByteType;
import mpicbg.imglib.type.numeric.integer.IntType;
import mpicbg.imglib.type.numeric.integer.LongType;
import mpicbg.imglib.type.numeric.integer.ShortType;
import mpicbg.imglib.type.numeric.integer.UnsignedByteType;
import mpicbg.imglib.type.numeric.integer.UnsignedIntType;
import mpicbg.imglib.type.numeric.integer.UnsignedShortType;
import mpicbg.imglib.type.numeric.real.DoubleType;
import mpicbg.imglib.type.numeric.real.FloatType;
// TODO
// createImagePlus() calls imp.setDimensions(z,c,t). But we may have other dims too. Change when we can call ImagePlus::setDimensions(int[] dims)
// Split this class into a separate project, imglib-utils, to avoid ij dependencies with other project (e.g., bf-imglib).
public class ImageUtils
{
public static int[] getDimsBeyondXY(int[] fullDims)
{
if (fullDims.length < 2)
throw new IllegalArgumentException("Image must be at least 2-D");
int[] extraDims = new int[fullDims.length-2];
for (int i = 0; i < extraDims.length; i++)
extraDims[i] = fullDims[i+2];
return extraDims;
}
public static long getTotalSamples(int[] dimensions)
{
int numDims = dimensions.length;
if (numDims == 0)
return 0;
long totalSamples = 1;
for (int i = 0; i < numDims; i++)
totalSamples *= dimensions[i];
return totalSamples;
}
public static long getTotalPlanes(int[] dimensions)
{
int numDims = dimensions.length;
if (numDims < 2)
return 0;
if (numDims == 2)
return 1;
// else numDims > 2
int[] sampleSpace = getDimsBeyondXY(dimensions);
return getTotalSamples(sampleSpace);
}
public static long getTotalSamples(Image<?> image)
{
return getTotalSamples(image.getDimensions());
}
public static RealType<?> getType(Image<?> image)
{
Cursor<?> cursor = image.createCursor();
RealType<?> type = (RealType<?>) cursor.getType();
cursor.close();
return type;
}
@SuppressWarnings({"rawtypes"})
public static double[] getPlaneData(Image<? extends RealType> image, int w, int h, int[] planePos) {
// TODO - use LocalizablePlaneCursor
// example in ImageJVirtualStack.extractSliceFloat
final double[] data = new double[w * h];
final LocalizableByDimCursor<? extends RealType> cursor = image.createLocalizableByDimCursor();
final int[] pos = Index.create(0,0,planePos);
int index = 0;
for (int y=0; y<h; y++) {
pos[1] = y;
for (int x=0; x<w; x++) {
pos[0] = x;
cursor.setPosition(pos);
// TODO: better handling of complex types
data[index++] = cursor.getType().getRealDouble();
}
}
return data;
}
// TODO: Can we extract these arrays without case logic? Seems difficult...
/** Obtains planar access instance backing the given image, if any. */
public static PlanarAccess<?> getPlanarAccess(Image<?> im) {
PlanarAccess<?> planarAccess = null;
Container<?> container = im.getContainer();
if (container instanceof Array) {
Array<?, ?> array = (Array<?, ?>) container;
final DataAccess dataAccess = array.update(null);
if (dataAccess instanceof PlanarAccess) {
// NB: This is the #2 container type mentioned above.
planarAccess = (PlanarAccess<?>) dataAccess;
}
}
return planarAccess;
}
/**
* Gets the plane at the given position from the specified image,
* by reference if possible.
*
* @param <T> Type of image.
* @param im Image from which to extract the plane.
* @param planePos Dimension position of the plane in question.
*/
public static <T extends RealType<T>> Object getPlane(Image<T> im, int[] planePos) {
// obtain dimensional lengths
final int[] dims = im.getDimensions();
if (dims.length < 2) {
throw new IllegalArgumentException("Too few dimensions: " + dims.length);
}
final PlanarAccess<?> planarAccess = getPlanarAccess(im);
if (planarAccess == null) {
return getPlaneCopy(im, planePos);
}
// TODO: Add utility method for this to Index class.
final int[] lengths = new int[dims.length - 2];
for (int i=2; i<dims.length; i++) lengths[i - 2] = dims[i];
final int no = Index.positionToRaster(lengths, planePos);
return planarAccess.getPlane(no);
}
/**
* Sets the plane at the given position for the specified image,
* by reference if possible.
*
* @param <T> Type of image.
* @param im Image from which to extract the plane.
* @param planePos Dimension position of the plane in question.
* @param plane The plane data to assign.
* @throws ClassCastException if the plane is incompatible with the image.
* @throws RuntimeException if the plane cannot be set by reference.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static <T extends RealType<T>> void setPlane(Image<T> im, int[] planePos, Object plane) {
// obtain dimensional lengths
final int[] dims = im.getDimensions();
if (dims.length < 2) {
throw new IllegalArgumentException("Too few dimensions: " + dims.length);
}
final PlanarAccess planarAccess = getPlanarAccess(im);
if (planarAccess == null) {
// TODO
throw new RuntimeException("Unimplemented");
}
// TODO: Add utility method for this to Index class.
final int[] lengths = new int[dims.length - 2];
for (int i=2; i<dims.length; i++) lengths[i - 2] = dims[i];
final int no = Index.positionToRaster(lengths, planePos);
planarAccess.setPlane(no, plane);
}
/** throws an exception if the combination of origins and spans is outside an image's dimensions */
public static void verifyDimensions(int[] imageDimensions, int[] origin, int[] span)
{
// span dims should match origin dims
if (origin.length != span.length)
throw new IllegalArgumentException("verifyDimensions() : origin (dim="+origin.length+") and span (dim="+span.length+") arrays are of differing sizes");
// origin/span dimensions should match image dimensions
if (origin.length != imageDimensions.length)
throw new IllegalArgumentException("verifyDimensions() : origin/span (dim="+origin.length+") different size than input image (dim="+imageDimensions.length+")");
// make sure origin in a valid range : within bounds of source image
for (int i = 0; i < origin.length; i++)
if ((origin[i] < 0) || (origin[i] >= imageDimensions[i]))
throw new IllegalArgumentException("verifyDimensions() : origin outside bounds of input image at index " + i);
// make sure span in a valid range : >= 1
for (int i = 0; i < span.length; i++)
if (span[i] < 1)
throw new IllegalArgumentException("verifyDimensions() : span size < 1 at index " + i);
// make sure origin + span within the bounds of the input image
for (int i = 0; i < span.length; i++)
if ( (origin[i] + span[i]) > imageDimensions[i] )
throw new IllegalArgumentException("verifyDimensions() : span range (origin+span) beyond input image boundaries at index " + i);
}
/** copies data from one image to another given origins and dimensional spans */
public static <K extends RealType<K>>
void copyFromImageToImage(Image<K> srcImage, int[] srcOrigin, int[] srcSpan,
Image<K> dstImage, int[] dstOrigin, int[] dstSpan)
{
ImageCopierOperation<K> copier = new ImageCopierOperation<K>(srcImage, srcOrigin, srcSpan, dstImage, dstOrigin, dstSpan);
copier.execute();
}
public static ImgLibProcessor<?> createProcessor(int width, int height, Object pixels, boolean unsigned)
{
ArrayContainerFactory containerFactory = new ArrayContainerFactory();
containerFactory.setPlanar(true);
ImgLibProcessor<?> proc = null;
int[] dimensions = new int[]{width, height, 1};
if (pixels instanceof byte[])
{
if (unsigned)
{
ImageFactory<UnsignedByteType> factory = new ImageFactory<UnsignedByteType>(new UnsignedByteType(),containerFactory);
Image<UnsignedByteType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<UnsignedByteType>(hatchedImage, 0);
}
else
{
ImageFactory<ByteType> factory = new ImageFactory<ByteType>(new ByteType(),containerFactory);
Image<ByteType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<ByteType>(hatchedImage, 0);
}
}
else if (pixels instanceof short[])
{
if (unsigned)
{
ImageFactory<UnsignedShortType> factory = new ImageFactory<UnsignedShortType>(new UnsignedShortType(),containerFactory);
Image<UnsignedShortType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<UnsignedShortType>(hatchedImage, 0);
}
else
{
ImageFactory<ShortType> factory = new ImageFactory<ShortType>(new ShortType(),containerFactory);
Image<ShortType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<ShortType>(hatchedImage, 0);
}
}
else if (pixels instanceof int[])
{
if (unsigned)
{
ImageFactory<UnsignedIntType> factory = new ImageFactory<UnsignedIntType>(new UnsignedIntType(),containerFactory);
Image<UnsignedIntType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<UnsignedIntType>(hatchedImage, 0);
}
else
{
ImageFactory<IntType> factory = new ImageFactory<IntType>(new IntType(),containerFactory);
Image<IntType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<IntType>(hatchedImage, 0);
}
}
else if (pixels instanceof long[])
{
if (unsigned)
{
throw new IllegalArgumentException("createProcessor(): unsigned long is not a supported pixel type");
}
else
{
ImageFactory<LongType> factory = new ImageFactory<LongType>(new LongType(),containerFactory);
Image<LongType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<LongType>(hatchedImage, 0);
}
}
else if (pixels instanceof float[])
{
ImageFactory<FloatType> factory = new ImageFactory<FloatType>(new FloatType(),containerFactory);
Image<FloatType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<FloatType>(hatchedImage, 0);
}
else if (pixels instanceof double[])
{
ImageFactory<DoubleType> factory = new ImageFactory<DoubleType>(new DoubleType(),containerFactory);
Image<DoubleType> hatchedImage = factory.createImage(dimensions);
proc = new ImgLibProcessor<DoubleType>(hatchedImage, 0);
}
else
throw new IllegalArgumentException("createProcessor(): passed unknown type of pixels - "+pixels.getClass());
proc.setPixels(pixels);
return proc;
}
public static ImagePlus createImagePlus(final Image<?> img)
{
return createImagePlus(img, null);
}
public static ImagePlus createImagePlus(final Image<?> img, final String id)
{
final int sizeX = getWidth(img);
final int sizeY = getHeight(img);
final int sizeC = getNChannels(img);
final int sizeZ = getNSlices(img);
final int sizeT = getNFrames(img);
final ImageStack stack = new ImageStack(img);
final ImagePlus imp = new ImagePlus(img.getName(), stack);
if (id != null) {
final FileInfo fi = new FileInfo();
fi.width = sizeX;
fi.height = sizeY;
final File file = new File(id);
if (file.exists()) {
fi.fileName = file.getName();
fi.directory = file.getParent();
imp.setTitle(fi.fileName);
}
else fi.url = id;
imp.setFileInfo(fi);
}
// let ImageJ know what dimensions we have
imp.setDimensions(sizeC, sizeZ, sizeT);
return imp;
}
@SuppressWarnings({"unchecked"})
public static <K extends RealType<K>> Image<K> createImage(RealType<K> type, ContainerFactory cFact, int[] dimensions)
{
ImageFactory<K> factory = new ImageFactory<K>((K)type, cFact);
return factory.createImage(dimensions);
}
public static int getWidth(final Image<?> img) {
return getDimSize(img, ImageOpener.X, 0);
}
public static int getHeight(final Image<?> img) {
return getDimSize(img, ImageOpener.Y, 1);
}
public static int getNChannels(final Image<?> img) {
return getDimSize(img, ImageOpener.Z, 2);
}
public static int getNSlices(final Image<?> img) {
return getDimSize(img, FormatTools.CHANNEL, 3);
}
public static int getNFrames(final Image<?> img) {
return getDimSize(img, ImageOpener.TIME, 4);
}
@SuppressWarnings({"unchecked"})
private static Object getPlaneCopy(Image<? extends RealType<?>> im, int[] planePos)
{
RealType<?> type = getType(im);
if (type instanceof ByteType)
return GetPlaneOperation.getPlaneAs((Image<ByteType>)im, planePos, ValueType.BYTE);
if (type instanceof UnsignedByteType)
return GetPlaneOperation.getPlaneAs((Image<UnsignedByteType>)im, planePos, ValueType.UBYTE);
if (type instanceof ShortType)
return GetPlaneOperation.getPlaneAs((Image<ShortType>)im, planePos, ValueType.SHORT);
if (type instanceof UnsignedShortType)
return GetPlaneOperation.getPlaneAs((Image<UnsignedShortType>)im, planePos, ValueType.USHORT);
if (type instanceof IntType)
return GetPlaneOperation.getPlaneAs((Image<IntType>)im, planePos, ValueType.INT);
if (type instanceof UnsignedIntType)
return GetPlaneOperation.getPlaneAs((Image<UnsignedIntType>)im, planePos, ValueType.UINT);
if (type instanceof LongType)
return GetPlaneOperation.getPlaneAs((Image<LongType>)im, planePos, ValueType.LONG);
if (type instanceof FloatType)
return GetPlaneOperation.getPlaneAs((Image<FloatType>)im, planePos, ValueType.FLOAT);
if (type instanceof DoubleType)
return GetPlaneOperation.getPlaneAs((Image<DoubleType>)im, planePos, ValueType.DOUBLE);
throw new IllegalArgumentException("getPlaneCopy(): unsupported type - "+type.getClass());
}
private static int getDimSize(final Image<?> img, final String dimType, final int defaultIndex) {
final String imgName = img.getName();
final int[] dimensions = img.getDimensions();
final String[] dimTypes = ImageOpener.decodeTypes(imgName);
int size = 1;
if (dimTypes.length == dimensions.length) {
for (int i = 0; i < dimTypes.length; i++) {
if (dimType.equals(dimTypes[i])) size *= dimensions[i];
}
}
else {
// assume default ordering
if (dimensions.length > defaultIndex) size = dimensions[defaultIndex];
}
return size;
}
} |
package com.jme.math;
import java.util.Random;
public class FastMath {
public static final double DBL_EPSILON = 2.220446049250313E-16d;
public static final float FLT_EPSILON = 1.1920928955078125E-7f;
public static final float PI = (float) (4.0 * atan(1.0f));
public static final float TWO_PI = 2.0f * PI;
public static final float HALF_PI = 0.5f * PI;
public static final float INV_PI = 1.0f / PI;
public static final float INV_TWO_PI = 1.0f / PI;
public static final float DEG_TO_RAD = PI / 180.0f;
public static final float RAD_TO_DEG = 180.0f / PI;
public static final Random rand = new Random();
public static float acos(float fValue) {
if ( -1.0f < fValue) {
if (fValue < 1.0f)
return (float) Math.acos( (double) fValue);
else
return 0.0f;
} else {
return PI;
}
}
public static float asin(float fValue) {
if ( -1.0f < fValue) {
if (fValue < 1.0f)
return (float) Math.asin( (double) fValue);
else
return -HALF_PI;
} else {
return HALF_PI;
}
}
public static float atan(float fValue) {
return (float) Math.atan( (double) fValue);
}
public static float atan2(float fY, float fX) {
return (float) Math.atan2( (double) fY, (double) fX);
}
public static float ceil(float fValue) {
return (float) Math.ceil( (double) fValue);
}
public static float cos(float fValue) {
return (float) Math.cos( (double) fValue);
}
public static float exp(float fValue) {
return (float) Math.exp( (double) fValue);
}
public static float abs(float fValue) {
return (float) Math.abs(fValue);
}
public static float floor(float fValue) {
return (float) Math.floor( (double) fValue);
}
public static float invSqrt(float fValue) {
return (float) (1.0 / Math.sqrt( (double) fValue));
}
public static float log(float fValue) {
return (float) Math.log( (double) fValue);
}
public static float pow(float fBase, float fExponent) {
return (float) Math.pow( (double) fBase, (double) fExponent);
}
public static float sin(float fValue) {
return (float) Math.sin( (double) fValue);
}
public static float sqr(float fValue) {
return fValue * fValue;
}
public static float sqrt(float fValue) {
return (float) Math.sqrt( (double) fValue);
}
public static float tan(float fValue) {
return (float) Math.tan( (double) fValue);
}
int sign(int iValue) {
if (iValue > 0)
return 1;
if (iValue < 0)
return -1;
return 0;
}
public static float sign(float fValue) {
if (fValue > 0.0f)
return 1.0f;
if (fValue < 0.0f)
return -1.0f;
return 0.0f;
}
public static float logGamma(float fX) {
float afCoeff[] = {
+76.18009173f,
-86.50532033f,
+24.01409822f,
-1.231739516f,
+ (float) 0.120858003e-02,
- (float) 0.536382000e-05};
fX -= 1.0f;
float fTmp = fX + 5.5f;
fTmp -= (fX + 0.5f) * log(fTmp);
float fSeries = 1.0f;
for (int j = 0; j <= 5; j++) {
fX += 1.0f;
fSeries += afCoeff[j] / fX;
}
return -fTmp + log( (2.50662827465f) * fSeries);
}
public static float gamma(float fX) {
return exp(logGamma(fX));
}
public static float incompleteGammaS(float fA, float fX) {
int iMaxIterations = 100;
float fTolerance = (float) 3e-07;
if (fX > 0.0f) {
float fAp = fA;
float fSum = (1.0f) / fA, fDel = fSum;
for (int i = 1; i <= iMaxIterations; i++) {
fAp += 1.0f;
fDel *= fX / fAp;
fSum += fDel;
if (abs(fDel) < abs(fSum) * fTolerance) {
float fArg = -fX + fA * log(fX) - logGamma(fA);
return fSum * exp(fArg);
}
}
}
if (fX == 0.0f)
return 0.0f;
return Float.MAX_VALUE; // LogGamma not defined for x < 0
}
public static float incompleteGammaCF(float fA, float fX) {
int iMaxIterations = 100;
float fTolerance = (float) 3e-07;
float fA0 = 1.0f, fA1 = fX;
float fB0 = 0, fB1 = 1.0f;
float fGold = 0.0f, fFac = 1.0f;
for (int i = 1; i <= iMaxIterations; i++) {
float fI = (float) i;
float fImA = fI - fA;
fA0 = (fA1 + fA0 * fImA) * fFac;
fB0 = (fB1 + fB0 * fImA) * fFac;
float fItF = fI * fFac;
fA1 = fX * fA0 + fItF * fA1;
fB1 = fX * fB0 + fItF * fB1;
if (fA1 != 0.0f) {
fFac = (1.0f) / fA1;
float fG = fB1 * fFac;
if (abs( (fG - fGold) / fG) < fTolerance) {
float fArg = -fX + fA * log(fX) - logGamma(fA);
return fG * exp(fArg);
}
fGold = fG;
}
}
return Float.MAX_VALUE; // numerical error if you get here
}
public static float incompleteGamma(float fA, float fX) {
if (fX < 1.0f + fA)
return incompleteGammaS(fA, fX);
else
return 1.0f - incompleteGammaCF(fA, fX);
}
public static float erf(float fX) {
return 1.0f - erfc(fX);
}
public static float erfc(float fX) {
float afCoeff[] = {
-1.26551223f,
+1.00002368f,
+0.37409196f,
+0.09678418f,
-0.18628806f,
+0.27886807f,
-1.13520398f,
+1.48851587f,
-0.82215223f,
+0.17087277f};
float fZ = abs(fX);
float fT = (1.0f) / (1.0f + (0.5f) * fZ);
float fSum = afCoeff[9];
for (int i = 9; i >= 0; i
fSum = fT * fSum + afCoeff[i];
float fResult = fT * exp( -fZ * fZ + fSum);
return (fX >= 0.0f ? fResult : 2.0f - fResult);
}
public static float modBessel0(float fX) {
if (fX < 0.0f) // function is even
fX = -fX;
float fT, fResult;
int i;
if (fX <= 3.75f) {
float afCoeff[] = {
1.0000000f,
3.5156229f,
3.0899424f,
1.2067492f,
0.2659732f,
0.0360768f,
0.0045813f};
fT = fX / 3.75f;
float fT2 = fT * fT;
fResult = afCoeff[6];
for (i = 5; i >= 0; i
fResult *= fT2;
fResult += afCoeff[i];
}
// |error| < 1.6e-07
} else {
float afCoeff[] = {
+0.39894228f,
+0.01328592f,
+0.00225319f,
-0.00157565f,
+0.00916281f,
-0.02057706f,
+0.02635537f,
-0.01647633f,
+0.00392377f};
fT = fX / 3.75f;
float fInvT = (1.0f) / fT;
fResult = afCoeff[8];
for (i = 7; i >= 0; i
fResult *= fInvT;
fResult += afCoeff[i];
}
fResult *= exp(fX);
fResult /= sqrt(fX);
// |error| < 1.9e-07
}
return fResult;
}
public static float modBessel1(float fX) {
int iSign;
if (fX > 0.0f) {
iSign = 1;
} else if (fX < 0.0f) {
fX = -fX;
iSign = -1;
} else {
return 0.0f;
}
float fT, fResult;
int i;
if (fX <= 3.75f) {
float afCoeff[] = {
0.50000000f,
0.87890549f,
0.51498869f,
0.15084934f,
0.02658733f,
0.00301532f,
0.00032411f};
fT = fX / 3.75f;
float fT2 = fT * fT;
fResult = afCoeff[6];
for (i = 5; i >= 0; i
fResult *= fT2;
fResult += afCoeff[i];
}
fResult *= fX;
// |error| < 8e-09
} else {
float afCoeff[] = {
+0.39894228f,
-0.03988024f,
-0.00362018f,
+0.00163801f,
-0.01031555f,
+0.02282967f,
-0.02895312f,
+0.01787654f,
-0.00420059f};
fT = fX / 3.75f;
float fInvT = (1.0f) / fT;
fResult = afCoeff[8];
for (i = 7; i >= 0; i
fResult *= fInvT;
fResult += afCoeff[i];
}
fResult *= exp(fX);
fResult /= sqrt(fX);
// |error| < 2.2e-07
}
fResult *= iSign;
return fResult;
}
public static float nextRandomFloat() {
return rand.nextFloat();
}
/**
* FastTrig
*
* @Author Erikd
*/
static public class FastTrig {
public static int PRECISION = 0x100000;
private static float RAD_SLICE = TWO_PI / PRECISION,
sinTable[] = null,
cosTable[] = null,
tanTable[] = null;
static {
RAD_SLICE = TWO_PI / PRECISION;
sinTable = new float[PRECISION];
cosTable = new float[PRECISION];
tanTable = new float[PRECISION];
float rad = 0;
for (int i = 0; i < PRECISION; i++) {
rad = (float) i * RAD_SLICE;
sinTable[i] = (float) java.lang.Math.sin(rad);
cosTable[i] = (float) java.lang.Math.cos(rad);
tanTable[i] = (float) java.lang.Math.tan(rad);
}
}
private static final int radToIndex(float radians) {
return (int) ( (radians / TWO_PI) * (float) PRECISION) & (PRECISION - 1);
}
public static float sin(float radians) {
return sinTable[radToIndex(radians)];
}
public static float cos(float radians) {
return cosTable[radToIndex(radians)];
}
public static float tan(float radians) {
return tanTable[radToIndex(radians)];
}
}
} |
package com.rcv;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
public class ResultsWriter {
// takes tabulation round tallies and generates a spreadsheet from them
public boolean generateSummarySpreadsheet(
int finalRound,
Map<Integer, Map<String, Integer>> roundTallies,
Map<String, Integer> candidatesToRoundEliminated,
String outputFilePath,
String electionName,
String winner
) {
// some pre-processing on the tabulation data:
// invert candidatesToRoundEliminated map so we can lookup who got eliminated for each round
Map<Integer, List<String>> roundToCandidatesEliminated = new HashMap<Integer, List<String>>();
for (String candidate : candidatesToRoundEliminated.keySet()) {
int round = candidatesToRoundEliminated.get(candidate);
if (roundToCandidatesEliminated.get(round) == null) {
roundToCandidatesEliminated.put(round, new LinkedList<String>());
}
roundToCandidatesEliminated.get(round).add(candidate);
}
// get a list of all candidates sorted by their first round tally -- that determines the display order
Map<String, Integer> firstRoundTally = roundTallies.get(1);
List<String> sortedCandidates = sortTally(firstRoundTally);
// build map of total votes cast in each round -- this will be used to calculate
// the percentage of total votes each candidate achieves
Map<Integer, Integer> totalActiveVotesPerRound = new HashMap<Integer, Integer>();
for (int round = 1; round <= finalRound; round++) {
Map<String, Integer> tally = roundTallies.get(round);
int total = 0;
for (int votes : tally.values()) {
total += votes;
}
totalActiveVotesPerRound.put(round, total);
}
// create the workbook and worksheet
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet worksheet = workbook.createSheet(electionName);
// Global Header
int rowCounter = 0;
// title
org.apache.poi.ss.usermodel.Row titleRow = worksheet.createRow(rowCounter++);
Cell headerCell = titleRow.createCell(0);
headerCell.setCellValue("Contest:");
headerCell = titleRow.createCell(1);
headerCell.setCellValue(electionName);
// total votes cast in election
org.apache.poi.ss.usermodel.Row totalVoteRow = worksheet.createRow(rowCounter++);
headerCell = totalVoteRow.createCell(0);
headerCell.setCellValue("Total votes cast:");
headerCell = totalVoteRow.createCell(1);
Integer totalActiveVotesFirstRound = totalActiveVotesPerRound.get(1);
headerCell.setCellValue(totalActiveVotesFirstRound);
// number of seats (we don't yet support multi-seat races)
org.apache.poi.ss.usermodel.Row numSeatsRow = worksheet.createRow(rowCounter++);
headerCell = numSeatsRow.createCell(0);
headerCell.setCellValue("Number to be elected:");
headerCell = numSeatsRow.createCell(1);
headerCell.setCellValue(1);
// threshold
int threshold = (totalActiveVotesFirstRound / 2) + 1;
org.apache.poi.ss.usermodel.Row thresholdRow = worksheet.createRow(rowCounter++);
headerCell = thresholdRow.createCell(0);
headerCell.setCellValue("Threshold:");
headerCell = thresholdRow.createCell(1);
headerCell.setCellValue(threshold);
// skip a row for visual clarity
worksheet.createRow(rowCounter++);
// Round-by-round reports
// each round (except the first) has three pieces of data for each candidate row:
// - change in votes from previous round
// - total votes in current round
// - percentage of total active votes
// in the first round we omit change in votes because... we were asked to do so
int COLUMNS_PER_ROUND = 3;
// column indexes are computed for all cells in the output xlsx spreadsheet
// columnIndex is (round - 1) because rounds are 1-based (cells are 0-based)
// columnIndex is offset by 1 to account for row "headers" which are the candidate names
int columnIndex;
// Headers for each round
org.apache.poi.ss.usermodel.Row headerRow1 = worksheet.createRow(rowCounter++);
for(int round = 1; round <= finalRound; round++) {
columnIndex = ((round-1)*COLUMNS_PER_ROUND)+1;
Cell roundLabelCell = headerRow1.createCell(columnIndex);
String label = String.format("ROUND %d", round);
if(round ==1) {
label = "INITIAL COUNT";
}
roundLabelCell.setCellValue(label);
}
// Header for winner
columnIndex = (finalRound*COLUMNS_PER_ROUND)+1;
Cell winnerLabelCell = headerRow1.createCell(columnIndex);
winnerLabelCell.setCellValue("Elected");
// Eliminations for each round
StringBuilder sb = new StringBuilder("Eliminations: ");
org.apache.poi.ss.usermodel.Row eliminationsRow = worksheet.createRow(rowCounter++);
Cell eliminationsRowHeader = eliminationsRow.createCell(0);
eliminationsRowHeader.setCellValue("DEFEATED: ");
for (int round = 1; round <= finalRound; round++) {
sb.append(round).append(": ");
List<String> eliminated = roundToCandidatesEliminated.get(round);
String cellText = String.join(", ", eliminated);
columnIndex = ((round-1)*COLUMNS_PER_ROUND)+1;
Cell cell = eliminationsRow.createCell(columnIndex);
cell.setCellValue(cellText);
sb.append(cellText);
sb.append(", ");
}
RCVLogger.log(sb.toString());
// Winners for each round
org.apache.poi.ss.usermodel.Row electedRow = worksheet.createRow(rowCounter++);
Cell electedCell = electedRow.createCell(0);
electedCell.setCellValue("ELECTED:");
columnIndex = ((finalRound)*COLUMNS_PER_ROUND)+1;
electedCell = electedRow.createCell(columnIndex);
electedCell.setCellValue(winner);
// Show total, change, percentage for each round EXCEPT skip "change" for first round
org.apache.poi.ss.usermodel.Row headerRow2 = worksheet.createRow(rowCounter++);
for(int round = 1; round <= finalRound; round++) {
columnIndex = ((round-1)*COLUMNS_PER_ROUND)+1;
String roundDeltaText = String.format("Change");
Cell roundDeltaCell = headerRow2.createCell(columnIndex);
roundDeltaCell.setCellValue(roundDeltaText);
columnIndex++;
Cell roundTotalCell = headerRow2.createCell(columnIndex++);
String roundTotalText = String.format("Total");
roundTotalCell.setCellValue(roundTotalText);
String roundPercentageText = String.format("Percentage (active votes)");
Cell roundPercentageCell = headerRow2.createCell(columnIndex);
roundPercentageCell.setCellValue(roundPercentageText);
}
// TODO: elected candidate lists
// Rows 2..n: Candidate votes [total, delta, percentage]
// EXCEPT skip "change" for first round
for (String candidate : sortedCandidates) {
org.apache.poi.ss.usermodel.Row candidateRow = worksheet.createRow(rowCounter++);
Cell rowHeaderCell = candidateRow.createCell(0);
rowHeaderCell.setCellValue(candidate);
sb = new StringBuilder(candidate).append(": ");
for (int round = 1; round <= finalRound; round++) {
// not all candidates may have a tally in every round
Integer total = roundTallies.get(round).get(candidate);
if (total == null) {
total = 0;
}
// get previous tally to calculate delta
Integer prevTotal = 0;
if (round > 1) {
prevTotal = roundTallies.get(round - 1).get(candidate);
if (prevTotal == null) {
prevTotal = 0;
}
}
int delta = total - prevTotal;
// percentage
Integer totalActiveVotes = totalActiveVotesPerRound.get(round);
float percentage = ((float)total / (float)totalActiveVotes) * 100f;
// log output
sb.append("Round ").append(round - 1).append(" change: ").append(delta).append(", ");
sb.append("Round ").append(round - 1).append(" total: ").append(total).append(", ");
sb.append("Round ").append(round - 1).append(" percentage: ").append(percentage).append(", ");
// create cells for spreadsheet
columnIndex = ((round-1)*COLUMNS_PER_ROUND)+1;
Cell deltaVotesCell = candidateRow.createCell(columnIndex);
deltaVotesCell.setCellValue(delta);
columnIndex++;
Cell totalVotesCell = candidateRow.createCell(columnIndex++);
totalVotesCell.setCellValue(total);
Cell percentageCell = candidateRow.createCell(columnIndex);
String percentageText = String.format("%.2f%%", percentage);
percentageCell.setCellValue(percentageText);
}
}
RCVLogger.log(sb.toString());
// Bottom rows:
// exhausted ballots for each round
org.apache.poi.ss.usermodel.Row exhaustedRow = worksheet.createRow(rowCounter++);
Cell exhaustedRowHeaderCell = exhaustedRow.createCell(0);
exhaustedRowHeaderCell.setCellValue("Exhausted Votes:");
sb = new StringBuilder("Exhausted Votes: ");
for (int round = 1; round <= finalRound; round++) {
int thisRoundExhausted = 0;
int deltaExhausted = 0;
// exhausted count is the difference between the total votes in round 1 and total votes in current round
if (round > 1) {
thisRoundExhausted = totalActiveVotesFirstRound - totalActiveVotesPerRound.get(round);
int prevRoundExhausted = totalActiveVotesFirstRound - totalActiveVotesPerRound.get(round - 1);
deltaExhausted = thisRoundExhausted - prevRoundExhausted;
}
// exhausted votes as percentage of ALL votes (note: this differs from the candidate vote percentages
// which are percentage of ACTIVE votes for the given round
float percentage = ((float)thisRoundExhausted / (float)totalActiveVotesFirstRound) * 100f;
// log file output
sb.append("Round ").append(round - 1).append(" delta: ").append(deltaExhausted).append(", ");
sb.append("Round ").append(round - 1).append(" total: ").append(thisRoundExhausted).append(", ");
sb.append("Round ").append(round - 1).append(" percentage: ").append(percentage).append(", ");
// xls output
columnIndex = ((round-1)*COLUMNS_PER_ROUND)+1;
Cell deltaVotesCell = exhaustedRow.createCell(columnIndex);
deltaVotesCell.setCellValue(deltaExhausted);
columnIndex++;
Cell totalVotesCell = exhaustedRow.createCell(columnIndex++);
totalVotesCell.setCellValue(thisRoundExhausted);
String percentageText = String.format("%.2f%%", percentage);
Cell percentageCell = exhaustedRow.createCell(columnIndex);
percentageCell.setCellValue(percentageText);
}
// Total active votes in this round
org.apache.poi.ss.usermodel.Row totalActiveVotesRow = worksheet.createRow(rowCounter++);
Cell totalActiveVotesHeader = totalActiveVotesRow.createCell(0);
totalActiveVotesHeader.setCellValue("Active Votes:");
sb = new StringBuilder("Active Votes:");
for (int round = 1; round <= finalRound; round++) {
int total = totalActiveVotesPerRound.get(round);
sb.append("Round ").append(round - 1).append(" active: ").append(total).append(", ");
// xls output
columnIndex = ((round-1)*COLUMNS_PER_ROUND)+2;
Cell totalVotesCell = totalActiveVotesRow.createCell(columnIndex);
totalVotesCell.setCellValue(total);
}
// Total votes in this round
org.apache.poi.ss.usermodel.Row totalVotesRow = worksheet.createRow(rowCounter++);
Cell totalVotesHeader = totalVotesRow.createCell(0);
totalVotesHeader.setCellValue("Total Votes:");
sb = new StringBuilder("Total Votes:");
for (int round = 1; round <= finalRound; round++) {
// TODO: actually calculate this value
sb.append("Round ").append(round - 1).append(" total: ").append(totalActiveVotesFirstRound).append(", ");
// xls output
columnIndex = ((round-1)*COLUMNS_PER_ROUND)+2;
Cell totalVotesCell = totalVotesRow.createCell(columnIndex);
totalVotesCell.setCellValue(totalActiveVotesFirstRound);
}
// write to log
RCVLogger.log(sb.toString());
// write xls to disk
try {
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
workbook.write(outputStream);
outputStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
RCVLogger.log("failed to write " + outputFilePath + " to disk!");
return false;
}
}
// helper
private List<String> sortTally(Map<String, Integer> tally) {
List<Map.Entry<String, Integer>> entries =
new LinkedList<Map.Entry<String, Integer>>(tally.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
List<String> sortedCandidates = new LinkedList<String>();
for (Map.Entry<String, Integer> entry : entries) {
sortedCandidates.add(entry.getKey());
}
return sortedCandidates;
}
} |
package com.rtg.graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.prefs.Preferences;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.reeltwo.jumble.annotations.JumbleIgnore;
import com.reeltwo.plot.Graph2D;
import com.reeltwo.plot.KeyPosition;
import com.reeltwo.plot.Plot2D;
import com.reeltwo.plot.Point2D;
import com.reeltwo.plot.PointPlot2D;
import com.reeltwo.plot.renderer.Mapping;
import com.reeltwo.plot.ui.PlotPanel;
import com.reeltwo.plot.ui.ZoomPlotPanel;
import com.rtg.util.ContingencyTable;
import com.rtg.util.Resources;
import com.rtg.util.StringUtils;
import com.rtg.util.io.FileUtils;
/**
* Starts a new Swing window for displaying {@code Graph2D}s in. The window has
* zooming and picture in picture functionality enabled.
*
*/
@JumbleIgnore
public final class RocPlot {
/** Minimum allowed line width */
public static final int LINE_WIDTH_MIN = 1;
/** Maximum allowed line width */
public static final int LINE_WIDTH_MAX = 10;
// File chooser stored user-preference keys
private static final String CHOOSER_WIDTH = "chooser-width";
private static final String CHOOSER_HEIGHT = "chooser-height";
private final ProgressBarDelegate mProgressBarDelegate;
private final JPanel mMainPanel;
/** panel showing plot */
private final PlotPanel mPlotPanel;
private final RocZoomPlotPanel mZoomPP;
/** a progress bar */
private final JProgressBar mProgressBar;
/** pop up menu */
private final JPopupMenu mPopup;
private final JLabel mIconLabel;
private final RocLinesPanel mRocLinesPanel;
private final JSlider mLineWidthSlider;
private final JCheckBox mScoreCB;
private final JCheckBox mSelectAllCB;
private final JButton mOpenButton;
private final JButton mCommandButton;
private final JTextField mTitleEntry;
private JSplitPane mSplitPane;
private final JLabel mStatusLabel;
// Graph data and state
final Map<String, DataBundle> mData = Collections.synchronizedMap(new HashMap<String, DataBundle>());
boolean mShowScores = true;
int mLineWidth = 2;
private float mMaxXHi = -1.0f;
private float mMaxYHi = -1.0f;
private final JScrollPane mScrollPane;
private final JFileChooser mFileChooser = new JFileChooser();
private File mFileChooserParent = null;
/** Creates a new swing plot. */
RocPlot() {
mMainPanel = new JPanel();
mPlotPanel = new PlotPanel(true);
mZoomPP = new RocZoomPlotPanel(mPlotPanel, mMainPanel);
mZoomPP.setOriginIsMin(true);
mProgressBar = new JProgressBar(-1, -1);
mProgressBarDelegate = new ProgressBarDelegate(mProgressBar);
mStatusLabel = new JLabel();
mPopup = new JPopupMenu();
mRocLinesPanel = new RocLinesPanel(this);
mScrollPane = new JScrollPane(mRocLinesPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
mScrollPane.setWheelScrollingEnabled(true);
//System.err.println("scroll: " + mScrollPane.getPreferredSize());
// mRocLinesPanel.setLayout(new GridLayout(0, 1));
mLineWidthSlider = new JSlider(JSlider.HORIZONTAL, LINE_WIDTH_MIN, LINE_WIDTH_MAX, 1);
mScoreCB = new JCheckBox("Show Scores");
mScoreCB.setSelected(true);
mSelectAllCB = new JCheckBox("Select / Deselect all");
mTitleEntry = new JTextField("ROC");
mOpenButton = new JButton("+");
mOpenButton.setToolTipText("Add a new ROC curve from a file");
mCommandButton = new JButton("Cmd");
mCommandButton.setToolTipText("Send equivalent rocplot command-line to terminal");
final ImageIcon icon = createImageIcon("com/rtg/graph/resources/realtimegenomics_logo.png", "RTG Logo");
mIconLabel = new JLabel(icon);
mIconLabel.setBackground(new Color(16, 159, 205));
mIconLabel.setForeground(Color.WHITE);
mIconLabel.setOpaque(true);
mIconLabel.setFont(new Font("Arial", Font.BOLD, 24));
mIconLabel.setHorizontalAlignment(JLabel.LEFT);
mIconLabel.setIconTextGap(50);
configureUI();
}
protected static ImageIcon createImageIcon(String path, String description) {
final java.net.URL imgURL = Resources.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Layout and show the GUI.
*/
private void configureUI() {
mMainPanel.setLayout(new BorderLayout());
final JPanel pane = new JPanel(new BorderLayout());
pane.add(mPlotPanel, BorderLayout.CENTER);
final Box rightPanel = new Box(BoxLayout.Y_AXIS);
mSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pane, rightPanel);
mSplitPane.setContinuousLayout(true);
mSplitPane.setOneTouchExpandable(true);
mSplitPane.setResizeWeight(1);
mMainPanel.add(mSplitPane, BorderLayout.CENTER);
mMainPanel.add(mStatusLabel, BorderLayout.SOUTH);
mPopup.setLightWeightPopupEnabled(false);
mPopup.add(mZoomPP.getZoomOutAction());
mPopup.addSeparator();
mPopup.add(mPlotPanel.getPrintAction());
mPopup.add(mPlotPanel.getSaveImageAction());
mPopup.add(mPlotPanel.getSnapShotAction());
// listener to show popup
mPlotPanel.addMouseListener(new PopupListener());
mPopup.addSeparator();
//Set up the content pane.
mPlotPanel.setBackground(Color.WHITE);
mPlotPanel.setGraphBGColor(new Color(0.8f, 0.9f, 1.0f), Color.WHITE);
mPlotPanel.setGraphShadowWidth(4);
final JPanel controlPanel = new JPanel(new GridLayout(0, 1));
controlPanel.add(new JLabel("Line Width", JLabel.CENTER));
mLineWidthSlider.setSnapToTicks(true);
mLineWidthSlider.setValue(mLineWidth);
//mLineWidthSlider.setPreferredSize(new Dimension(300, mLineWidthSlider.getPreferredSize().height));
mLineWidthSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
mLineWidth = mLineWidthSlider.getValue();
showCurrentGraph();
}
});
controlPanel.add(mLineWidthSlider);
mScoreCB.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
mShowScores = mScoreCB.isSelected();
showCurrentGraph();
}
});
controlPanel.add(mScoreCB);
final JPanel titlePanel = new JPanel(new GridLayout(0, 1));
titlePanel.add(new JLabel("Title", JLabel.CENTER));
mTitleEntry.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
mIconLabel.setText(mTitleEntry.getText());
showCurrentGraph();
}
}
});
titlePanel.add(mTitleEntry);
controlPanel.add(titlePanel);
rightPanel.add(controlPanel);
final JPanel checkControlPanel = new JPanel(new GridBagLayout());
final GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0; constraints.gridy = 0;
constraints.anchor = GridBagConstraints.LINE_START;
checkControlPanel.add(mOpenButton, constraints);
constraints.gridy++;
constraints.anchor = GridBagConstraints.CENTER;
checkControlPanel.add(mSelectAllCB, constraints);
mSelectAllCB.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
for (final Component component : mRocLinesPanel.getComponents()) {
final RocLinePanel cp = (RocLinePanel) component;
cp.setSelected(mSelectAllCB.isSelected());
}
}
});
mSelectAllCB.setSelected(true);
mOpenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (mFileChooserParent != null) {
mFileChooser.setCurrentDirectory(mFileChooserParent);
}
final Preferences prefs = Preferences.userNodeForPackage(RocPlot.this.getClass());
if (prefs.getInt(CHOOSER_WIDTH, -1) != -1 && prefs.getInt(CHOOSER_HEIGHT, -1) != -1) {
mFileChooser.setPreferredSize(new Dimension(prefs.getInt(CHOOSER_WIDTH, 640), prefs.getInt(CHOOSER_HEIGHT, 480)));
}
if (mFileChooser.showOpenDialog(checkControlPanel) == JFileChooser.APPROVE_OPTION) {
final File f = mFileChooser.getSelectedFile();
if (f != null) {
try {
loadFile(f, f.getCanonicalFile().getParentFile().getName(), true);
updateProgress();
showCurrentGraph();
} catch (final IOException e1) {
JOptionPane.showInternalMessageDialog(checkControlPanel, "Could not open file " + f.getPath());
}
final Dimension r = mFileChooser.getSize();
prefs.putInt(CHOOSER_WIDTH, (int) r.getWidth());
prefs.putInt(CHOOSER_HEIGHT, (int) r.getHeight());
}
}
}
});
mCommandButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Equivalent rocplot command:\n" + getCommand() + "\n");
}
});
final JPanel namePanel = new JPanel(new GridBagLayout());
final GridBagConstraints checkConstraints = new GridBagConstraints();
checkConstraints.gridx = 0; checkConstraints.gridy = 0;
checkConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
namePanel.add(checkControlPanel, checkConstraints);
final GridBagConstraints scrollConstraints = new GridBagConstraints();
scrollConstraints.gridx = 0; scrollConstraints.gridy = 1;
scrollConstraints.weightx = 2; scrollConstraints.weighty = 2;
scrollConstraints.fill = GridBagConstraints.BOTH;
mRocLinesPanel.setPreferredSize(new Dimension(mScrollPane.getViewport().getViewSize().width, mRocLinesPanel.getPreferredSize().height));
namePanel.add(mScrollPane, scrollConstraints);
final GridBagConstraints cmdConstraints = new GridBagConstraints();
cmdConstraints.anchor = GridBagConstraints.LINE_START;
cmdConstraints.gridx = 0; cmdConstraints.gridy = 2;
namePanel.add(mCommandButton, cmdConstraints);
rightPanel.add(namePanel);
pane.add(mProgressBar, BorderLayout.SOUTH);
mIconLabel.setText(mTitleEntry.getText());
pane.add(mIconLabel, BorderLayout.NORTH);
}
private String getCommand() {
final StringBuilder sb = new StringBuilder("rtg rocplot ");
sb.append("--").append(RocPlotCli.LINE_WIDTH_FLAG).append(' ').append(mLineWidth);
if (mShowScores) {
sb.append(" --").append(RocPlotCli.SCORES_FLAG);
}
sb.append(" --").append(RocPlotCli.TITLE_FLAG).append(' ').append(StringUtils.dumbQuote(mTitleEntry.getText()));
for (final Component component : mRocLinesPanel.getComponents()) {
final RocLinePanel cp = (RocLinePanel) component;
if (cp.isSelected()) {
sb.append(" --").append(RocPlotCli.CURVE_FLAG).append(" ").append(StringUtils.dumbQuote(cp.getPath() + "=" + cp.getLabel()));
}
}
return sb.toString();
}
// Adds the notion of painting a current crosshair position
@JumbleIgnore
private static class RocZoomPlotPanel extends ZoomPlotPanel {
private final PlotPanel mPlotPanel;
private Point mCrosshair; // In TP / FP coordinates.
RocZoomPlotPanel(PlotPanel plotPanel, Container container) {
super(plotPanel, container);
mPlotPanel = plotPanel;
}
@Override
public void paint(Graphics g) {
super.paint(g);
final Mapping[] mapping = mPlotPanel.getMapping();
if (mapping != null && mapping.length > 1 && mCrosshair != null) {
Point p = new Point((int) mapping[0].worldToScreen(mCrosshair.x), (int) mapping[1].worldToScreen(mCrosshair.y));
p = SwingUtilities.convertPoint(mPlotPanel, p, this);
g.setColor(Color.BLACK);
final int size = 9;
g.drawLine(p.x - size, p.y - size, p.x + size, p.y + size);
g.drawLine(p.x - size, p.y + size, p.x + size, p.y - size);
}
}
void setCrossHair(Point p) {
mCrosshair = p;
}
}
// Adds the notion of the baseline total number of variants, for calculating sensitivity
@JumbleIgnore
static class RocGraph2D extends Graph2D {
private final int mMaxVariants;
RocGraph2D(ArrayList<String> lineOrdering, int lineWidth, boolean showScores, Map<String, DataBundle> data, String title) {
setKeyVerticalPosition(KeyPosition.BOTTOM);
setKeyHorizontalPosition(KeyPosition.RIGHT);
setGrid(true);
setLabel(Graph2D.Y, "True Positives");
setLabel(Graph2D.X, "False Positives");
setTitle(title);
int maxVariants = -1;
for (int i = 0; i < lineOrdering.size(); i++) {
final DataBundle db = data.get(lineOrdering.get(i));
if (db.show()) {
addPlot(db.getPlot(lineWidth, i));
if (showScores) {
addPlot(db.getScorePoints(lineWidth, i));
addPlot(db.getScoreLabels());
}
if (db.getTotalVariants() > maxVariants) {
maxVariants = db.getTotalVariants();
}
}
}
if (maxVariants > 0) {
setRange(Graph2D.Y, 0, maxVariants);
setTitle(title + " (baseline total = " + maxVariants + ")");
setRange(Graph2D.Y, Graph2D.TWO, 0, 100);
setShowTics(Graph2D.Y, Graph2D.TWO, true);
setGrid(Graph2D.Y, Graph2D.TWO, false);
setLabel(Graph2D.Y, Graph2D.TWO, "%");
// dummy plot to show Y2 axis
final PointPlot2D pp = new PointPlot2D(Graph2D.ONE, Graph2D.TWO);
addPlot(pp);
}
mMaxVariants = maxVariants;
}
public int getMaxVariants() {
return mMaxVariants;
}
}
void showCurrentGraph() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Graph2D graph = new RocGraph2D(RocPlot.this.mRocLinesPanel.plotOrder(), RocPlot.this.mLineWidth, RocPlot.this.mShowScores, RocPlot.this.mData, RocPlot.this.mTitleEntry.getText());
maintainZoomMax(graph);
graph.addPlot(invisibleGraph());
mZoomPP.setGraph(graph, true);
}
});
}
private Plot2D invisibleGraph() {
// Invisible graph to maintain graph size when no lines are shown
final PointPlot2D plot = new PointPlot2D();
plot.setData(Arrays.asList(new Point2D(0, 0), new Point2D(mMaxXHi, mMaxYHi)));
plot.setLines(false);
plot.setPoints(false);
return plot;
}
private void maintainZoomMax(Graph2D graph) {
mMaxXHi = Math.max(mMaxXHi, graph.getHi(Graph2D.X, Graph2D.ONE));
mMaxYHi = Math.max(mMaxYHi, graph.getHi(Graph2D.Y, Graph2D.ONE));
}
void updateProgress() {
mProgressBarDelegate.done();
}
public ProgressBarDelegate getProgressBarDelegate() {
return mProgressBarDelegate;
}
/**
* Set the title of the plot
* @param title plot title
*/
public void setTitle(final String title) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mIconLabel.setText(title);
mTitleEntry.setText(title);
}
});
}
/**
* Set whether to show scores on the plot lines
* @param flag show scores
*/
public void showScores(boolean flag) {
mShowScores = flag;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mScoreCB.setSelected(mShowScores);
}
});
}
/**
* Set whether to show the open file button
* @param flag show open file button
*/
public void showOpenButton(boolean flag) {
mOpenButton.setVisible(flag);
}
/**
* Set whether to show the command dump button
* @param flag show command dump button
*/
public void showCommandButton(boolean flag) {
mCommandButton.setVisible(flag);
}
/**
* Set the line width slider to the given value
* @param width line width
*/
public void setLineWidth(int width) {
mLineWidth = width < LINE_WIDTH_MIN ? LINE_WIDTH_MIN : width > LINE_WIDTH_MAX ? LINE_WIDTH_MAX : width;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mLineWidthSlider.setValue(mLineWidth);
}
});
}
/**
* Sets the split pane divider location
* @param loc proportional location
*/
public void setSplitPaneDividerLocation(double loc) {
mSplitPane.setDividerLocation(loc);
}
/**
* Returns the main application panel
* @return main panel
*/
public JPanel getMainPanel() {
return mMainPanel;
}
/**
* Returns the zooming part of the plot panel
* @return zoom plot panel
*/
public ZoomPlotPanel getZoomPlotPanel() {
return mZoomPP;
}
/**
* Set a status message
* @param message test to display
*/
public void setStatus(String message) {
mStatusLabel.setText(message);
}
private void loadData(ArrayList<File> files, ArrayList<String> names, boolean showProgress) throws IOException {
for (int i = 0; i < files.size(); i++) {
final File f = files.get(i);
final String name = names.get(i);
loadFile(f, name, showProgress);
}
if (showProgress) {
updateProgress();
}
}
private void loadFile(final File f, final String name, boolean showProgress) throws IOException {
mFileChooserParent = f.getParentFile();
final DataBundle data = ParseRocFile.loadStream(mProgressBarDelegate, FileUtils.createInputStream(f, false), name, showProgress);
addLine(f.getAbsolutePath(), data);
}
private void addLine(String path, DataBundle dataBundle) {
mData.put(path, dataBundle);
mRocLinesPanel.addLine(new RocLinePanel(this, path, dataBundle.getTitle(), dataBundle, mProgressBar));
showCurrentGraph();
}
/**
* A class required to listen for right-clicks
*/
@JumbleIgnore
private class PopupListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
final Point p = e.getPoint();
final Mapping[] mapping = mPlotPanel.getMapping();
final int maxVariants = ((RocGraph2D) mPlotPanel.getGraph()).getMaxVariants();
if (mapping != null && mapping.length > 1) {
final float fp = mapping[0].screenToWorld((float) p.getX());
final float tp = mapping[1].screenToWorld((float) p.getY());
if (fp >= 0 && tp >= 0 && (fp + tp > 0)) {
mProgressBar.setString(getMetricString(tp, fp, maxVariants));
mZoomPP.setCrossHair(new Point((int) fp, (int) tp));
} else {
mZoomPP.setCrossHair(null);
mProgressBar.setString("");
}
}
}
@Override
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
mPopup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
static String getMetricString(double truePositive, double falsePositive, int totalPositive) {
final double precision = ContingencyTable.precision(truePositive, falsePositive);
String message = String.format("TP=%.0f FP=%.0f Precision=%.2f%%", truePositive, falsePositive, precision * 100);
if (totalPositive > 0) {
final double falseNegative = totalPositive - truePositive;
final double recall = ContingencyTable.recall(truePositive, falseNegative);
final double fMeasure = ContingencyTable.fMeasure(precision, recall);
message += String.format(" Sensitivity=%.2f%% F-measure=%.2f%%", recall * 100, fMeasure * 100);
}
return message;
}
void rocStandalone(ArrayList<File> fileList, ArrayList<String> nameList, String title, boolean scores, final boolean hideSidePanel, int lineWidth) throws InterruptedException, InvocationTargetException, IOException {
final RocPlot rp = new RocPlot();
rp.setLineWidth(lineWidth);
final JFrame frame = new JFrame("ROC");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(rp.mMainPanel, BorderLayout.CENTER);
frame.setGlassPane(rp.mZoomPP);
frame.getGlassPane().setVisible(true);
final CountDownLatch lock = new CountDownLatch(1);
rp.mPopup.add(new AbstractAction("Exit", null) {
@Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
frame.dispose();
lock.countDown();
}
});
rp.showScores(scores);
if (title != null) {
rp.setTitle(title);
}
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frame.pack();
frame.setSize(1024, 768);
frame.setLocation(50, 50);
frame.setVisible(true);
rp.showCurrentGraph();
if (hideSidePanel) {
rp.setSplitPaneDividerLocation(1.0);
}
}
});
rp.loadData(fileList, nameList, true);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
rp.mZoomPP.setGraph(new RocGraph2D(rp.mRocLinesPanel.plotOrder(), rp.mLineWidth, rp.mShowScores, rp.mData, rp.mTitleEntry.getText()), false);
}
});
lock.await();
}
} |
package com.taig.dna;
import java.util.ArrayList;
import java.util.Collection;
/**
* A list of {@link Nucleotide Nucleotides} that allows to perform domain specific operations in order to analyze the
* DNA sequence.
*/
public class Sequence extends ArrayList<Nucleotide>
{
public Sequence()
{
super();
}
public Sequence( int i )
{
super( i );
}
public Sequence( Collection<? extends Nucleotide> nucleotides )
{
super( nucleotides );
}
public Sequence( String sequence )
{
for( char abbreviation : sequence.toCharArray() )
{
add( Nucleotide.newInstance( abbreviation ) );
}
}
/**
* Get the complement of the current Sequence.
*
* @return The complement of the current Sequence.
*/
public Sequence getComplement()
{
Sequence complement = new Sequence();
for( Nucleotide nucleotide : this )
{
complement.add( nucleotide.getComplement() );
}
return complement;
}
/**
* Convert the Sequence to a String representation without spaces consisting of the {@link Nucleotide Nucleotides}
* abbreviations (uppercase).
*
* @return The Sequence's current state represented as String resource.
*/
@Override
public String toString()
{
StringBuilder sequence = new StringBuilder();
for( Nucleotide nucleotide : this )
{
sequence.append( nucleotide );
}
return sequence.toString();
}
} |
package ij.io;
import ij.*;
import static org.junit.Assert.*;
import org.junit.Test;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.io.*;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
import ij.process.*;
public class FileOpenerTest {
FileOpener fo;
@Test
public void testFileOpener() {
// define one on a null file
FileOpener opener = new FileOpener(null);
assertNotNull(opener);
// define one on a default file info object
FileInfo info = new FileInfo();
opener = new FileOpener(info);
assertNotNull(opener);
// define one on a modified FileInfo
info.fileName = "miniTiled.tif";
info.fileType = FileInfo.GRAY8;
opener = new FileOpener(info);
assertNotNull(opener);
}
// note - no need to test this - it just does a open(true) and true means display results which we can't test
@Test
public void testOpen() {
}
// note - only testing false case - true means display results which we can't test
@Test
public void testOpenBoolean() {
FileInfo info;
ImagePlus ip;
// test for a non existent file
// ideally open() would pass back the exception for an unknown file. As it is something lower catches the
// exception, prints a stack trace, and does nothing
info = new FileInfo();
info.fileName = "SuperPuppy.tif";
info.fileType = FileInfo.GRAY8;
info.height = 3; // required
info.width = 4; // required
fo = new FileOpener(info);
ip = fo.open(false);
assertNull(ip);
// test for a real 8 bit file
info = new FileInfo();
info.fileName = "gray8-2x3-sub1.tif";
info.fileType = FileInfo.GRAY8;
info.height = 2;
info.width = 3;
info.directory = "data/";
fo = new FileOpener(info);
ip = fo.open(false);
assertNotNull(ip);
assertEquals(8,ip.getBitDepth());
assertEquals(1,ip.getBytesPerPixel());
assertEquals(2,ip.getHeight());
assertEquals(3,ip.getWidth());
assertTrue(ip.getProcessor() instanceof ByteProcessor);
// test for a real 16 bit file
info = new FileInfo();
info.fileName = "gray16-2x3-sub1.tif";
info.fileType = FileInfo.GRAY16_UNSIGNED;
info.height = 2;
info.width = 3;
info.directory = "data/";
fo = new FileOpener(info);
ip = fo.open(false);
assertNotNull(ip);
assertEquals(16,ip.getBitDepth());
assertEquals(2,ip.getBytesPerPixel());
assertEquals(2,ip.getHeight());
assertEquals(3,ip.getWidth());
assertTrue(ip.getProcessor() instanceof ShortProcessor);
// test for a real 32 bit file
info = new FileInfo();
info.fileName = "gray32float-2x3-sub1.tif";
info.fileType = FileInfo.GRAY32_FLOAT;
info.height = 2;
info.width = 3;
info.directory = "data/";
fo = new FileOpener(info);
ip = fo.open(false);
assertNotNull(ip);
assertEquals(32,ip.getBitDepth());
assertEquals(4,ip.getBytesPerPixel());
assertEquals(2,ip.getHeight());
assertEquals(3,ip.getWidth());
assertTrue(ip.getProcessor() instanceof FloatProcessor);
// test for a real 24 bit file
info = new FileInfo();
info.fileName = "gray24-2x3-sub1.tif";
info.fileType = FileInfo.RGB;
info.height = 2;
info.width = 3;
info.directory = "data/";
fo = new FileOpener(info);
ip = fo.open(false);
assertNotNull(ip);
assertEquals(24,ip.getBitDepth());
assertEquals(4,ip.getBytesPerPixel());
assertEquals(2,ip.getHeight());
assertEquals(3,ip.getWidth());
assertTrue(ip.getProcessor() instanceof ColorProcessor);
// test for a 48 bit file - use fake data for now - also testing Property() setting/getting
info = new FileInfo();
info.fileName = "head8bit.tif";
info.fileType = FileInfo.RGB48_PLANAR;
info.height = 256;
info.width = 38;
info.directory = "data/";
info.info = "Yuletide Greetings";
info.sliceLabels = new String[] {"Carrots"};
fo = new FileOpener(info);
ip = fo.open(false);
assertNotNull(ip);
assertEquals(16,ip.getBitDepth());
assertEquals(2,ip.getBytesPerPixel());
assertEquals(256,ip.getHeight());
assertEquals(38,ip.getWidth());
assertTrue(ip.getProcessor() instanceof ShortProcessor);
assertNotNull(ip.getStack());
assertEquals("Red",ip.getStack().getSliceLabel(1));
assertEquals("Green",ip.getStack().getSliceLabel(2));
assertEquals("Blue",ip.getStack().getSliceLabel(3));
assertTrue(ip instanceof CompositeImage);
assertNotNull(ip.getStack());
assertEquals("Red",ip.getStack().getSliceLabel(1));
assertEquals("Green",ip.getStack().getSliceLabel(2));
assertEquals("Blue",ip.getStack().getSliceLabel(3));
assertTrue(ip instanceof CompositeImage);
assertEquals("Yuletide Greetings",ip.getProperty("Info"));
assertEquals("Carrots",ip.getProperty("Label"));
// try to open an image stack
info = new FileInfo();
info.fileName = "gray8-2x3-sub1.tif";
info.fileType = FileInfo.GRAY8;
info.nImages = 2;
info.height = 2;
info.width = 3;
info.directory = "data/";
fo = new FileOpener(info);
ip = fo.open(false);
assertNotNull(ip);
assertNotNull(ip.getStack());
}
@Test
public void testCreateColorModel() {
FileInfo fi;
ColorModel cm;
byte[] lutVals = new byte[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
// test non COLOR8 file
fi = new FileInfo();
fi.fileType = FileInfo.GRAY8;
fo = new FileOpener(fi);
cm = fo.createColorModel(fi);
assertTrue(cm instanceof IndexColorModel);
// assert its a gray scale lut
for (int i = 0; i < 256; i++)
{
assertEquals(i,cm.getRed(i));
assertEquals(i,cm.getGreen(i));
assertEquals(i,cm.getBlue(i));
}
// test a COLOR8 file with no attached lut data
fi = new FileInfo();
fi.fileType = FileInfo.COLOR8;
fi.lutSize = 0;
fo = new FileOpener(fi);
cm = fo.createColorModel(fi);
assertTrue(cm instanceof IndexColorModel);
// assert its a gray scale lut
for (int i = 0; i < 256; i++)
{
assertEquals(i,cm.getRed(i));
assertEquals(i,cm.getGreen(i));
assertEquals(i,cm.getBlue(i));
}
// test a COLOR8 file with lut info
fi = new FileInfo();
fi.fileType = FileInfo.COLOR8;
fi.lutSize = lutVals.length;
fi.reds = lutVals;
fi.greens = lutVals;
fi.blues = lutVals;
fo = new FileOpener(fi);
cm = fo.createColorModel(fi);
assertTrue(cm instanceof IndexColorModel);
for (int i = 0; i < lutVals.length; i++)
{
assertEquals(lutVals[i],cm.getRed(i));
assertEquals(lutVals[i],cm.getGreen(i));
assertEquals(lutVals[i],cm.getBlue(i));
}
}
@Test
public void testCreateInputStream() {
FileInfo fi;
InputStream istr;
// note - won't test URL subcase
// fi.inputStream != null
fi = new FileInfo();
fi.inputStream = new ByteArrayInputStream(new byte[] {1,2,3,4,5,6});
fi.height = 2;
fi.width = 3;
fo = new FileOpener(fi);
try {
istr = fo.createInputStream(fi);
assertNotNull(istr);
} catch (Exception e) {
fail();
}
// fi.inputStream != null and gzip
fi = new FileInfo();
fi.height = 2;
fi.width = 3;
fi.directory = "data/";
fi.fileName = "fake.gz";
try {
fi.inputStream = new FileInputStream("data/fake.gz");
fo = new FileOpener(fi);
istr = fo.createInputStream(fi);
assertNotNull(istr);
assertTrue(istr instanceof GZIPInputStream);
} catch (Exception e) {
System.out.println(e.getMessage());
fail();
}
// fi.inputStream != null and compression >= lzw
fi = new FileInfo();
fi.inputStream = new ByteArrayInputStream(new byte[] {1,2,3,4,5,6});
fi.height = 2;
fi.width = 3;
fi.compression = FileInfo.LZW;
fo = new FileOpener(fi);
try {
istr = fo.createInputStream(fi);
assertNotNull(istr);
assertTrue(istr instanceof RandomAccessStream);
} catch (Exception e) {
fail();
}
// fi.inputStream == null -> try to open file
// file is null
// can't get File to be null -- even on null input - this test may be impossible
// fi.inputStream == null -> try to open file
// file is directory
fi = new FileInfo();
// use a known directory name
fi.fileName = "data";
fo = new FileOpener(fi);
try {
istr = fo.createInputStream(fi);
assertNull(istr);
} catch (Exception e) {
System.out.println(e.getMessage());
fail();
}
// fi.inputStream == null -> try to open file
// can't validateFileInfo(file,fi)
fi = new FileInfo();
fo = new FileOpener(fi);
// 0 width and height should cause this subcase
try {
istr = fo.createInputStream(fi);
assertNull(istr);
} catch (Exception e) {
System.out.println(e.getMessage());
fail();
}
}
@Test
public void testDecodeDescriptionString() {
FileInfo fi;
Properties p;
// fi.decription == null
fi = new FileInfo();
fo = new FileOpener(fi);
assertNull(fo.decodeDescriptionString(fi));
// fi.decription len < 7
fi = new FileInfo();
fi.description = "123456";
fo = new FileOpener(fi);
assertNull(fo.decodeDescriptionString(fi));
// fi.decription not start with ImageJ
fi = new FileInfo();
fi.description = "NotImageJ";
fo = new FileOpener(fi);
assertNull(fo.decodeDescriptionString(fi));
// otherwise from here on out descrip must start with ImageJ
fi = new FileInfo();
fi.description = "ImageJ=1.43n1\nc0=0\nc1=1\nc2=2\nc3=3\nc4=4\nunit=millidevs\ncf=13\nvunit=peeps\nimages=704\nspacing=-48.5";
fo = new FileOpener(fi);
p = fo.decodeDescriptionString(fi);
assertNotNull(p);
assertEquals("1.43n1",p.getProperty("ImageJ"));
assertEquals("704",p.getProperty("images"));
assertEquals(704,fi.nImages);
assertEquals("13",p.getProperty("cf"));
assertEquals(13,fi.calibrationFunction);
assertEquals("millidevs",p.getProperty("unit"));
assertEquals("millidevs",fi.unit);
assertEquals("peeps",p.getProperty("vunit"));
assertEquals("peeps",fi.valueUnit);
assertEquals("-48.5",p.getProperty("spacing"));
assertEquals(48.5,fi.pixelDepth,Assert.DOUBLE_TOL);
assertEquals("0",p.getProperty("c0"));
assertEquals(0,fi.coefficients[0],Assert.DOUBLE_TOL);
assertEquals("1",p.getProperty("c1"));
assertEquals(1,fi.coefficients[1],Assert.DOUBLE_TOL);
assertEquals("2",p.getProperty("c2"));
assertEquals(2,fi.coefficients[2],Assert.DOUBLE_TOL);
assertEquals("3",p.getProperty("c3"));
assertEquals(3,fi.coefficients[3],Assert.DOUBLE_TOL);
assertEquals("4",p.getProperty("c4"));
assertEquals(4,fi.coefficients[4],Assert.DOUBLE_TOL);
}
@Test
public void testSetShowConflictMessage() {
// nothing is testable except existence
FileOpener.setShowConflictMessage(true);
FileOpener.setShowConflictMessage(false);
}
// In method below
// open image
// save orig info
// make some changes
// assert their values
// revert
// assert vals back to original
private void expectSuccess(String fname, int format, int nImages, int height, int width)
{
FileInfo fi;
ImagePlus ip;
int origPix,newPix;
fi = new FileInfo();
fi.directory = "data/";
fi.fileName = fname;
fi.fileFormat = format;
fi.nImages = nImages;
fi.height = height;
fi.width = width;
fo = new FileOpener(fi);
//ip = fo.open(false);
ip = new Opener().openImage("data/",fname);
assertNotNull(ip);
origPix = ip.getProcessor().getPixel(0,0);
ip.getProcessor().set(0,0,origPix+1);
newPix = ip.getProcessor().getPixel(0,0);
if (origPix == newPix)
fail("Failed to set pixel correctly");
//else
// System.out.println("OrigPix = "+origPix+" and newPix = "+newPix);
fo.revertToSaved(ip);
assertEquals(origPix,ip.getProcessor().getPixel(0,0));
}
private void expectSuccessReadPixelsCase(String fname, int format, int height, int width)
{
FileInfo fi;
ImagePlus ip;
int origPix,newPix;
fi = new FileInfo();
fi.directory = "data/";
fi.fileName = fname;
fi.fileFormat = format;
fi.nImages = 1;
fi.height = height;
fi.width = width;
fo = new FileOpener(fi);
ip = fo.open(false);
//ip = new Opener().openImage("data/",fname);
assertNotNull(ip);
origPix = ip.getProcessor().getPixel(0,0);
ip.getProcessor().set(0,0,origPix+1);
newPix = ip.getProcessor().getPixel(0,0);
if (origPix == newPix)
fail("Failed to set pixel correctly");
//else
// System.out.println("OrigPix = "+origPix+" and newPix = "+newPix);
fo.revertToSaved(ip);
assertEquals(origPix,ip.getProcessor().getPixel(0,0));
}
private void expectFailureReadPixelsCase(String fname, int format, int nImages, int height, int width)
{
FileInfo fi;
ImagePlus ip;
int origPix,newPix;
fi = new FileInfo();
fi.directory = "data/";
fi.fileName = fname;
fi.fileFormat = format;
fi.nImages = nImages;
fi.height = height;
fi.width = width;
fo = new FileOpener(fi);
ip = fo.open(false);
//ip = new Opener().openImage("data/",fname);
assertNotNull(ip);
origPix = ip.getProcessor().getPixel(0,0);
ip.getProcessor().set(0,0,origPix+1);
newPix = ip.getProcessor().getPixel(0,0);
if (origPix == newPix)
fail("Failed to set pixel correctly");
//else
// System.out.println("OrigPix = "+origPix+" and newPix = "+newPix);
fo.revertToSaved(ip);
assertFalse(origPix == ip.getProcessor().getPixel(0,0));
}
@Test
public void testRevertToSaved() {
// various file formats - supported ones
expectSuccess("blobs.gif",FileInfo.GIF_OR_JPG,1,254,256);
expectSuccess("Cell_Colony.jpg",FileInfo.GIF_OR_JPG,1,408,406);
expectSuccess("embryos.bmp",FileInfo.BMP,1,1200,1600);
expectSuccess("Tree_Rings.pgm",FileInfo.PGM,1,162,1796);
expectSuccess("bat-cochlea-renderings.fits",FileInfo.FITS,1,154,284);
expectSuccess("gray16.zip",FileInfo.ZIP_ARCHIVE,1,154,284);
expectSuccess("lena-std.png",FileInfo.IMAGEIO,1,154,284);
expectSuccess("01.dcm",FileInfo.DICOM,1,426,640);
// note - tifs failing - following up with Wayne
//expectSuccess("head8bit.tif",FileInfo.TIFF,1,228,256);
// fall through case -> it calls readPixels()
expectSuccessReadPixelsCase("clown.raw",FileInfo.UNKNOWN,100,100);
// nImages > 1 and not a special case file -> no reversion
expectFailureReadPixelsCase("clown.raw",FileInfo.UNKNOWN,2,256,228);
}
} |
package couk.doridori.android.lib.util;
import android.util.Log;
public class XLog {
private static final int NONE = 0;
private static final int ERRORS_ONLY = 1;
private static final int ERRORS_WARNINGS = 2;
private static final int ERRORS_WARNINGS_INFO = 3;
private static final int ERRORS_WARNINGS_INFO_DEBUG = 4;
private static final int ALL = 5;
private static final int LOGGING_LEVEL_FILTER = ALL;
private static final String TAG_NO_FILTER = "XLog";
static {
if(LOGGING_LEVEL_FILTER >= ALL)
Log.v(TAG_NO_FILTER, "ILog class reloaded");
}
public static void e(String text, Exception e) {
e(text + " : " + e.getClass().getName() + ": " + e.getMessage());
}
public static void e(String text) {
if (LOGGING_LEVEL_FILTER >= ERRORS_ONLY) {
Log.e(TAG_NO_FILTER, getTrace() + text);
}
}
public static void w(String text) {
if (LOGGING_LEVEL_FILTER >= ERRORS_WARNINGS) {
Log.w(TAG_NO_FILTER, getTrace() + text);
}
}
public static void i(String text) {
if (LOGGING_LEVEL_FILTER >= ERRORS_WARNINGS_INFO) {
Log.i(TAG_NO_FILTER, getTrace() + text);
}
}
public static void d() {
if (LOGGING_LEVEL_FILTER >= ERRORS_WARNINGS_INFO_DEBUG) {
Log.d(TAG_NO_FILTER, getTrace() + "<method>");
}
}
public static void d(Object obj){
if (LOGGING_LEVEL_FILTER >= ERRORS_WARNINGS_INFO_DEBUG) {
Log.d(obj.toString(), getTrace());
}
}
public static void d(String text) {
if (LOGGING_LEVEL_FILTER >= ERRORS_WARNINGS_INFO_DEBUG) {
Log.d(TAG_NO_FILTER, getTrace() + text);
}
}
public static void d(String tag, String text) {
if (LOGGING_LEVEL_FILTER >= ERRORS_WARNINGS_INFO_DEBUG) {
Log.d(tag, getTrace() + text);
}
}
public static void d(Object obj, String text) {
if (LOGGING_LEVEL_FILTER >= ERRORS_WARNINGS_INFO_DEBUG) {
Log.d(obj.getClass().getName(), getTrace() + text);
}
}
public static void v() {
if (LOGGING_LEVEL_FILTER >= ALL) {
Log.v(TAG_NO_FILTER, getTrace() + "<method>");
}
}
public static void v(String text) {
if (LOGGING_LEVEL_FILTER >= ALL) {
Log.v(TAG_NO_FILTER, getTrace() + text);
}
}
private static String getTrace() {
int depth = 2;
Throwable t = new Throwable();
StackTraceElement[] elements = t.getStackTrace();
String callerMethodName = elements[depth].getMethodName();
String callerClassPath = elements[depth].getClassName();
int lineNum = elements[depth].getLineNumber();
int i = callerClassPath.lastIndexOf('.');
String callerClassName = callerClassPath.substring(i + 1);
String trace = callerClassName + ": " + callerMethodName + "() [" + lineNum + "] - ";
return trace;
}
} |
package deltagruppen.circles;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Iterator;
import java.util.LinkedList;
public class DrawView extends View
{
private final LinkedList<PointF> points;
private final Paint paint;
public DrawView(Context context, AttributeSet attrs)
{
super(context, attrs);
points = new LinkedList<>();
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
paint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if (points.size() == 0) return;
Iterator<PointF> iterator = points.iterator();
PointF point = iterator.next();
while (iterator.hasNext()) {
PointF next = iterator.next();
canvas.drawLine(point.x, point.y, next.x, next.y, paint);
point = next;
}
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
points.clear();
points.add(new PointF(event.getX(), event.getY()));
invalidate();
return true;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
for (int i = 0; i < event.getHistorySize(); i++) {
points.add(new PointF(event.getHistoricalX(i), event.getHistoricalY(i)));
}
points.add(new PointF(event.getX(), event.getY()));
invalidate();
return true;
}
return false;
}
} |
package org.json.junit;
import static org.junit.Assert.*;
import org.json.*;
import org.junit.Test;
/**
* Unit tests for JSON-Java HTTP.java. See RFC7230.
*/
public class HTTPTest {
/**
* Attempt to call HTTP.toJSONObject() with a null string
* Expects a NUllPointerException.
*/
@Test(expected=NullPointerException.class)
public void nullHTTPException() {
String httpStr = null;
HTTP.toJSONObject(httpStr);
}
/**
* Attempt to call HTTP.toJSONObject() with a string containing
* an empty object. Expects a JSONException.
*/
@Test
public void notEnoughHTTPException() {
String httpStr = "{}";
JSONObject jsonObject = new JSONObject(httpStr);
try {
HTTP.toString(jsonObject);
assertTrue("Expected to throw exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Not enough material for an HTTP header.".equals(e.getMessage()));
}
}
/**
* Calling HTTP.toJSONObject() with an empty string will result in a
* populated JSONObject with keys but no values for Request-URI, Method,
* and HTTP-Version.
*/
@Test
public void emptyStringHTTPRequest() {
String httpStr = "";
String expectedHTTPStr = "{\"Request-URI\":\"\",\"Method\":\"\",\"HTTP-Version\":\"\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a Request-URI, Method,
* and HTTP-Version.
*/
@Test
public void simpleHTTPRequest() {
String httpStr = "GET /hello.txt HTTP/1.1";
String expectedHTTPStr =
"{\"Request-URI\":\"/hello.txt\",\"Method\":\"GET\",\"HTTP-Version\":\"HTTP/1.1\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a response string containing a
* HTTP-Version, Status-Code, and Reason.
*/
@Test
public void simpleHTTPResponse() {
String httpStr = "HTTP/1.1 200 OK";
String expectedHTTPStr =
"{\"HTTP-Version\":\"HTTP/1.1\",\"Status-Code\":\"200\",\"Reason-Phrase\":\"OK\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full request string including
* request headers.
*/
@Test
public void extendedHTTPRequest() {
String httpStr =
"POST /enlighten/calais.asmx HTTP/1.1\n"+
"Host: api.opencalais.com\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100\n"+
"SOAPAction: \"http://clearforest.com/Enlighten\"";
String expectedHTTPStr =
"{"+
"\"Request-URI\":\"/enlighten/calais.asmx\","+
"\"Host\":\"api.opencalais.com\","+
"\"Method\":\"POST\","+
"\"HTTP-Version\":\"HTTP/1.1\","+
"\"Content-Length\":\"100\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
/**
* Not too easy for JSONObject to parse a string with embedded quotes.
* For the sake of the test, add it here.
*/
expectedJsonObject.put("SOAPAction","\"http://clearforest.com/Enlighten\"");
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full response string including
* response headers.
*/
@Test
public void extendedHTTPResponse() {
String httpStr =
"HTTP/1.1 200 OK\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100\n";
String expectedHTTPStr =
"{\"HTTP-Version\":\"HTTP/1.1\","+
"\"Status-Code\":\"200\","+
"\"Content-Length\":\"100\","+
"\"Reason-Phrase\":\"OK\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full POST request string including
* response headers, then convert it back into an HTTP string.
*/
@Test
public void convertHTTPRequestToString() {
String httpStr =
"POST /enlighten/calais.asmx HTTP/1.1\n"+
"Host: api.opencalais.com\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100";
String expectedHTTPStr =
"{"+
"\"Request-URI\":\"/enlighten/calais.asmx\","+
"\"Host\":\"api.opencalais.com\","+
"\"Method\":\"POST\","+
"\"HTTP-Version\":\"HTTP/1.1\","+
"\"Content-Length\":\"100\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
String httpToStr = HTTP.toString(jsonObject);
/**
* JSONObject objects to crlfs and any trailing chars.
* For the sake of the test, simplify the resulting string
*/
httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", "");
httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n");
JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full response string including
* response headers, then convert it back into an HTTP string.
*/
@Test
public void convertHTTPResponseToString() {
String httpStr =
"HTTP/1.1 200 OK\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100\n";
String expectedHTTPStr =
"{\"HTTP-Version\":\"HTTP/1.1\","+
"\"Status-Code\":\"200\","+
"\"Content-Length\":\"100\","+
"\"Reason-Phrase\":\"OK\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
String httpToStr = HTTP.toString(jsonObject);
/**
* JSONObject objects to crlfs and any trailing chars.
* For the sake of the test, simplify the resulting string
*/
httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", "");
httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n");
JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
} |
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.DefaultListModel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
@SuppressWarnings("serial")
public class Frame extends JFrame {
private JPanel contentPane;
private JTextField txtName;
private JMenuItem mntmExit;
private JList<String> listA;
private JList<String> listB;
private DefaultListModel<String> nameA;
private DefaultListModel<String> nameB;
private Random rand = new MersenneTwister();
private static final int RETRY_MAX = 5000000;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame frame = new Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Frame() {
setTitle("Pair Up");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 500);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
JMenuItem mntmClear = new JMenuItem("Clear");
mntmClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nameA.clear();
nameB.clear();
}
});
mnFile.add(mntmClear);
mnFile.add(mntmExit);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
this.listB = new JList<String>();
nameB = new DefaultListModel<String>();
listB.setModel(nameB);
listB.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
listB.setBounds(223, 45, 201, 322);
contentPane.add(listB);
this.listA = new JList<String>();
listA.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE){
if (listA.getSelectedIndex() >= 0){
nameA.remove(listA.getSelectedIndex());
}
}
}
});
nameA = new DefaultListModel<String>();
listA.setModel(nameA);
listA.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
listA.setBounds(12, 45, 201, 322);
contentPane.add(listA);
txtName = new JTextField();
txtName.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_ENTER){
//add a name only if the text is greater than 0 trimmed
if (txtName.getText().trim().length()>0){
nameA.addElement(txtName.getText());
txtName.setText(""); //clear text when added
}
}
}
});
txtName.setBounds(10, 14, 128, 20);
contentPane.add(txtName);
txtName.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//add a name only if the text is greater than 0 trimmed
if (txtName.getText().trim().length()>0){
nameA.addElement(txtName.getText());
txtName.setText(""); //clear text when added
}
}
});
btnAdd.setBounds(148, 13, 65, 23);
contentPane.add(btnAdd);
JButton btnRandomize = new JButton("Pair Up");
btnRandomize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pairUp();
}
});
btnRandomize.setFont(new Font("Tahoma", Font.BOLD, 14));
btnRandomize.setBounds(155, 398, 124, 32);
contentPane.add(btnRandomize);
JLabel lblPartnerA = new JLabel("Partner A");
lblPartnerA.setBounds(12, 373, 65, 14);
contentPane.add(lblPartnerA);
JLabel lblPartnerB = new JLabel("Partner B");
lblPartnerB.setBounds(223, 373, 65, 14);
contentPane.add(lblPartnerB);
JButton btnClear = new JButton("Clear");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nameA.clear();
nameB.clear();
}
});
btnClear.setBounds(12, 405, 65, 23);
contentPane.add(btnClear);
}
/**
* Pairs up the list of names in A randomly with other members
* in list A.
* Output is a list of names in B corresponding to the pairs on
* A, where there are no reflexive relations.
*/
private void pairUp(){
if (nameA.size() <= 1){
JOptionPane.showMessageDialog(this, "Enter at least two items to start pair up.", "Information", JOptionPane.INFORMATION_MESSAGE);
}
else{
//clear the old list
nameB.clear();
String[] names = new String[nameA.size()];
nameA.copyInto(names);
//convert array to collections
ArrayList<String> raw = new ArrayList<String>(names.length);
for (String s : names){
raw.add(s);
}
//shuffle, ensure that pairing is not the same.
int retryCount = 0;
boolean validShuffle = false;
while (validShuffle == false){
Collections.shuffle(raw, rand);
validShuffle = true;
for (int i =0; i < names.length ; i++){
if (names[i].equals(raw.get(i))){
//retry shuffle
validShuffle = false;
}
}
retryCount++;
if (retryCount >= RETRY_MAX){
int response = JOptionPane.showConfirmDialog(this, "Shuffler has tried " + RETRY_MAX + " times to pair the list but has had no success. It is likely that there is no solution for a small set of data. \n\nAbort?", "Application Deadlock", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.YES_OPTION){
break;
}
retryCount =0;
}
}
//valid shuffle, display on screen
for(String s : raw){
nameB.addElement(s);
}
}
}
} |
package ai.grakn.remote;
import ai.grakn.GraknSession;
import ai.grakn.GraknTx;
import ai.grakn.GraknTxType;
import ai.grakn.QueryRunner;
import ai.grakn.concept.Attribute;
import ai.grakn.concept.AttributeType;
import ai.grakn.concept.Concept;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.EntityType;
import ai.grakn.concept.Label;
import ai.grakn.concept.RelationshipType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Rule;
import ai.grakn.concept.SchemaConcept;
import ai.grakn.concept.Type;
import ai.grakn.exception.InvalidKBException;
import ai.grakn.graql.Graql;
import ai.grakn.graql.Pattern;
import ai.grakn.graql.QueryBuilder;
import ai.grakn.graql.Var;
import ai.grakn.graql.VarPattern;
import ai.grakn.graql.admin.Answer;
import ai.grakn.graql.internal.query.QueryBuilderImpl;
import ai.grakn.grpc.GrpcUtil;
import ai.grakn.kb.admin.GraknAdmin;
import ai.grakn.rpc.generated.GraknGrpc;
import ai.grakn.rpc.generated.GraknOuterClass.TxRequest;
import ai.grakn.util.Schema;
import com.google.common.collect.ImmutableSet;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static ai.grakn.graql.Graql.var;
import static ai.grakn.util.Schema.MetaSchema.ATTRIBUTE;
import static ai.grakn.util.Schema.MetaSchema.ENTITY;
import static ai.grakn.util.Schema.MetaSchema.RELATIONSHIP;
import static ai.grakn.util.Schema.MetaSchema.ROLE;
import static ai.grakn.util.Schema.MetaSchema.RULE;
/**
* Remote implementation of {@link GraknTx} and {@link GraknAdmin} that communicates with a Grakn server using gRPC.
*
* <p>
* Most of the gRPC legwork is handled in the embedded {@link GrpcClient}. This class is an adapter to that,
* translating Java calls into gRPC messages.
* </p>
*
* @author Felix Chapman
*/
public final class RemoteGraknTx implements GraknTx, GraknAdmin {
private final GraknSession session;
private final GraknTxType txType;
private final GrpcClient client;
private RemoteGraknTx(GraknSession session, GraknTxType txType, GrpcClient client) {
this.session = session;
this.txType = txType;
this.client = client;
}
// TODO: ideally the transaction should not hold a reference to the session or at least depend on a session interface
public static RemoteGraknTx create(RemoteGraknSession session, TxRequest openRequest) {
GraknGrpc.GraknStub stub = session.stub();
GrpcClient client = GrpcClient.create(stub);
client.open(openRequest);
return new RemoteGraknTx(session, GrpcUtil.convert(openRequest.getOpen().getTxType()), client);
}
public GrpcClient client() {
return client;
}
@Override
public EntityType putEntityType(Label label) {
return putSchemaConcept(label, ENTITY);
}
@Override
public <V> AttributeType<V> putAttributeType(Label label, AttributeType.DataType<V> dataType) {
return putSchemaConcept(label, ATTRIBUTE, var -> var.datatype(dataType));
}
@Override
public Rule putRule(Label label, Pattern when, Pattern then) {
return putSchemaConcept(label, RULE, var -> var.when(when).then(then));
}
@Override
public RelationshipType putRelationshipType(Label label) {
return putSchemaConcept(label, RELATIONSHIP);
}
@Override
public Role putRole(Label label) {
return putSchemaConcept(label, ROLE);
}
private <X extends SchemaConcept> X putSchemaConcept(Label label, Schema.MetaSchema meta){
return putSchemaConcept(label, meta, null);
}
private <X extends SchemaConcept> X putSchemaConcept(Label label, Schema.MetaSchema meta,
@Nullable Function<VarPattern, VarPattern> extender){
Var var = var("x");
VarPattern pattern = var.label(label).sub(var().label(meta.getLabel()));
if(extender != null) pattern = extender.apply(pattern);
return (X) queryRunner().run(Graql.define(pattern)).get(var);
}
@Nullable
@Override
public <T extends Concept> T getConcept(ConceptId id) {
Var var = var("x");
VarPattern pattern = var.id(id);
Optional<Answer> answer = queryRunner().run(Graql.match(pattern).get(ImmutableSet.of(var))).findAny();
return answer.map(answer1 -> (T) answer1.get(var)).orElse(null);
}
@Nullable
@Override
public <T extends SchemaConcept> T getSchemaConcept(Label label) {
return getSchemaConcept(label, null);
}
@Nullable
@Override
public <T extends Type> T getType(Label label) {
return getSchemaConcept(label);
}
@Override
public <V> Collection<Attribute<V>> getAttributesByValue(V value) {
Var var = var("x");
VarPattern pattern = var.val(value);
Stream<Answer> answer = queryRunner().run(Graql.match(pattern).get(ImmutableSet.of(var)));
return answer.map(a -> (Attribute<V>) a.get(var)).collect(Collectors.toList());
}
@Nullable
@Override
public EntityType getEntityType(String label) {
return getSchemaConcept(Label.of(label), ENTITY);
}
@Nullable
@Override
public RelationshipType getRelationshipType(String label) {
return getSchemaConcept(Label.of(label), RELATIONSHIP);
}
@Nullable
@Override
public <V> AttributeType<V> getAttributeType(String label) {
return getSchemaConcept(Label.of(label), ATTRIBUTE);
}
@Nullable
@Override
public Role getRole(String label) {
return getSchemaConcept(Label.of(label), ROLE);
}
@Nullable
@Override
public Rule getRule(String label) {
return getSchemaConcept(Label.of(label), RULE);
}
@Nullable
private <X extends SchemaConcept> X getSchemaConcept(Label label, @Nullable Schema.MetaSchema meta){
Var var = var("x");
VarPattern pattern = var.label(label);
if(meta != null) pattern = pattern.sub(var().label(meta.getLabel()));
Optional<Answer> result = queryRunner().run(Graql.match(pattern).get()).findAny();
return result.map(answer -> (X) answer.get(var)).orElse(null);
}
@Override
public GraknAdmin admin() {
return this;
}
@Override
public GraknTxType txType() {
return txType;
}
@Override
public GraknSession session() {
return session;
}
@Override
public boolean isClosed() {
return client.isClosed();
}
@Override
public QueryBuilder graql() {
return new QueryBuilderImpl(this);
}
@Override
public void close() {
client.close();
}
@Override
public void commit() throws InvalidKBException {
client.commit();
close();
}
@Override
public Stream<SchemaConcept> sups(SchemaConcept schemaConcept) {
throw new UnsupportedOperationException(); // TODO
}
@Override
public void delete() {
throw new UnsupportedOperationException(); // TODO
}
@Override
public QueryRunner queryRunner() {
return RemoteQueryRunner.create(this, client, null);
}
} |
package org.genericsystem.cv;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
public class MotionDetector2 extends AbstractApp {
static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
launch(args);
}
private final VideoCapture capture = new VideoCapture(0);
private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
@Override
protected void fillGrid(GridPane mainGrid) {
Mat frame = new Mat();
capture.read(frame);
ImageView src = new ImageView(Tools.mat2jfxImage(frame));
ImageView src2 = new ImageView(Tools.mat2jfxImage(frame));
ImageView src3 = new ImageView(Tools.mat2jfxImage(frame));
ImageView src4 = new ImageView(Tools.mat2jfxImage(frame));
mainGrid.add(src, 0, 0);
mainGrid.add(src2, 1, 0);
mainGrid.add(src3, 0, 1);
mainGrid.add(src4, 1, 1);
timer.scheduleAtFixedRate(() -> {
try {
capture.read(frame);
Img adaptativThreshold = new Img(frame).cvtColor(Imgproc.COLOR_BGR2GRAY).adaptativeThresHold(255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 17, 9);
Img closed = adaptativThreshold.morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_ELLIPSE, new Size(11, 7));
Img frameCopy = new Img(frame);
double angle = detection_contours(frame, closed.getSrc());
Mat matrix = Imgproc.getRotationMatrix2D(new Point(frame.width() / 2, frame.height() / 2), angle, 1);
Mat rotated = new Mat();
Imgproc.warpAffine(frameCopy.getSrc(), rotated, matrix, new Size(frame.size().width, frame.size().height));
double crop = 0.15;
Img croppedImg = new Img(new Mat(rotated, new Rect(Double.valueOf(rotated.width() * crop).intValue(), Double.valueOf(rotated.height() * crop).intValue(), Double.valueOf(rotated.width() * (1 - 2 * crop)).intValue(),
Double.valueOf(rotated.height() * (1 - 2 * crop)).intValue())));
src.setImage(Tools.mat2jfxImage(closed.getSrc()));
src2.setImage(Tools.mat2jfxImage(frame));
Img croppedAdaptativ = croppedImg.cvtColor(Imgproc.COLOR_BGR2GRAY).adaptativeThresHold(255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 17, 9);
Img croppedDilated = croppedAdaptativ.morphologyEx(Imgproc.MORPH_DILATE, Imgproc.MORPH_RECT, new Size(15, 3));
detection_deskiew_contours(croppedImg.getSrc(), croppedDilated.getSrc());
// croppedImg.recursivSplit(5, true);
src3.setImage(Tools.mat2jfxImage(croppedDilated.getSrc()));
src4.setImage(Tools.mat2jfxImage(croppedImg.getSrc()));
} catch (Exception e) {
e.printStackTrace();
}
}, 0, 33, TimeUnit.MILLISECONDS);
}
public double detection_contours(Mat frame, Mat dilated) {
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(dilated, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
double minArea = 100;
double crop = 0.10;
Predicate<RotatedRect> filter = rect -> rect.center.x > Double.valueOf(frame.width() * crop).intValue() && rect.center.y > Double.valueOf(frame.height() * crop).intValue() && rect.center.x < Double.valueOf(frame.width() * (1 - crop)).intValue()
&& rect.center.y < Double.valueOf(frame.height() * (1 - crop)).intValue();
List<RotatedRect> rotatedRects = contours.stream().filter(contour -> Imgproc.contourArea(contour) > minArea).map(contour -> Imgproc.minAreaRect(new MatOfPoint2f(contour.toArray()))).filter(filter).collect(Collectors.toList());
double mean = 0;
for (RotatedRect rotatedRect : rotatedRects) {
if (rotatedRect.angle < -45.) {
rotatedRect.angle += 90.0;
double tmp = rotatedRect.size.width;
rotatedRect.size.width = rotatedRect.size.height;
rotatedRect.size.height = tmp;
}
mean += rotatedRect.angle;
}
final double average = mean / rotatedRects.size();
List<RotatedRect> goodRects = rotatedRects.stream().filter(rotatedRect -> Math.abs(rotatedRect.angle - average) < 10).collect(Collectors.toList());
double goodRectsMean = 0;
for (RotatedRect rotatedRect : goodRects) {
goodRectsMean += rotatedRect.angle;
}
final double goodAverage = goodRectsMean / goodRects.size();
goodRects.forEach(rotatedRect -> rotatedRect.angle = goodAverage);
System.out.println(average);
System.out.println(goodAverage);
goodRects.forEach(rotatedRect -> {
Point[] result = new Point[4];
rotatedRect.points(result);
List<MatOfPoint> mof = Collections.singletonList(new MatOfPoint(new MatOfPoint(result)));
Imgproc.drawContours(frame, mof, 0, new Scalar(0, 255, 0), 1);
// Imgproc.drawContours(dilated, mof, 0, new Scalar(255), 1);
});
return goodAverage;
}
public void detection_deskiew_contours(Mat frame, Mat dilated) {
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(dilated, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
double minArea = 100;
List<Rect> rects = contours.stream().filter(contour -> Imgproc.contourArea(contour) > minArea).map(contour -> Imgproc.boundingRect(contour)).collect(Collectors.toList());
rects.forEach(rect -> Imgproc.rectangle(frame, rect.tl(), rect.br(), new Scalar(0, 255, 0), 1));
}
@Override
public void stop() throws Exception {
timer.shutdown();
capture.release();
super.stop();
}
} |
package lecho.lib.hellocharts.model;
import java.util.Collections;
import java.util.List;
import android.graphics.Color;
public class Line {
private List<LinePoint> points = Collections.emptyList();
private LineStyle style = new LineStyle();
public Line(List<LinePoint> points) {
setPoints(points);
}
public void setPoints(List<LinePoint> points) {
if (null == points) {
this.points = Collections.emptyList();
} else {
this.points = points;
}
}
public List<LinePoint> getPoints() {
return this.points;
}
public LineStyle getStyle() {
return style;
}
public void setStyle(LineStyle lineStyle) {
if (null == lineStyle) {
this.style = new LineStyle();
} else {
this.style = lineStyle;
}
}
public interface LineValueFormatter {
public static final String DEFAULT_LINE_VALUE_FORMAT = "%.0f";
public String formatValue(LinePoint linePoint);
}
public static class DefaultLineValueFormatter implements LineValueFormatter {
@Override
public String formatValue(LinePoint linePoint) {
return String.format(DEFAULT_LINE_VALUE_FORMAT, linePoint.getY());
}
}
public static class LineStyle {
public static final int DEFAULT_LINE_VALUE_TEXT_SIZE_SP = 10;
public static final int DEFAULT_LINE_WIDTH_DP = 3;
public static final int DEFAULT_POINT_RADIUS_DP = 6;
public static final int DEFAULT_AREA_TRANSPARENCY = 64;
private int color = Color.LTGRAY;
private int textColor = Color.WHITE;
private int textSize = DEFAULT_LINE_VALUE_TEXT_SIZE_SP;
private int lineWidth = DEFAULT_LINE_WIDTH_DP;
private int pointRadius = DEFAULT_POINT_RADIUS_DP;
private int areaTransparency = DEFAULT_AREA_TRANSPARENCY;
private boolean hasPoints = true;
private boolean hasLines = true;
private boolean hasAnnotations = false;
private boolean isSmooth = false;
private boolean isFilled = false;
private LineValueFormatter lineValueFormatter = new DefaultLineValueFormatter();
public int getColor() {
return color;
}
public LineStyle setColor(int color) {
this.color = color;
return this;
}
public int getTextColor() {
return textColor;
}
public LineStyle setTextColor(int textColor) {
this.textColor = textColor;
return this;
}
public int getTextSize() {
return textSize;
}
public LineStyle setTextSize(int textSize) {
this.textSize = textSize;
return this;
}
public int getLineWidth() {
return lineWidth;
}
public LineStyle setLineWidth(int lineWidth) {
this.lineWidth = lineWidth;
return this;
}
public int getPointRadius() {
return pointRadius;
}
public LineStyle setPointRadius(int pointRadius) {
this.pointRadius = pointRadius;
return this;
}
public int getAreaTransparency() {
return areaTransparency;
}
public LineStyle setAreaTransparency(int areaTransparency) {
this.areaTransparency = areaTransparency;
return this;
}
public boolean hasPoints() {
return hasPoints;
}
public LineStyle setHasPoints(boolean hasPoints) {
this.hasPoints = hasPoints;
return this;
}
public boolean hasLines() {
return hasLines;
}
public LineStyle setHasLines(boolean hasLines) {
this.hasLines = hasLines;
return this;
}
public boolean hasAnnotations() {
return hasAnnotations;
}
public LineStyle setHasAnnotations(boolean hasAnnotations) {
this.hasAnnotations = hasAnnotations;
return this;
}
public boolean isSmooth() {
return isSmooth;
}
public LineStyle setSmooth(boolean isSmooth) {
this.isSmooth = isSmooth;
return this;
}
public boolean isFilled() {
return isFilled;
}
public LineStyle setFilled(boolean isFilled) {
this.isFilled = isFilled;
return this;
}
public LineValueFormatter getLineValueFormatter() {
return lineValueFormatter;
}
public LineStyle setLineValueFormatter(LineValueFormatter lineValueFormatter) {
if (null == lineValueFormatter) {
this.lineValueFormatter = new DefaultLineValueFormatter();
} else {
this.lineValueFormatter = lineValueFormatter;
}
return this;
}
}
} |
package roart.action;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import roart.common.config.ConfigConstants;
import roart.common.constants.Constants;
import roart.common.pipeline.PipelineConstants;
import roart.common.util.JsonUtil;
import roart.common.util.TimeUtil;
import roart.component.Component;
import roart.component.ComponentFactory;
import roart.component.model.ComponentData;
import roart.component.model.ComponentInput;
import roart.config.IclijXMLConfig;
import roart.constants.IclijConstants;
import roart.db.IclijDbDao;
import roart.iclij.config.IclijConfig;
import roart.iclij.config.MLConfig;
import roart.iclij.config.MLConfigs;
import roart.iclij.config.Market;
import roart.iclij.model.IncDecItem;
import roart.iclij.model.MapList;
import roart.iclij.model.MemoryItem;
import roart.iclij.model.Parameters;
import roart.iclij.model.TimingItem;
import roart.iclij.model.Trend;
import roart.iclij.model.WebData;
import roart.service.ControlService;
import roart.service.model.ProfitData;
import roart.service.model.ProfitInputData;
import roart.util.ServiceUtil;
public abstract class MarketAction extends Action {
private Logger log = LoggerFactory.getLogger(this.getClass());
protected abstract List<IncDecItem> getIncDecItems();
protected abstract List getAnArray();
protected abstract Boolean getBool();
public abstract String getName();
protected abstract List<String> getProfitComponents(IclijConfig config, String marketName);
public abstract Short getTime(Market market);
public abstract Boolean[] getBooleans();
protected abstract boolean getEvolve(Component component, ComponentData param);
protected abstract List<MemoryItem> getMemItems(MarketComponentTime marketTime, WebData myData, ComponentData param, IclijConfig config, Boolean evolve, Map<String, ComponentData> dataMap);
protected abstract LocalDate getPrevDate(ComponentData param, Market market);
protected abstract void setValMap(ComponentData param);
public abstract ComponentFactory getComponentFactory();
public abstract int getPriority(IclijConfig conf);
public int getPriority(IclijConfig conf, String key) {
Integer value = (Integer) conf.getConfigValueMap().get(key + "[@priority]");
return value != null ? value : 0;
}
@Override
public void goal(Action parent, ComponentData param, Integer priority) {
getMarkets(parent, new ComponentInput(IclijXMLConfig.getConfigInstance(), null, null, null, 0, true, false, new ArrayList<>(), new HashMap<>()), null, priority);
}
public WebData getMarket(Action parent, ComponentData param, Market market, Boolean evolve, Integer priority) {
List<Market> markets = new ArrayList<>();
markets.add(market);
return getMarkets(parent, param, markets, new ArrayList<>(), evolve, priority);
}
public WebData getMarkets(Action parent, ComponentInput input, Boolean evolve, Integer priority) {
List<TimingItem> timings = null;
try {
timings = IclijDbDao.getAllTiming();
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
List<Market> markets = getMarkets();
ComponentData param = null;
try {
param = ServiceUtil.getParam(input, 0);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return getMarkets(parent, param, markets, timings, evolve, priority);
}
private WebData getMarkets(Action parent, ComponentData paramTemplate, List<Market> markets, List<TimingItem> timings, Boolean evolve, Integer priority) {
// test picks for aggreg recommend, predict etc
// remember and make confidence
// memory is with date, confidence %, inc/dec, semantic item
// find recommended picks
WebData myData = new WebData();
myData.incs = new ArrayList<>();
myData.decs = new ArrayList<>();
myData.updateMap = new HashMap<>();
myData.timingMap = new HashMap<>();
myData.updateMap2 = new HashMap<>();
myData.timingMap2 = new HashMap<>();
markets = filterMarkets(markets);
IclijConfig config = paramTemplate.getInput().getConfig();
List<MarketComponentTime> marketTimes = new ArrayList<>();
Map<String, ComponentData> componentDataMap = new HashMap<>();
for (Market market : markets) {
String marketName = market.getConfig().getMarket();
ComponentInput input = new ComponentInput(config, null, marketName, null, 0, paramTemplate.getInput().isDoSave(), false, new ArrayList<>(), new HashMap<>());
ComponentData param = null;
try {
param = ServiceUtil.getParam(input, 0);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
param.setAction(getName());
ControlService srv = new ControlService();
//srv.getConfig();
param.setService(srv);
srv.conf.setMarket(market.getConfig().getMarket());
if (!isDataset()) {
List<String> stockDates = param.getService().getDates(marketName);
if (stockDates == null || stockDates.isEmpty()) {
continue;
}
}
componentDataMap.put(marketName, param);
LocalDate olddate = param.getInput().getEnddate();
try {
//param.setFuturedays(market.getFilter().getRecordage());
//param.setDates(market.getFilter().getRecordage(), 0, TimeUtil.convertDate2(olddate));
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
Short time = getTime(market);
if (getTime(market) == null) {
continue;
}
List<TimingItem> currentTimings = ServiceUtil.getCurrentTimings(olddate, timings, market, getName(), time);
List<IncDecItem> currentIncDecs = null; // ServiceUtil.getCurrentIncDecs(olddate, incdecitems, market);
if (true) {
List<String> componentList = getProfitComponents(config, marketName);
Map<String, Component> componentMap = getComponentMap(componentList, market);
Map<String, Component> componentMapFiltered = new HashMap<>();
for (Entry<String, Component> entry : componentMap.entrySet()) {
int mypriority = getPriority(config) + entry.getValue().getPriority(config);
if (priority == null || (mypriority >= priority && mypriority < (priority + 9))) {
componentMapFiltered.put(entry.getKey(), entry.getValue());
}
}
List<MarketComponentTime> marketTime = getList(getName(), componentMapFiltered, timings, market, param, currentTimings);
marketTimes.addAll(marketTime);
} else {
int jj = 0;
}
}
Collections.sort(marketTimes, (o1, o2) -> (Double.valueOf(o2.time).compareTo(Double.valueOf(o1.time))));
List<MarketComponentTime> run = marketTimes.stream().filter(m -> m.haverun).collect(Collectors.toList());
List<MarketComponentTime> notrun = marketTimes.stream().filter(m -> !m.haverun).collect(Collectors.toList());
for (MarketComponentTime marketTime : marketTimes) {
log.info("MarketTime {}", marketTime);
}
for (MarketComponentTime marketTime : notrun) {
if (marketTime.time == 0.0) {
ComponentData param = componentDataMap.get(marketTime.market.getConfig().getMarket());
getPicksFiltered(myData, param, config, marketTime, evolve);
}
}
for (MarketComponentTime marketTime : notrun) {
if (marketTime.time > 0.0) {
if (config.serverShutdownHour() != null) {
int shutdown = config.serverShutdownHour();
shutdown
LocalTime now = LocalTime.now();
int minutes = 60 * now.getHour() + now.getMinute();
minutes += marketTime.time / 60;
if (minutes >= shutdown * 60) {
continue;
}
}
ComponentData param = componentDataMap.get(marketTime.market.getConfig().getMarket());
getPicksFiltered(myData, param, config, marketTime, evolve);
}
}
for (MarketComponentTime marketTime : run) {
if (marketTime.time == 0.0) {
log.error("should not be here");
}
if (marketTime.time > 0.0) {
if (config.serverShutdownHour() != null) {
int shutdown = config.serverShutdownHour();
shutdown
LocalTime now = LocalTime.now();
int minutes = 60 * now.getHour() + now.getMinute();
minutes += marketTime.time / 60;
if (minutes >= shutdown * 60) {
continue;
}
}
ComponentData param = componentDataMap.get(marketTime.market.getConfig().getMarket());
getPicksFiltered(myData, param, config, marketTime, evolve);
}
}
return myData;
}
protected boolean isDataset() {
return false;
}
public List<Market> filterMarkets(List<Market> markets) {
List<Market> filtered = new ArrayList<>();
for (Market market : markets) {
Boolean dataset = market.getConfig().getDataset();
boolean adataset = dataset != null && dataset;
if (adataset == isDataset()) {
filtered.add(market);
}
}
return filtered;
}
private static final int AVERAGE_SIZE = 5;
private List<MarketComponentTime> getList(String action, Map<String, Component> componentMap, List<TimingItem> timings, Market market, ComponentData param, List<TimingItem> currentTimings) {
List<MarketComponentTime> marketTimes = new ArrayList<>();
String marketName = market.getConfig().getMarket();
//= ServiceUtil.getFindProfitComponents(config);
for (Entry<String, Component> entry : componentMap.entrySet()) {
String componentName = entry.getKey();
Component component = entry.getValue();
boolean evolve = getEvolve(component, param);
Double[] thresholds = getThresholds(param.getInput().getConfig());
Integer[] futuredays = getFuturedays(param.getInput().getConfig());
List<String> subComponents = component.getSubComponents(market, param, null);
for(String subComponent : subComponents) {
for (Integer aFutureday : futuredays) {
for (Double threshold : thresholds) {
Parameters parameters = new Parameters();
parameters.setThreshold(threshold);
parameters.setFuturedays(aFutureday);
String parameterString = JsonUtil.convert(parameters);
Boolean[] booleans = getBooleans();
for (Boolean buy : booleans) {
List<TimingItem> currentTimingFiltered = currentTimings.stream().filter(m -> m != null
&& componentName.equals(m.getComponent())
&& (subComponents == null || subComponent.equals(m.getSubcomponent()))
&& (m.getParameters() == null || parameterString.equals(m.getParameters()))
&& (buy == null || ((m.getBuy() == null || m.getBuy() == buy)))).collect(Collectors.toList());
if (!currentTimingFiltered.isEmpty()) {
continue;
}
//List<TimingItem> timingToDo = new ArrayList<>();
MarketComponentTime marketTime = new MarketComponentTime();
marketTime.market = market;
marketTime.componentName = componentName;
marketTime.component = component;
marketTime.subcomponent = subComponent;
marketTime.parameters = parameters;
//marketTime.timings = timingToDo;
marketTime.buy = buy;
List<TimingItem> filterTimingsEvolution = getMyTimings(timings, marketName, action, componentName, true, buy, subComponent, parameters);
if (evolve) {
handleFilterTimings(action, market, marketTime, componentName, filterTimingsEvolution, evolve, param.getInput().getEnddate(), buy, timings, subComponent, parameters);
}
// evolve is not false
if (getName().equals(IclijConstants.FINDPROFIT)) {
List<TimingItem> filterTimings = getMyTimings(timings, marketName, action, componentName, false, buy, subComponent, parameters);
handleFilterTimings(action, market, marketTime, componentName, filterTimings, evolve, param.getInput().getEnddate(), buy, timings, subComponent, parameters);
}
marketTimes.add(marketTime);
}
}
}
}
}
return marketTimes;
}
private void handleFilterTimings(String action, Market market, MarketComponentTime marketTime,
String component, List<TimingItem> filterTimings, boolean evolve, LocalDate date, Boolean buy, List<TimingItem> timings, String subComponent, Parameters parameters) {
if (!filterTimings.isEmpty()) {
Collections.sort(filterTimings, (o1, o2) -> (o2.getDate().compareTo(o1.getDate())));
LocalDate olddate = date.minusDays(((long) AVERAGE_SIZE) * getTime(market));
OptionalDouble average = getAverage(filterTimings);
if (olddate.isBefore(filterTimings.get(0).getDate())) {
// no recent enough is found
marketTime.time += average.orElse(0);
if (!evolve) {
marketTime.time += average.orElse(0);
}
marketTime.haverun = true;
} else {
// recent enough is found
// nothing to do
log.error("should not be here");
}
} else {
List<TimingItem> filterTimingsEvolution = getMyTimings(timings, action, component, evolve, buy, subComponent, parameters);
OptionalDouble average = getAverage(filterTimingsEvolution);
marketTime.time += average.orElse(0);
if (!evolve) {
marketTime.time += average.orElse(0);
}
marketTime.haverun = false;
}
}
private OptionalDouble getAverage(List<TimingItem> timings) {
Collections.sort(timings, (o1, o2) -> (o2.getDate().compareTo(o1.getDate())));
int size = Math.min(AVERAGE_SIZE, timings.size());
return timings
.subList(0, size)
.stream()
.mapToDouble(TimingItem::getMytime)
.average();
}
public MarketComponentTime getMCT(String componentName, Component component, String subcomponent, Market market, double time, boolean haverun, Boolean buy, Parameters parameters) {
MarketComponentTime mct = new MarketComponentTime();
mct.componentName = componentName;
mct.component = component;
mct.subcomponent = subcomponent;
mct.market = market;
mct.time = time;
mct.haverun = haverun;
mct.buy = buy;
mct.parameters = parameters;
return mct;
}
public class MarketComponentTime {
String componentName;
Component component;
String subcomponent;
Market market;
double time;
boolean haverun;
//List<TimingItem> timings;
Boolean buy;
Parameters parameters;
@Override
public String toString() {
String paramString = JsonUtil.convert(parameters);
return market.getConfig().getMarket() + " " + componentName + " " + subcomponent + " " + paramString + " " + buy + " " + time + " " + haverun;
}
}
private List<TimingItem> getMyTimings(List<TimingItem> timings, String market, String action, String component, boolean evolve, Boolean buy, String subcomponent, Parameters parameters) {
List<TimingItem> filterTimings = new ArrayList<>();
String paramString = JsonUtil.convert(parameters);
for (TimingItem timing : timings) {
if (buy != null && timing.getBuy() != null && buy != timing.getBuy()) {
continue;
}
if (market.equals(timing.getMarket()) && action.equals(timing.getAction()) && component.equals(timing.getComponent()) && subcomponent.equals(timing.getSubcomponent()) && evolve == timing.isEvolve() && paramString == timing.getParameters()) {
filterTimings.add(timing);
}
}
return filterTimings;
}
private List<TimingItem> getMyTimings(List<TimingItem> timings, String action, String component, boolean evolve, Boolean buy, String subcomponent, Parameters parameters) {
List<TimingItem> filterTimings = new ArrayList<>();
String paramString = JsonUtil.convert(parameters);
for (TimingItem timing : timings) {
if (timing.getBuy() != null && buy != timing.getBuy()) {
continue;
}
if (action.equals(timing.getAction()) && component.equals(timing.getComponent()) && subcomponent.equals(timing.getSubcomponent()) && evolve == timing.isEvolve() && paramString == timing.getParameters()) {
filterTimings.add(timing);
}
}
return filterTimings;
}
public Market findMarket(ComponentData param) {
IclijConfig instance = IclijXMLConfig.getConfigInstance();
List<Market> markets = getMarkets(instance);
Market foundMarket = null;
for (Market aMarket : markets) {
if (param.getMarket().equals(aMarket.getConfig().getMarket())) {
foundMarket = aMarket;
break;
}
}
return foundMarket;
}
public void getPicksFiltered(WebData myData, ComponentData param, IclijConfig config, MarketComponentTime marketTime, Boolean evolve) {
log.info("Getting picks for date {}", param.getInput().getEnddate());
Market market = marketTime.market;
Map<String, ComponentData> dataMap = new HashMap<>();
ProfitData profitdata = new ProfitData();
Map<Boolean, Map<String, List<Integer>>> listComponentMap = new HashMap<>();
myData.memoryItems = getMemItems(marketTime, myData, param, config, evolve, dataMap);
LocalDate prevdate = getPrevDate(param, market);
LocalDate olddate = prevdate.minusDays(((int) AVERAGE_SIZE) * getTime(market));
ProfitInputData inputdata = getListComponents(myData, param, config, marketTime, evolve, market, dataMap, listComponentMap, prevdate, olddate);
profitdata.setInputdata(inputdata);
Map<String, Component> componentMap = new HashMap<>();
componentMap.put(marketTime.componentName, marketTime.component);
setValMap(param);
Map<String, Map<String, Object>> maps = param.getResultMaps();
Map<String, String> nameMap = getNameMap(maps);
inputdata.setNameMap(nameMap);
param.setTimings(new ArrayList<>());
handleComponent(this, market, profitdata, param, listComponentMap.get(marketTime.buy), componentMap, dataMap, marketTime.buy, marketTime.subcomponent, myData, config, marketTime.parameters);
if (!isDataset()) {
filterIncDecs(param, market, profitdata, maps, true);
filterIncDecs(param, market, profitdata, maps, false);
}
//filterDecs(param, market, profitdata, maps);
//buys = buys.values().stream().filter(m -> olddate.compareTo(m.getRecord()) <= 0).collect(Collectors.toList());
myData.profitData = profitdata;
Map<String, Object> timingMap = new HashMap<>();
timingMap.put(market.getConfig().getMarket(), param.getTimings());
if (marketTime.buy == null || marketTime.buy) {
myData.timingMap = timingMap;
if (marketTime.buy != null) {
myData.updateMap.putAll(param.getUpdateMap());
}
} else {
myData.timingMap2 = timingMap;
myData.updateMap2.putAll(param.getUpdateMap());
}
}
protected ProfitInputData getListComponents(WebData myData, ComponentData param, IclijConfig config,
MarketComponentTime marketTime, Boolean evolve, Market market, Map<String, ComponentData> dataMap,
Map<Boolean, Map<String, List<Integer>>> listComponentMap, LocalDate prevdate, LocalDate olddate) {
ProfitInputData inputdata;
List<MemoryItem> marketMemory = getMarketMemory(marketTime.market, getName(), marketTime.componentName, marketTime.subcomponent, JsonUtil.convert(marketTime.parameters), olddate, prevdate);
if (marketMemory == null) {
myData.profitData = new ProfitData();
}
marketMemory.addAll(myData.memoryItems);
List<MemoryItem> currentList = filterKeepRecent(marketMemory, prevdate, ((int) AVERAGE_SIZE) * getTime(market));
// or make a new object instead of the object array. use this as a pair
//System.out.println(currentList.get(0).getRecord());
Map<Pair<String, Integer>, List<MemoryItem>> listMap = new HashMap<>();
// map subcat + posit -> list
currentList.forEach(m -> listGetterAdder(listMap, new ImmutablePair<String, Integer>(m.getComponent(), m.getPosition()), m));
inputdata = filterMemoryListMapsWithConfidence(market, listMap);
Map<String, List<Integer>> listComponent = createComponentPositionListMap(inputdata.getListMap());
Map<String, List<Integer>> aboveListComponent = createComponentPositionListMap(inputdata.getAboveListMap());
Map<String, List<Integer>> belowListComponent = createComponentPositionListMap(inputdata.getBelowListMap());
listComponentMap.put(null, listComponent);
listComponentMap.put(true, aboveListComponent);
listComponentMap.put(false, belowListComponent);
return inputdata;
}
private <K, E> List<E> listGetter(Map<K, List<E>> listMap, K key) {
return listMap.computeIfAbsent(key, k -> new ArrayList<>());
}
public <K, E> void listGetterAdder(Map<K, List<E>> listMap, K key, E element) {
List<E> list = listGetter(listMap, key);
list.add(element);
}
private <T> String nullToEmpty(T s) {
return s != null ? "" + s : "";
}
private List<Market> getMarkets(IclijConfig instance) {
List<Market> markets = null;
try {
markets = IclijXMLConfig.getMarkets(instance);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return markets;
}
public Map<String, List<Integer>> createComponentPositionListMapOld(Map<Object[], List<MemoryItem>> okListMap) {
Map<String, List<Integer>> listComponent = new HashMap<>();
for (Object[] keys : okListMap.keySet()) {
String component = (String) keys[0];
Integer position = (Integer) keys[1];
listGetterAdder(listComponent, component, position);
}
return listComponent;
}
public Map<String, List<Integer>> createComponentPositionListMap(Map<Pair<String, Integer>, List<MemoryItem>> okListMap) {
Map<String, List<Integer>> listComponent = new HashMap<>();
for (Pair<String, Integer> key : okListMap.keySet()) {
/*
String component = (String) keys[0];
String subcomponent = (String) keys[1];
Integer position = (Integer) keys[2];
*/
listGetterAdder(listComponent, key.getLeft(), key.getRight());
}
return listComponent;
}
protected void filterIncDecs(ComponentData param, Market market, ProfitData profitdata,
Map<String, Map<String, Object>> maps, boolean inc) {
List<String> dates = param.getService().getDates(param.getService().conf.getMarket());
String category;
if (inc) {
category = market.getFilter().getInccategory();
} else {
category = market.getFilter().getDeccategory();
}
if (category != null) {
Map<String, Object> categoryMap = maps.get(category);
if (categoryMap != null) {
Integer offsetDays = null;
Integer days;
if (inc) {
days = market.getFilter().getIncdays();
} else {
days = market.getFilter().getDecdays();
}
if (days != null) {
if (days == 0) {
int year = param.getInput().getEnddate().getYear();
List<String> yearDates = new ArrayList<>();
for (String date : dates) {
int aYear = Integer.valueOf(date.substring(0, 4));
if (year == aYear) {
yearDates.add(date);
}
}
Collections.sort(yearDates);
String oldestDate = yearDates.get(0);
int index = dates.indexOf(oldestDate);
offsetDays = dates.size() - 1 - index;
} else {
offsetDays = days;
}
}
Double threshold;
if (inc) {
threshold = market.getFilter().getIncthreshold();
} else {
threshold = market.getFilter().getDecthreshold();
}
Map<String, List<List>> listMap3 = getCategoryList(maps, category);
Map<String, IncDecItem> buysFilter = incdecFilterOnIncreaseValue(market, inc ? profitdata.getBuys() : profitdata.getSells(), maps, threshold, categoryMap,
listMap3, offsetDays, inc);
if (inc) {
profitdata.setBuys(buysFilter);
} else {
profitdata.setSells(buysFilter);
}
}
}
}
protected abstract ProfitInputData filterMemoryListMapsWithConfidence(Market market, Map<Pair<String, Integer>, List<MemoryItem>> listMap);
public List<MemoryItem> getMarketMemory(Market market) {
List<MemoryItem> marketMemory = null;
try {
marketMemory = IclijDbDao.getAll(market.getConfig().getMarket());
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return marketMemory;
}
public List<MemoryItem> getMarketMemory(Market market, String action, String component, String subcomponent, String parameters, LocalDate startDate, LocalDate endDate) {
List<MemoryItem> marketMemory = null;
try {
marketMemory = IclijDbDao.getAllMemories(market.getConfig().getMarket(), action, component, subcomponent, parameters, startDate, endDate);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
return marketMemory;
}
protected Map<String, String> getNameMap(Map<String, Map<String, Object>> maps) {
Map<String, String> nameMap = null;
for (Entry<String, Map<String, Object>> entry : maps.entrySet()) {
Map<String, Object> map = entry.getValue();
nameMap = (Map<String, String>) map.get(PipelineConstants.NAME);
if (nameMap != null) {
break;
}
}
return nameMap;
}
protected abstract void handleComponent(MarketAction action, Market market, ProfitData profitdata, ComponentData param, Map<String, List<Integer>> listComponent, Map<String, Component> componentMap, Map<String, ComponentData> dataMap, Boolean buy, String subcomponent, WebData myData, IclijConfig config, Parameters parameters);
public List<MemoryItem> filterKeepRecent(List<MemoryItem> marketMemory, LocalDate date, int days) {
LocalDate olddate = date.minusDays(days);
for (MemoryItem item : marketMemory) {
if (item.getRecord() == null) {
item.setRecord(LocalDate.now());
}
}
// temp workaround
if (date == null) {
return marketMemory;
}
List<MemoryItem> currentList = marketMemory.stream().filter(m -> olddate.compareTo(m.getFuturedate()) <= 0).collect(Collectors.toList());
currentList = currentList.stream().filter(m -> date.compareTo(m.getFuturedate()) >= 0).collect(Collectors.toList());
return currentList;
}
public Map<String, List<List>> getCategoryList(Map<String, Map<String, Object>> maps, String category) {
String newCategory = null;
if (Constants.PRICE.equals(category)) {
newCategory = "" + Constants.PRICECOLUMN;
}
if (Constants.INDEX.equals(category)) {
newCategory = "" + Constants.INDEXVALUECOLUMN;
}
if (newCategory != null) {
Map<String, Object> map = maps.get(newCategory);
return (Map<String, List<List>>) map.get(PipelineConstants.LIST);
}
Map<String, List<List>> listMap3 = null;
for (Entry<String, Map<String, Object>> entry : maps.entrySet()) {
Map<String, Object> map = entry.getValue();
if (category.equals(map.get(PipelineConstants.CATEGORYTITLE))) {
listMap3 = (Map<String, List<List>>) map.get(PipelineConstants.LIST);
}
}
return listMap3;
}
public Map<String, IncDecItem> incdecFilterOnIncreaseValue(Market market, Map<String, IncDecItem> incdecs,
Map<String, Map<String, Object>> maps, Double threshold, Map<String, Object> categoryMap,
Map<String, List<List>> listMap3, Integer offsetDays, boolean inc) {
Map<String, IncDecItem> incdecsFilter = new HashMap<>();
for(IncDecItem item : incdecs.values()) {
String key = item.getId();
if (listMap3 == null) {
if (categoryMap != null) {
System.out.println(categoryMap.keySet());
}
if (maps != null) {
System.out.println(maps.keySet());
}
System.out.println("market" + market.getConfig().getMarket() + "null map");
continue;
}
List<List> list = listMap3.get(key);
List<Double> list0 = list.get(0);
Double value = null;
if (offsetDays == null) {
value = list0.get(list0.size() - 1);
if (value != null) {
value = 1 + (value / 100);
}
} else {
Double curValue = list0.get(list0.size() - 1);
Double oldValue = list0.get(list0.size() - 1 - offsetDays);
if (curValue != null && oldValue != null) {
value = curValue / oldValue;
}
}
if (value == null) {
continue;
}
if (inc && value < threshold) {
continue;
}
if (!inc && value > threshold) {
continue;
}
incdecsFilter.put(key, item);
}
return incdecsFilter;
}
public List<Market> getMarkets() {
IclijConfig instance = IclijXMLConfig.getConfigInstance();
List<Market> markets = new ArrayList<>();
try {
markets = IclijXMLConfig.getMarkets(instance);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
markets = filterMarkets(markets);
return markets;
}
public List<MapList> getList(Map<String, Object> map) {
List<MapList> retList = new ArrayList<>();
for (Entry<String, Object> entry : map.entrySet()) {
MapList ml = new MapList();
ml.setKey(entry.getKey());
ml.setValue((String) entry.getValue().toString());
retList.add(ml);
}
return retList;
}
public Map<String, Component> getComponentMap(Collection<String> listComponent, Market market) {
Map<String, Component> componentMap = new HashMap<>();
for (String componentName : listComponent) {
Component component = getComponentFactory().factory(componentName);
if (market != null && componentName.equals(PipelineConstants.PREDICTOR)) {
MLConfigs mlConfigs = market.getMlconfig();
if (mlConfigs != null) {
MLConfig mlConfig = mlConfigs.getTensorflow().getLstm();
if (mlConfig != null) {
if (!mlConfig.getEnable()) {
//continue;
}
}
}
}
componentMap.put(componentName, component);
}
return componentMap;
}
public Map<Boolean, String> getBooleanTexts() {
Map<Boolean, String> map = new HashMap<>();
map.put(null, "");
map.put(false, "down");
map.put(true, "up");
return map;
}
protected abstract String getFuturedays0(IclijConfig conf);
public Integer[] getFuturedays(IclijConfig conf) {
String thresholdString = getFuturedays0(conf);
try {
Double.valueOf(thresholdString);
log.error("Using old format {}", thresholdString);
thresholdString = "[" + thresholdString + "]";
} catch (Exception e) {
}
return JsonUtil.convert(thresholdString, Integer[].class);
}
public abstract String getThreshold(IclijConfig conf);
private Double[] getThresholds(IclijConfig conf) {
String thresholdString = getThreshold(conf);
try {
Double.valueOf(thresholdString);
log.error("Using old format {}", thresholdString);
thresholdString = "[" + thresholdString + "]";
} catch (Exception e) {
}
return JsonUtil.convert(thresholdString, Double[].class);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.