answer stringlengths 17 10.2M |
|---|
public class RepairDroid
{
public static final String INITIAL_INPUT = "";
public RepairDroid (Vector<String> instructions, boolean debug)
{
_debug = debug;
_theComputer = new Intcode(instructions, INITIAL_INPUT, _debug);
_location = new Coordinate(0, 0);
_visitedLocations = new Vector<Coordinate>();
_visitedLocations.add(_location);
}
public final int moveToOxygenStation ()
{
int numberOfSteps = 0;
return numberOfSteps;
}
public void printGrid ()
{
}
private boolean _debug;
private Intcode _theComputer;
private Coordinate _location;
private Vector<Coordinate> _visitedLocations;
} |
package ru.szhernovoy.control;
import ru.szhernovoy.view.Cell;
public class Logic {
/**game board */
private Cell[][] cells;
/**
* Setter game board
* @param cells
*/
public void loadBoard(Cell[][] cells) {
this.cells = cells;
}
/**
* If not empty cell - game over
* @return
*/
public boolean finish() {
boolean finish = true;
for (Cell[] row : cells) {
for (Cell cell : row) {
finish = !cell.isEmpty();
if(!finish){
break;
}
}
if(!finish){
break;
}
}
return finish;
}
/**
* Check game on win. 0 - winner X ; 1 - winner O. Who game X or O set on start game.
* @return
*/
public int isWinner(){
// X - 0 || O - 1
int rowFieldO,columnFieldO,rowFieldX,columnFieldX;
int winner = -1;
for (int valueX = 0; valueX < this.cells.length;valueX++) {
rowFieldO = columnFieldO = rowFieldX = columnFieldX = 0;
for (int valueY = 0; valueY < this.cells.length; valueY++) {
if(currentValueField(this.cells[valueX][valueY]) == 1){
rowFieldX++;
}
if(currentValueField(this.cells[valueX][valueY]) == 2){
rowFieldO +=2;
}
if(currentValueField(this.cells[valueY][valueX]) == 1){
columnFieldX++;
}
if(currentValueField(this.cells[valueY][valueX]) == 2){
columnFieldO +=2;
}
}
if(rowFieldX%this.cells.length == 0 && rowFieldX !=0 || columnFieldX%this.cells.length == 0 && columnFieldX !=0){
winner = 0;
break;
}
if(rowFieldO%this.cells.length == 0 && rowFieldO !=0 || columnFieldO%this.cells.length == 0 && columnFieldO !=0){
winner = 1;
break;
}
}
if(winner == -1){
rowFieldO = columnFieldO = rowFieldX = columnFieldX = 0;
int valuePlus = 0;
int valueMinus = this.cells.length -1;
for (; valuePlus < this.cells.length;valuePlus++,valueMinus
if(currentValueField(this.cells[valuePlus][valuePlus]) == 1){
rowFieldX ++;
}
if(currentValueField(this.cells[valuePlus][valuePlus]) == 2){
rowFieldO += 2;
}
if(currentValueField(this.cells[valueMinus][valueMinus]) == 1){
columnFieldX ++;
}
if(currentValueField(this.cells[valueMinus][valueMinus]) == 2){
columnFieldO += 2;
}
}
if(rowFieldX%this.cells.length == 0 && rowFieldX !=0 || columnFieldX%this.cells.length == 0 && columnFieldX !=0){
winner = 0;
}
if(rowFieldO%this.cells.length == 0 && rowFieldO !=0 || columnFieldO%this.cells.length == 0 && columnFieldO !=0){
winner = 1;
}
}
return winner;
}
/**
* Return value cell 1 = X; 2 = O; empty = 0.
* @param cell
* @return
*/
private int currentValueField(Cell cell){
return cell.isEmpty() ? 0 : cell.isIconX() ? 1 : 2;
}
/**
* Control position on set value in array cell.
* @param answer
* @return
*/
public boolean control(int[] answer){
boolean result = false;
if(this.cells[answer[0]][answer[1]].isEmpty()){
result = true;
}
return result;
}
/**
* Set value in cell.
* @param answer
* @param index
*/
public void setValue(int[] answer, int index){
if(index == 0){
this.cells[answer[0]][answer[1]].setIconX(true);
}
else{
this.cells[answer[0]][answer[1]].setIconO(true);
}
}
} |
package org.gem.hdf5;
import javax.swing.tree.DefaultMutableTreeNode;
import ncsa.hdf.hdf5lib.HDF5Constants;
import ncsa.hdf.object.Dataset;
import ncsa.hdf.object.Datatype;
import ncsa.hdf.object.Group;
import ncsa.hdf.object.h5.H5Datatype;
import ncsa.hdf.object.h5.H5File;
/**
* Contains utility functions for reading and writing 5D matrices to HDF5 files.
*
*/
public class HDF5Util
{
/**
* 64-bit float data type.
*/
private static Datatype DOUBLE_DT = new H5Datatype(Datatype.CLASS_FLOAT, 8, Datatype.NATIVE, Datatype.NATIVE);
private static int DEFAULT_GZIP_COMPRESSION = 0; // No compression
/**
* Write a 5D matrix to the specified file path using default compression
* (no compression).
* @param path Destination path for the HDF5 matrix output file.
* @param matrixDesc Description of the matrix
* @param dims An array defining the dimensions of the matrix. For example:
* an array of {10, 10, 10, 10, 5} indicates a 10x10x10x10x5 array
* (with 50000 elements).
* @param matrix 5D matrix to write to the file
* @throws Exception
*/
public static void writeMatrix(String path, String matrixDesc,
long [] dims, double[][][][][] matrix) throws Exception
{
writeMatrix(path, matrixDesc, dims, matrix, DEFAULT_GZIP_COMPRESSION);
}
/**
* Write a 5D matrix to the specified file path.
* @param path Destination path for the HDF5 matrix output file.
* @param matrixDesc Description of the matrix
* @param dims An array defining the dimensions of the matrix. For example:
* an array of {10, 10, 10, 10, 5} indicates a 10x10x10x10x5 array
* (with 50000 elements).
* @param matrix 5D matrix to write to the file
* @param gzipLevel Level of gzip compression. Valid compression levels are
* 1-9; use 0 or a negative value for no compression.
* @throws Exception
*/
private static void writeMatrix(String path, String matrixDesc,
long [] dims, double[][][][][] matrix, int gzipLevel) throws Exception
{
H5File output = new H5File(path, HDF5Constants.H5F_ACC_RDWR);
output.createNewFile();
output.open();
Group root = getRootGroup(output);
output.createScalarDS(matrixDesc, root, DOUBLE_DT, dims, null, null, gzipLevel, matrix);
output.close();
}
/**
* Read a 5D matrix from the specified file.
* @param path Path to an HDF5 file containing a 5D matrix.
* @return 5D double array
* @throws Exception
*/
public static double [][][][][] readMatrix(String path) throws Exception
{
H5File input = new H5File(path, HDF5Constants.H5F_ACC_RDONLY);
input.open();
Group root = getRootGroup(input);
Dataset dataset = (Dataset) root.getMemberList().get(0);
dataset.read();
return readMatrix(dataset);
}
private static double[][][][][] readMatrix(Dataset dataset) throws OutOfMemoryError, Exception
{
long[] maxDims = dataset.getMaxDims();
long[] selectedDims = dataset.getSelectedDims();
// Copy maxDims to selectedDims, then read the data.
// Note: selectedDims is a reference to the dataset's `selectedDims`
// member. Changing the content selectedDims will have an affect
// on the subsequent dataset.getData() call. If we don't do this,
// we'll only extract a subset of the data.
for (int i = 0; i < maxDims.length; i++)
{
selectedDims[i] = maxDims[i];
}
// this gives us the entire matrix flattened into a 1 dimensional array
double[] data = (double[])dataset.getData();
return reshape(data, maxDims);
}
/**
* Get the root Group from an HDF5 file.
* @param h5file An open hdf5 file handle.
* @return Group
*/
public static Group getRootGroup(H5File h5file)
{
return (Group)((DefaultMutableTreeNode)h5file.getRootNode()).getUserObject();
}
/**
* Reshape a 1D array into a 5D array, given specific shape/dimensions.
* @param array Flattened array
* @param shape Defines the shape of the output. For example, a shape of
* {1, 2, 3, 4, 5} defines a 1x2x3x4x5 array (containing 120
* elements).
* @return reshaped 5D array
* @throws HDF5Exception
*/
public static double[][][][][] reshape(double [] array, long[] shape) throws HDF5Exception
{
// Validity checks:
if (shape.length != 5)
{
throw new HDF5Exception("invalid shape; must be 5 dimensional");
}
// next, validate the array length against the requested shape
int expectedLength = 1;
for (long s: shape)
{
expectedLength *= s;
}
if (expectedLength != array.length)
{
throw new HDF5Exception(
"array length does not match request shape");
}
// now reshape:
double[][][][][] reshaped = new double[(int) shape[0]][(int) shape[1]]
[(int) shape[2]][(int) shape[3]][(int) shape[4]];
int arrayIndex = 0;
for (int i = 0; i < shape[0]; i++)
{
for (int j = 0; j < shape[1]; j++)
{
for (int k = 0; k < shape[2]; k++)
{
for (int l = 0; l < shape[3]; l++)
{
for (int m = 0; m < shape[4]; m++)
{
reshaped[i][j][k][l][m] = array[arrayIndex];
arrayIndex++;
}
}
}
}
}
return reshaped;
}
} |
package com.armandgray.taap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
public class DrillActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drill);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_drill, 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_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
private ArrayAdapter<String> createSpinnerAdapter() {
return new ArrayAdapter<>(this, R.layout.spinner_drills_text_layout);
}
} |
package com.magshimim.torch;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
import com.magshimim.torch.services.RecorderService;
public class MainActivity extends AppCompatActivity {
private final static boolean DEBUG = BuildConfig.DEBUG;
private final int REQUEST_MEDIA_PROJECTION = 1;
private final String TAG = getClass().getSimpleName();
private MediaProjectionManager mediaProjectionManager;
private boolean recording = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
if(DEBUG) Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaProjectionManager = (MediaProjectionManager)
getSystemService(MEDIA_PROJECTION_SERVICE);
final ToggleButton recordingToggleButton = (ToggleButton) findViewById(R.id.recordingToggleButton);
recordingToggleButton.setChecked(recording);
recordingToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
startRecording();
else
stopRecording();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(DEBUG) Log.d(TAG, "onActivityResult");
if(requestCode == REQUEST_MEDIA_PROJECTION) {
if(resultCode != RESULT_OK) {
Log.i(TAG, "user cancelled");
return;
}
Log.d(TAG, "result code is " + resultCode);
Log.d(TAG, "result canceled is " + RESULT_CANCELED);
Intent recordingIntent = new Intent(this, RecorderService.class);
recordingIntent.putExtra(RecorderService.EXTRA_ADDRESS, "10.0.2.2");
recordingIntent.putExtra(RecorderService.EXTRA_PORT, 27015);
recordingIntent.putExtra(RecorderService.EXTRA_FPS, 5);
recordingIntent.putExtra(RecorderService.EXTRA_RESULT_CODE, resultCode);
recordingIntent.putExtra(RecorderService.EXTRA_RESULT_DATA, data);
String content = "";
for(String key : recordingIntent.getExtras().keySet()) {
Object value = recordingIntent.getExtras().get(key);
content += String.format("%s %s\n", key, value.toString());
}
Log.w(TAG, "intent:\n" + content);
startService(recordingIntent);
recording = true;
if(DEBUG) Log.d(TAG, "service start intent sent");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("recording", recording);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
recording = savedInstanceState.getBoolean("recording", false);
}
private void startRecording() {
if(DEBUG) Log.d(TAG, "startRecording");
if(recording) {
Log.w(TAG, "already recording");
return;
}
startActivityForResult(
mediaProjectionManager.createScreenCaptureIntent(),
REQUEST_MEDIA_PROJECTION);
}
/**
* Stop the recorder service
*/
private void stopRecording() {
if(DEBUG) Log.d(TAG, "stopRecording");
Intent recordingIntent = new Intent(this, RecorderService.class);
stopService(recordingIntent);
recording = false;
if(DEBUG) Log.d(TAG, "service stopped");
}
public class MessageHandler extends Handler {
@Override
public void handleMessage(Message message) {
Bundle data = message.getData();
Object param = data.get("frame");
}
}
} |
package com.techshroom.unplanned.util;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
public final class Maths {
public static final double med = calculateMachineEpsilonDouble();
static {
System.err.println("Got MED " + med);
System.err.println("Java reports ulp for 1.0 is " + Math.ulp(1.0));
}
private static double calculateMachineEpsilonDouble() {
double machEps = 1.0d;
do
machEps /= 2.0d;
while ((double) (1.0 + (machEps / 2.0)) != 1.0);
return machEps;
}
/**
* Provides geometry manipulation, such as axis-normalization and rectangle
* rotations.
*
* @author Kenzie Togami
*/
public static final class Geometry {
private Geometry() {
throw new AssertionError("Don't create");
}
/**
* Rotates the given rectangle by <code>theta</code> degrees, treating
* it as if it were drawn at that angle and not axis-aligned.
*
* @param r
* - the original rectangle
* @param theta
* - the rotation angle
* @return <code>r</code>, rotated by <code>theta</code>
*/
public static Rectangle2D rotateRect(Rectangle2D r, double theta) {
// store data
double x = r.getX(), y = r.getY(), w = r.getWidth(), h = r
.getHeight();
// clear rect
r.setRect(0, 0, 0, 0);
// get points
Point2D[] points = new Point2D[] { new Point2D.Double(x, y),
new Point2D.Double(w + x, h + y) };
// calc cos/sin
double s = TrigTableLookup.sin(theta), c = TrigTableLookup
.cos(theta);
// expand rect to fit
for (Point2D p : points) {
p.setLocation((p.getX() * c) - (p.getY() * s), (p.getX() * s)
+ (p.getY() * c));
}
r.setRect(points[0].getX(), points[0].getY(), points[1].getX()
- points[0].getX(), points[1].getY() - points[0].getY());
return r;
}
public static double[] pointsAsDoubles(Point2D[] points) {
double[] out = new double[points.length * 2];
for (int i = 0; i < out.length; i += 2) {
Point2D p = points[i / 2];
out[i] = p.getX();
out[i + 1] = p.getY();
}
return out;
}
public static Point2D[] doublesAsPoints(double[] points) {
if (points.length % 2 != 0) {
throw new IllegalArgumentException("need pairs of doubles");
}
Point2D[] temp = new Point2D[points.length / 2];
for (int i = 0; i < points.length; i += 2) {
temp[i / 2] = new Point2D.Double(points[i], points[i + 1]);
}
return temp;
}
}
private Maths() {
throw new AssertionError("Don't create");
}
/**
* Finds the length of a line when projected along another line. Used for
* collisions.
*
* @param thetaSurface
* - The angle the surface to be projected upon makes with the
* horizontal
* @param thetaLineToProject
* - The angle the line makes with the horizontal
* @param magnitude
* - The length of the line.
* @param getY
* - Gets the length of the line when projected along the line
* perpendicular to the thetaSurface given (eg, find the y).
*/
public static double projectLineAlongSurface(double thetaSurface,
double thetaLineToProject, double magnitude, boolean getY) {
double dp = dotProductAngles(magnitude, thetaLineToProject, 1,
thetaSurface);
if (!getY) {
System.out.println(dp);
return dp * Math.cos(Math.toRadians(thetaSurface));
} else {
System.out.println(dp);
return dp * Math.sin(Math.toRadians(thetaSurface));
}
}
public static double projectLineAlongSurfaceXY(double xSurface,
double ySurface, double xLine, double yLine, boolean DoY) {
double dp = dotProduct(xLine, yLine,
Maths.normalizeX(xSurface, ySurface),
Maths.normalizeY(xSurface, ySurface));
if (!DoY) {
System.out.println(dp);
return dp * xSurface;
} else {
System.out.println(dp);
return dp * ySurface;
}
}
public static double normalizeX(double x, double y) {
double len_v = Math.sqrt(x * x + y * y);
return x / len_v;
}
public static double normalizeY(double x, double y) {
double len_v = Math.sqrt(x * x + y * y);
return y / len_v;
}
public static double dotProduct(double ax, double ay, double bx, double by) {
return ax * ay + bx * by;
}
public static double dotProductAngles(double amag, double atheta,
double bmag, double btheta) {
double ax = Math.cos(Math.toRadians(atheta)) * amag;
double bx = Math.cos(Math.toRadians(btheta)) * bmag;
double ay = Math.sin(Math.toRadians(atheta)) * amag;
double by = Math.sin(Math.toRadians(btheta)) * bmag;
return ax * bx + ay * by;
}
/**
* Perform linear interpolation on positions
*
* @param pos1
* -The first position (does not matter x or y)
* @param pos2
* -The second position
* @param v
* -The interpolaty-bit. Decimal between 0 and 1.
* @return -The position (actually an average of pos1/pos2 + pos1).
*/
public static float lerp(float pos1, float pos2, float v) {
return pos1 + (pos2 - pos1) * v;
}
public static boolean lessThanOrEqualTo(double a, double b) {
int c = Double.compare(a, b);
return c <= 0;
}
public static boolean lessThan(double a, double b) {
int c = Double.compare(a, b);
return c < 0;
}
public static boolean greaterThanOrEqualTo(double a, double b) {
int c = Double.compare(a, b);
return c >= 0;
}
public static boolean greaterThan(double a, double b) {
int c = Double.compare(a, b);
return c > 0;
}
public static final class TrigTableLookup {
// Set to Math.PI*2 if you want radians, or 360d for degrees
private static final double circleSize = 360d;
private static final double doubleCircleSize = circleSize * 2;
private static final int virtualSize = 1048576;
private static final double conversionFactor = (virtualSize / circleSize);
private static final double tanLeadingCoefficient = (-circleSize
/ Math.PI * 2);
private static final double[] SinTable = new double[16384];
static {
for (int i = 0; i < 16384; i++) {
SinTable[i] = Math.sin(i * Math.PI * 2 / 16384);
}
}
private static double lookup(int val) {
int index = val / 64;
double LUTSinA = SinTable[index & 16383];
double LUTSinB = SinTable[(index + 1) & 16383];
double LUTSinW = (val & 63) / 63d;
return LUTSinW * (LUTSinB - LUTSinA) + LUTSinA;
}
public static double sin(double Value) {
return lookup((int) (Value * conversionFactor));
}
public static double cos(double Value) {
return lookup((int) (Value * conversionFactor) + 262144);
}
public static double tan(double Value) {
int k = (int) (Value * conversionFactor);
// Central 5000 values use
// the 1/x form
int wrapped = (((k + 2000) << 13) >> 13);
if (wrapped < -258144) { // 262144-5000
return tanLeadingCoefficient
/ ((4 * Value) % (doubleCircleSize) - circleSize);
}
return lookup(k) / lookup(k + 262144);
}
}
public static boolean isPowerOfTwo(int x) {
return x != 0 && (x & (x - 1)) == 0;
};
} |
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.QueryBizLogic;
import edu.wustl.catissuecore.query.ResultData;
import edu.wustl.catissuecore.util.Permissions;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.security.SecurityManager;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* DataViewAction is used to show the query results data
* in spreadsheet or individaul view.
* @author gautam_shetty
*/
public class DataViewAction extends BaseAction
{
/**
* Overrides the execute method in Action class.
*/
public ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
HttpSession session = request.getSession();
String target = Constants.SUCCESS;
String nodeName = request.getParameter("nodeName");
if(nodeName==null)
nodeName = (String)session.getAttribute(Constants.SELECTED_NODE);
Logger.out.debug("nodename of selected node"+nodeName);
StringTokenizer str = new StringTokenizer(nodeName,":");
String name = str.nextToken().trim();
String id = new String();
String parentName = new String();
String parentId = new String();
//Get the column display names and select column names if it is configured and set in session
List filteredColumnDisplayNames=(List)session.getAttribute(Constants.CONFIGURED_COLUMN_DISPLAY_NAMES);
Logger.out.debug("ColumnDisplayNames from configuration"+filteredColumnDisplayNames);
String[] columnList= (String[])session.getAttribute(Constants.CONFIGURED_SELECT_COLUMN_LIST);
if(columnList!=null)
{
Logger.out.debug("size of configured columns from session:"+columnList.length);
session.setAttribute(Constants.CONFIGURED_SELECT_COLUMN_LIST,columnList);
}
// List filteredColumnDisplayNames = new ArrayList();
//Get column display names from session which is set in session in AdvanceSearchResultsAction
// if(columnDisplayNames==null)
// columnDisplayNames = (List)session.getAttribute(Constants.COLUMN_DISPLAY_NAMES);
// else
// filteredColumnDisplayNames = columnDisplayNames;
if (name.equals(Constants.ROOT)|| name.equals(Constants.PARTICIPANT))
{
if(filteredColumnDisplayNames==null)
filteredColumnDisplayNames = (List)session.getAttribute(Constants.COLUMN_DISPLAY_NAMES);
}
if (!name.equals(Constants.ROOT))
{
id = str.nextToken();
}
/*Incase of collection protocol selected, the whereCondition should contain the participant conditions also
* as Collection Protocol and Participant have many to many relationship
*/
if(str.hasMoreTokens())
{
parentName = str.nextToken();
parentId = str.nextToken();
}
//get the type of view to show (spreadsheet/individual)
String viewType = request.getParameter(Constants.VIEW_TYPE);
if(viewType==null)
viewType=Constants.SPREADSHEET_VIEW;
if (viewType.equals(Constants.SPREADSHEET_VIEW))
{
Map columnIdsMap = (Map)session.getAttribute(Constants.COLUMN_ID_MAP);
if (!name.equals(Constants.ROOT))
{
Logger.out.debug("node name selected inside if condition:"+name);
Logger.out.debug("column list inside if condition::"+columnList);
if (!name.equals(Constants.PARTICIPANT) && columnList==null)
{
Logger.out.debug("Inside if condition of filtercolumns");
filteredColumnDisplayNames=new ArrayList();
columnList = getColumnNamesForFilter(name,filteredColumnDisplayNames,columnIdsMap);
Logger.out.debug("select column list size:"+columnList.length);
Logger.out.debug("filteredColumnDisplayNames after func call"+filteredColumnDisplayNames);
}
Logger.out.debug("alias name of selected node in adv tree:"+name);
Logger.out.debug("column ids map in data view action"+columnIdsMap);
String key = name+"."+Constants.IDENTIFIER;
int columnId = ((Integer)columnIdsMap.get(name+"."+Constants.IDENTIFIER)).intValue()-1;
Logger.out.debug("columnid of selected node:"+columnId+"in the map for key:"+key);
name=Constants.COLUMN+columnId;
Logger.out.debug("Column name of the selected column in the tree:"+name);
if(!parentName.equals(""))
{
key = parentName+"."+Constants.IDENTIFIER;
columnId = ((Integer)columnIdsMap.get(parentName+"."+Constants.IDENTIFIER)).intValue()-1;
parentName=Constants.COLUMN+columnId;
}
}
//Add specimen identifier column if it is not there,required for shopping cart action
int specimenColumnId = ((Integer)columnIdsMap.get(Constants.SPECIMEN+"."+Constants.IDENTIFIER)).intValue()-1;
Logger.out.debug("specimenColumnId for adding compulsory specimen id:"+specimenColumnId);
String specimenColumn = Constants.COLUMN+specimenColumnId;
Logger.out.debug("specimenColumn for adding compulsory specimen id:"+specimenColumn);
boolean exists = false;
if(columnList!=null)
{
for(int i=0;i<columnList.length;i++)
{
Logger.out.debug("column loop :"+columnList[i]);
if(columnList[i].equals(specimenColumn))
{
Logger.out.debug("Specimen id column does not exist");
exists=true;
}
}
if(!exists)
{
String columnListWithoutSpecimenId[] = columnList;
columnList = new String[columnListWithoutSpecimenId.length+1];
for(int i=0;i<columnListWithoutSpecimenId.length;i++)
{
columnList[i] = columnListWithoutSpecimenId[i];
}
columnList[columnListWithoutSpecimenId.length]=specimenColumn;
//filteredColumnDisplayNames.add("Identifier");
}
}
Logger.out.debug("column names before func call to resultdata"+filteredColumnDisplayNames);
String[] whereColumnName= new String[1];
String[] whereColumnValue = new String[1];
String[] whereColumnCondition = new String[1];
if(!parentName.equals(""))
{
whereColumnName=new String[2];
whereColumnValue = new String[2];
whereColumnCondition = new String[2];
Logger.out.debug("parentname & id for coll prot"+parentName+"&"+parentId);
whereColumnName[1]=parentName;
whereColumnValue[1]=parentId;
whereColumnCondition[1]="=";
}
whereColumnName[0]=name;
whereColumnValue[0] =id;
whereColumnCondition[0]="=";
List list = null;
ResultData resultData = new ResultData();
list = resultData.getSpreadsheetViewData(whereColumnName,whereColumnValue,whereColumnCondition,columnList, getSessionData(request), Constants.OBJECT_LEVEL_SECURE_RETRIEVE);
Logger.out.debug("list of data after advance search"+list);
Logger.out.debug("column list after advance search"+filteredColumnDisplayNames);
// If the result contains no data, show error message.
if (list.isEmpty())
{
Logger.out.debug("inside if condition for empty list");
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("advanceQuery.noRecordsFound"));
saveErrors(request, errors);
request.setAttribute(Constants.PAGEOF,Constants.PAGEOF_QUERY_RESULTS);
//target = Constants.FAILURE;
}
else
{
Logger.out.debug("List of data in dataview action:"+list);
Logger.out.debug("column names in dataview action:"+filteredColumnDisplayNames);
//if specimen id is added to the columns then add display name identifier to the filteredColumnDisplayNames
if(columnList!=null)
{
if(columnList.length-filteredColumnDisplayNames.size()==1)
filteredColumnDisplayNames.add("Identifier");
}
request.setAttribute(Constants.SPREADSHEET_COLUMN_LIST,filteredColumnDisplayNames);
request.setAttribute(Constants.SPREADSHEET_DATA_LIST,list);
request.setAttribute(Constants.PAGEOF,Constants.PAGEOF_QUERY_RESULTS);
session.setAttribute(Constants.SELECT_COLUMN_LIST,columnList);
session.setAttribute(Constants.SELECTED_NODE,nodeName);
}
}
else
{
String url = null;
Logger.out.debug("selected node name in object view:"+name+"object");
// or not
if(!SecurityManager.getInstance(this.getClass()).isAuthorized(getUserLoginName(request)
,Constants.PACKAGE_DOMAIN+"."+name,Permissions.UPDATE))
{
ActionErrors errors = new ActionErrors();
ActionError error = new ActionError("access.edit.object.denied",getUserLoginName(request),Constants.PACKAGE_DOMAIN+"."+name
);
errors.add(ActionErrors.GLOBAL_ERROR,error);
saveErrors(request,errors);
return mapping.findForward(Constants.FAILURE);
}
if (name.equals(Constants.PARTICIPANT))
{
url = new String(Constants.QUERY_PARTICIPANT_SEARCH_ACTION+id+"&"+Constants.PAGEOF+"="+
Constants.PAGEOF_PARTICIPANT_QUERY_EDIT);
}
else if (name.equals(Constants.COLLECTION_PROTOCOL))
{
url = new String(Constants.QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION+id+"&"+Constants.PAGEOF+"="+
Constants.PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT);
}
else if (name.equals(Constants.SPECIMEN_COLLECTION_GROUP))
{
url = new String(Constants.QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION+id+"&"+Constants.PAGEOF+"="+
Constants.PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT);
}
else if (name.equals(Constants.SPECIMEN))
{
url = new String(Constants.QUERY_SPECIMEN_SEARCH_ACTION+id+"&"+Constants.PAGEOF+"="+
Constants.PAGEOF_SPECIMEN_QUERY_EDIT);
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher(url);
requestDispatcher.forward(request,response);
}
return mapping.findForward(target);
}
//returns the filtered select column list to be shown when clicked on a node of the results tree
private String[] getColumnNamesForFilter(String aliasName,List filteredColumnDisplayNames,Map columnIdsMap) throws DAOException,ClassNotFoundException
{
List columnDisplayNames=new ArrayList();
QueryBizLogic bizLogic = (QueryBizLogic)BizLogicFactory.getBizLogic(Constants.SIMPLE_QUERY_INTERFACE_ID);
List columns =new ArrayList();
//Filter the data according to the node clicked. Show only the data lower in the heirarchy
if(aliasName.equals(Constants.COLLECTION_PROTOCOL))
{
columns.addAll(bizLogic.setColumnNames(Constants.COLLECTION_PROTOCOL));
columns.addAll(bizLogic.setColumnNames(Constants.COLLECTION_PROTOCOL_REGISTRATION));
columns.addAll(bizLogic.setColumnNames(Constants.SPECIMEN_COLLECTION_GROUP));
columns.addAll(bizLogic.setColumnNames(Constants.SPECIMEN));
}
else if(aliasName.equals(Constants.SPECIMEN_COLLECTION_GROUP))
{
columns.addAll(bizLogic.setColumnNames(Constants.SPECIMEN_COLLECTION_GROUP));
columns.addAll(bizLogic.setColumnNames(Constants.SPECIMEN));
}
else if(aliasName.equals(Constants.SPECIMEN))
{
columns.addAll(bizLogic.setColumnNames(Constants.SPECIMEN));
}
String selectColumnList[] = new String[columns.size()];
Iterator columnsItr = columns.iterator();
int i=0;
while(columnsItr.hasNext())
{
NameValueBean columnsNameValues = (NameValueBean)columnsItr.next();
StringTokenizer columnsTokens = new StringTokenizer(columnsNameValues.getValue(),".");
Logger.out.debug("value in namevaluebean:"+columnsNameValues.getValue());
int columnId = ((Integer)columnIdsMap.get(columnsTokens.nextToken()+"."+columnsTokens.nextToken())).intValue()-1;
selectColumnList[i++]=(Constants.COLUMN+columnId);
columnDisplayNames.add(columnsTokens.nextToken());
}
filteredColumnDisplayNames.addAll(columnDisplayNames);
return selectColumnList;
}
} |
package edu.wustl.catissuecore.util.global;
import java.util.HashMap;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String SESSION_DATA = "sessionData";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
//Database constants.
public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y";
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
//public static final String TRUE = "true";
//public static final String FALSE = "false";
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String ACCESS_DENIED = "access_denied";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String IDENTIFIER = "IDENTIFIER";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String ERROR_DETAIL = "Error Detail";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//Constants for audit of disabled objects.
public static final String UPDATE_OPERATION = "UPDATE";
public static final String ACTIVITY_STATUS_COLUMN = "ACTIVITY_STATUS";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_NAME_LIST = "objectNameList";
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String ATTRIBUTE_NAME_LIST = "attributeNameList";
public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList";
//Constants for Storage Container.
public static final String STORAGE_CONTAINER_TYPE = "storageType";
public static final String STORAGE_CONTAINER_TO_BE_SELECTED = "storageToBeSelected";
public static final String STORAGE_CONTAINER_POSITION = "position";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROMSITELIST="fromsiteList";
public static final String TOSITELIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final boolean switchSecurity = true;
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String MOLECULAR = "Molecular";
public static final String RNA = "RNA";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "ShowStorageGridView.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_ACTION = "/SimpleQueryInterface.do";
public static final String SEARCH_OBJECT_ACTION = "/SearchObject.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
public static final String TABLE_DATA_TABLE_NAME = "CATISSUE_QUERY_INTERFACE_TABLE_DATA";
public static final String TABLE_DISPLAY_NAME_COLUMN = "DISPLAY_NAME";
public static final String TABLE_ALIAS_NAME_COLUMN = "ALIAS_NAME";
public static final String TABLE_FOR_SQI_COLUMN = "FOR_SQI";
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//TissueSite Tree View Constants.
public static final String PROPERTY_NAME = "propertyName";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Object View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
//Tree Data Action
public static final String TREE_DATA_ACTION = "Data.do";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//SimpleSearchAction
public static final String SIMPLE_QUERY_NO_RESULTS = "noResults";
public static final String SIMPLE_QUERY_SINGLE_RESULT = "singleResult";
//For getting the tables for Simple Query and Fcon Query.
public static final int SIMPLE_QUERY_TABLES = 1;
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int SIMPLE_QUERY_INTERFACE_ID = 40;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
//Misc
public static final String SEPARATOR = " : ";
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_ACTIVE = "Active";
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
public static final String ACTIVITY_STATUS_DISABLED = "Disabled";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Tree View Constants.
public static final String ROOT = "Root";
public static final String CATISSUE_CORE = "caTISSUE Core";
public static final String TISSUE_SITE = "Tissue Site";
public static final int TISSUE_SITE_TREE_ID = 1;
public static final int STORAGE_CONTAINER_TREE_ID = 2;
public static final int QUERY_RESULTS_TREE_ID = 3;
//Edit Object Constants.
public static final String TABLE_ALIAS_NAME = "aliasName";
public static final String FIELD_TYPE_VARCHAR = "varchar";
public static final String FIELD_TYPE_DATE = "date";
public static final String FIELD_TYPE_TEXT = "text";
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Tree Applet
public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults";
public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation";
public static final String PAGEOF_SPECIMEN = "pageOfSpecimen";
public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite";
//For Simple Query Interface and Edit.
public static final String PAGEOF_SIMPLE_QUERY_INTERFACE = "pageOfSimpleQueryInterface";
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
public static final String TREE_APPLET_NAME = "treeApplet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
//public static final String SELECT_OPTION = "-- Select --";
public static final int SELECT_OPTION_VALUE = -1;
// public static final String[] TISSUE_SITE_ARRAY = {
// SELECT_OPTION,"Sex","male","female",
// "Tissue","kidney","Left kidney","Right kidney"
public static final String[] ATTRIBUTE_NAME_ARRAY = {
SELECT_OPTION
};
public static final String[] ATTRIBUTE_CONDITION_ARRAY = {
"=","<",">"
};
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
public static final String [] STATEARRAY =
{
SELECT_OPTION,
"Alabama",//Alabama
"Alaska",//Alaska
"Arizona",//Arizona
"Arkansas",//Arkansas
"California",//California
"Colorado",//Colorado
"Connecticut",//Connecticut
"Delaware",//Delaware
"D.C.",
"Florida",//Florida
"Georgia",//Georgia
"Hawaii",//Hawaii
"Idaho",//Idaho
"Illinois",//Illinois
"Indiana",//Indiana
"Iowa",//Iowa
"Kansas",//Kansas
"Kentucky",//Kentucky
"Louisiana",//Louisiana
"Maine",//Maine
"Maryland",//Maryland
"Massachusetts",//Massachusetts
"Michigan",//Michigan
"Minnesota",//Minnesota
"Mississippi",//Mississippi
"Missouri",//Missouri
"Montana",//Montana
"Nebraska",//Nebraska
"Nevada",//Nevada
"New Hampshire",//New Hampshire
"New Jersey",//New Jersey
"New Mexico",//New Mexico
"New York",//New York
"North Carolina",//North Carolina
"North Dakota",//North Dakota
"Ohio",//Ohio
"Oklahoma",//Oklahoma
"Oregon",//Oregon
"Pennsylvania",//Pennsylvania
"Rhode Island",//Rhode Island
"South Carolina",//South Carolina
"South Dakota",//South Dakota
"Tennessee",//Tennessee
"Texas",//Texas
"Utah",//Utah
"Vermont",//Vermont
"Virginia",//Virginia
"Washington",//Washington
"West Virginia",//West Virginia
"Wisconsin",//Wisconsin
"Wyoming",//Wyoming
"Other",//Other
};
public static final String [] COUNTRYARRAY =
{
SELECT_OPTION,
"United States",
"Canada",
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",//Cameroon
"Cape Verde",//Cape Verde
"Cayman Islands",//Cayman Islands
"Central African Republic",//Central African Republic
"Chad",//Chad
"Chile",//Chile
"China",//China
"Christmas Island",//Christmas Island
"Cocos Islands",//Cocos Islands
"Colombia",//Colombia
"Comoros",//Comoros
"Congo",//Congo
"Cook Islands",//Cook Islands
"Costa Rica",//Costa Rica
"Cote D ivoire",//Cote D ivoire
"Croatia",//Croatia
"Cyprus",//Cyprus
"Czech Republic",//Czech Republic
"Denmark",//Denmark
"Djibouti",//Djibouti
"Dominica",//Dominica
"Dominican Republic",//Dominican Republic
"East Timor",//East Timor
"Ecuador",//Ecuador
"Egypt",//Egypt
"El Salvador",//El Salvador
"Equatorial Guinea",//Equatorial Guinea
"Eritrea",//Eritrea
"Estonia",//Estonia
"Ethiopia",//Ethiopia
"Falkland Islands",//Falkland Islands
"Faroe Islands",//Faroe Islands
"Fiji",//Fiji
"Finland",//Finland
"France",//France
"French Guiana",//French Guiana
"French Polynesia",//French Polynesia
"French S. Territories",//French S. Territories
"Gabon",//Gabon
"Gambia",//Gambia
"Georgia",//Georgia
"Germany",//Germany
"Ghana",//Ghana
"Gibraltar",//Gibraltar
"Greece",//Greece
"Greenland",//Greenland
"Grenada",//Grenada
"Guadeloupe",//Guadeloupe
"Guam",//Guam
"Guatemala",//Guatemala
"Guinea",//Guinea
"Guinea-Bissau",//Guinea-Bissau
"Guyana",//Guyana
"Haiti",//Haiti
"Honduras",//Honduras
"Hong Kong",//Hong Kong
"Hungary",//Hungary
"Iceland",//Iceland
"India",//India
"Indonesia",//Indonesia
"Iran",//Iran
"Iraq",//Iraq
"Ireland",//Ireland
"Israel",//Israel
"Italy",//Italy
"Jamaica",//Jamaica
"Japan",//Japan
"Jordan",//Jordan
"Kazakhstan",//Kazakhstan
"Kenya",//Kenya
"Kiribati",//Kiribati
"Korea",//Korea
"Kuwait",//Kuwait
"Kyrgyzstan",//Kyrgyzstan
"Laos",//Laos
"Latvia",//Latvia
"Lebanon",//Lebanon
"Lesotho",//Lesotho
"Liberia",//Liberia
"Liechtenstein",//Liechtenstein
"Lithuania",//Lithuania
"Luxembourg",//Luxembourg
"Macau",//Macau
"Macedonia",//Macedonia
"Madagascar",//Madagascar
"Malawi",//Malawi
"Malaysia",//Malaysia
"Maldives",//Maldives
"Mali",//Mali
"Malta",//Malta
"Marshall Islands",//Marshall Islands
"Martinique",//Martinique
"Mauritania",//Mauritania
"Mauritius",//Mauritius
"Mayotte",//Mayotte
"Mexico",//Mexico
"Micronesia",//Micronesia
"Moldova",//Moldova
"Monaco",//Monaco
"Mongolia",//Mongolia
"Montserrat",//Montserrat
"Morocco",//Morocco
"Mozambique",//Mozambique
"Myanmar",//Myanmar
"Namibia",//Namibia
"Nauru",//Nauru
"Nepal",//Nepal
"Netherlands",//Netherlands
"Netherlands Antilles",//Netherlands Antilles
"New Caledonia",//New Caledonia
"New Zealand",//New Zealand
"Nicaragua",//Nicaragua
"Niger",//Niger
"Nigeria",//Nigeria
"Niue",//Niue
"Norfolk Island",//Norfolk Island
"Norway",//Norway
"Oman",//Oman
"Pakistan",//Pakistan
"Palau",//Palau
"Panama",//Panama
"Papua New Guinea",//Papua New Guinea
"Paraguay",//Paraguay
"Peru",//Peru
"Philippines",//Philippines
"Pitcairn",//Pitcairn
"Poland",//Poland
"Portugal",//Portugal
"Puerto Rico",//Puerto Rico
"Qatar",//Qatar
"Reunion",//Reunion
"Romania",//Romania
"Russian Federation",//Russian Federation
"Rwanda",//Rwanda
"Saint Helena",//Saint Helena
"Saint Kitts and Nevis",//Saint Kitts and Nevis
"Saint Lucia",//Saint Lucia
"Saint Pierre",//Saint Pierre
"Saint Vincent",//Saint Vincent
"Samoa",//Samoa
"San Marino",//San Marino
"Sao Tome and Principe",//Sao Tome and Principe
"Saudi Arabia",//Saudi Arabia
"Senegal",//Senegal
"Seychelles",//Seychelles
"Sierra Leone",//Sierra Leone
"Singapore",//Singapore
"Slovakia",//Slovakia
"Slovenia",//Slovenia
"Solomon Islands",//Solomon Islands
"Somalia",//Somalia
"South Africa",//South Africa
"Spain",//Spain
"Sri Lanka",//Sri Lanka
"Sudan",//Sudan
"Suriname",//Suriname
"Swaziland",//Swaziland
"Sweden",//Sweden
"Switzerland",//Switzerland
"Syrian Arab Republic",//Syrian Arab Republic
"Taiwan",//Taiwan
"Tajikistan",//Tajikistan
"Tanzania",//Tanzania
"Thailand",//Thailand
"Togo",//Togo
"Tokelau",//Tokelau
"Tonga",//Tonga
"Trinidad and Tobago",//Trinidad and Tobago
"Tunisia",//Tunisia
"Turkey",//Turkey
"Turkmenistan",//Turkmenistan
"Turks and Caicos Islands",//Turks and Caicos Islands
"Tuvalu",//Tuvalu
"Uganda",//Uganda
"Ukraine",//Ukraine
"United Arab Emirates",//United Arab Emirates
"United Kingdom",//United Kingdom
"Uruguay",//Uruguay
"Uzbekistan",//Uzbekistan
"Vanuatu",//Vanuatu
"Vatican City State",//Vatican City State
"Venezuela",//Venezuela
"Vietnam",//Vietnam
"Virgin Islands",//Virgin Islands
"Wallis And Futuna Islands",//Wallis And Futuna Islands
"Western Sahara",//Western Sahara
"Yemen",//Yemen
"Yugoslavia",//Yugoslavia
"Zaire",//Zaire
"Zambia",//Zambia
"Zimbabwe",//Zimbabwe
};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
"Tissue",
"Fluid",
"Cell",
"Molecular"
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final HashMap STATIC_PROTECTION_GROUPS_FOR_OBJECT_TYPES = new HashMap();
//public static final String CDE_CONF_FILE = "CDEConfig.xml";
public static final String CDE_NAME_TISSUE_SITE = "Tissue Site";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
public static final String [] CLINICALDIAGNOSISARRAY = {
SELECT_OPTION,
"CLINICALDIAGNOSIS 1",
"CLINICALDIAGNOSIS 2",
"CLINICALDIAGNOSIS 3"
};
public static final String [] HISTOLOGICAL_QUALITY_ARRAY = {
SELECT_OPTION,
"GOOD",
"OK",
"DAMAGED"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER = "systemIdentifier";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
public static final String getCollectionProtocolPGName(Long identifier)
{
if(identifier == null)
{
return "COLLECTION_PROTOCOL_";
}
return "COLLECTION_PROTOCOL_"+identifier;
}
public static final String getCollectionProtocolPIGroupName(Long identifier)
{
return "COLLECTION_PROTOCOL_"+identifier;
}
public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
{
return "COLLECTION_PROTOCOL_"+identifier;
}
public static final String ACCESS_DENIED_ADMIN = "access_denied_admin";
public static final String ACCESS_DENIED_BIOSPECIMEN = "access_denied_biospecimen";
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
//public static final String ANY = "Any";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param systemIdentifier
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param systemIdentifier
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
public static final String SLIDE = "Slide";
public static final String PARAFFIN_BLOCK = "Paraffin Block";
public static final String FROZEN_BLOCK = "Frozen Block";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtocolRegistration","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
//public static final String DELIMETER = ",";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Specimen Identifier",
"Specimen.TYPE.Specimen Type",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side",
"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status",
"DistributedItem.QUANTITY.Specimen Quantity"};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?operation=add&pageOf=pageOfDistribution&specimenIdKey=";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_NON_VALIDATE_ACTION = "ConfigureSimpleQueryNonValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SIMPLE_QUERY_MAP = "simpleQueryMap";
public static final String SIMPLE_QUERY_ALIAS_NAME = "simpleQueryAliasName";
public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
// MD : LightYellow and Green colors
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// Aarti: Constants for security parameter required
//while retrieving data from DAOs
public static final int INSECURE_RETRIEVE = 0;
public static final int CLASS_LEVEL_SECURE_RETRIEVE = 1;
public static final int OBJECT_LEVEL_SECURE_RETRIEVE = 2;
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Derive New From This Specimen", "createNew"},
{"Add Events", "eventParameters"},
{"Add More To Same Collection Group", "sameCollectionGroup"}
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Add New Specimen", "createNewSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Specimen Collection Group", "createSpecimenCollectionGroup"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String COLLECTION_PROTOCOL ="CollectionProtocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITION_NODES_MAP = "advancedConditionNodesMap";
public static final String TREE_VECTOR = "treeVector";
public static final String ADVANCED_CONDITIONS_ROOT = "advancedCondtionsRoot";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String COLUMN_ID_MAP = "columnIdsMap";
public static final String PARENT_SPECIMEN_ID_COLUMN = "PARENT_SPECIMEN_ID";
public static final String COLUMN = "Column";
public static final String COLUMN_DISPLAY_NAMES = "columnDisplayNames";
// -- menu selection related
public static final String MENU_SELECTED = "menuSelected";
public static final String CONSTRAINT_VOILATION_ERROR = "Submission failed since a {0} with the same {1} already exists";
public static final String GENERIC_DATABASE_ERROR = "An error occured during a database operation. Please report this problem to the adminstrator";
// The unique key voilation message is "Duplicate entry %s for key %d"
// This string is used for searching " for key " string in the above error message
public static final String MYSQL_DUPL_KEY_MSG = " for key ";
public static final String CATISSUE_SPECIMEN = "CATISSUE_SPECIMEN";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String DATABASE_IN_USED = "MYSQL";
public static final String PASSWORD_CHANGE_IN_SESSION = "changepassword";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
} |
package edu.wustl.catissuecore.util.global;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
//Constants added for Catissuecore V1.2
public static final String PAGE_OF_ADMINISTRATOR = "pageOfAdministrator";
public static final String PAGE_OF_SUPERVISOR = "pageOfSupervisor";
public static final String PAGE_OF_TECHNICIAN = "pageOfTechnician";
public static final String PAGE_OF_SCIENTIST = "pageOfScientist";
//Constants added for Validation
public static final String DEFAULT_TISSUE_SITE ="defaultTissueSite";
public static final String DEFAULT_CLINICAL_STATUS ="defaultClinicalStatus";
public static final String DEFAULT_GENDER = "defaultGender";
public static final String DEFAULT_GENOTYPE = "defaultGenotype";
public static final String DEFAULT_SPECIMEN = "defaultSpecimen";
public static final String DEFAULT_TISSUE_SIDE = "defaultTissueSide";
public static final String DEFAULT_PATHOLOGICAL_STATUS = "defaultPathologicalStatus";
public static final String DEFAULT_RECEIVED_QUALITY= "defaultReceivedQuality";
public static final String DEFAULT_FIXATION_TYPE = "defaultFixationType";
public static final String DEFAULT_COLLECTION_PROCEDURE="defaultCollectionProcedure";
public static final String DEFAULT_CONTAINER= "defaultContainer";
public static final String DEFAULT_METHOD= "defaultMethod";
public static final String DEFAULT_EMBEDDING_MEDIUM="defaultEmbeddingMedium";
public static final String DEFAULT_BIOHAZARD="defaultBiohazard";
public static final String DEFAULT_SITE_TYPE ="defaultSiteType";
public static final String DEFAULT_SPECIMEN_TYPE ="defaultSpecimenType";
public static final String DEFAULT_ETHNICITY ="defaultEthnicity";
public static final String DEFAULT_RACE ="defaultRace";
public static final String DEFAULT_CLINICAL_DIAGNOSIS = "defaultClinicalDiagnosis";
public static final String DEFAULT_STATES ="defaultStates";
public static final String DEFAULT_COUNTRY ="defaultCountry";
public static final String DEFAULT_HISTOLOGICAL_QUALITY="defaultHistologicalQuality";
public static final String DEFAULT_VITAL_STATUS ="defaultVitalStatus";
//Consent tracking
public static final String SHOW_CONSENTS="showConsents";
public static final String SPECIMEN_CONSENTS="specimenConsents";
public static final String YES="yes";
public static final String CP_ID="cpID";
public static final String BARCODE_LABLE="barcodelabel";
public static final String DISTRIBUTION_ON="labelBarcode";
public static final String POPUP="popup";
public static final String ERROR="error";
public static final String ERROR_SHOWCONSENTS="errorShowConsent";
public static final String COMPLETE="Complete";
public static final String VIEW_CONSENTS="View";
public static final String APPLY="Apply";
public static final String APPLY_ALL="ApplyAll";
public static final String APPLY_NONE="ApplyNone";
public static final String PREDEFINED_CADSR_CONSENTS="predefinedConsentsList";
public static final String DISABLED="disabled";
public static final String VIEWAll="ViewAll";
public static final String BARCODE_DISTRIBUTION="1";
public static final String LABLE_DISTRIBUTION="2";
public static final String CONSENT_WAIVED="Consent Waived";
public static final String NO_CONSENTS="No Consents";
public static final String INVALID="Invalid";
public static final String VALID="valid";
public static final String FALSE="false";
public static final String TRUE="true";
public static final String NULL="null";
public static final String CONSENT_TABLE="tableId4";
public static final String DISABLE="disable";
public static final String SCG_ID="-1";
public static final String SELECTED_TAB="tab";
public static final String TAB_SELECTED="tabSelected";
public static final String NEWSPECIMEN_FORM="newSpecimenForm";
public static final String CONSENT_TABLE_SHOWHIDE="tableStatus";
public static final String SPECIMEN_RESPONSELIST="specimenResponseList";
public static final String PROTOCOL_EVENT_ID="protocolEventId";
public static final String SCG_DROPDOWN="value";
public static final String HASHED_OUT="
public static final String VERIFIED="Verified";
public static final String STATUS="status";
public static final String NOT_APPLICABLE="Not Applicable";
public static final String WITHDRAW_ALL="withrawall";
public static final String RESPONSE="response";
public static final String WITHDRAW="withdraw";
public static final String VIRTUALLY_LOCATED="Virtually Located";
public static final String LABLE="Lable";
public static final String STORAGE_CONTAINER_LOCATION="Storage Container Location";
public static final String CLASS_NAME="Class Name";
public static final String SPECIMEN_LIST="specimenDetails";
public static final String COLUMNLIST="columnList";
public static final String [][] defaultValueKeys= {
{Constants.DEFAULT_TISSUE_SITE, Constants.CDE_NAME_TISSUE_SITE},
{Constants.DEFAULT_CLINICAL_STATUS, Constants.CDE_NAME_CLINICAL_STATUS},
{Constants.DEFAULT_GENDER, Constants.CDE_NAME_GENDER},
{Constants.DEFAULT_GENOTYPE, Constants.CDE_NAME_GENOTYPE},
{Constants.DEFAULT_SPECIMEN, Constants.CDE_NAME_SPECIMEN_CLASS},
{Constants.DEFAULT_TISSUE_SIDE, Constants.CDE_NAME_TISSUE_SIDE},
{Constants.DEFAULT_PATHOLOGICAL_STATUS, Constants.CDE_NAME_PATHOLOGICAL_STATUS},
{Constants.DEFAULT_RECEIVED_QUALITY, Constants.CDE_NAME_RECEIVED_QUALITY},
{Constants.DEFAULT_FIXATION_TYPE, Constants.CDE_NAME_FIXATION_TYPE},
{Constants.DEFAULT_COLLECTION_PROCEDURE, Constants.CDE_NAME_COLLECTION_PROCEDURE},
{Constants.DEFAULT_CONTAINER, Constants.CDE_NAME_CONTAINER},
{Constants.DEFAULT_METHOD, Constants.CDE_NAME_METHOD},
{Constants.DEFAULT_EMBEDDING_MEDIUM,Constants.CDE_NAME_EMBEDDING_MEDIUM},
{Constants.DEFAULT_BIOHAZARD, Constants.CDE_NAME_BIOHAZARD},
{Constants.DEFAULT_SITE_TYPE, Constants.CDE_NAME_SITE_TYPE},
{Constants.DEFAULT_SPECIMEN_TYPE, Constants.CDE_NAME_SPECIMEN_TYPE},
{Constants.DEFAULT_ETHNICITY, Constants.CDE_NAME_ETHNICITY},
{Constants.DEFAULT_RACE, Constants.CDE_NAME_RACE},
{Constants.DEFAULT_CLINICAL_DIAGNOSIS, Constants.CDE_NAME_CLINICAL_DIAGNOSIS},
{Constants.DEFAULT_STATES, Constants.CDE_NAME_STATE_LIST},
{Constants.DEFAULT_COUNTRY, Constants.CDE_NAME_COUNTRY_LIST},
{Constants.DEFAULT_HISTOLOGICAL_QUALITY, Constants.CDE_NAME_HISTOLOGICAL_QUALITY},
{Constants.DEFAULT_VITAL_STATUS, Constants.CDE_VITAL_STATUS}
};
//Constants added for Catissuecore V1.2
public static final String MYSQL_NUM_TO_STR_FUNCTION_NAME_FOR_LABEL_GENRATION= "cast(label as signed)";
public static final String ORACLE_NUM_TO_STR_FUNCTION_NAME_FOR_LABEL_GENRATION = "catissue_label_to_num(label)";
// Query Module Interface UI constants
public static final String ViewSearchResultsAction = "ViewSearchResultsAction.do";
public static final String categorySearchForm = "categorySearchForm";
public static final String SearchCategory = "SearchCategory.do";
public static final String DefineSearchResultsViewAction = "DefineSearchResultsView.do";
public static final String DefineSearchResultsViewJSPAction = "ViewSearchResultsJSPAction.do";
public static final String QUERY_DAG_VIEW_APPLET = "edu/wustl/catissuecore/applet/ui/querysuite/DiagrammaticViewApplet.class";
public static final String QUERY_DAG_VIEW_APPLET_NAME = "Dag View Applet";
public static final String APP_DYNAMIC_UI_XML = "xmlfile.dynamicUI";
public static final String QUERY_CONDITION_DELIMITER = "@#condition#@";
public static final String QUERY_OPERATOR_DELIMITER = "!*=*!";
public static final String SEARCHED_ENTITIES_MAP = "searchedEntitiesMap";
public static final String SUCCESS = "success";
public static final String LIST_OF_ENTITIES_IN_QUERY = "ListOfEntitiesInQuery";
public static final String DYNAMIC_UI_XML = "dynamicUI.xml";
public static final String TREE_DATA = "treeData";
public static final String ZERO_ID = "0";
public static final String TEMP_OUPUT_TREE_TABLE_NAME = "temp_OutputTree";
public static final String CREATE_TABLE = "Create table ";
public static final String AS = "as";
public static final String UNDERSCORE = "_";
public static final String ID_NODES_MAP = "idNodesMap";
public static final String ID_COLUMNS_MAP = "idColumnsMap";
public static final String COLUMN_NAME = "Column";
public static final String[] ATTRIBUTE_NAMES_FOR_TREENODE_LABEL = {
"firstName",
"lastName",
"title",
"name",
"label"
};
public static final String MISSING_TWO_VALUES = "missingTwoValues";
public static final String DATE = "date";
public static final String DEFINE_RESULTS_VIEW = "DefineResultsView";
public static final String CURRENT_PAGE = "currentPage";
public static final String ADD_LIMITS = "AddLimits";
public static final String LABEL_TREE_NODE = "Label";
public static final String ENTITY_NAME = "Entity Name";
public static final String COUNT = "Count";
public static final String TREE_NODE_FONT = "<font color='#FF9BFF' face='Verdana'><i>";
public static final String TREE_NODE_FONT_CLOSE = "</i></font>";
public static final String NULL_ID = "NULL";
public static final String NODE_SEPARATOR = "::";
public static final String DEFINE_SEARCH_RULES = "Define Search Rules For";
public static final String DATE_FORMAT = "MM-dd-yyyy";
public static final String OUTPUT_TREE_MAP = "outputTreeMap";
// Frame names in Query Module Results page.
public static final String GRID_DATA_VIEW_FRAME = "gridFrame";
public static final String TREE_VIEW_FRAME = "treeViewFrame";
public static final String QUERY_TREE_VIEW_ACTION = "QueryTreeView.do";
public static final String QUERY_GRID_VIEW_ACTION = "QueryGridView.do";
public static final String NO_OF_TREES = "noOfTrees";
public static final String PAGEOF_QUERY_MODULE = "pageOfQueryModule";
public static final String TREE_ROOTS = "treeRoots";
// Frame names in Query Module Results page.--ends here
public static final String MAX_IDENTIFIER = "maxIdentifier";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String DATE_SEPARATOR_DOT = ".";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
public static final String VIEW = "view";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
public static final String ACCESS = "access";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String VITAL_STATUS_LIST = "vitalStatusList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
public static final String SPECIMEN_COLL_GP_NAME = "specimenCollectionGroupName";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String MAP_OF_STORAGE_CONTAINERS = "storageContainerMap";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerIds";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
public static final String MAP_COLLECTION_PROTOCOL_LIST = "collectionProtocolList";
public static final String MAP_SPECIMEN_CLASS_LIST = "specimenClassList";
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROM_SITE_LIST="fromsiteList";
public static final String TO_SITE_LIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String RNA = "RNA";
// New Participant Event Parameters
public static final String PARTICIPANT_ID="participantId";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String HOLDS_LIST1 = "HoldsList1";
public static final String HOLDS_LIST2 = "HoldsList2";
public static final String HOLDS_LIST3 = "HoldsList3";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "AddSpecimen.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
public static final String SPECIMENARRAYTYPE_ADD_ACTION = "SpecimenArrayTypeAdd.do?operation=add";
public static final String SPECIMENARRAYTYPE_EDIT_ACTION = "SpecimenArrayTypeEdit.do?operation=edit";
public static final String ARRAY_DISTRIBUTION_ADD_ACTION = "ArrayDistributionAdd.do";
public static final String SPECIMENARRAY_ADD_ACTION = "SpecimenArrayAdd.do";
public static final String SPECIMENARRAY_EDIT_ACTION = "SpecimenArrayEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Aliquots Action
public static final String ALIQUOT_ACTION = "Aliquots.do";
public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do";
public static final String ALIQUOT_SUMMARY_ACTION = "AliquotSummary.do";
//Constants related to Aliquots functionality
public static final String PAGEOF_ALIQUOT = "pageOfAliquot";
public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot";
public static final String PAGEOF_ALIQUOT_SUMMARY = "pageOfAliquotSummary";
public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap";
public static final String COMMON_ADD_EDIT = "commonAddEdit";
//Constants related to SpecimenArrayAliquots functionality
public static final String STORAGE_TYPE_ID="storageTypeId";
public static final String ALIQUOT_SPECIMEN_ARRAY_TYPE="SpecimenArrayType";
public static final String ALIQUOT_SPECIMEN_CLASS="SpecimenClass";
public static final String ALIQUOT_SPECIMEN_TYPES="SpecimenTypes";
public static final String ALIQUOT_ALIQUOT_COUNTS="AliquotCounts";
//Specimen Array Aliquots pages
public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT = "pageOfSpecimenArrayAliquot";
public static final String PAGEOF_SPECIMEN_ARRAY_CREATE_ALIQUOT = "pageOfSpecimenArrayCreateAliquot";
public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT_SUMMARY = "pageOfSpecimenArrayAliquotSummary";
//Specimen Array Aliquots Action
public static final String SPECIMEN_ARRAY_ALIQUOT_ACTION = "SpecimenArrayAliquots.do";
public static final String SPECIMEN_ARRAY_CREATE_ALIQUOT_ACTION = "SpecimenArrayCreateAliquots.do";
//Constants related to QuickEvents functionality
public static final String QUICKEVENTS_ACTION = "QuickEventsSearch.do";
public static final String QUICKEVENTSPARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//SimilarContainers Action
public static final String SIMILAR_CONTAINERS_ACTION = "SimilarContainers.do";
public static final String CREATE_SIMILAR_CONTAINERS_ACTION = "CreateSimilarContainers.do";
public static final String SIMILAR_CONTAINERS_ADD_ACTION = "SimilarContainersAdd.do";
//Constants related to Similar Containsers
public static final String PAGEOF_SIMILAR_CONTAINERS = "pageOfSimilarContainers";
public static final String PAGEOF_CREATE_SIMILAR_CONTAINERS = "pageOfCreateSimilarContainers";
public static final String PAGEOF_STORAGE_CONTAINER = "pageOfStorageContainer";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String TABLE_NAME_COLUMN = "TABLE_NAME";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?id=";
public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?id=";
public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?id=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "QuerySpecimenCollectionGroupAdd.do";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?id=";
public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?id=";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//For getting the tables for Simple Query and Fcon Query.
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int DEFAULT_BIZ_LOGIC = 0;
public static final int USER_FORM_ID = 1;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int ALIQUOT_FORM_ID = 44;
public static final int QUICKEVENTS_FORM_ID = 45;
public static final int LIST_SPECIMEN_EVENT_PARAMETERS_FORM_ID = 46;
public static final int SIMILAR_CONTAINERS_FORM_ID = 47; // chetan (13-07-2006)
public static final int SPECIMEN_ARRAY_TYPE_FORM_ID = 48;
public static final int ARRAY_DISTRIBUTION_FORM_ID = 49;
public static final int SPECIMEN_ARRAY_FORM_ID = 50;
public static final int SPECIMEN_ARRAY_ALIQUOT_FORM_ID = 51;
public static final int ASSIGN_PRIVILEGE_FORM_ID = 52;
public static final int CDE_FORM_ID = 53;
public static final int MULTIPLE_SPECIMEN_STOGAGE_LOCATION_FORM_ID = 54;
public static final int REQUEST_LIST_FILTERATION_FORM_ID = 55;
public static final int ORDER_FORM_ID = 56;
public static final int ORDER_ARRAY_FORM_ID = 57;
public static final int REQUEST_DETAILS_FORM_ID = 64;
public static final int ORDER_PATHOLOGY_FORM_ID = 58;
public static final int NEW_PATHOLOGY_FORM_ID=59;
public static final int DEIDENTIFIED_SURGICAL_PATHOLOGY_REPORT_FORM_ID=60;
public static final int PATHOLOGY_REPORT_REVIEW_FORM_ID=61;
public static final int QUARANTINE_EVENT_PARAMETER_FORM_ID=62;
//Misc
public static final String SEPARATOR = " : ";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 20;
public static final int NUMBER_RESULTS_PER_PAGE_SEARCH = 15;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Query Interface Results View Constants
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Simple Query Interface and Edit.
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_DEASSIGN = false;
public static final String OPERATION_DISALLOW = "Disallow";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class";
public static final String APPLET_CODEBASE = "Applet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final int SELECT_OPTION_VALUE = -1;
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String [] DISPOSAL_EVENT_ACTIVITY_STATUS_VALUES = {
"Closed",
"Disabled"
};
public static final String TISSUE = "Tissue";
public static final String FLUID = "Fluid";
public static final String CELL = "Cell";
public static final String MOLECULAR = "Molecular";
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
TISSUE,
FLUID,
CELL,
MOLECULAR
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String UNIT_CL = "cells";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_VITAL_STATUS = "Vital Status";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
public static final String CDE_NAME_COUNTRY_LIST = "Countries";
public static final String CDE_NAME_STATE_LIST = "States";
public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String DERIVED_SPECIMEN_COLUMNS[] = { "Label",
"Class", "Type", "Quantity", "rowSelected"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege";
public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param id
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param id
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
//Mandar 25-Apr-06 : bug 1414 : Tissue units as per type
// tissue types with unit= count
public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK
public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE
public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK
public static final String NOT_SPECIFIED = "Not Specified";
public static final String WITHDRAWN = "Withdrawn";
// tissue types with unit= g
public static final String FRESH_TISSUE = "Fresh Tissue";
public static final String FROZEN_TISSUE = "Frozen Tissue";
public static final String FIXED_TISSUE = "Fixed Tissue";
public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide";
//tissue types with unit= cc
public static final String MICRODISSECTED = "Microdissected";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String SPECIMEN_COLUMN_NAMES_LIST = "specimenColumnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
public static final String ARRAY_DISTRIBUTION_REPORT_ACTION = "ArrayDistributionReport.do";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="ArrayDistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.LABEL.Lable : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"Specimen.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
"DistributedItem.QUANTITY.Quantity : Distribution"};
//"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
public static final String SPECIMEN_IN_ARRAY_SELECTED_COLUMNS[] = {
"Specimen.LABEL.Label : Specimen",
"Specimen.BARCODE.barcode : Specimen",
"SpecimenArrayContent.PositionDimensionOne.PositionDimensionOne : Specimen",
"SpecimenArrayContent.PositionDimensionTwo.PositionDimensionTwo : Specimen",
"Specimen.CLASS.CLASS : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
};
public static final String ARRAY_SELECTED_COLUMNS[] = {
"SpecimenArray.Name.Name : SpecimenArray",
"Container.barcode.Barcode : SpecimenArray",
"ContainerType.name.ArrayType : ContainerType",
"Container.PositionDimensionOne.Position One: Container",
"Container.PositionDimensionTwo.Position Two: Container",
"Container.CapacityOne.Dimension One: Container",
"Container.CapacityTwo.Dimension Two: Container",
"ContainerType.SpecimenClass.specimen class : ContainerType",
"ContainerType.SpecimenTypes.specimen Types : ContainerType",
"Container.Comment.comment: Container",
};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
public static final String DISTRIBUTED_ITEM = "DistributedItem";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute";
//public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
public static final String UNSPECIFIED = "Unspecified";
public static final String NOTSPECIFIED = "Not Specified";
public static final String SEARCH_RESULT = "SearchResult.csv";
// Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
// Light and dark shades of GREY.
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Derive", "createNew"},
{"Add Events", "eventParameters"},
{"More", "sameCollectionGroup"},
{"Distribute", "distribution" }
};
public static final String [] SPECIMEN_BUTTON_TIPS = {
"Submit only",
"Submit and derive",
"Submit and add events",
"Submit and add more to same group",
"Submit and distribute"
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Add Specimen", "createNewSpecimen"},
{"Add Multiple Specimens", "createMultipleSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Specimen Collection Group", "createSpecimenCollectionGroup"}
};
public static final String [][] PARTICIPANT_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Register to Protocol", "createParticipantRegistration"},
{"Specimen Collection Group", "specimenCollectionGroup"}
};
public static final String [][] STORAGE_TYPE_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Add Container", "storageContainer"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String[] ADVANCE_QUERY_TREE_HEIRARCHY={ //Represents the Advance Query tree Heirarchy.
Constants.PARTICIPANT,
Constants.COLLECTION_PROTOCOL,
Constants.SPECIMEN_COLLECTION_GROUP,
Constants.SPECIMEN
};
public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol";
public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group";
public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "pAND";
public static final String EVENT_CONDITIONS = "eventConditions";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit";
public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit";
public static final String PARTICIPANT_COLUMNS = "particpantColumns";
public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns";
public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns";
public static final String SPECIMEN_COLUMNS = "SpecimenColumns";
public static final String USER_ID_COLUMN = "USER_ID";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain";
//Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic
public static final boolean IS_AUDITABLE_TRUE = true;
public static final boolean IS_SECURE_UPDATE_TRUE = true;
public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false;
//Constants for HTTP-API
public static final String CONTENT_TYPE = "CONTENT-TYPE";
// For StorageContainer isFull status
public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList";
public static final String [] IS_CONTAINER_FULL_VALUES = {
SELECT_OPTION,
"True",
"False"
};
public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel";
public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel";
// public static final String SPECIMEN_TYPE_TISSUE = "Tissue";
// public static final String SPECIMEN_TYPE_FLUID = "Fluid";
// public static final String SPECIMEN_TYPE_CELL = "Cell";
// public static final String SPECIMEN_TYPE_MOL = "Molecular";
public static final String SPECIMEN_TYPE_COUNT = "Count";
public static final String SPECIMEN_TYPE_QUANTITY = "Quantity";
public static final String SPECIMEN_TYPE_DETAILS = "Details";
public static final String SPECIMEN_COUNT = "totalSpecimenCount";
public static final String TOTAL = "Total";
public static final String SPECIMENS = "Specimens";
//User Roles
public static final String TECHNICIAN = "Technician";
public static final String SUPERVISOR = "Supervisor";
public static final String SCIENTIST = "Scientist";
public static final String CHILD_CONTAINER_TYPE = "childContainerType";
public static final String UNUSED = "Unused";
public static final String TYPE = "Type";
//Mandar: 28-Apr-06 Bug 1129
public static final String DUPLICATE_SPECIMEN="duplicateSpecimen";
//Constants required in ParticipantLookupAction
public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter";
public static final String PARTICIPANT_LOOKUP_CUTOFF="lookup.cutoff";
public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo";
public static final String PARTICIPANT_LOOKUP_SUCCESS="success";
public static final String PARTICIPANT_ADD_FORWARD="participantAdd";
public static final String PARTICIPANT_SYSTEM_IDENTIFIER="IDENTIFIER";
public static final String PARTICIPANT_LAST_NAME="LAST_NAME";
public static final String PARTICIPANT_FIRST_NAME="FIRST_NAME";
public static final String PARTICIPANT_MIDDLE_NAME="MIDDLE_NAME";
public static final String PARTICIPANT_BIRTH_DATE="BIRTH_DATE";
public static final String PARTICIPANT_DEATH_DATE="DEATH_DATE";
public static final String PARTICIPANT_VITAL_STATUS="VITAL_STATUS";
public static final String PARTICIPANT_GENDER="GENDER";
public static final String PARTICIPANT_SEX_GENOTYPE="SEX_GENOTYPE";
public static final String PARTICIPANT_RACE="RACE";
public static final String PARTICIPANT_ETHINICITY="ETHINICITY";
public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SOCIAL_SECURITY_NUMBER";
public static final String PARTICIPANT_PROBABLITY_MATCH="Probability";
public static final String PARTICIPANT_SSN_EXACT="SSNExact";
public static final String PARTICIPANT_SSN_PARTIAL="SSNPartial";
public static final String PARTICIPANT_DOB_EXACT="DOBExact";
public static final String PARTICIPANT_DOB_PARTIAL="DOBPartial";
public static final String PARTICIPANT_LAST_NAME_EXACT="LastNameExact";
public static final String PARTICIPANT_LAST_NAME_PARTIAL="LastNamePartial";
public static final String PARTICIPANT_FIRST_NAME_EXACT="NameExact";
public static final String PARTICIPANT_FIRST_NAME_PARTIAL="NamePartial";
public static final String PARTICIPANT_MIDDLE_NAME_EXACT="MiddleNameExact";
public static final String PARTICIPANT_MIDDLE_NAME_PARTIAL="MiddleNamePartial";
public static final String PARTICIPANT_GENDER_EXACT="GenderExact";
public static final String PARTICIPANT_RACE_EXACT="RaceExact";
public static final String PARTICIPANT_RACE_PARTIAL="RacePartial";
public static final String PARTICIPANT_BONUS="Bonus";
public static final String PARTICIPANT_TOTAL_POINTS="TotalPoints";
public static final String PARTICIPANT_MATCH_CHARACTERS_FOR_LAST_NAME="MatchCharactersForLastName";
//Constants for integration of caTies and CAE with caTissue Core
public static final String LINKED_DATA = "linkedData";
public static final String APPLICATION_ID = "applicationId";
public static final String CATIES = "caTies";
public static final String CAE = "cae";
public static final String EDIT_TAB_LINK = "editTabLink";
public static final String CATIES_PUBLIC_SERVER_NAME = "CaTiesPublicServerName";
public static final String CATIES_PRIVATE_SERVER_NAME = "CaTiesPrivateServerName";
//Constants for StorageContainerMap Applet
public static final String CONTAINER_STYLEID = "containerStyleId";
public static final String CONTAINER_STYLE = "containerStyle";
public static final String XDIM_STYLEID = "xDimStyleId";
public static final String YDIM_STYLEID = "yDimStyleId";
public static final String SELECTED_CONTAINER_NAME="selectedContainerName";
public static final String CONTAINERID="containerId";
public static final String POS1="pos1";
public static final String POS2="pos2";
//Constants for QuickEvents
public static final String EVENT_SELECTED = "eventSelected";
//Constant for SpecimenEvents page.
public static final String EVENTS_TITLE_MESSAGE = "Existing events for the specimen with label {0}";
public static final String SURGICAL_PATHOLOGY_REPORT = "Surgical Pathology Report";
public static final String CLINICAL_ANNOTATIONS = "Clinical Annotations";
//Constants for Specimen Collection Group name- new field
public static final String RESET_NAME ="resetName";
// Labels for Storage Containers
public static final String[] STORAGE_CONTAINER_LABEL = {" Name"," Pos1"," Pos2"};
//Constans for Any field
public static final String HOLDS_ANY = "--All
//Constants : Specimen -> lineage
public static final String NEW_SPECIMEN = "New";
public static final String DERIVED_SPECIMEN = "Derived";
public static final String ALIQUOT = "Aliquot";
//Constant for length of messageBody in Reported problem page
public static final int messageLength= 500;
public static final String NEXT_NUMBER="nextNumber";
// public static final String getCollectionProtocolPIGroupName(Long identifier)
// if(identifier == null)
// return "PI_COLLECTION_PROTOCOL_";
// return "PI_COLLECTION_PROTOCOL_"+identifier;
// public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
// if(identifier == null)
// return "COORDINATORS_COLLECTION_PROTOCOL_";
// return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier;
// public static final String getDistributionProtocolPIGroupName(Long identifier)
// if(identifier == null)
// return "PI_DISTRIBUTION_PROTOCOL_";
// return "PI_DISTRIBUTION_PROTOCOL_"+identifier;
// public static final String getCollectionProtocolPGName(Long identifier)
// if(identifier == null)
// return "COLLECTION_PROTOCOL_";
// return "COLLECTION_PROTOCOL_"+identifier;
// public static final String getDistributionProtocolPGName(Long identifier)
// if(identifier == null)
// return "DISTRIBUTION_PROTOCOL_";
// return "DISTRIBUTION_PROTOCOL_"+identifier;
public static final String ALL = "All";
//constant for pagination data list
public static final String PAGINATION_DATA_LIST = "paginationDataList";
public static final int SPECIMEN_DISTRIBUTION_TYPE = 1;
public static final int SPECIMEN_ARRAY_DISTRIBUTION_TYPE = 2;
public static final int BARCODE_BASED_DISTRIBUTION = 1;
public static final int LABEL_BASED_DISTRIBUTION = 2;
public static final String DISTRIBUTION_TYPE_LIST = "DISTRIBUTION_TYPE_LIST";
public static final String DISTRIBUTION_BASED_ON = "DISTRIBUTION_BASED_ON";
public static final String SYSTEM_LABEL = "label";
public static final String SYSTEM_BARCODE = "barcode";
public static final String SYSTEM_NAME = "name";
//Mandar : 05Sep06 Array for multiple specimen field names
public static final String DERIVED_OPERATION = "derivedOperation";
public static final String [] MULTIPLE_SPECIMEN_FIELD_NAMES = {
"Collection Group",
"Parent ID",
"Name",
"Barcode",
"Class",
"Type",
"Tissue Site",
"Tissue Side",
"Pathological Status",
"Concentration",
"Quantity",
"Storage Location",
"Comments",
"Events",
"External Identifier",
"Biohazards"
// "Derived",
// "Aliquots"
};
public static final String PAGEOF_MULTIPLE_SPECIMEN = "pageOfMultipleSpecimen";
public static final String PAGEOF_MULTIPLE_SPECIMEN_MAIN = "pageOfMultipleSpecimenMain";
public static final String MULTIPLE_SPECIMEN_ACTION = "MultipleSpecimen.do";
public static final String INIT_MULTIPLE_SPECIMEN_ACTION = "InitMultipleSpecimen.do";
public static final String MULTIPLE_SPECIMEN_APPLET_ACTION = "MultipleSpecimenAppletAction.do";
public static final String NEW_MULTIPLE_SPECIMEN_ACTION = "NewMultipleSpecimenAction.do";
public static final String MULTIPLE_SPECIMEN_RESULT = "multipleSpecimenResult";
public static final String SAVED_SPECIMEN_COLLECTION = "savedSpecimenCollection";
public static final String [] MULTIPLE_SPECIMEN_FORM_FIELD_NAMES = {
"CollectionGroup",
"ParentID",
"Name",
"Barcode",
"Class",
"Type",
"TissueSite",
"TissueSide",
"PathologicalStatus",
"Concentration",
"Quantity",
"StorageLocation",
"Comments",
"Events",
"ExternalIdentifier",
"Biohazards"
// "Derived",
// "Aliquots"
};
public static final String MULTIPLE_SPECIMEN_MAP_KEY = "MULTIPLE_SPECIMEN_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_EVENT_MAP_KEY = "MULTIPLE_SPECIMEN_EVENT_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY = "MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY = "MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_LABEL_MAP_KEY = "MULTIPLE_SPECIMEN_LABEL_MAP_KEY";
public static final String DERIVED_FORM = "DerivedForm";
public static final String SPECIMEN_ATTRIBUTE_KEY = "specimenAttributeKey";
public static final String SPECIMEN_CLASS = "specimenClass";
public static final String SPECIMEN_CALL_BACK_FUNCTION = "specimenCallBackFunction";
public static final String APPEND_COUNT = "_count";
public static final String EXTERNALIDENTIFIER_TYPE = "ExternalIdentifier";
public static final String BIOHAZARD_TYPE = "BioHazard";
public static final String COMMENTS_TYPE = "comments";
public static final String EVENTS_TYPE = "Events";
public static final String MULTIPLE_SPECIMEN_APPLET_NAME = "MultipleSpecimenApplet";
public static final String INPUT_APPLET_DATA = "inputAppletData";
// Start Specimen Array Applet related constants
public static final String SPECIMEN_ARRAY_APPLET = "edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.class";
public static final String SPECIMEN_ARRAY_APPLET_NAME = "specimenArrayApplet";
public static final String SPECIMEN_ARRAY_CONTENT_KEY = "SpecimenArrayContentKey";
public static final String SPECIMEN_LABEL_COLUMN_NAME = "label";
public static final String SPECIMEN_BARCODE_COLUMN_NAME = "barcode";
public static final String ARRAY_SPECIMEN_DOES_NOT_EXIST_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!!specimen does not exist ";
public static final String ARRAY_SPECIMEN_NOT_ACTIVE_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!! Specimen is closed/disabled ";
public static final String ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE = "Specimen Array should contain at least one specimen";
public static final String ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE = "Please add compatible specimens to specimen array (belong to same specimen class & specimen types of Array)";
public static final String ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE = "Please enter quantity for Molecular Specimen
/**
* Specify the SPECIMEN_ARRAY_LIST as key for specimen array type list
*/
public static final String SPECIMEN_ARRAY_TYPE_LIST = "specimenArrayList";
public static final String SPECIMEN_ARRAY_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArray";
public static final String SPECIMEN_ARRAY_TYPE_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArrayType";
// End
// Common Applet Constants
public static final String APPLET_SERVER_HTTP_START_STR = "http:
public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL";
public static final String IS_NOT_NULL = "is not null";
public static final String IS_NULL = "is null";
// Used in array action
public static final String ARRAY_TYPE_ANY_VALUE = "2";
public static final String ARRAY_TYPE_ANY_NAME = "Any";
// end
// Array Type All Id in table
public static final short ARRAY_TYPE_ALL_ID = 2;
// constants required for caching mechanism of ParticipantBizLogic
public static final String MAP_OF_PARTICIPANTS = "listOfParticipants";
public static final String LIST_OF_REGISTRATION_INFO = "listOfParticipantRegistrations";
public static final String EHCACHE_FOR_CATISSUE_CORE = "cacheForCaTissueCore";
public static final String MAP_OF_DISABLED_CONTAINERS = "listOfDisabledContainers";
public static final String MAP_OF_CONTAINER_FOR_DISABLED_SPECIEN = "listOfContainerForDisabledContainerSpecimen";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String ID = "id";
public static final String MANAGE_BIO_SPECIMEN_ACTION = "/ManageBioSpecimen.do";
public static final String CREATE_PARTICIPANT_REGISTRATION = "createParticipantRegistration";
public static final String CREATE_PARTICIPANT_REGISTRATION_ADD = "createParticipantRegistrationAdd";
public static final String CREATE_PARTICIPANT_REGISTRATION_EDIT= "createParticipantRegistrationEdit";
public static final String CAN_HOLD_CONTAINER_TYPE = "holdContainerType";
public static final String CAN_HOLD_SPECIMEN_CLASS = "holdSpecimenClass";
public static final String CAN_HOLD_COLLECTION_PROTOCOL = "holdCollectionProtocol";
public static final String CAN_HOLD_SPECIMEN_ARRAY_TYPE = "holdSpecimenArrayType";
public static final String COLLECTION_PROTOCOL_ID = "collectionProtocolId";
public static final String SPECIMEN_CLASS_NAME = "specimeClassName";
public static final String ENABLE_STORAGE_CONTAINER_GRID_PAGE = "enablePage";
public static final int ALL_STORAGE_TYPE_ID = 1; //Constant for the "All" storage type, which can hold all container type
public static final int ALL_SPECIMEN_ARRAY_TYPE_ID = 2;//Constant for the "All" storage type, which can hold all specimen array type
public static final String SPECIMEN_LABEL_CONTAINER_MAP = "Specimen : ";
public static final String CONTAINER_LABEL_CONTAINER_MAP = "Container : ";
public static final String SPECIMEN_ARRAY_LABEL_CONTAINER_MAP = "Array : ";
public static final String SPECIMEN_PROTOCOL ="SpecimenProtocol";
public static final String SPECIMEN_PROTOCOL_SHORT_TITLE ="SHORT_TITLE";
public static final String SPECIMEN_COLLECTION_GROUP_NAME ="NAME";
public static final String SPECIMEN_LABEL = "LABEL";
// Patch ID: Bug#3184_14
public static final String NUMBER_OF_SPECIMEN = "numberOfSpecimen";
//Constants required for max limit on no. of containers in the drop down
public static final String CONTAINERS_MAX_LIMIT = "containers_max_limit";
public static final String EXCEEDS_MAX_LIMIT = "exceedsMaxLimit";
//MultipleSpecimen Constants
public static final String MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE="multipleSpecimen.ColumnsPerPage";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="MultipleSpecimenStorageLocationAdd.do";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_AVAILABLE_MAP="locationMap";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_SPECIMEN_MAP= "specimenMap";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_KEY_SEPARATOR = "$";
public static final String PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "formSubmitted";
public static final String MULTIPLE_SPECIMEN_SUBMIT_SUCCESSFUL = "submitSuccessful";
public static final String MULTIPLE_SPECIMEN_SPECIMEN_ORDER_LIST= "specimenOrderList";
public static final String MULTIPLE_SPECIMEN_DELETELAST_SPECIMEN_ID = "SpecimenId";
public static final String MULTIPLE_SPECIMEN_PARENT_COLLECTION_GROUP = "ParentSpecimenCollectionGroup";
public static final String NO_OF_RECORDS_PER_PAGE="resultView.noOfRecordsPerPage";
/**
* Name: Prafull
* Description: Query performance issue. Instead of saving complete query results in session, resultd will be fetched for each result page navigation.
* object of class QuerySessionData will be saved session, which will contain the required information for query execution while navigating through query result pages.
* Changes resultper page options, removed 5000 from the array & added 500 as another option.
*/
public static final int[] RESULT_PERPAGE_OPTIONS = {10,50,100,500,1000};
/**
* Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action.
*/
public static final String SPECIMEN_MAP_KEY = "Specimen_derived_map_key";
/**
* Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action.
*/
public static final String CONTAINER_MAP_KEY = "container_map_key";
/**
* Used to saperate storage container, xPos, yPos
*/
public static final String STORAGE_LOCATION_SAPERATOR = "@";
public static final String METHOD_NAME="method";
public static final String GRID_FOR_EVENTS="eventParameter";
public static final String GRID_FOR_EDIT_SEARCH="editSearch";
public static final String GRID_FOR_DERIVED_SPECIMEN="derivedSpecimen";
//CpBasedSearch Constants
public static final String CP_QUERY = "CPQuery";
public static final String CP_QUERY_PARTICIPANT_EDIT_ACTION = "CPQueryParticipantEdit.do";
public static final String CP_QUERY_PARTICIPANT_ADD_ACTION = "CPQueryParticipantAdd.do";
public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "CPQuerySpecimenCollectionGroupAdd.do";
public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "CPQuerySpecimenCollectionGroupEdit.do";
public static final String CP_AND_PARTICIPANT_VIEW="cpAndParticipantView";
public static final String DATA_DETAILS_VIEW="dataDetailsView";
public static final String SHOW_CP_AND_PARTICIPANTS_ACTION="showCpAndParticipants.do";
public static final String PAGE_OF_CP_QUERY_RESULTS = "pageOfCpQueryResults";
public static final String CP_LIST = "cpList";
public static final String CP_ID_TITLE_MAP = "cpIDTitleMap";
public static final String REGISTERED_PARTICIPANT_LIST = "participantList";
public static final String PAGE_OF_PARTICIPANT_CP_QUERY = "pageOfParticipantCPQuery";
public static final String PAGE_OF_SCG_CP_QUERY = "pageOfSpecimenCollectionGroupCPQuery";
public static final String CP_SEARCH_PARTICIPANT_ID="cpSearchParticipantId";
public static final String CP_SEARCH_CP_ID="cpSearchCpId";
public static final String CP_TREE_VIEW = "cpTreeView";
public static final String CP_TREE_VIEW_ACTION = "showTree.do";
public static final String PAGE_OF_SPECIMEN_CP_QUERY = "pageOfNewSpecimenCPQuery";
public static final String CP_QUERY_SPECIMEN_ADD_ACTION = "CPQueryNewSpecimenAdd.do";
public static final String CP_QUERY_CREATE_SPECIMEN_ACTION = "CPQueryCreateSpecimen.do";
public static final String CP_QUERY_SPECIMEN_EDIT_ACTION = "CPQueryNewSpecimenEdit.do";
public static final String PAGE_OF_CREATE_SPECIMEN_CP_QUERY = "pageOfCreateSpecimenCPQuery";
public static final String PAGE_OF_ALIQUOT_CP_QUERY = "pageOfAliquotCPQuery";
public static final String PAGE_OF_CREATE_ALIQUOT_CP_QUERY = "pageOfCreateAliquotCPQuery";
public static final String PAGE_OF_ALIQUOT_SUMMARY_CP_QUERY = "pageOfAliquotSummaryCPQuery";
public static final String CP_QUERY_CREATE_ALIQUOT_ACTION = "CPQueryCreateAliquots.do";
public static final String CP_QUERY_ALIQUOT_SUMMARY_ACTION = "CPQueryAliquotSummary.do";
public static final String CP_QUERY_CREATE_SPECIMEN_ADD_ACTION = "CPQueryAddSpecimen.do";
public static final String PAGE_OF_DISTRIBUTION_CP_QUERY = "pageOfDistributionCPQuery";
public static final String CP_QUERY_DISTRIBUTION_EDIT_ACTION = "CPQueryDistributionEdit.do";
public static final String CP_QUERY_DISTRIBUTION_ADD_ACTION = "CPQueryDistributionAdd.do";
public static final String CP_QUERY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryDistributionReportSave.do";
public static final String CP_QUERY_ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryArrayDistributionReportSave.do";
public static final String CP_QUERY_CONFIGURE_DISTRIBUTION_ACTION = "CPQueryConfigureDistribution.do";
public static final String CP_QUERY_DISTRIBUTION_REPORT_ACTION = "CPQueryDistributionReport.do";
public static final String PAGE_OF_LIST_SPECIMEN_EVENT_PARAMETERS_CP_QUERY = "pageOfListSpecimenEventParametersCPQuery";
public static final String PAGE_OF_COLLECTION_PROTOCOL_REGISTRATION_CP_QUERY = "pageOfCollectionProtocolRegistrationCPQuery";
public static final String PAGE_OF_MULTIPLE_SPECIMEN_CP_QUERY = "pageOfMultipleSpecimenCPQuery";
public static final String CP_QUERY_NEW_MULTIPLE_SPECIMEN_ACTION = "CPQueryNewMultipleSpecimenAction.do";
public static final String CP_QUERY_MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="CPQueryMultipleSpecimenStorageLocationAdd.do";
public static final String CP_QUERY_PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "CPQueryformSubmitted";
public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_ADD_ACTION = "CPQueryCollectionProtocolRegistrationAdd.do";
public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CPQueryCollectionProtocolRegistrationEdit.do";
public static final String CP_QUERY_PARTICIPANT_LOOKUP_ACTION= "CPQueryParticipantLookup.do";
public static final String CP_QUERY_BIO_SPECIMEN = "/QueryManageBioSpecimen.do";
//Mandar : 15-Jan-07
public static final String WITHDRAW_RESPONSE_NOACTION= "No Action";
public static final String WITHDRAW_RESPONSE_DISCARD= "Discard";
public static final String WITHDRAW_RESPONSE_RETURN= "Return";
public static final String WITHDRAW_RESPONSE_RESET= "Reset";
public static final String WITHDRAW_RESPONSE_REASON= "Specimen consents withdrawn";
public static final String SEARCH_CATEGORY_LIST_SELECT_TAG_NAME="selectCategoryList";
public static final String SEARCH_CATEGORY_LIST_FUNCTION_NAME="getSelectedEntities";
public static final String EDIT_CONDN = "Edit";
public static final String SPLITTER_STATUS_REQ_PARAM = "SPLITTER_STATUS";
//mulltiple specimen Applet constants
public static final int VALIDATE_TEXT =1;
public static final int VALIDATE_COMBO =2;
public static final int VALIDATE_DATE =3;
/**
* Constants required for maintaining toolTipText for event button on multiple specimen page
*/
public static final String TOOLTIP_TEXT="TOOLTIPTEXT";
public static final String MULTIPLE_SPECIMEN_TOOLTIP_MAP_KEY="multipleSpecimenTooltipMapKey";
public static final String DEFAULT_TOOLTIP_TEXT="DEFAULTTOOLTIPTEXT";
/**
* Patch ID: Bug#3184_15 (for Multiple Specimen)
* Description: The following constants are used as key in the Map
*/
public static final String KEY_SPECIMEN_CLASS = "SpecimenClass";
public static final String KEY_SPECIMEN_TYPE = "SpecimenType";
public static final String KEY_TISSUE_SITE = "TissueSite";
public static final String KEY_PATHOLOGICAL_STATUS = "PathologicalStatus";
public static final String KEY_SPECIMEN_REQUIREMENT_PREFIX = "SpecimenRequirement_";
public static final String KEY_RESTRICTED_VALUES = "RestictedValues";
public static final String KEY_QUANTITY = "Quantity";
// The following constants are used for multiple specimens applet classes
public static final String NUMBER_OF_SPECIMEN_REQUIREMENTS = "numberOfSpecimenRequirements";
public static final String RESTRICT_SCG_CHECKBOX = "restrictSCGCheckbox";
public static final String ON_COLL_OR_CLASSCHANGE = "onCollOrClassChange";
public static final String NUMBER_OF_SPECIMENS = "numberOfSpecimens";
public static final String CHANGE_ON = "changeOn";
// Patch ID: Bug#4180_3
public static final String EVENT_NAME = "eventName";
public static final String USER_NAME = "userName";
public static final String EVENT_DATE = "eventDate";
public static final String PAGE_OF = "pageOf";
/**
* Patch ID: for Future SCG_15
* Description: The following constants are used as id for future scg in tree
*/
public static final String FUTURE_SCG = "future";
// Patch ID: SimpleSearchEdit_5
// AliasName constants, used in Edit in Simple Search feature.
public static final String ALIAS_COLLECTION_PROTOCOL = "CollectionProtocol";
public static final String ALIAS_BIOHAZARD = "Biohazard";
public static final String ALIAS_CANCER_RESEARCH_GROUP = "CancerResearchGroup";
public static final String ALIAS_COLLECTION_PROTOCOL_REG = "CollectionProtReg";
public static final String ALIAS_DEPARTMENT = "Department";
public static final String ALIAS_DISTRIBUTION = "Distribution";
public static final String ALIAS_DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String ALIAS_DISTRIBUTION_ARRAY = "Distribution_array";
public static final String ALIAS_INSTITUTE = "Institution";
public static final String ALIAS_PARTICIPANT = "Participant";
public static final String ALIAS_SITE = "Site";
public static final String ALIAS_SPECIMEN = "Specimen";
public static final String ALIAS_SPECIMEN_ARRAY = "SpecimenArray";
public static final String ALIAS_SPECIMEN_ARRAY_TYPE = "SpecimenArrayType";
public static final String ALIAS_SPECIMEN_COLLECTION_GROUP = "SpecimenCollectionGroup";
public static final String ALIAS_STORAGE_CONTAINER = "StorageContainer";
public static final String ALIAS_STORAGE_TYPE= "StorageType";
public static final String ALIAS_USER= "User";
public static final String PAGE_OF_BIOHAZARD = "pageOfBioHazard";
public static final String PAGE_OF_CANCER_RESEARCH_GROUP = "pageOfCancerResearchGroup";
public static final String PAGE_OF_COLLECTION_PROTOCOL = "pageOfCollectionProtocol";
public static final String PAGE_OF_COLLECTION_PROTOCOL_REG = "pageOfCollectionProtocolRegistration";
public static final String PAGE_OF_DEPARTMENT = "pageOfDepartment";
public static final String PAGE_OF_DISTRIBUTION = "pageOfDistribution";
public static final String PAGE_OF_DISTRIBUTION_PROTOCOL = "pageOfDistributionProtocol";
public static final String PAGE_OF_DISTRIBUTION_ARRAY = "pageOfArrayDistribution";
public static final String PAGE_OF_INSTITUTE = "pageOfInstitution";
public static final String PAGE_OF_PARTICIPANT = "pageOfParticipant";
public static final String PAGE_OF_SITE = "pageOfSite";
public static final String PAGE_OF_SPECIMEN = "pageOfNewSpecimen";
public static final String PAGE_OF_SPECIMEN_ARRAY = "pageOfSpecimenArray";
public static final String PAGE_OF_SPECIMEN_ARRAY_TYPE = "pageOfSpecimenArrayType";
public static final String PAGE_OF_SPECIMEN_COLLECTION_GROUP = "pageOfSpecimenCollectionGroup";
public static final String PAGE_OF_STORAGE_CONTAINER = "pageOfStorageContainer";
public static final String PAGE_OF_STORAGE_TYPE = "pageOfStorageType";
public static final String PAGE_OF_USER = "pageOfUserAdmin";
//Patch ID: Bug#4227_3
public static final String SUBMIT_AND_ADD_MULTIPLE = "submitAndAddMultiple";
//constants for Storage container map radio button identification Patch id: 4283_3
public static final int RADIO_BUTTON_VIRTUALLY_LOCATED=1;
public static final int RADIO_BUTTON_FOR_MAP=3;
// constant for putting blank screen in the framed pages
public static final String BLANK_SCREEN_ACTION="blankScreenAction.do";
public static final String COLUMN_NAME_SPECIMEN_ID = "specimen.id";
public static final String PARTICIPANT_MEDICAL_IDENTIFIER="ParticipantMedicalIdentifier:";
public static final String PARTICIPANT_MEDICAL_IDENTIFIER_SITE_ID="_Site_id";
public static final String PARTICIPANT_MEDICAL_IDENTIFIER_MEDICAL_NUMBER="_medicalRecordNumber";
public static final String PARTICIPANT_MEDICAL_IDENTIFIER_ID="_id";
public static final String COLUMN_NAME_SPECIEMEN_REQUIREMENT_COLLECTION="elements(specimenRequirementCollection)";
public static final String COLUMN_NAME_PARTICIPANT="participant";
public static final String ADDNEW_LINK="AddNew";
public static final String COLUMN_NAME_STORAGE_CONTAINER = "storageContainer";
public static final String COLUMN_NAME_SCG_CPR_CP_ID = "specimenCollectionGroup.collectionProtocolRegistration.collectionProtocol.id";
public static final String COLUMN_NAME_CPR_CP_ID = "collectionProtocolRegistration.collectionProtocol.id";
public static final String EQUALS = "=";
public static final String COLUMN_NAME_SCG_NAME = "specimenCollectionGroup.name";
public static final String COLUMN_NAME_SPECIMEN = "specimen";
public static final String COLUMN_NAME_SCG = "specimenCollectionGroup";
public static final String COLUMN_NAME_CHILDREN = "elements(children)";
public static final String COLUMN_NAME_SCG_ID="specimenCollectionGroup.id";
public static final String COLUMN_NAME_PART_MEDICAL_ID_COLL="elements(participantMedicalIdentifierCollection)";
public static final String COLUMN_NAME_PART_RACE_COLL="elements(raceCollection)";
public static final String COLUMN_NAME_CPR_COLL="elements(collectionProtocolRegistrationCollection)";
public static final String COLUMN_NAME_SCG_COLL="elements(specimenCollectionGroupCollection)";
public static final String COLUMN_COLL_PROT_EVENT_COLL="elements(collectionProtocolEventCollection)";
public static final String COLUMN_NAME_CONCEPT_REF_COLL="elements(conceptReferentCollection)";
public static final String COLUMN_NAME_DEID_REPORT="deIdentifiedSurgicalPathologyReport";
public static final String COLUMN_NAME_REPORT_SOURCE="reportSource";
public static final String COLUMN_NAME_TEXT_CONTENT="textContent";
public static final String COLUMN_NAME_TITLE="title";
public static final String COLUMN_NAME_PARTICIPANT_ID = "participant.id";
public static final String COLUMN_NAME_REPORT_SECTION_COLL="elements(reportSectionCollection)";
public static final String COLUMN_NAME_SCG_SITE="specimenCollectionSite";
//Bug 2833. Field for the length of CP Title
public static final int COLLECTION_PROTOCOL_TITLE_LENGTH=30;
//Bug ID 4794: Field for advance time to warn a user about session expiry
public static final String SESSION_EXPIRY_WARNING_ADVANCE_TIME = "session.expiry.warning.advanceTime";
// Constants required in RequestDetailsPage
public static final String SUBMIT_REQUEST_DETAILS_ACTION="SubmitRequestDetails.do";
public static final String REQUEST_HEADER_OBJECT = "requestHeaderObject";
public static final String SITE_LIST_OBJECT = "siteList";
public static final String REQUEST_DETAILS_PAGE = "RequestDetails.do";
public static final String ARRAYREQUEST_DETAILS_PAGE = "ArrayRequests.do";
public static final String ARRAY_REQUESTS_LIST = "arrayRequestsList";
public static final String EXISISTINGARRAY_REQUESTS_LIST = "existingArrayRequestDetailsList";
public static final String DEFINEDARRAY_REQUESTS_LIST = "DefinedRequestDetailsMapList";
public static final String ITEM_STATUS_LIST="itemsStatusList";
public static final String ITEM_STATUS_LIST_WO_DISTRIBUTE="itemsStatusListWithoutDistribute";
public static final String ITEM_STATUS_LIST_FOR_ITEMS_IN_ARRAY="itemsStatusListForItemsInArray";
public static final String REQUEST_FOR_LIST="requestForList";
// Constants for Order Request Status.
public static final String ORDER_REQUEST_STATUS_NEW = "New";
public static final String ORDER_REQUEST_STATUS_PENDING_PROTOCOL_REVIEW = "Pending - Protocol Review";
public static final String ORDER_REQUEST_STATUS_PENDING_SPECIMEN_PREPARATION = "Pending - Specimen Preparation";
public static final String ORDER_REQUEST_STATUS_PENDING_FOR_DISTRIBUTION = "Pending - For Distribution";
public static final String ORDER_REQUEST_STATUS_REJECTED_INAPPROPRIATE_REQUEST = "Rejected - Inappropriate Request";
public static final String ORDER_REQUEST_STATUS_REJECTED_SPECIMEN_UNAVAILABLE = "Rejected - Specimen Unavailable";
public static final String ORDER_REQUEST_STATUS_REJECTED_UNABLE_TO_CREATE = "Rejected - Unable to Create";
public static final String ORDER_REQUEST_STATUS_DISTRIBUTED = "Distributed";
public static final String ORDER_REQUEST_STATUS_READY_FOR_ARRAY_PREPARATION = "Ready For Array Preparation";
// Used for tree display in RequestDetails page
public static final String TREE_DATA_LIST = "treeDataList";
//Constants for Order Status
public static final String ORDER_STATUS_NEW = "New";
public static final String ORDER_STATUS_PENDING = "Pending";
public static final String ORDER_STATUS_REJECTED = "Rejected";
public static final String ORDER_STATUS_COMPLETED = "Completed";
// Ordering System Status
public static final String CDE_NAME_REQUEST_STATUS="Request Status";
public static final String CDE_NAME_REQUESTED_ITEMS_STATUS="Requested Items Status";
public static final String REQUEST_LIST="requestStatusList";
public static final String REQUESTED_ITEMS_STATUS_LIST="requestedItemsStatusList";
public static final String ARRAY_STATUS_LIST="arrayStatusList";
public static final String REQUEST_OBJECT="requestObjectList";
public static final String REQUEST_DETAILS_LIST="requestDetailsList";
public static final String ARRAY_REQUESTS_BEAN_LIST="arrayRequestsBeanList";
public static final String SPECIMEN_ORDER_FORM_TYPE = "specimen";
public static final String ARRAY_ORDER_FORM_TYPE = "specimenArray";
public static final String PATHOLOGYCASE_ORDER_FORM_TYPE="pathologyCase";
public static final String REQUESTED_BIOSPECIMENS="RequestedBioSpecimens";
//Constants required in Ordering System.
public static final String ACTION_ORDER_LIST = "OrderExistingSpecimen.do";
public static final String SPECIMEN_TREE_SPECIMEN_ID = "specimenId";
public static final String SPECIMEN_TREE_SPECCOLLGRP_ID = "specimenCollGrpId";
public static final String ACTION_REMOVE_ORDER_ITEM = "AddToOrderListSpecimen.do?remove=yes";
public static final String ACTION_REMOVE_ORDER_ITEM_ARRAY = "AddToOrderListArray.do?remove=yes";
public static final String ACTION_REMOVE_ORDER_ITEM_PATHOLOGYCASE = "AddToOrderListPathologyCase.do?remove=yes";
public static final String DEFINEARRAY_REQUESTMAP_LIST = "definedArrayRequestMapList";
public static final String CREATE_DEFINED_ARRAY = "CreateDefinedArray.do";
public static final String ACTION_SAVE_ORDER_ITEM = "SaveOrderItems.do";
public static final String ORDERTO_LIST_ARRAY = "orderToListArrayList";
public static final String ACTION_SAVE_ORDER_ARRAY_ITEM = "SaveOrderArrayItems.do";
public static final String ACTION_SAVE_ORDER_PATHOLOGY_ITEM="SaveOrderPathologyItems.do";
public static final String ACTION_ADD_ORDER_SPECIMEN_ITEM="AddToOrderListSpecimen.do";
public static final String ACTION_ADD_ORDER_ARRAY_ITEM="AddToOrderListArray.do";
public static final String ACTION_ADD_ORDER_PATHOLOGY_ITEM="AddToOrderListPathologyCase.do";
public static final String ACTION_DEFINE_ARRAY="DefineArraySubmit.do";
public static final String ACTION_ORDER_SPECIMEN="OrderExistingSpecimen.do";
public static final String ACTION_ORDER_BIOSPECIMENARRAY="OrderBiospecimenArray.do";
public static final String ACTION_ORDER_PATHOLOGYCASE="OrderPathologyCase.do";
//Specimen Label generation realted constants
public static final String PARENT_SPECIMEN_ID_KEY="parentSpecimenID";
public static final String PARENT_SPECIMEN_LABEL_KEY="parentSpecimenLabel";
public static final String SCG_NAME_KEY="SCGName";
//ordering system
public static final String TAB_INDEX_ID="tabIndexId";
public static final String FORWARD_TO_HASHMAP="forwardToHashMap";
public static final String SELECTED_COLLECTION_PROTOCOL_ID = "0";
public static final String LIST_OF_SPECIMEN_COLLECTION_GROUP = "specimenCollectionGroupResponseList";
public static final String PARTICIPANT_PROTOCOL_ID="participantProtocolId";
// caTIES
public static final String REPORT_QUEUE_LIST = "ReportQueueList";
public static final String BUTTON_NAME = "button";
public static final String CREATE_PARTICIPANT_BUTTON = "createParticipant";
public static final String ASSOCIATE_PARTICIPANT_BUTTON = "associateParticipant";
public static final String REPORT_PARTICIPANT_OBJECT = "reportParticipantObject";
public static final String REPORT_ID = "reportQueueId";
public static final String PARTICIPANT_ID_TO_ASSOCIATE = "participantIdToAssociate";
public static final String SCG_ID_TO_ASSOCIATE = "scgIdToAssociate";
public static final String CONCEPT_REFERENT_CLASSIFICATION_LIST = "conceptRefernetClassificationList";
public static final String CONCEPT_LIST = "conceptList";
public static final String[] CATEGORY_HIGHLIGHTING_COLOURS = {"yellow","green","red","pink","blue"};
public static final String CONCEPT_BEAN_LIST = "conceptBeanList";
//Admin View
public static final String IDENTIFIER_NO="
public static final String REQUEST_DATE="Request Date";
public static final String USER_NAME_ADMIN_VIEW="User Name";
public static final String SCG_NAME="Specimen Collection Group";
public static final String ACCESSION_NO="Accession Number";
public static final String REVIEW_SPR="reviewSPR";
public static final String QUARANTINE_SPR="quarantineSPR";
public static final String SITE="Site";
public static final String REQUEST_FOR="requestFor";
public static final String REPORT_ACTION="reportAction";
public static final String REPORT_STATUS_LIST="reportStatusList";
public static final String COLUMN_LIST="columnList";
//Surgical Pathology Report UI constants
public static final String VIEW_SPR_ACTION="ViewSurgicalPathologyReport.do";
public static final String SPR_EVENT_PARAM_ACTION="SurgicalPathologyReportEventParam.do";
public static final String VIEW_SURGICAL_PATHOLOGY_REPORT="viewSPR";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP="pageOfSpecimenCollectionGroup";
public static final String PAGEOF_PARTICIPANT="pageOfParticipant";
public static final String PAGEOF_SPECIMEN="pageOfNewSpecimen";
public static final String REVIEW="REVIEW";
public static final String QUARANTINE="QUARANTINE";
public static final String COMMENT_STATUS_RENDING="PENDING";
public static final String COMMENT_STATUS_REVIEWED="REVIEWED";
public static final String COMMENT_STATUS_REPLIED="REPLIED";
public static final String COMMENT_STATUS_NOT_REVIEWED="NOT_REVIEWED";
public static final String COMMENT_STATUS_QUARANTINED="QUARANTINED";
public static final String COMMENT_STATUS_NOT_QUARANTINED="DEQUARANTINED";
public static final String ROLE_ADMINISTRATOR="Administrator";
public static final String REPORT_LIST="reportIdList";
public static final String QUARANTINE_REQUEST="QUARANTINEREQUEST";
public static final String IDENTIFIED_REPORT_NOT_FOUND_MSG="Indentified Report Not Found!";
public static final String DEID_REPORT_NOT_FOUND_MSG="De-Indentified Report Not Found!";
} |
package edu.wustl.catissuecore.util.global;
import java.util.Vector;
/**
* @author aarti_sharma
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Variables extends edu.wustl.common.util.global.Variables
{
public static String catissueHome=new String();
public static Vector databaseDefinitions=new Vector();
public static String databaseDriver=new String();
public static String[] databasenames;
public static String catissueURL=new String();
} |
package io.digdag.cli;
import java.util.Properties;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import javax.servlet.ServletException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.Parameter;
import io.digdag.core.config.PropertyUtils;
import io.digdag.server.ServerBootstrap;
import static io.digdag.cli.Main.systemExit;
import static io.digdag.server.ServerConfig.DEFAULT_PORT;
import static io.digdag.server.ServerConfig.DEFAULT_BIND;
public class Server
extends Command
{
private static final Logger logger = LoggerFactory.getLogger(Server.class);
@Parameter(names = {"-n", "--port"})
Integer port = null;
@Parameter(names = {"-b", "--bind"})
String bind = null;
@Parameter(names = {"-m", "--memory"})
boolean memoryDatabase = false;
@Parameter(names = {"-o", "--database"})
String database = null;
@Parameter(names = {"-O", "--task-log"})
String taskLogPath = null;
@Parameter(names = {"-c", "--config"})
String configPath = null;
@Override
public void main()
throws Exception
{
if (args.size() != 0) {
throw usage(null);
}
if (database == null && memoryDatabase == false && configPath == null) {
throw usage("--database, --memory, or --config option is required");
}
if (database != null && memoryDatabase == true) {
throw usage("Setting both --database and --memory is invalid");
}
server();
}
@Override
public SystemExitException usage(String error)
{
System.err.println("Usage: digdag server [options...]");
System.err.println(" Options:");
System.err.println(" -n, --port PORT port number to listen for web interface and api clients (default: " + DEFAULT_PORT + ")");
System.err.println(" -b, --bind ADDRESS IP address to listen HTTP clients (default: " + DEFAULT_BIND + ")");
System.err.println(" -m, --memory uses memory database");
System.err.println(" -o, --database DIR store status to this database");
System.err.println(" -O, --task-log DIR store task logs to this database");
System.err.println(" -c, --config PATH.properties server configuration property path");
Main.showCommonOptions();
return systemExit(error);
}
private void server()
throws ServletException, IOException
{
ServerBootstrap.startServer(buildServerProperties(), ServerBootstrap.class);
}
protected Properties buildServerProperties()
throws IOException
{
// parameters for ServerBootstrap
Properties props = loadSystemProperties();
if (configPath != null) {
props.putAll(PropertyUtils.loadFile(new File(configPath)));
}
// overwrite by command-line parameters
if (database != null) {
props.setProperty("database.type", "h2");
props.setProperty("database.path", Paths.get(database).toAbsolutePath().toString());
}
else if (memoryDatabase) {
props.setProperty("database.type", "memory");
}
if (port != null) {
props.setProperty("server.port", Integer.toString(port));
}
if (bind != null) {
props.setProperty("server.bind", bind);
}
if (taskLogPath != null) {
props.setProperty("log-server.type", "local");
props.setProperty("log-server.local.path", taskLogPath);
}
return props;
}
} |
package rhogenwizard.wizards;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import java.io.*;
import org.eclipse.ui.*;
import org.eclipse.ui.views.navigator.*;
import rhogenwizard.RhodesAdapter;
import rhogenwizard.RhodesProjectSupport;
public class RhogenModelWizard extends Wizard implements INewWizard
{
private RhodesModelWizardPage m_pageModel = null;
private ISelection m_selection = null;
private RhodesAdapter m_rhogenAdapter = new RhodesAdapter();
private String m_projectLocation = null;
private IProject m_currentProject = null;
public RhogenModelWizard()
{
super();
setNeedsProgressMonitor(true);
m_currentProject = RhodesProjectSupport.getSelectedProject();
m_projectLocation = m_currentProject.getLocation().toOSString();
}
/**
* Constructor for SampleNewWizard.
*/
public RhogenModelWizard(IProject currentProject)
{
super();
setNeedsProgressMonitor(true);
m_currentProject = currentProject;
m_projectLocation = m_currentProject.getLocation().toOSString();
}
/**
* Adding the page to the wizard.
*/
public void addPages()
{
m_pageModel = new RhodesModelWizardPage(m_selection);
addPage(m_pageModel);
}
/**
* This method is called when 'Finish' button is pressed in
* the wizard. We will create an operation and run it
* using wizard as execution context.
*/
public boolean performFinish()
{
final String modelName = m_pageModel.getModelName();
final String modelParams = m_pageModel.getModelParams();
IRunnableWithProgress op = new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException
{
try
{
doFinish(modelName, modelParams, monitor);
}
catch (CoreException e) {
throw new InvocationTargetException(e);
}
finally {
monitor.done();
}
}
};
try
{
getContainer().run(true, false, op);
}
catch (InterruptedException e)
{
return false;
}
catch (InvocationTargetException e)
{
Throwable realException = e.getTargetException();
MessageDialog.openError(getShell(), "Error", realException.getMessage());
return false;
}
return true;
}
/**
* The worker method. It will find the container, create the
* file if missing or just replace its contents, and open
* the editor on the newly created file.
*/
private void doFinish(
String modelName,
String modelParams,
IProgressMonitor monitor)
throws CoreException
{
try
{
monitor.beginTask("Creating model " + modelName, 2);
monitor.worked(1);
monitor.setTaskName("Opening file for editing...");
if (null != m_projectLocation)
{
m_rhogenAdapter.generateModel(m_projectLocation, modelName, modelParams);
}
else
{
//TODO show error message
}
m_currentProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
monitor.worked(1);
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
/**
* We will accept the selection in the workbench to see if
* we can initialize from it.
* @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.m_selection = selection;
}
} |
package com.bloatit.model.data;
import java.util.Iterator;
import org.hibernate.Query;
import com.bloatit.common.PageIterable;
import com.bloatit.model.data.util.SessionManager;
public class QueryCollection<T> implements PageIterable<T> {
private final Query query;
private final Query sizeQuery;
private int pageSize;
private int size;
private int currentPage;
/**
* Use this constructor with query that start with "from ..."
*
* @param query
*/
protected QueryCollection(Query query) {
this(query, SessionManager.getSessionFactory().getCurrentSession().createQuery("select count (*) " + query.getQueryString()));
}
protected QueryCollection(Query query, Query sizeQuery) {
pageSize = 0;
size = -1;
this.query = query;
this.sizeQuery = sizeQuery;
}
@Override
@SuppressWarnings("unchecked")
public Iterator<T> iterator() {
return query.list().iterator();
}
@Override
public void setPage(int page) {
currentPage = page;
query.setFirstResult(page * pageSize);
}
@Override
public void setPageSize(int pageSize) {
query.setMaxResults(pageSize);
query.setFetchSize(pageSize);
this.pageSize = pageSize;
}
@Override
public int getPageSize() {
return pageSize;
}
@Override
public int size() {
if (size == -1) {
return size = ((Long) sizeQuery.uniqueResult()).intValue();
}
return size;
}
@Override
public int pageNumber() {
if (pageSize != 0) {
return size() / pageSize;
} else {
return 1;
}
}
@Override
public int getCurrentPage() {
return currentPage;
}
} |
package com.bwssystems.HABridge.hue;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.api.UserCreateRequest;
import com.bwssystems.HABridge.api.hue.DeviceResponse;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.HueApiResponse;
import com.bwssystems.HABridge.dao.*;
import com.bwssystems.NestBridge.NestInstruction;
import com.bwssystems.NestBridge.NestHome;
import com.bwssystems.harmony.ButtonPress;
import com.bwssystems.harmony.HarmonyHandler;
import com.bwssystems.harmony.HarmonyHome;
import com.bwssystems.harmony.RunActivity;
import com.bwssystems.nest.controller.Nest;
import com.bwssystems.util.JsonTransformer;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import net.java.dev.eval.Expression;
import static spark.Spark.get;
import static spark.Spark.options;
import static spark.Spark.post;
import static spark.Spark.put;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
/**
* Based on Armzilla's HueMulator - a Philips Hue emulator using sparkjava rest server
*/
public class HueMulator {
private static final Logger log = LoggerFactory.getLogger(HueMulator.class);
private static final String INTENSITY_PERCENT = "${intensity.percent}";
private static final String INTENSITY_BYTE = "${intensity.byte}";
private static final String INTENSITY_MATH = "${intensity.math(";
private static final String INTENSITY_MATH_VALUE = "X";
private static final String INTENSITY_MATH_CLOSE = ")}";
private static final String HUE_CONTEXT = "/api";
private DeviceRepository repository;
private HarmonyHome myHarmonyHome;
private Nest theNest;
private HttpClient httpClient;
private ObjectMapper mapper;
private BridgeSettingsDescriptor bridgeSettings;
private byte[] sendData;
public HueMulator(BridgeSettingsDescriptor theBridgeSettings, DeviceRepository aDeviceRepository, HarmonyHome theHarmonyHome, NestHome aNestHome){
httpClient = HttpClients.createDefault();
mapper = new ObjectMapper(); //armzilla: work around Echo incorrect content type and breaking mapping. Map manually
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
repository = aDeviceRepository;
if(theBridgeSettings.isValidHarmony())
this.myHarmonyHome = theHarmonyHome;
else
this.myHarmonyHome = null;
if(theBridgeSettings.isValidNest())
this.theNest = aNestHome.getTheNest();
else
this.theNest = null;
bridgeSettings = theBridgeSettings;
}
// This function sets up the sparkjava rest calls for the hue api
public void setupServer() {
log.info("Hue emulator service started....");
get(HUE_CONTEXT + "/:userid/lights", "application/json", (request, response) -> {
String userId = request.params(":userid");
if(bridgeSettings.isTraceupnp())
log.info("Traceupnp: hue lights list requested: " + userId + " from " + request.ip());
log.debug("hue lights list requested: " + userId + " from " + request.ip());
List<DeviceDescriptor> deviceList = repository.findAll();
Map<String, DeviceResponse> deviceResponseMap = new HashMap<>();
for (DeviceDescriptor device : deviceList) {
DeviceResponse deviceResponse = DeviceResponse.createResponse(device);
deviceResponseMap.put(device.getId(), deviceResponse);
}
response.type("application/json; charset=utf-8");
response.status(HttpStatus.SC_OK);
return deviceResponseMap;
} , new JsonTransformer());
options(HUE_CONTEXT, "application/json", (request, response) -> {
response.status(HttpStatus.SC_OK);
response.header("Access-Control-Allow-Origin", request.headers("Origin"));
response.header("Access-Control-Allow-Methods", "GET, POST, PUT");
response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
response.header("Content-Type", "text/html; charset=utf-8");
return "";
});
post(HUE_CONTEXT, "application/json", (request, response) -> {
UserCreateRequest aNewUser = null;
String newUser = null;
String aDeviceType = null;
if(bridgeSettings.isTraceupnp())
log.info("Traceupnp: hue api/ user create requested: " + request.body() + " from " + request.ip());
log.debug("hue api user create requested: " + request.body() + " from " + request.ip());
if(request.body() != null && !request.body().isEmpty()) {
aNewUser = new Gson().fromJson(request.body(), UserCreateRequest.class);
newUser = aNewUser.getUsername();
aDeviceType = aNewUser.getDevicetype();
}
if(newUser == null)
newUser = "lightssystem";
if(aDeviceType == null)
aDeviceType = "<not given>";
if(bridgeSettings.isTraceupnp())
log.info("Traceupnp: hue api user create requested for device type: " + aDeviceType + " and username: " + newUser);
log.debug("hue api user create requested for device type: " + aDeviceType + " and username: " + newUser);
response.header("Access-Control-Allow-Origin", request.headers("Origin"));
response.type("application/json; charset=utf-8");
response.status(HttpStatus.SC_OK);
return "[{\"success\":{\"username\":\"" + newUser + "\"}}]";
} );
/**
* strangely enough the Echo sends a content type of application/x-www-form-urlencoded even though
* it sends a json object
*/
String userId = request.params(":userid");
String lightId = request.params(":id");
String responseString = null;
String url = null;
DeviceState state = null;
log.debug("hue state change requested: " + userId + " from " + request.ip() + " body: " + request.body());
response.header("Access-Control-Allow-Origin", request.headers("Origin"));
response.type("application/json; charset=utf-8");
response.status(HttpStatus.SC_OK);
try {
state = mapper.readValue(request.body(), DeviceState.class);
} catch (IOException e) {
log.warn("Object mapper barfed on input of body.", e);
responseString = "[{\"error\":{\"type\": 2, \"address\": \"/lights/" + lightId + "\",\"description\": \"Object mapper barfed on input of body.\"}}]";
return responseString;
}
DeviceDescriptor device = repository.findOne(lightId);
if (device == null) {
log.warn("Could not find device: " + lightId + " for hue state change request: " + userId + " from " + request.ip() + " body: " + request.body());
responseString = "[{\"error\":{\"type\": 3, \"address\": \"/lights/" + lightId + "\",\"description\": \"Could not find device\", \"resource\": \"/lights/" + lightId + "\"}}]";
return responseString;
}
if(request.body().contains("bri"))
{
url = device.getDimUrl();
if(url == null || url.length() == 0)
url = device.getOnUrl();
}
else
{
if (state.isOn()) {
url = device.getOnUrl();
state.setBri(255);
} else if (request.body().contains("false")) {
url = device.getOffUrl();
state.setBri(0);
}
}
if (url == null) {
log.warn("Could not find url: " + lightId + " for hue state change request: " + userId + " from " + request.ip() + " body: " + request.body());
responseString = "[{\"error\":{\"type\": 3, \"address\": \"/lights/" + lightId + "\",\"description\": \"Could not find url\", \"resource\": \"/lights/" + lightId + "\"}}]";
return responseString;
}
responseString = this.formatSuccessHueResponse(state, request.body(), lightId);
if(device.getDeviceType().toLowerCase().contains("activity") || (device.getMapType() != null && device.getMapType().equalsIgnoreCase("harmonyActivity")))
{
log.debug("executing HUE api request to change activity to Harmony: " + url);
if(myHarmonyHome != null)
{
RunActivity anActivity = new Gson().fromJson(url, RunActivity.class);
HarmonyHandler myHarmony = myHarmonyHome.getHarmonyHandler(device.getTargetDevice());
if(myHarmony == null)
{
log.warn("Should not get here, no harmony hub available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Should not get here, no harmony hub available\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
else
myHarmony.startActivity(anActivity);
}
else {
log.warn("Should not get here, no harmony configured");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Should not get here, no harmony configured\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
}
else if(device.getDeviceType().toLowerCase().contains("button") || (device.getMapType() != null && device.getMapType().equalsIgnoreCase("harmonyButton")))
{
log.debug("executing HUE api request to button press(es) to Harmony: " + url);
if(myHarmonyHome != null)
{
if(url.substring(0, 1).equalsIgnoreCase("{")) {
url = "[" + url +"]";
}
ButtonPress[] deviceButtons = new Gson().fromJson(url, ButtonPress[].class);
HarmonyHandler myHarmony = myHarmonyHome.getHarmonyHandler(device.getTargetDevice());
if(myHarmony == null)
{
log.warn("Should not get here, no harmony hub available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Should not get here, no harmony hub available\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
else {
for(int i = 0; i < deviceButtons.length; i++) {
if( i > 0)
Thread.sleep(bridgeSettings.getButtonsleep());
log.debug("pressing button: " + deviceButtons[i].getDevice() + " - " + deviceButtons[i].getButton() + " - iteration: " + String.valueOf(i));
myHarmony.pressButton(deviceButtons[i]);
}
}
}
else {
log.warn("Should not get here, no harmony configured");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Should not get here, no harmony configured\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
}
else if(device.getDeviceType().toLowerCase().contains("home") || (device.getMapType() != null && device.getMapType().equalsIgnoreCase("nestHomeAway")))
{
log.debug("executing HUE api request to set away for nest home: " + url);
if(theNest == null)
{
log.warn("Should not get here, no Nest available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Should not get here, no Nest available\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
else {
NestInstruction homeAway = new Gson().fromJson(url, NestInstruction.class);
theNest.getHome(homeAway.getName()).setAway(homeAway.getAway());
}
}
else if(device.getDeviceType().toLowerCase().contains("thermo") || (device.getMapType() != null && device.getMapType().equalsIgnoreCase("nestThermoSet")))
{
log.debug("executing HUE api request to set thermostat for nest: " + url);
if(theNest == null)
{
log.warn("Should not get here, no Nest available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Should not get here, no Nest available\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
else {
NestInstruction thermoSetting = new Gson().fromJson(url, NestInstruction.class);
if(thermoSetting.getControl().equalsIgnoreCase("temp")) {
if(request.body().contains("bri")) {
if(bridgeSettings.isFarenheit())
thermoSetting.setTemp(String.valueOf((Double.parseDouble(replaceIntensityValue(thermoSetting.getTemp(), state.getBri())) - 32.0)/1.8));
else
thermoSetting.setTemp(String.valueOf(Double.parseDouble(replaceIntensityValue(thermoSetting.getTemp(), state.getBri()))));
log.debug("Setting thermostat: " + thermoSetting.getName() + " to " + thermoSetting.getTemp() + "C");
theNest.getThermostat(thermoSetting.getName()).setTargetTemperature(Float.parseFloat(thermoSetting.getTemp()));
}
}
else if (thermoSetting.getControl().contains("range") ||thermoSetting.getControl().contains("heat") ||thermoSetting.getControl().contains("cool") ||thermoSetting.getControl().contains("off")) {
log.debug("Setting thermostat target type: " + thermoSetting.getName() + " to " + thermoSetting.getControl());
theNest.getThermostat(thermoSetting.getName()).setTargetType(thermoSetting.getControl());
}
else if(thermoSetting.getControl().contains("fan")) {
log.debug("Setting thermostat fan mode: " + thermoSetting.getName() + " to " + thermoSetting.getControl().substring(4));
theNest.getThermostat(thermoSetting.getName()).setFanMode(thermoSetting.getControl().substring(4));
}
else {
log.warn("no valid Nest control info: " + thermoSetting.getControl());
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"no valid Nest control info\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
}
}
else if(url.startsWith("udp:
{
log.debug("executing HUE api request to UDP: " + url);
try {
String intermediate = url.substring(6);
String ipAddr = intermediate.substring(0, intermediate.indexOf(':'));
String port = intermediate.substring(intermediate.indexOf(':') + 1, intermediate.indexOf('/'));
String theBody = intermediate.substring(intermediate.indexOf('/')+1);
DatagramSocket responseSocket = new DatagramSocket(Integer.parseInt(port));
if(theBody.startsWith("0x")) {
sendData = DatatypeConverter.parseHexBinary(theBody.substring(2));
}
else
sendData = theBody.getBytes();
InetAddress IPAddress = InetAddress.getByName(ipAddr);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Integer.parseInt(port));
responseSocket.send(sendPacket);
responseSocket.close();
} catch (IOException e) {
log.warn("Could not send UDP Datagram packet for request.", e);
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Error on calling out to device\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
}
else
{
log.debug("executing HUE api request to Http " + (device.getHttpVerb() == null?"GET":device.getHttpVerb()) + ": " + url);
// quick template
String body;
url = replaceIntensityValue(url, state.getBri());
if (state.isOn())
body = replaceIntensityValue(device.getContentBody(), state.getBri());
else
body = replaceIntensityValue(device.getContentBodyOff(), state.getBri());
// make call
if (!doHttpRequest(url, device.getHttpVerb(), device.getContentType(), body)) {
log.warn("Error on calling url to change device state: " + url);
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId + "\",\"description\": \"Error on calling url to change device state\", \"parameter\": \"/lights/" + lightId + "state\"}}]";
}
}
if(!responseString.contains("[{\"error\":")) {
device.setDeviceState(state);
}
return responseString;
});
}
/* light weight templating here, was going to use free marker but it was a bit too
* heavy for what we were trying to do.
*
* currently provides:
* intensity.byte : 0-255 brightness. this is raw from the echo
* intensity.percent : 0-100, adjusted for the vera
* intensity.math(X*1) : where X is the value from the interface call and can use net.java.dev.eval math
*/
protected String replaceIntensityValue(String request, int intensity){
if(request == null){
return "";
}
if(request.contains(INTENSITY_BYTE)){
String intensityByte = String.valueOf(intensity);
request = request.replace(INTENSITY_BYTE, intensityByte);
}else if(request.contains(INTENSITY_PERCENT)){
int percentBrightness = (int) Math.round(intensity/255.0*100);
String intensityPercent = String.valueOf(percentBrightness);
request = request.replace(INTENSITY_PERCENT, intensityPercent);
} else if(request.contains(INTENSITY_MATH)){
Map<String, BigDecimal> variables = new HashMap<String, BigDecimal>();
String mathDescriptor = request.substring(request.indexOf(INTENSITY_MATH) + INTENSITY_MATH.length(),request.indexOf(INTENSITY_MATH_CLOSE));
variables.put(INTENSITY_MATH_VALUE, new BigDecimal(intensity));
try {
log.debug("Math eval is: " + mathDescriptor + ", Where " + INTENSITY_MATH_VALUE + " is: " + String.valueOf(intensity));
Expression exp = new Expression(mathDescriptor);
BigDecimal result = exp.eval(variables);
Integer endResult = Math.round(result.floatValue());
request = request.replace(INTENSITY_MATH + mathDescriptor + INTENSITY_MATH_CLOSE, endResult.toString());
} catch (Exception e) {
log.warn("Could not execute Math: " + mathDescriptor, e);
}
}
return request;
}
// This function executes the url from the device repository against the vera
protected boolean doHttpRequest(String url, String httpVerb, String contentType, String body) {
HttpUriRequest request = null;
try {
if(HttpGet.METHOD_NAME.equalsIgnoreCase(httpVerb) || httpVerb == null) {
request = new HttpGet(url);
}else if(HttpPost.METHOD_NAME.equalsIgnoreCase(httpVerb)){
HttpPost postRequest = new HttpPost(url);
ContentType parsedContentType = ContentType.parse(contentType);
StringEntity requestBody = new StringEntity(body, parsedContentType);
postRequest.setEntity(requestBody);
request = postRequest;
}else if(HttpPut.METHOD_NAME.equalsIgnoreCase(httpVerb)){
HttpPut putRequest = new HttpPut(url);
ContentType parsedContentType = ContentType.parse(contentType);
StringEntity requestBody = new StringEntity(body, parsedContentType);
putRequest.setEntity(requestBody);
request = putRequest;
}
} catch(IllegalArgumentException e) {
log.warn("Error calling out to HA gateway: IllegalArgumentException in log", e);
return false;
}
log.debug("Making outbound call in doHttpRequest: " + request);
try {
HttpResponse response = httpClient.execute(request);
EntityUtils.consume(response.getEntity()); //close out inputstream ignore content
log.debug((httpVerb == null?"GET":httpVerb) + " execute on URL responded: " + response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300){
return true;
}
} catch (IOException e) {
log.warn("Error calling out to HA gateway: IOException in log", e);
}
return false;
}
private String formatSuccessHueResponse(DeviceState state, String body, String lightId) {
String responseString = "[{\"success\":{\"/lights/" + lightId + "/state/on\":";
boolean justState = true;
if(body.contains("bri"))
{
if(justState)
responseString = responseString + "true}}";
responseString = responseString + ",{\"success\":{\"/lights/" + lightId + "/state/bri\":" + state.getBri() + "}}";
justState = false;
}
if(body.contains("ct"))
{
if(justState)
responseString = responseString + "true}}";
responseString = responseString + ",{\"success\":{\"/lights/" + lightId + "/state/ct\":" + state.getCt() + "}}";
justState = false;
}
if(body.contains("xy"))
{
if(justState)
responseString = responseString + "true}}";
responseString = responseString + ",{\"success\":{\"/lights/" + lightId + "/state/xy\":" + state.getXy() + "}}";
justState = false;
}
if(body.contains("hue"))
{
if(justState)
responseString = responseString + "true}}";
responseString = responseString + ",{\"success\":{\"/lights/" + lightId + "/state/hue\":" + state.getHue() + "}}";
justState = false;
}
if(body.contains("sat"))
{
if(justState)
responseString = responseString + "true}}";
responseString = responseString + ",{\"success\":{\"/lights/" + lightId + "/state/sat\":" + state.getSat() + "}}";
justState = false;
}
if(body.contains("colormode"))
{
if(justState)
responseString = responseString + "true}}";
responseString = responseString + ",{\"success\":{\"/lights/" + lightId + "/state/colormode\":" + state.getColormode() + "}}";
justState = false;
}
if(justState)
{
if (state.isOn()) {
responseString = responseString + "true}}]";
state.setBri(255);
} else if (body.contains("false")) {
responseString = responseString + "false}}";
state.setBri(0);
}
}
responseString = responseString + "]";
return responseString;
}
} |
package ljdp.minechem.api.core;
import static ljdp.minechem.api.core.EnumElement.*;
import java.util.ArrayList;
import java.util.Random;
// Na2OLi2O(SiO2)2(B2O3)3H2O
// MOLECULE IDS MUST BE CONTINIOUS OTHERWISE THE ARRAY WILL BE MISALIGNED.
public enum EnumMolecule {
cellulose(0, "Cellulose", new Element(C, 6), new Element(H, 10), new Element(O, 5)),
water(1, "Water", new Element(H, 2), new Element(O)),
carbonDioxide(2, "Carbon Dioxide", new Element(C), new Element(O, 2)),
nitrogenDioxide(3, "Nitrogen Dioxide", new Element(N), new Element(O, 2)),
toluene(4, "Toluene", new Element(C, 7), new Element(H, 8)),
potassiumNitrate(5, "Potassium Nitrate", new Element(K), new Element(N), new Element(O, 3)),
tnt(6, "Trinitrotoluene", new Element(C, 6), new Element(H, 2), new Molecule(nitrogenDioxide, 3), new Molecule(toluene)),
siliconDioxide(7, "Silicon Dioxide", new Element(Si), new Element(O, 2)),
calcite(8, "Calcite", new Element(Ca), new Element(C), new Element(O, 3)),
pyrite(9, "Pyrite", new Element(Fe), new Element(S, 2)),
nepheline(10, "Nepheline", new Element(Al), new Element(Si), new Element(O, 4)),
sulfate(11, "Sulfate (ion)", new Element(S), new Element(O, 4)),
noselite(12, "Noselite", new Element(Na, 8), new Molecule(nepheline, 6), new Molecule(sulfate)),
sodalite(13, "Sodalite", new Element(Na, 8), new Molecule(nepheline, 6), new Element(Cl, 2)),
nitrate(14, "Nitrate (ion)", new Element(N), new Element(O, 3)),
carbonate(15, "Carbonate (ion)", new Element(C), new Element(O, 3)),
cyanide(16, "Potassium Cyanide", new Element(K), new Element(C), new Element(N)),
phosphate(17, "Phosphate (ion)", new Element(P), new Element(O, 4)),
acetate(18, "Acetate (ion)", new Element(C, 2), new Element(H, 3), new Element(O, 2)),
chromate(19, "Chromate (ion)", new Element(Cr), new Element(O, 4)),
hydroxide(20, "Hydroxide (ion)", new Element(O), new Element(H)),
ammonium(21, "Ammonium (ion)", new Element(N), new Element(H, 4)),
hydronium(22, "Hydronium (ion)", new Element(H, 3), new Element(O)),
peroxide(23, "Hydrogen Peroxide", new Element(H, 2), new Element(O, 2)),
calciumOxide(24, "Calcium Oxide", new Element(Ca), new Element(O)),
calciumCarbonate(25, "Calcium Carbonate", new Element(Ca), new Molecule(carbonate)),
magnesiumCarbonate(26, "Magnesium Carbonate", new Element(Mg), new Molecule(carbonate)),
lazurite(27, "Lazurite", new Element(Na, 8), new Molecule(nepheline), new Molecule(sulfate)),
isoprene(28, "Isoprene", new Element(C, 5), new Element(H, 8)),
butene(29, "Butene", new Element(C, 4), new Element(H, 8)),
polyisobutylene(30, "Polyisobutylene Rubber", new Molecule(butene, 16), new Molecule(isoprene)),
malicAcid(31, "Malic Acid", new Element(C, 4), new Element(H, 6), new Element(O, 5)),
vinylChloride(32, "Vinyl Chloride Monomer", new Element(C, 2), new Element(H, 3), new Element(Cl)),
polyvinylChloride(33, "Polyvinyl Chloride", new Molecule(vinylChloride, 64)),
methamphetamine(34, "Methamphetamine", new Element(C, 10), new Element(H, 15), new Element(N)),
psilocybin(35, "Psilocybin", new Element(C, 12), new Element(H, 17), new Element(N, 2), new Element(O, 4), new Element(P)),
iron3oxide(36, "Iron (III) Oxide", new Element(Fe, 2), new Element(O, 3)),
strontiumNitrate(37, "Strontium Nitrate", new Element(Sr), new Molecule(nitrate, 2)),
magnetite(38, "Magnetite", new Element(Fe, 3), new Element(O, 4)),
magnesiumOxide(39, "Magnesium Oxide", new Element(Mg), new Element(O)),
cucurbitacin(40, "Cucurbitacin", new Element(C, 30), new Element(H, 42), new Element(O, 7)),
asparticAcid(41, "Aspartic Acid", new Element(C, 4), new Element(H, 7), new Element(N), new Element(O, 4)),
hydroxylapatite(42, "Hydroxylapatite", new Element(Ca, 5), new Molecule(phosphate, 3), new Element(O), new Element(H)),
alinine(43, "Alinine (amino acid)", new Element(C, 3), new Element(H, 7), new Element(N), new Element(O, 2)),
glycine(44, "Glycine (amino acid)", new Element(C, 2), new Element(H, 5), new Element(N), new Element(O, 2)),
serine(45, "Serine (amino acid)", new Element(C, 3), new Element(H, 7), new Molecule(nitrate)),
mescaline(46, "Mescaline", new Element(C, 11), new Element(H, 17), new Molecule(nitrate)),
methyl(47, "Methyl (ion)", new Element(C), new Element(H, 3)),
methylene(48, "Methylene (ion)", new Element(C), new Element(H, 2)),
cyanoacrylate(49, "Cyanoacrylate", new Molecule(methyl), new Molecule(methylene), new Element(C, 3), new Element(N), new Element(H), new Element(O, 2)),
polycyanoacrylate(50, "Poly-cyanoacrylate", new Molecule(cyanoacrylate, 3)),
redPigment(51, "Cobalt(II) nitrate", new Element(Co), new Molecule(nitrate, 2)),
orangePigment(52, "Potassium Dichromate", new Element(K, 2), new Element(Cr, 2), new Element(O, 7)),
yellowPigment(53, "Potassium Chromate", new Element(Cr), new Element(K, 2), new Element(O, 4)),
limePigment(54, "Nickel(II) Chloride", new Element(Ni), new Element(Cl, 2)),
lightbluePigment(55, "Copper(II) Sulfate", new Element(Cu), new Molecule(sulfate)),
purplePigment(56, "Potassium Permanganate", new Element(K), new Element(Mn), new Element(O, 4)),
greenPigment(57, "Zinc Green", new Element(Co), new Element(Zn), new Element(O, 2)),
blackPigment(58, "Carbon Black", new Element(C), new Element(H, 2), new Element(O)),
whitePigment(59, "Titanium Dioxide", new Element(Ti), new Element(O, 2)),
metasilicate(60, "Metasilicate", new Element(Si), new Element(O, 3)),
beryl(61, "Beryl", new Element(Be, 3), new Element(Al, 2), new Molecule(metasilicate, 6)),
ethanol(62, "Ethyl Alchohol", new Element(C, 2), new Element(H, 6), new Element(O)),
amphetamine(63, "Aphetamine", new Element(C, 9), new Element(H, 13), new Element(N)),
theobromine(64, "Theobromine", new Element(C, 7), new Element(H, 8), new Element(N, 4), new Element(O, 2)),
starch(65, "Starch", new Molecule(cellulose, 2), new Molecule(cellulose, 1)),
sucrose(66, "Sucrose", new Element(C, 12), new Element(H, 22), new Element(O, 11)),
muscarine(67, "Muscarine", new Element(C, 9), new Element(H, 20), new Element(N), new Element(O, 2)),
aluminiumOxide(68, "Aluminium Oxide", new Element(Al, 2), new Element(O, 3)),
fullrene(69, "Carbon Nanotubes", new Element(C, 64), new Element(C, 64), new Element(C, 64), new Element(C, 64)),
keratin(70, "Keratin", new Element(C, 2), new Molecule(water), new Element(N)),
penicillin(71, "Penicillin", new Element(C, 16), new Element(H, 18), new Element(N, 2), new Element(O, 4), new Element(S)),
testosterone(72, "Testosterone", new Element(C, 19), new Element(H, 28), new Element(O, 2)),
kaolinite(73, "Kaolinite", new Element(Al, 2), new Element(Si, 2), new Element(O, 5), new Molecule(hydroxide, 4)),
fingolimod(74, "Fingolimod", new Element(C, 19), new Element(H, 33), new Molecule(nitrogenDioxide)), // LJDP, You ment to say fingolimod not myrocin.
arginine(75, "Arginine (amino acid)", new Element(C, 6), new Element(H, 14), new Element(N, 4), new Element(O, 2)),
shikimicAcid(76, "Shikimic Acid", new Element(C, 7), new Element(H, 10), new Element(O, 5)),
sulfuricAcid(77, "Sulfuric Acid", new Element(H, 2), new Element(S), new Element(O, 4)),
glyphosate(78, "Glyphosate", new Element(C, 3), new Element(H, 8), new Element(N), new Element(O, 5), new Element(P)),
quinine(79, "Quinine", new Element(C, 20), new Element(H, 24), new Element(N, 2), new Element(O, 2)),
ddt(80, "DDT", new Element(C, 14), new Element(H, 9), new Element(Cl, 5)),
dota(81, "DOTA", new Element(C, 16), new Element(H, 28), new Element(N, 4), new Element(O, 8)),
poison(82, "T-2 Mycotoxin", new Element(C, 24), new Element(H, 34), new Element(O, 9)),
salt(83, "Salt", new Element(Na, 1), new Element(Cl, 1)),
nhthree(84, "Ammonia", new Element(N, 1), new Element(H, 3)),
nod(85, "Nodularin", new Element(C, 41), new Element(H, 60), new Element(N, 8), new Element(O, 10)),
ttx(86, "TTX (Tetrodotoxin)", new Element(C, 11), new Element(H, 11), new Element(N, 3), new Element(O, 8)),
afroman(87, "THC", new Element(C, 21), new Element(H, 30), new Element(O, 2)),
mt(88, "Methylcyclopentadienyl Manganese Tricarbonyl", new Element(C, 9), new Element(H, 7), new Element(Mn, 1), new Element(O, 3)), // Level 1
buli(89, "Tert-Butyllithium", new Element(Li, 1), new Element(C, 4), new Element(H, 9)), // Level 2
plat(90, "Chloroplatinic acid", new Element(H, 2), new Element(Pt, 1), new Element(Cl, 6)), // Level 3
phosgene(91, "Phosgene", new Element(C, 1), new Element(O, 1), new Element(Cl, 2)),
aalc(92, "Allyl alcohol", new Element(C, 3), new Element(H, 6), new Element(O, 1)),
hist(93, "Diphenhydramine", new Element(C, 17), new Element(H, 21), new Element(N), new Element(O)),
pal2(94, "Batrachotoxin", new Element(C, 31), new Element(H, 42), new Element(N, 2), new Element(O, 6)),
ret(95, "Retinol", new Element(C, 20), new Element(H, 30), new Element(O)),
stevenk(96, "Xylitol", new Element(C, 5), new Element(H, 12), new Element(O, 5)),
weedex(97, "Aminocyclopyrachlor", new Element(C,8), new Element(H,8), new Element(Cl), new Element(N,3), new Element(O,2)),
biocide(98, "Ptaquiloside", new Element(C, 20), new Element(H, 30), new Element(O, 8)),
xanax(99, "Alprazolam", new Element(C,17), new Element(H,13), new Element(Cl), new Element(N,4))
;
public static EnumMolecule[] molecules = values();
private final String descriptiveName;
private final ArrayList<Chemical> components;
private int id;
public float red;
public float green;
public float blue;
public float red2;
public float green2;
public float blue2;
EnumMolecule(int id, String descriptiveName, Chemical... chemicals) {
this.id = id;
this.components = new ArrayList<Chemical>();
this.descriptiveName = descriptiveName;
for (Chemical chemical : chemicals) {
this.components.add(chemical);
}
Random random = new Random(id);
this.red = random.nextFloat();
this.green = random.nextFloat();
this.blue = random.nextFloat();
this.red2 = random.nextFloat();
this.green2 = random.nextFloat();
this.blue2 = random.nextFloat();
}
public static EnumMolecule getById(int id) {
for (EnumMolecule molecule : molecules) {
if (molecule.id == id)
return molecule;
}
return null;
}
public int id() {
return this.id;
}
public String descriptiveName() {
return this.descriptiveName;
}
public ArrayList<Chemical> components() {
return this.components;
}
} |
package com.conveyal.r5.transit.fare;
import com.conveyal.r5.api.util.Fare;
import com.conveyal.r5.api.util.Stop;
import com.conveyal.r5.util.P2;
import com.csvreader.CsvReader;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
/**
* Stop names are just strings. Only works on fares from a single feed.
*/
public class FareTable {
private static final Logger LOG = LoggerFactory.getLogger(FareTable.class);
private Map<P2<String>, Fare> fares = Maps.newHashMap();
private boolean ignoreAgencyId;
public FareTable (String name) {
this(name, false);
}
public FareTable (String name, boolean ignoreAgencyId) {
this.ignoreAgencyId = ignoreAgencyId;
InputStream is = FareTable.class.getClassLoader().getResourceAsStream(name);
CsvReader reader = new CsvReader(is, ',', Charset.forName("UTF-8"));
try {
reader.readHeaders();
while (reader.readRecord()) {
String from = reader.get("from_stop_id");
String to = reader.get("to_stop_id");
double low = Double.parseDouble(reader.get("low_fare"));
double peak = Double.parseDouble(reader.get("peak_fare"));
double senior = Double.parseDouble(reader.get("senior_fare"));
Fare fare = new Fare(low, peak, senior);
fares.put(new P2<String>(from, to), fare);
}
} catch (IOException ex) {
LOG.error("Exception while loading fare table CSV.");
}
}
public Fare lookup (String from, String to) {
return new Fare(fares.get(new P2<>(from, to))); // defensive copy, in case the caller discounts
}
public Fare lookup (Stop from, Stop to) {
if (this.ignoreAgencyId) {
String fromWithoutFeedId = from.stopId.split(":", 2)[1];
String toWithoutFeedId = to.stopId.split(":", 2)[1];
return lookup(fromWithoutFeedId, toWithoutFeedId);
} else {
return lookup(from.stopId, to.stopId);
}
}
} |
package com.markjmind.uni.common;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.util.Base64;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
/**
* start : 2012.08.30<br>
* <br>
* Layout Controll JwViewController .<br>
* Layout Util .<br>
*
* @author
* @version 2013.11.17
*/
public class Jwc{
public static int getColor(String color){
return Color.parseColor(color);
}
public static float getDensity(Context context){
return context.getResources().getDisplayMetrics().density;
}
public static float getDensity(Activity context){
return context.getResources().getDisplayMetrics().density;
}
public static float getDensity(View view){
return view.getContext().getResources().getDisplayMetrics().density;
}
public static int getDp(Context context, int pix){
return (int)(pix/context.getResources().getDisplayMetrics().density);
}
public static int getPix(Context context, int dp){
return (int)(dp*context.getResources().getDisplayMetrics().density);
}
public static int getWindowHeight(Context context){
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.y;
}
public static int getWindowWidth(Context context){
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
public static void setVisible(View target, boolean isVisible, int falseVisible){
if(isVisible){
target.setVisibility(View.VISIBLE);
}else{
target.setVisibility(falseVisible);
}
}
public static void setVisible(View target, boolean isVisible){
Jwc.setVisible(target,isVisible, View.GONE);
}
public static boolean isActivityRunning(Context context){
ActivityManager actMng = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> list = actMng.getRunningAppProcesses();
for(ActivityManager.RunningAppProcessInfo info : list){
if(info.processName.equals(context.getPackageName()))
{
return true;
}
}
return false;
}
public static void toast(Context context, String msg){
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
public static void hideKeyboard(Context context, EditText editText){
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
public static void hideKeyboard(Activity activity){
View view = activity.getCurrentFocus();
if ( view != null ) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public static void showKeyboard(Context context, EditText editText){
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, 0);
}
public static View lastChild(ViewGroup parantView){
return parantView.getChildAt(parantView.getChildCount() - 1);
}
public static View getInfalterView(Context context, int layout_id){
// return LayoutInflater.from(context).inflate(layout_id, null);
return ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(layout_id, null);
// return View.inflate(context, layout_id,null);
}
public static View getInfalterView(Context context, int layout_id, ViewGroup parents){
return ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(layout_id, parents);
}
public static View findViewById(View view, int R_id){
return view.findViewById(R_id);
}
public static View findViewWithTag(View parants, Object tag){
return parants.findViewWithTag(tag);
}
public static void saveViewToImage(View saveView, File saveFile) throws IOException {
OutputStream out = new FileOutputStream(saveFile);
Bitmap bitmap = Bitmap.createBitmap(saveView.getMeasuredWidth(),saveView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bitmapHolder = new Canvas(bitmap);
saveView.draw(bitmapHolder);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
saveFile.setReadable(true, false);
}
public static void setlargeDialog(Dialog dialog){
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes( ) ;
WindowManager wm = ((WindowManager)dialog.getContext().getApplicationContext().getSystemService(dialog.getContext().getApplicationContext().WINDOW_SERVICE)) ;
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
lp.width = size.x;
lp.height = size.y - getStatusBarHeight(dialog.getContext())-(int)(50*getDensity(dialog.getContext()));
dialog.getWindow().setAttributes( lp ) ;
// dialog.getWindow().setLayout(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
}
public static String getHashKey(Context context) throws NoSuchAlgorithmException, PackageManager.NameNotFoundException {
MessageDigest md = null;
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
md = MessageDigest.getInstance("SHA1");
md.update(signature.toByteArray());
}
return Base64.encodeToString(md.digest(), Base64.DEFAULT);
}
public static String getVersion(Context context) throws PackageManager.NameNotFoundException {
return getPackageInfo(context).versionName;
}
public static PackageInfo getPackageInfo(Context context) throws PackageManager.NameNotFoundException {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
}
public static void gotMarket(Context context){
String packageName = context.getPackageName();
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName)));
} catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
}
}
public static void appStore(Context context){
gotMarket(context);
}
} |
package org.commcare.util.cli;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.javarosa.core.model.condition.EvaluationContext;
import java.io.PrintStream;
import java.util.Arrays;
public class EntityDetailSubscreen extends Subscreen<EntityScreen> {
private final int SCREEN_WIDTH = 100;
private final String[] rows;
private final String[] mDetailListTitles;
private final Object[] data ;
private final String[] headers;
private final int mCurrentIndex;
public EntityDetailSubscreen(int currentIndex, Detail detail, EvaluationContext subContext, String[] detailListTitles) {
DetailField[] fields = detail.getFields();
rows = new String[fields.length];
headers = new String[fields.length];
data = new Object[fields.length];
detail.populateEvaluationContextVariables(subContext);
for (int i = 0; i < fields.length; ++i) {
data[i] = createData(fields[i], subContext);
headers[i] = createHeader(fields[i], subContext);
rows[i] = createRow(fields[i], subContext, data[i]);
}
mDetailListTitles = detailListTitles;
mCurrentIndex = currentIndex;
}
private String createHeader(DetailField field, EvaluationContext ec){return field.getHeader().evaluate(ec);}
private Object createData(DetailField field, EvaluationContext ec){
return field.getTemplate().evaluate(ec);
}
private String createRow(DetailField field, EvaluationContext ec, Object o) {
StringBuilder row = new StringBuilder();
String header = field.getHeader().evaluate(ec);
CliUtils.addPaddedStringToBuilder(row, header, SCREEN_WIDTH / 2);
row.append(" | ");
String value;
if (!(o instanceof String)) {
value = "{ " + field.getTemplateForm() + " data}";
} else {
value = (String)o;
}
CliUtils.addPaddedStringToBuilder(row, value, SCREEN_WIDTH / 2);
return row.toString();
}
@Override
public void prompt(PrintStream out) {
boolean multipleInputs = false;
if (mDetailListTitles.length > 1) {
createTabHeader(out);
out.println("==============================================================================================");
multipleInputs = true;
}
for (int i = 0; i < rows.length; ++i) {
String row = rows[i];
out.println(row);
}
String msg;
if (multipleInputs) {
msg = "Press enter to select this case, or the number of the detail tab to view";
} else {
msg = "Press enter to select this case";
}
out.println();
out.println(msg);
}
@Override
public String[] getOptions() {
return rows;
}
private void createTabHeader(PrintStream out) {
StringBuilder sb = new StringBuilder();
int widthPerTab = (int)(SCREEN_WIDTH * 1.0 / mDetailListTitles.length);
for (int i = 0; i < mDetailListTitles.length; ++i) {
String title = i + ") " + mDetailListTitles[i];
if (i == this.mCurrentIndex) {
title = "[" + title + "]";
}
CliUtils.addPaddedStringToBuilder(sb, title, widthPerTab);
}
out.println(sb.toString());
}
@Override
public boolean handleInputAndUpdateHost(String input, EntityScreen host) throws CommCareSessionException {
if (input.trim().equals("")) {
return true;
}
try {
int i = Integer.parseInt(input);
if (i >= 0 && i < mDetailListTitles.length) {
host.setCurrentScreenToDetail(i);
return false;
}
} catch (NumberFormatException e) {
//This will result in things just executing again, which is fine.
}
return false;
}
public Object[] getData() {
return data;
}
public String[] getHeaders(){
return headers;
}
public String[] getTitles() { return mDetailListTitles;}
} |
package com.distelli.europa.db;
import java.util.List;
import com.distelli.persistence.ConvertMarker;
import com.distelli.persistence.Index;
import com.distelli.persistence.Index;
import com.distelli.persistence.PageIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.distelli.jackson.transform.TransformModule;
import com.distelli.europa.EuropaConfiguration;
import com.distelli.europa.Constants;
import com.distelli.europa.ajax.*;
import com.distelli.europa.models.*;
import com.distelli.europa.webserver.*;
import org.apache.log4j.Logger;
import javax.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class ContainerRepoDb
{
private static final Logger log = Logger.getLogger(ContainerRepoDb.class);
private Index<ContainerRepo> _main;
private Index<ContainerRepo> _secondaryIndex;
private EuropaConfiguration _europaConfiguration;
private final ObjectMapper _om = new ObjectMapper();
private TransformModule createTransforms(TransformModule module) {
module.createTransform(ContainerRepo.class)
.put("hk", String.class,
(item) -> getHashKey(item),
(item, domain) -> setHashKey(item, domain))
.put("id", String.class,
(item) -> item.getId().toLowerCase(),
(item, id) -> item.setId(id))
.put("sidx", String.class,
(item) -> getSecondaryKey(item.getProvider(), item.getRegion(), item.getName()))
.put("prov", RegistryProvider.class, "provider")
.put("region", String.class, "region")
.put("name", String.class, "name")
.put("cid", String.class, "credId");
return module;
}
private final String getHashKey(ContainerRepo repo)
{
if(_europaConfiguration.isMultiTenant())
{
if(repo == null)
throw(new IllegalArgumentException("Invalid null repo in multi-tenant setup"));
return getHashKey(repo.getDomain());
}
return Constants.DOMAIN_ZERO;
}
private final String getHashKey(String domain)
{
if(_europaConfiguration.isMultiTenant())
{
if(domain == null)
throw(new IllegalArgumentException("Invalid null domain in multi-tenant setup for ContainerRepo"));
return domain.toLowerCase();
}
return Constants.DOMAIN_ZERO;
}
private final void setHashKey(ContainerRepo repo, String domain)
{
if(_europaConfiguration.isMultiTenant())
{
if(domain == null)
throw(new IllegalArgumentException("Invalid null domain in multi-tenant setup for ContainerRepo"));
repo.setDomain(domain);
}
repo.setDomain(null);
}
private final String getSecondaryKey(RegistryProvider provider, String region, String name)
{
return String.format("%s:%s:%s",
provider.toString().toLowerCase(),
region.toLowerCase(),
name.toLowerCase());
}
@Inject
protected ContainerRepoDb(Index.Factory indexFactory,
ConvertMarker.Factory convertMarkerFactory,
EuropaConfiguration europaConfiguration) {
_europaConfiguration = europaConfiguration;
_om.registerModule(createTransforms(new TransformModule()));
_main = indexFactory.create(ContainerRepo.class)
.withTableName("repos")
.withNoEncrypt("hk", "id", "sidx")
.withHashKeyName("hk")
.withRangeKeyName("id")
.withConvertValue(_om::convertValue)
.withConvertMarker(convertMarkerFactory.create("hk", "id"))
.build();
_secondaryIndex = indexFactory.create(ContainerRepo.class)
.withIndexName("repos", "provider-index")
.withNoEncrypt("hk", "id", "sidx")
.withHashKeyName("hk")
.withRangeKeyName("sidx")
.withConvertValue(_om::convertValue)
.withConvertMarker(convertMarkerFactory.create("hk", "sidx"))
.build();
}
public void save(ContainerRepo repo)
{
String region = repo.getRegion();
if(region == null || region.contains(":"))
throw(new AjaxClientException("Invalid Region "+region+" in Container Repo", JsonError.Codes.BadContent, 400));
String name = repo.getName();
if(name == null || name.contains(":"))
throw(new AjaxClientException("Invalid Name "+name+" in Container Repo", JsonError.Codes.BadContent, 400));
String id = repo.getId();
if(id == null)
throw(new IllegalArgumentException("Invalid id "+id+" in container repo"));
if(_europaConfiguration.isMultiTenant() && repo.getDomain() == null)
throw(new IllegalArgumentException("Invalid null domain in multi-tenant setup for ContainerRepo: "+
repo));
_main.putItem(repo);
}
public void deleteRepo(String domain, String id)
{
_main.deleteItem(getHashKey(domain),
id.toLowerCase());
}
public List<ContainerRepo> listRepos(String domain, PageIterator pageIterator)
{
return _main.queryItems(getHashKey(domain), pageIterator).list();
}
public List<ContainerRepo> listRepos(String domain,
RegistryProvider provider,
PageIterator pageIterator)
{
String rangeKey = String.format("%s:", provider.toString().toLowerCase());
return _secondaryIndex.queryItems(getHashKey(domain), pageIterator)
.beginsWith(rangeKey)
.list();
}
public List<ContainerRepo> listRepos(String domain,
RegistryProvider provider,
String region,
PageIterator pageIterator)
{
String rangeKey = String.format("%s:%s:",
provider.toString().toLowerCase(),
region.toLowerCase());
return _main.queryItems(getHashKey(domain), pageIterator)
.beginsWith(rangeKey)
.list();
}
public ContainerRepo getRepo(String domain, String id)
{
return _main.getItem(getHashKey(domain),
id.toLowerCase());
}
} |
package com.epam.ta.reportportal.ws.model;
import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.Iterator;
/**
* Paged response representation
* Re-implementation of Spring's HATEAOS Page implementation to get rid of Spring's deps in model package
*
* @author Andrei Varabyeu
*/
public class Page<T> implements Iterable<T>{
private final Collection<T> content;
private final PageMetadata page;
public Page(Collection<T> content, PageMetadata page) {
this.content = content;
this.page = page;
}
public Page(Collection<T> content, long size, long number, long totalElements, long totalPages) {
this.content = content;
this.page = new PageMetadata(size, number, totalElements, totalPages);
}
public Page(Collection<T> content, long size, long number, long totalElements) {
this.content = content;
this.page = new PageMetadata(size, number, totalElements);
}
public Collection<T> getContent() {
return content;
}
public PageMetadata getPage() {
return page;
}
@Override
public Iterator<T> iterator() {
return content.iterator();
}
public static class PageMetadata {
long number;
long size;
long totalElements;
long totalPages;
public PageMetadata(long size, long number, long totalElements, long totalPages) {
Preconditions.checkArgument(size > -1, "Size must not be negative!");
Preconditions.checkArgument(number > -1, "Number must not be negative!");
Preconditions.checkArgument(totalElements > -1, "Total elements must not be negative!");
Preconditions.checkArgument(totalPages > -1, "Total pages must not be negative!");
this.number = number;
this.size = size;
this.totalElements = totalElements;
this.totalPages = totalPages;
}
public PageMetadata(long size, long number, long totalElements) {
this(size, number, totalElements, size == 0 ? 0 : (long) Math.ceil((double) totalElements / (double) size));
}
public long getNumber() {
return number;
}
public long getSize() {
return size;
}
public long getTotalElements() {
return totalElements;
}
public long getTotalPages() {
return totalPages;
}
}
} |
package com.frostwire.jlibtorrent;
import com.frostwire.jlibtorrent.swig.libtorrent;
import com.frostwire.jlibtorrent.swig.torrent_flags_t;
/**
* @author gubatron
* @author aldenml
*/
public final class TorrentFlags {
private TorrentFlags() {
}
// If ``seed_mode`` is set, libtorrent will assume that all files
// are present for this torrent and that they all match the hashes in
// the torrent file. Each time a peer requests to download a block,
// the piece is verified against the hash, unless it has been verified
// already. If a hash fails, the torrent will automatically leave the
// seed mode and recheck all the files. The use case for this mode is
// if a torrent is created and seeded, or if the user already know
// that the files are complete, this is a way to avoid the initial
// file checks, and significantly reduce the startup time.
// Setting ``seed_mode`` on a torrent without metadata (a
// .torrent file) is a no-op and will be ignored.
// If resume data is passed in with this torrent, the seed mode saved
// in there will override the seed mode you set here.
public static final torrent_flags_t SEED_MODE = libtorrent.getSeed_mode();
// If ``upload_mode`` is set, the torrent will be initialized in
// upload-mode, which means it will not make any piece requests. This
// state is typically entered on disk I/O errors, and if the torrent
// is also auto managed, it will be taken out of this state
// periodically (see ``settings_pack::optimistic_disk_retry``).
// This mode can be used to avoid race conditions when
// adjusting priorities of pieces before allowing the torrent to start
// downloading.
// If the torrent is auto-managed (``auto_managed``), the torrent
// will eventually be taken out of upload-mode, regardless of how it
// got there. If it's important to manually control when the torrent
// leaves upload mode, don't make it auto managed.
public static final torrent_flags_t UPLOAD_MODE = libtorrent.getUpload_mode();
// determines if the torrent should be added in *share mode* or not.
// Share mode indicates that we are not interested in downloading the
// torrent, but merely want to improve our share ratio (i.e. increase
// it). A torrent started in share mode will do its best to never
// download more than it uploads to the swarm. If the swarm does not
// have enough demand for upload capacity, the torrent will not
// download anything. This mode is intended to be safe to add any
// number of torrents to, without manual screening, without the risk
// of downloading more than is uploaded.
// A torrent in share mode sets the priority to all pieces to 0,
// except for the pieces that are downloaded, when pieces are decided
// to be downloaded. This affects the progress bar, which might be set
// to "100% finished" most of the time. Do not change file or piece
// priorities for torrents in share mode, it will make it not work.
// The share mode has one setting, the share ratio target, see
// ``settings_pack::share_mode_target`` for more info.
public static final torrent_flags_t SHARE_MODE = libtorrent.getShare_mode();
// determines if the IP filter should apply to this torrent or not. By
// default all torrents are subject to filtering by the IP filter
// (i.e. this flag is set by default). This is useful if certain
// torrents needs to be exempt for some reason, being an auto-update
// torrent for instance.
public static final torrent_flags_t APPLY_IP_FILTER = libtorrent.getApply_ip_filter();
// specifies whether or not the torrent is to be started in a paused
// state. I.e. it won't connect to the tracker or any of the peers
// until it's resumed. This is typically a good way of avoiding race
// conditions when setting configuration options on torrents before
// starting them.
public static final torrent_flags_t PAUSED = libtorrent.getPaused();
// If the torrent is auto-managed (``auto_managed``), the torrent
// may be resumed at any point, regardless of how it paused. If it's
// important to manually control when the torrent is paused and
// resumed, don't make it auto managed.
// If ``auto_managed`` is set, the torrent will be queued,
// started and seeded automatically by libtorrent. When this is set,
// the torrent should also be started as paused. The default queue
// order is the order the torrents were added. They are all downloaded
// in that order. For more details, see queuing_.
// If you pass in resume data, the auto_managed state of the torrent
// when the resume data was saved will override the auto_managed state
// you pass in here. You can override this by setting
// ``override_resume_data``.
public static final torrent_flags_t AUTO_MANAGED = libtorrent.getAuto_managed();
public static final torrent_flags_t DUPLICATE_IS_ERROR = libtorrent.getDuplicate_is_error();
// on by default and means that this torrent will be part of state
// updates when calling post_torrent_updates().
public static final torrent_flags_t UPDATE_SUBSCRIBE = libtorrent.getUpdate_subscribe();
// sets the torrent into super seeding mode. If the torrent is not a
// seed, this flag has no effect. It has the same effect as calling
// ``torrent_handle::super_seeding(true)`` on the torrent handle
// immediately after adding it.
public static final torrent_flags_t SUPER_SEEDING = libtorrent.getSuper_seeding();
// sets the sequential download state for the torrent. It has the same
// effect as calling ``torrent_handle::sequential_download(true)`` on
// the torrent handle immediately after adding it.
public static final torrent_flags_t SEQUENTIAL_DOWNLOAD = libtorrent.getSequential_download();
// When this flag is set, the
// torrent will *force stop* whenever it transitions from a
// non-data-transferring state into a data-transferring state (referred to
// as being ready to download or seed). This is useful for torrents that
// should not start downloading or seeding yet, but want to be made ready
// to do so. A torrent may need to have its files checked for instance, so
// it needs to be started and possibly queued for checking (auto-managed
// and started) but as soon as it's done, it should be stopped.
// *Force stopped* means auto-managed is set to false and it's paused. As
// if auto_manage(false) and pause() were called on the torrent.
// Note that the torrent may transition into a downloading state while
// calling this function, and since the logic is edge triggered you may
// miss the edge. To avoid this race, if the torrent already is in a
// downloading state when this call is made, it will trigger the
// stop-when-ready immediately.
// When the stop-when-ready logic fires, the flag is cleared. Any
// subsequent transitions between downloading and non-downloading states
// will not be affected, until this function is used to set it again.
// The behavior is more robust when setting this flag as part of adding
// the torrent. See add_torrent_params.
// The stop-when-ready flag fixes the inherent race condition of waiting
// for the state_changed_alert and then call pause(). The download/seeding
// will most likely start in between posting the alert and receiving the
// call to pause.
public static final torrent_flags_t STOP_WHEN_READY = libtorrent.getStop_when_ready();
// when this flag is set, the tracker list in the add_torrent_params
// object override any trackers from the torrent file. If the flag is
// not set, the trackers from the add_torrent_params object will be
// added to the list of trackers used by the torrent.
public static final torrent_flags_t OVERRIDE_TRACKERS = libtorrent.getOverride_trackers();
// If this flag is set, the web seeds from the add_torrent_params
// object will override any web seeds in the torrent file. If it's not
// set, web seeds in the add_torrent_params object will be added to the
// list of web seeds used by the torrent.
public static final torrent_flags_t OVERRIDE_WEB_SEEDS = libtorrent.getOverride_web_seeds();
/**
* If this flag is set (which it is by default) the torrent will be
* considered needing to save its resume data immediately as it's
* added. New torrents that don't have any resume data should do that.
* This flag is cleared by a successful call to save_resume_data()
*/
public static final torrent_flags_t NEED_SAVE_RESUME = libtorrent.getNeed_save_resume();
/**
* Set this flag to disable DHT for this torrent. This lets you have the DHT
* enabled for the whole client, and still have specific torrents not
* participating in it. i.e. not announcing to the DHT nor picking up peers
* from it.
*/
public static final torrent_flags_t DISABLE_DHT = libtorrent.getDisable_dht();
/**
* Set this flag to disable local service discovery for this torrent.
*/
public static final torrent_flags_t DISABLE_LSD = libtorrent.getDisable_lsd();
/**
* Set this flag to disable peer exchange for this torrent.
*/
public static final torrent_flags_t DISABLE_PEX = libtorrent.getDisable_pex();
public static final torrent_flags_t ALL = libtorrent.getAll();
} |
package com.github.abel533.mapper;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.scripting.xmltags.*;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.ibatis.jdbc.SqlBuilder.*;
public class MapperHelper {
private class Config {
private String UUID = "";
private String IDENTITY = "";
private boolean BEFORE = false;
}
private Config config = new Config();
public void setUUID(String UUID) {
config.UUID = UUID;
}
public void setIDENTITY(String IDENTITY) {
config.IDENTITY = IDENTITY;
}
public void setBEFORE(String BEFORE) {
config.BEFORE = "BEFORE".equalsIgnoreCase(BEFORE);
}
private String getUUID() {
if (config.UUID != null && config.UUID.length() > 0) {
return config.UUID;
}
return "@java.util.UUID@randomUUID().toString().replace(\"-\", \"\")";
}
private String getIDENTITY() {
if (config.IDENTITY != null && config.IDENTITY.length() > 0) {
return config.IDENTITY;
}
return "CALL IDENTITY()";
}
private boolean getBEFORE() {
return config.BEFORE;
}
public static final String DYNAMIC_SQL = "dynamicSQL";
/**
* skip
*/
private final Map<String, Boolean> msIdSkip = new HashMap<String, Boolean>();
private final Map<String, Class<?>> entityType = new HashMap<String, Class<?>>();
public final String[] METHODS = {
"select",
"selectByPrimaryKey",
"selectCount",
"insert",
"insertSelective",
"delete",
"deleteByPrimaryKey",
"updateByPrimaryKey",
"updateByPrimaryKeySelective"};
public String dynamicSQL(Object record) {
return DYNAMIC_SQL;
}
private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
/**
* Mybatis
*
* @param object
* @return
*/
public static MetaObject forObject(Object object) {
return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
}
/**
* msId
*
* @param msId
* @return
* @throws ClassNotFoundException
*/
public Class<?> getMapperClass(String msId) throws ClassNotFoundException {
String mapperClassStr = msId.substring(0, msId.lastIndexOf("."));
return Class.forName(mapperClassStr);
}
/**
* Mapper
*
* @param mapperClass
* @return
*/
public boolean extendsMapper(Class mapperClass) {
return Mapper.class.isAssignableFrom(mapperClass);
}
/**
*
*
* @param msId
* @return
*/
public boolean isMapperMethod(String msId) {
if (msIdSkip.get(msId) != null) {
return msIdSkip.get(msId);
}
try {
String methodName = msId.substring(msId.lastIndexOf(".") + 1);
boolean rightMethod = false;
for (String method : METHODS) {
if (method.equals(methodName)) {
rightMethod = true;
break;
}
}
if (!rightMethod) {
return false;
}
Boolean skip = extendsMapper(getMapperClass(msId));
msIdSkip.put(msId, skip);
return skip;
} catch (ClassNotFoundException e) {
return false;
}
}
/**
*
*
* @param ms
* @return
*/
public Class<?> getSelectReturnType(MappedStatement ms) {
String msId = ms.getId();
if (entityType.get(msId) != null) {
return entityType.get(msId);
}
Class<?> mapperClass = null;
try {
mapperClass = getMapperClass(msId);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Mapper:" + msId);
}
Type[] types = mapperClass.getGenericInterfaces();
for (Type type : types) {
if (type instanceof ParameterizedType) {
ParameterizedType t = (ParameterizedType) type;
if (t.getRawType() == Mapper.class) {
Class<?> returnType = (Class) t.getActualTypeArguments()[0];
entityType.put(msId, returnType);
return returnType;
}
}
}
throw new RuntimeException("Mapper<T>:" + msId);
}
public String getMethodName(MappedStatement ms) {
String msId = ms.getId();
return msId.substring(msId.lastIndexOf(".") + 1);
}
/**
* SqlSource
*
* @param ms
* @param sqlSource
*/
private void setSqlSource(MappedStatement ms, SqlSource sqlSource) {
MetaObject msObject = forObject(ms);
msObject.setValue("sqlSource", sqlSource);
}
/**
* selectSqlSource
*
* @param ms
*/
public void selectSqlSource(MappedStatement ms) {
String methodName = getMethodName(ms);
Class<?> entityClass = getSelectReturnType(ms);
//sql
if (methodName.equals(METHODS[0])) {
DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), getSelectSqlNode(ms));
setSqlSource(ms, dynamicSqlSource);
} else if (methodName.equals(METHODS[1])) {//sql
List<ParameterMapping> parameterMappings = getPrimaryKeyParameterMappings(ms);
BEGIN();
SELECT(EntityHelper.getSelectColumns(entityClass));
FROM(EntityHelper.getTableName(entityClass));
WHERE(EntityHelper.getPrimaryKeyWhere(entityClass));
StaticSqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), SQL(), parameterMappings);
setSqlSource(ms, sqlSource);
} else {
DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), getSelectCountSqlNode(ms));
setSqlSource(ms, dynamicSqlSource);
}
if (methodName.equals(METHODS[0]) || methodName.equals(METHODS[1])) {
ResultMap resultMap = ms.getResultMaps().get(0);
MetaObject metaObject = MapperHelper.forObject(resultMap);
metaObject.setValue("type", entityClass);
}
}
/**
* insertSqlSource
*
* @param ms
*/
public void insertSqlSource(MappedStatement ms) {
String methodName = getMethodName(ms);
Class<?> entityClass = getSelectReturnType(ms);
//sql
if (methodName.equals(METHODS[4])) {
DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), getInsertSqlNode(ms));
setSqlSource(ms, dynamicSqlSource);
} else {//sql
//selectKeysql
DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), getInsertAllSqlNode(ms));
setSqlSource(ms, dynamicSqlSource);
}
}
/**
* updateSqlSource
*
* @param ms
*/
public void updateSqlSource(MappedStatement ms) {
String methodName = getMethodName(ms);
Class<?> entityClass = getSelectReturnType(ms);
//sql
if (methodName.equals(METHODS[8])) {
DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), getUpdateSqlNode(ms));
setSqlSource(ms, dynamicSqlSource);
} else {//sql - updateByPrimaryKey
//set=?where=?
List<ParameterMapping> parameterMappings = getColumnParameterMappings(ms);
parameterMappings.addAll(getPrimaryKeyParameterMappings(ms));
BEGIN();
UPDATE(EntityHelper.getTableName(entityClass));
List<EntityHelper.EntityColumn> columnList = EntityHelper.getColumns(entityClass);
for (EntityHelper.EntityColumn column : columnList) {
SET(column.getColumn() + " = ?");
}
WHERE(EntityHelper.getPrimaryKeyWhere(entityClass));
StaticSqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), SQL(), parameterMappings);
setSqlSource(ms, sqlSource);
}
}
/**
* deleteSqlSource
*
* @param ms
*/
public void deleteSqlSource(MappedStatement ms) {
String methodName = getMethodName(ms);
Class<?> entityClass = getSelectReturnType(ms);
//delete
if (methodName.equals(METHODS[5])) {
DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), getDeleteSqlNode(ms));
setSqlSource(ms, dynamicSqlSource);
} else {
List<ParameterMapping> parameterMappings = getPrimaryKeyParameterMappings(ms);
BEGIN();
DELETE_FROM(EntityHelper.getTableName(entityClass));
WHERE(EntityHelper.getPrimaryKeyWhere(entityClass));
StaticSqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), SQL(), parameterMappings);
setSqlSource(ms, sqlSource);
}
}
/**
*
*
* @param ms
* @return
*/
private List<ParameterMapping> getPrimaryKeyParameterMappings(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<EntityHelper.EntityColumn> entityColumns = EntityHelper.getPKColumns(entityClass);
List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
for (EntityHelper.EntityColumn column : entityColumns) {
ParameterMapping.Builder builder = new ParameterMapping.Builder(ms.getConfiguration(), column.getProperty(), column.getJavaType());
builder.mode(ParameterMode.IN);
parameterMappings.add(builder.build());
}
return parameterMappings;
}
/**
*
*
* @param ms
* @return
*/
private List<ParameterMapping> getColumnParameterMappings(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<EntityHelper.EntityColumn> entityColumns = EntityHelper.getColumns(entityClass);
List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
for (EntityHelper.EntityColumn column : entityColumns) {
ParameterMapping.Builder builder = new ParameterMapping.Builder(ms.getConfiguration(), column.getProperty(), column.getJavaType());
builder.mode(ParameterMode.IN);
parameterMappings.add(builder.build());
}
return parameterMappings;
}
/**
* select
*
* @param ms
* @return
*/
private MixedSqlNode getSelectSqlNode(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<SqlNode> sqlNodes = new ArrayList<SqlNode>();
//select column ... from table
sqlNodes.add(new StaticTextSqlNode("SELECT "
+ EntityHelper.getSelectColumns(entityClass)
+ " FROM "
+ EntityHelper.getTableName(entityClass)));
List<EntityHelper.EntityColumn> columnList = EntityHelper.getColumns(entityClass);
List<SqlNode> ifNodes = new ArrayList<SqlNode>();
boolean first = true;
for (EntityHelper.EntityColumn column : columnList) {
StaticTextSqlNode columnNode = new StaticTextSqlNode((first ? "" : " AND ") + column.getColumn() + " = #{" + column.getProperty() + "} ");
IfSqlNode ifSqlNode = new IfSqlNode(columnNode, column.getProperty() + " != null ");
ifNodes.add(ifSqlNode);
first = false;
}
sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes)));
return new MixedSqlNode(sqlNodes);
}
/**
* select
*
* @param ms
* @return
*/
private MixedSqlNode getSelectCountSqlNode(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<SqlNode> sqlNodes = new ArrayList<SqlNode>();
//select column ... from table
sqlNodes.add(new StaticTextSqlNode("SELECT COUNT(*) FROM "
+ EntityHelper.getTableName(entityClass)));
List<EntityHelper.EntityColumn> columnList = EntityHelper.getColumns(entityClass);
List<SqlNode> ifNodes = new ArrayList<SqlNode>();
boolean first = true;
for (EntityHelper.EntityColumn column : columnList) {
StaticTextSqlNode columnNode = new StaticTextSqlNode((first ? "" : " AND ") + column.getColumn() + " = #{" + column.getProperty() + "} ");
IfSqlNode ifSqlNode = new IfSqlNode(columnNode, column.getProperty() + " != null ");
ifNodes.add(ifSqlNode);
first = false;
}
sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes)));
return new MixedSqlNode(sqlNodes);
}
/**
* insert
*
* @param ms
* @return
*/
private MixedSqlNode getInsertSqlNode(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<SqlNode> sqlNodes = new ArrayList<SqlNode>();
sqlNodes.add(new StaticTextSqlNode("INSERT INTO " + EntityHelper.getTableName(entityClass)));
List<EntityHelper.EntityColumn> columnList = EntityHelper.getColumns(entityClass);
List<SqlNode> ifNodes = new ArrayList<SqlNode>();
Boolean hasIdentityKey = false;
for (EntityHelper.EntityColumn column : columnList) {
if (column.getSequenceName() != null && column.getSequenceName().length() > 0) {
ifNodes.add(new StaticTextSqlNode(column.getColumn() + ","));
} else if (column.isIdentity()) {
if (hasIdentityKey) {
throw new RuntimeException(ms.getId() + "" + entityClass.getCanonicalName() + "MySql,!");
}
//selectKey-MS
newSelectKeyMappedStatement(ms, column);
hasIdentityKey = true;
ifNodes.add(new StaticTextSqlNode(column.getColumn() + ","));
sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_cache", column.getProperty()));
} else if (column.isUuid()) {
sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_bind", getUUID()));
ifNodes.add(new StaticTextSqlNode(column.getColumn() + ","));
} else {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode(column.getColumn() + ","), column.getProperty() + " != null "));
}
}
sqlNodes.add(new TrimSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes), "(", null, ")", ","));
ifNodes = new ArrayList<SqlNode>();
for (EntityHelper.EntityColumn column : columnList) {
//,,property_cache
if (column.isIdentity()) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "_cache },"), column.getProperty() + "_cache != null "));
} else {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "},"), column.getProperty() + " != null "));
}
if (column.getSequenceName() != null && column.getSequenceName().length() > 0) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode(column.getProperty() + ".nextval ,"), column.getProperty() + " == null "));
} else if (column.isIdentity()) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + " },"), column.getProperty() + " == null "));
} else if (column.isUuid()) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "_bind },"), column.getProperty() + " == null "));
}
}
sqlNodes.add(new TrimSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes), "VALUES (", null, ")", ","));
return new MixedSqlNode(sqlNodes);
}
/**
* insert
*
* @param ms
* @return
*/
private MixedSqlNode getInsertAllSqlNode(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<SqlNode> sqlNodes = new ArrayList<SqlNode>();
sqlNodes.add(new StaticTextSqlNode("INSERT INTO " + EntityHelper.getTableName(entityClass)));
List<EntityHelper.EntityColumn> columnList = EntityHelper.getColumns(entityClass);
Boolean hasIdentityKey = false;
//Key
for (EntityHelper.EntityColumn column : columnList) {
if (column.getSequenceName() != null && column.getSequenceName().length() > 0) {
} else if (column.isIdentity()) {
if (hasIdentityKey) {
throw new RuntimeException(ms.getId() + "" + entityClass.getCanonicalName() + "MySql,!");
}
newSelectKeyMappedStatement(ms, column);
hasIdentityKey = true;
sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_cache", column.getProperty()));
} else if (column.isUuid()) {
sqlNodes.add(new VarDeclSqlNode(column.getProperty() + "_bind", getUUID()));
}
}
sqlNodes.add(new StaticTextSqlNode("(" + EntityHelper.getAllColumns(entityClass) + ")"));
List<SqlNode> ifNodes = new ArrayList<SqlNode>();
for (EntityHelper.EntityColumn column : columnList) {
//,,property_cache
if (column.isIdentity()) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "_cache },"), column.getProperty() + "_cache != null "));
} else {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "},"), column.getProperty() + " != null "));
}
if (column.getSequenceName() != null && column.getSequenceName().length() > 0) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode(column.getProperty() + ".nextval ,"), column.getProperty() + " == null "));
} else if (column.isIdentity()) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + " },"), column.getProperty() + "_cache == null "));
} else if (column.isUuid()) {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "_bind },"), column.getProperty() + " == null "));
} else {
ifNodes.add(new IfSqlNode(new StaticTextSqlNode("#{" + column.getProperty() + "},"), column.getProperty() + " == null "));
}
}
sqlNodes.add(new TrimSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes), "VALUES (", null, ")", ","));
return new MixedSqlNode(sqlNodes);
}
/**
* select
*
* @param ms
* @return
*/
private MixedSqlNode getDeleteSqlNode(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<SqlNode> sqlNodes = new ArrayList<SqlNode>();
sqlNodes.add(new StaticTextSqlNode("DELETE FROM " + EntityHelper.getTableName(entityClass)));
List<EntityHelper.EntityColumn> columnList = EntityHelper.getColumns(entityClass);
List<SqlNode> ifNodes = new ArrayList<SqlNode>();
boolean first = true;
for (EntityHelper.EntityColumn column : columnList) {
StaticTextSqlNode columnNode = new StaticTextSqlNode((first ? "" : " AND ") + column.getColumn() + " = #{" + column.getProperty() + "} ");
ifNodes.add(new IfSqlNode(columnNode, column.getProperty() + " != null "));
first = false;
}
sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes)));
return new MixedSqlNode(sqlNodes);
}
/**
* select
*
* @param ms
* @return MixedSqlNode
*/
private MixedSqlNode getUpdateSqlNode(MappedStatement ms) {
Class<?> entityClass = getSelectReturnType(ms);
List<SqlNode> sqlNodes = new ArrayList<SqlNode>();
sqlNodes.add(new StaticTextSqlNode("UPDATE " + EntityHelper.getTableName(entityClass)));
List<EntityHelper.EntityColumn> columnList = EntityHelper.getColumns(entityClass);
List<SqlNode> ifNodes = new ArrayList<SqlNode>();
for (EntityHelper.EntityColumn column : columnList) {
StaticTextSqlNode columnNode = new StaticTextSqlNode(column.getColumn() + " = #{" + column.getProperty() + "}, ");
ifNodes.add(new IfSqlNode(columnNode, column.getProperty() + " != null "));
}
sqlNodes.add(new SetSqlNode(ms.getConfiguration(), new MixedSqlNode(ifNodes)));
columnList = EntityHelper.getPKColumns(entityClass);
List<SqlNode> whereNodes = new ArrayList<SqlNode>();
boolean first = true;
for (EntityHelper.EntityColumn column : columnList) {
whereNodes.add(new StaticTextSqlNode((first ? "" : " AND ") + column.getColumn() + " = #{" + column.getProperty() + "} "));
first = false;
}
sqlNodes.add(new WhereSqlNode(ms.getConfiguration(), new MixedSqlNode(whereNodes)));
return new MixedSqlNode(sqlNodes);
}
/**
*
*
* @param ms
* @param args
*/
public void processParameterObject(MappedStatement ms, Object[] args) {
Class<?> entityClass = getSelectReturnType(ms);
String methodName = getMethodName(ms);
Object parameterObject = args[1];
if (methodName.equals(METHODS[1]) || methodName.equals(METHODS[6])) {
TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
List<ParameterMapping> parameterMappings = getPrimaryKeyParameterMappings(ms);
Map<String, Object> parameterMap = new HashMap<String, Object>();
for (ParameterMapping parameterMapping : parameterMappings) {
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
if (parameterMappings.size() > 1) {
StringBuilder propertyBuilder = new StringBuilder("!:");
for (ParameterMapping mapping : parameterMappings) {
propertyBuilder.append(mapping.getProperty()).append(",");
}
throw new RuntimeException(propertyBuilder.substring(0, propertyBuilder.length() - 1));
}
value = parameterObject;
} else {
MetaObject metaObject = forObject(parameterObject);
value = metaObject.getValue(propertyName);
}
parameterMap.put(propertyName, value);
}
}
args[1] = parameterMap;
} else if (parameterObject == null) {
throw new RuntimeException("!");
} else if (!entityClass.isAssignableFrom(parameterObject.getClass())) {
throw new RuntimeException(":"
+ entityClass.getCanonicalName()
+ ",:"
+ parameterObject.getClass().getCanonicalName());
}
}
/**
* SelectKey - mysqlOracle
*
* @param ms
* @param column
*/
private void newSelectKeyMappedStatement(MappedStatement ms, EntityHelper.EntityColumn column) {
String keyId = ms.getId() + SelectKeyGenerator.SELECT_KEY_SUFFIX;
if (ms.getConfiguration().hasKeyGenerator(keyId)) {
return;
}
Class<?> entityClass = getSelectReturnType(ms);
//defaults
Configuration configuration = ms.getConfiguration();
KeyGenerator keyGenerator = new NoKeyGenerator();
Boolean executeBefore = getBEFORE();
String IDENTITY = (column.getGenerator() == null || column.getGenerator().equals("")) ? getIDENTITY() : column.getGenerator();
SqlSource sqlSource = new RawSqlSource(configuration, IDENTITY, entityClass);
MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, keyId, sqlSource, SqlCommandType.SELECT);
statementBuilder.resource(ms.getResource());
statementBuilder.fetchSize(null);
statementBuilder.statementType(StatementType.STATEMENT);
statementBuilder.keyGenerator(keyGenerator);
statementBuilder.keyProperty(column.getProperty());
statementBuilder.keyColumn(null);
statementBuilder.databaseId(null);
statementBuilder.lang(configuration.getDefaultScriptingLanuageInstance());
statementBuilder.resultOrdered(false);
statementBuilder.resulSets(null);
statementBuilder.timeout(configuration.getDefaultStatementTimeout());
List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
ParameterMap.Builder inlineParameterMapBuilder = new ParameterMap.Builder(
configuration,
statementBuilder.id() + "-Inline",
entityClass,
parameterMappings);
statementBuilder.parameterMap(inlineParameterMapBuilder.build());
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder(
configuration,
statementBuilder.id() + "-Inline",
int.class,
new ArrayList<ResultMapping>(),
null);
resultMaps.add(inlineResultMapBuilder.build());
statementBuilder.resultMaps(resultMaps);
statementBuilder.resultSetType(null);
statementBuilder.flushCacheRequired(false);
statementBuilder.useCache(false);
statementBuilder.cache(null);
MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);
MappedStatement keyStatement = configuration.getMappedStatement(keyId, false);
configuration.addKeyGenerator(keyId, new SelectKeyGenerator(keyStatement, executeBefore));
//keyGenerator
try {
MetaObject msObject = forObject(ms);
msObject.setValue("keyGenerator", configuration.getKeyGenerator(keyId));
} catch (Exception e) {
//ignore
}
}
} |
package com.github.ansell.csvsum;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.github.ansell.jdefaultdict.JDefaultDict;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
/**
* Summarises CSV files to easily debug and identify likely parse issues before
* pushing them through a more heavy tool or process.
*
* @author Peter Ansell p_ansell@yahoo.com
*/
public final class CSVSummariser {
/**
* The default number of samples to include for each field in the summarised
* CSV.
*/
private static final int DEFAULT_SAMPLE_COUNT = 20;
/**
* Private constructor for static only class
*/
private CSVSummariser() {
}
public static void main(String... args) throws Exception {
final OptionParser parser = new OptionParser();
final OptionSpec<Void> help = parser.accepts("help").forHelp();
final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required()
.describedAs("The input CSV file to be summarised.");
final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class)
.describedAs("The output file, or the console if not specified.");
final OptionSpec<Integer> samplesToShow = parser.accepts("samples").withRequiredArg().ofType(Integer.class)
.defaultsTo(DEFAULT_SAMPLE_COUNT).describedAs(
"The maximum number of sample values for each field to include in the output, or -1 to dump all sample values for each field.");
OptionSet options = null;
try {
options = parser.parse(args);
} catch (final OptionException e) {
System.out.println(e.getMessage());
parser.printHelpOn(System.out);
throw e;
}
if (options.has(help)) {
parser.printHelpOn(System.out);
return;
}
final Path inputPath = input.value(options).toPath();
if (!Files.exists(inputPath)) {
throw new FileNotFoundException("Could not find input CSV file: " + inputPath.toString());
}
final Writer writer;
if (options.has(output)) {
writer = Files.newBufferedWriter(output.value(options).toPath());
} else {
writer = new BufferedWriter(new OutputStreamWriter(System.out));
}
runSummarise(Files.newBufferedReader(inputPath), writer, samplesToShow.value(options));
}
/**
* Summarise the CSV file from the input {@link Reader} and emit the summary
* CSV file to the output {@link Writer}, including the default maximum
* number of sample values in the summary for each field.
*
* @param input
* The input CSV file, as a {@link Reader}.
* @param output
* The output CSV file as a {@link Writer}.
* @throws IOException
* If there is an error reading or writing.
*/
public static void runSummarise(Reader input, Writer output) throws IOException {
runSummarise(input, output, DEFAULT_SAMPLE_COUNT);
}
/**
* Summarise the CSV file from the input {@link Reader} and emit the summary
* CSV file to the output {@link Writer}, including the given maximum number
* of sample values in the summary for each field.
*
* @param input
* The input CSV file, as a {@link Reader}.
* @param output
* The output CSV file as a {@link Writer}.
* @param maxSampleCount
* THe maximum number of sample values in the summary for each
* field. Set to -1 to include all unique values for each field.
* @throws IOException
* If there is an error reading or writing.
*/
public static void runSummarise(Reader input, Writer output, int maxSampleCount) throws IOException {
final JDefaultDict<String, AtomicInteger> emptyCounts = new JDefaultDict<>(k -> new AtomicInteger());
final JDefaultDict<String, AtomicInteger> nonEmptyCounts = new JDefaultDict<>(k -> new AtomicInteger());
final JDefaultDict<String, AtomicBoolean> possibleIntegerFields = new JDefaultDict<>(
k -> new AtomicBoolean(true));
final JDefaultDict<String, AtomicBoolean> possibleDoubleFields = new JDefaultDict<>(
k -> new AtomicBoolean(true));
final JDefaultDict<String, JDefaultDict<String, AtomicInteger>> valueCounts = new JDefaultDict<String, JDefaultDict<String, AtomicInteger>>(
k -> new JDefaultDict<>(l -> new AtomicInteger()));
final List<String> headers = new ArrayList<String>();
final AtomicInteger rowCount = new AtomicInteger();
CSVUtil.streamCSV(input, h -> headers.addAll(h), (h, l) -> {
rowCount.incrementAndGet();
for (int i = 0; i < h.size(); i++) {
if (l.get(i).trim().isEmpty()) {
emptyCounts.get(h.get(i)).incrementAndGet();
} else {
nonEmptyCounts.get(h.get(i)).incrementAndGet();
valueCounts.get(h.get(i)).get(l.get(i)).incrementAndGet();
try {
Integer.parseInt(l.get(i));
} catch (NumberFormatException nfe) {
possibleIntegerFields.get(h.get(i)).set(false);
}
try {
Double.parseDouble(l.get(i));
} catch (NumberFormatException nfe) {
possibleDoubleFields.get(h.get(i)).set(false);
}
}
}
return l;
} , l -> {
// We are a streaming summariser, and do not store the raw original
// lines. Only unique, non-empty, values are stored in the
// valueCounts map for uniqueness summaries
});
// This schema defines the fields and order for the columns in the
// summary CSV file
final CsvSchema schema = CsvSchema.builder().addColumn("fieldName")
.addColumn("emptyCount", CsvSchema.ColumnType.NUMBER)
.addColumn("nonEmptyCount", CsvSchema.ColumnType.NUMBER)
.addColumn("uniqueValueCount", CsvSchema.ColumnType.NUMBER)
.addColumn("possiblePrimaryKey", CsvSchema.ColumnType.BOOLEAN)
.addColumn("possiblyInteger", CsvSchema.ColumnType.BOOLEAN)
.addColumn("possiblyFloatingPoint", CsvSchema.ColumnType.BOOLEAN).addColumn("sampleValues")
.setUseHeader(true).build();
// Shared StringBuilder across fields for efficiency
// After each field the StringBuilder is truncated
final StringBuilder sampleValue = new StringBuilder();
final Consumer<? super String> sampleHandler = s -> {
if (sampleValue.length() > 0) {
sampleValue.append(", ");
}
sampleValue.append(s);
};
try (final SequenceWriter csvWriter = CSVUtil.newCSVWriter(output, schema);) {
headers.forEach(h -> {
final int emptyCount = emptyCounts.get(h).get();
final int nonEmptyCount = nonEmptyCounts.get(h).get();
final int valueCount = valueCounts.get(h).keySet().size();
final boolean possiblePrimaryKey = valueCount == nonEmptyCount && valueCount == rowCount.get();
boolean possiblyInteger = false;
boolean possiblyDouble = false;
// Only expose our numeric type guess if non-empty values found
if (nonEmptyCount > 0) {
possiblyInteger = possibleIntegerFields.get(h).get();
possiblyDouble = possibleDoubleFields.get(h).get();
}
final Stream<String> stream = valueCounts.get(h).keySet().stream();
if (maxSampleCount >= 0) {
stream.limit(maxSampleCount).sorted().forEach(sampleHandler);
if (valueCount > maxSampleCount) {
sampleValue.append(", ...");
}
} else {
stream.sorted().forEach(sampleHandler);
}
try {
csvWriter.write(Arrays.asList(h, emptyCount, nonEmptyCount, valueCount, possiblePrimaryKey,
possiblyInteger, possiblyDouble, sampleValue));
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
sampleValue.setLength(0);
}
});
}
}
} |
package musician101.minetanks.listeners;
import java.io.File;
import java.util.Arrays;
import java.util.UUID;
import musician101.minetanks.MineTanks;
import musician101.minetanks.battlefield.BattleField;
import musician101.minetanks.battlefield.PlayerTank;
import musician101.minetanks.menu.Menus;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
public class FieldListener implements Listener
{
MineTanks plugin;
public FieldListener(MineTanks plugin)
{
this.plugin = plugin;
}
private boolean isInField(UUID playerId)
{
for (BattleField field : plugin.fieldStorage.getFields())
if (field.getPlayer(playerId) != null)
return true;
return false;
}
private boolean isSword(Material material)
{
//It's technically a sword without a blade.
//Stick is the default item if a player hasn't chosen a tank.
if (material == Material.STICK)
return true;
if (material == Material.WOOD_SWORD)
return true;
if (material == Material.STONE_SWORD)
return true;
if (material == Material.IRON_SWORD)
return true;
if (material == Material.GOLD_SWORD)
return true;
if (material == Material.DIAMOND_SWORD)
return true;
return false;
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event)
{
event.setCancelled(isInField(event.getPlayer().getUniqueId()));
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event)
{
event.setCancelled(isInField(event.getPlayer().getUniqueId()));
}
@EventHandler
public void onBlockInteract(PlayerInteractEvent event)
{
if (!isInField(event.getPlayer().getUniqueId()))
return;
if (event.getAction() != Action.RIGHT_CLICK_AIR || event.getAction() != Action.RIGHT_CLICK_BLOCK)
return;
if (!isSword(event.getItem().getType()) || event.getItem().getType() != Material.WATCH)
return;
if (isSword(event.getItem().getType()))
{
Menus.countrySelection.open(event.getPlayer());
return;
}
if (event.getItem().getType() == Material.WATCH)
{
for (BattleField field : plugin.fieldStorage.getFields())
{
PlayerTank pt = field.getPlayer(event.getPlayer().getUniqueId());
if (pt != null)
{
pt.setReady(true);
field.startMatch();
}
}
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent event)
{
event.setCancelled(isInField(event.getPlayer().getUniqueId()));
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
File file = new File(plugin.getDataFolder() + File.separator + "InventoryStorage", player.getUniqueId().toString() + ".yml");
if (!file.exists())
return;
player.sendMessage(ChatColor.GREEN + plugin.prefix + " You logged off with items still stored away. They will now be returned to you.");
YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
for (int slot = 0; slot < player.getInventory().getSize(); slot++)
player.getInventory().setItem(slot, yml.getItemStack("inventory." + slot));
ItemStack[] armor = new ItemStack[4];
for (int slot = 0; slot < player.getInventory().getArmorContents().length; slot++)
armor[slot] = yml.getItemStack("armor." + slot);
player.getInventory().setArmorContents(armor);
file.delete();
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event)
{
Player player = event.getEntity();
for (BattleField field : plugin.fieldStorage.getFields())
{
PlayerTank pt = field.getPlayer(player.getUniqueId());
if (pt != null)
{
field.playerKilled(pt);
field.endMatch();
return;
}
}
}
@EventHandler
public void onPlayerDisconnect(PlayerQuitEvent event)
{
for (BattleField field : plugin.fieldStorage.getFields())
{
PlayerTank pt = field.getPlayer(event.getPlayer().getUniqueId());
if (pt != null)
{
field.removePlayer(event.getPlayer());
return;
}
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event)
{
if (!isInField(event.getPlayer().getUniqueId()))
return;
Player player = event.getPlayer();
for (BattleField field : plugin.fieldStorage.getFields())
{
if (field.getPlayer(player.getUniqueId()) != null)
{
Location loc = player.getLocation();
double[] x = new double[2];
x[0] = field.getPoint1().getX();
x[1] = field.getPoint2().getX();
Arrays.sort(x);
double[] z = new double[2];
z[0] = field.getPoint1().getZ();
z[1] = field.getPoint2().getZ();
Arrays.sort(z);
if (loc.getX() < x[0] || loc.getX() > x[1] || loc.getZ() < z[0] || loc.getZ() > z[1])
{
player.sendMessage(ChatColor.RED + plugin.prefix + " Out of bounds!");
event.setCancelled(true);
return;
}
}
}
}
} |
package com.github.mavogel.ilias.utils;
import com.github.mavogel.ilias.model.RegistrationPeriod;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class IOUtils {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
/**
* Reads and parses a multiple choices from the user.<br>
* Handles wrong inputs and ensures the choices are meaningful (lo <= up) and in
* the range of the possible choices.
*
* @param choices the possible choices
* @return the choice of the user.
*/
public static List<Integer> readAndParseChoicesFromUser(final List<?> choices) {
boolean isCorrectInputDigits = false, isCorrectInputRanges = false;
String line = null;
final Pattern range = Pattern.compile("(\\d+)-(\\d+)");
final Pattern digit = Pattern.compile("\\d+");
List<Integer> digitsInput = null;
List<String[]> rangesInput = null;
try (Scanner scanner = new Scanner(System.in)) {
while (!(isCorrectInputDigits && isCorrectInputRanges)) {
try {
line = scanner.nextLine();
List<String> trimmedSplit = Arrays.stream(line.split(","))
.map(StringUtils::deleteWhitespace)
.collect(Collectors.toList());
// digits
digitsInput = trimmedSplit.stream()
.filter(s -> digit.matcher(s).matches())
.map(Integer::valueOf)
.collect(Collectors.toList());
isCorrectInputDigits = digitsInput.stream().allMatch(idx -> isInRange(choices, idx));
// ranges
rangesInput = trimmedSplit.stream()
.filter(s -> range.matcher(s).matches())
.map(r -> r.split("-"))
.collect(Collectors.toList());
isCorrectInputRanges = rangesInput.stream().allMatch(r -> isInMeaningfulRange(choices, Integer.valueOf(r[0]), Integer.valueOf(r[1])));
} catch (NumberFormatException nfe) {
if (!isCorrectInputDigits) {
System.err.println("'" + line + " contains incorrect indexes! Try again");
}
if (!isCorrectInputRanges) {
System.err.println("'" + line + " contains incorrect ranges! Try again");
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
return Stream.concat(digitsInput.stream(), expandRanges(rangesInput).orElse(Stream.empty()))
.sorted()
.distinct()
.collect(Collectors.toList());
}
/**
* Reads and parses a single choice from the user.<br>
* Handles wrong inputs and ensures the choice is in
* the range of the possible choices.
*
* @param choices the possible choices
* @return the choice of the user.
*/
public static int readAndParseSingleChoiceFromUser(final List<?> choices) {
boolean isCorrectInput = false;
String line = null;
int userChoice = -1;
try (Scanner scanner = new Scanner(System.in)) {
while (!isCorrectInput) {
try {
line = scanner.nextLine();
userChoice = Integer.valueOf(line);
isCorrectInput = isInRange(choices, userChoice);
} catch (NumberFormatException nfe) {
System.err.println("'" + line + " is not a number! Try again");
} catch (IllegalArgumentException iae) {
System.err.println(iae.getMessage());
}
}
}
return userChoice;
}
private static boolean isInRange(final List<?> list, final int index) {
if (index >= 0 && index < list.size()) {
return true;
} else {
throw new IllegalArgumentException("Choice '" + index + "' is not in range! Try again");
}
}
/**
* Checks if the given range of the array is in meaningful sense. <br>
* <ul>
* <li>lower is less or equals than upper</li>
* <li>both bounds are in the range of the array</li>
* </ul>
*
* @param choices the list of choices
* @param lower the lower bound
* @param upper the upper bound
* @return <code>true</code> if the bounds are meanigful, <code>false</code> otherwise.
*/
private static boolean isInMeaningfulRange(final List<?> choices, final int lower, final int upper) {
return lower <= upper && isInRange(choices, lower) && isInRange(choices, upper);
}
/**
* Expands the ranges.<br>
* Example:
* <ul>
* <li>1-4 -> 1,2,3,4</li>
* <li>1-4,6-8 -> 1,2,3,4,6,7,8</li>
* </ul>
*
* @param ranges the ranges to expand
* @return the expanded ranges.
*/
private static Optional<Stream<Integer>> expandRanges(List<String[]> ranges) { // TODO maybe as Integer[]
return ranges.stream()
.map(eachRange -> IntStream.rangeClosed(Integer.valueOf(eachRange[0]), Integer.valueOf(eachRange[1])))
.map(eachExpandedRange -> eachExpandedRange.mapToObj(Integer::valueOf))
.reduce(Stream::concat);
}
/**
* Reads and parses the registration period.<br>
* Validates the format and that the start is after the end.
*
* @return the {@link RegistrationPeriod}
*/
public static RegistrationPeriod readAndParseRegistrationDates() {
System.out.println("Date need to be of the format '" + DATE_FORMAT + "'"); // TODO
LocalDateTime registrationStart = null, registrationEnd = null;
boolean validStart = false, validEnd = false;
try (Scanner scanner = new Scanner(System.in)) {
while (!validStart) {
System.out.print("Registration start: ");
String line = scanner.nextLine();
try {
registrationStart = LocalDateTime.parse(line, DATE_FORMAT);
validStart = true;
} catch (DateTimeParseException dtpe) {
System.err.println("'" + line + "' is not a valid date");
}
}
while (!validEnd) {
System.out.print("Registration end: ");
String line = scanner.nextLine();
try {
registrationEnd = LocalDateTime.parse(line, DATE_FORMAT);
validEnd = registrationStart.isBefore(registrationEnd);
if (!validEnd) {
System.err.println("End of registration has to be after the start'" + registrationStart + "'");
}
} catch (DateTimeParseException dtpe) {
System.err.println("'" + line + "# is not a valid date");
}
}
}
return new RegistrationPeriod(registrationStart, registrationEnd);
}
} |
package net.ssehub.kernel_haven.util;
import static net.ssehub.kernel_haven.util.null_checks.NullHelpers.notNull;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
/**
* <p>
* A utility class for performance measurements. This is especially useful for measuring code that is called a lot,
* since all measurements are aggregated to min/avg/med/max at the end.
* </p>
* <p>
* Measurements are done for "contexts", which are simply string identifiers for the code to measure. All measurements
* are aggregated per context at the end (when {@link #printResult()} is called).
* </p>
*
* @author Adam
*/
public final class PerformanceProbe implements Closeable {
private static @NonNull Map<String, Deque<@NonNull PerformanceProbe>> probes = new ConcurrentHashMap<>(500);
private @NonNull String context;
private @NonNull Map<String, Double> extraData;
private long tStart;
private long tEnd;
/**
* Creates a new performance probe for a single measurement.
*
* @param context The context that is measured.
*/
public PerformanceProbe(@NonNull String context) {
this.context = context;
this.extraData = new HashMap<>();
this.tStart = System.nanoTime();
}
/**
* Adds an additional bit of data to this probe. This additional data will be aggregated based on the context of
* this probe and the given type. Each performance probe may only contain one data point per type.
*
* @param type The type of data that is provided.
* @param value The additional data.
*/
public void addExtraData(@NonNull String type, double value) {
this.extraData.put(type, value);
}
/**
* Signals the end of this measurement.
*/
@Override
public void close() {
this.tEnd = System.nanoTime();
if (isEnabled(context)) {
Deque<@NonNull PerformanceProbe> newList = new ConcurrentLinkedDeque<>();
Deque<@NonNull PerformanceProbe> list = probes.putIfAbsent(context, newList);
if (list == null) {
list = newList;
}
list.add(this);
}
}
/**
* Returns the elapsed time of this probe, in nanoseconds.
*
* @return The elapsed time.
*/
private long getElapsed() {
return tEnd - tStart;
}
/**
* Determines if a measurement for the given context should be done.
*
* @param context The context to measure.
*
* @return Whether to measure the given context.
*/
private static boolean isEnabled(@NonNull String context) {
return true; // TODO: implement mechanism to disable contexts
}
/**
* Aggregates the given list of doubles and adds the result strings to the given string list.
*
* @param list The list of doubles to aggregate.
* @param lines The list to add the result lines to.
*/
private static void aggregateList(@NonNull List<Double> list, @NonNull List<@NonNull String> lines) {
double[] values = new double[list.size()];
double sum = 0;
int i = 0;
for (Double d : list) {
values[i++] = d;
sum += d;
}
Arrays.sort(values);
double min = values[0];
double max = values[values.length - 1];
double avg = sum / values.length;
double med;
if (values.length % 2 == 0) {
med = (values[values.length / 2 - 1] + values[values.length / 2]) / 2.0;
} else {
med = values[values.length / 2];
}
lines.add(" Num Measures: " + values.length);
lines.add(" Min: " + min);
lines.add(" Med: " + med);
lines.add(" Avg: " + avg);
lines.add(" Max: " + max);
lines.add(" Sum: " + sum);
}
/**
* Aggregates the measurements per context and prints it to the {@link Logger}.
*/
public static void printResult() {
if (probes.isEmpty()) {
return;
}
List<@NonNull String> lines = new ArrayList<>(probes.size() * 20 + 1);
lines.add("Performance Measurements:");
probes.entrySet().stream()
.sorted((e1, e2) -> e1.getKey().compareToIgnoreCase(e2.getKey()))
.forEach((entry) -> {
String context = notNull(entry.getKey());
long[] timeValues = new long[entry.getValue().size()];
Map<String, ArrayList<Double>> extraData = new HashMap<>();
long tSum = 0;
int i = 0;
for (PerformanceProbe p : notNull(entry.getValue())) {
timeValues[i++] = p.getElapsed();
tSum += p.getElapsed();
for (Map.Entry<String, Double> ed : p.extraData.entrySet()) {
extraData.putIfAbsent(ed.getKey(), new ArrayList<>());
extraData.get(ed.getKey()).add(ed.getValue());
}
}
Arrays.sort(timeValues);
long tMin = timeValues[0];
long tMax = timeValues[timeValues.length - 1];
double tAvg = (double) tSum / timeValues.length;
double tMed;
if (timeValues.length % 2 == 0) {
tMed = (timeValues[timeValues.length / 2 - 1] + timeValues[timeValues.length / 2]) / 2.0;
} else {
tMed = timeValues[timeValues.length / 2];
}
lines.add(" " + context);
lines.add(" Time:");
lines.add(" Num Measures: " + timeValues.length);
lines.add(" Min: " + Util.formatDurationMs(tMin / 1000000));
lines.add(" Med: " + Util.formatDurationMs((long) tMed / 1000000));
lines.add(" Avg: " + Util.formatDurationMs((long) tAvg / 1000000));
lines.add(" Max: " + Util.formatDurationMs(tMax / 1000000));
lines.add(" Sum: " + Util.formatDurationMs(tSum / 1000000));
for (Map.Entry<String, ArrayList<Double>> ed : extraData.entrySet()) {
lines.add(" " + ed.getKey() + ":");
aggregateList(notNull(ed.getValue()), lines);
}
});
Logger.get().logInfo(lines.toArray(new String[0]));
}
} |
package com.github.peterpaul.cli;
import com.github.peterpaul.cli.exceptions.ValueParseException;
import com.github.peterpaul.cli.instantiator.InstantiatorSupplier;
import com.github.peterpaul.cli.parser.ValueParser;
import com.github.peterpaul.fn.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static com.github.peterpaul.fn.Function.mapper;
import static com.github.peterpaul.fn.Stream.stream;
public class ProgramRunner {
public static final Function<Class, String> GET_COMMAND_NAME = new Function<Class, String>() {
@Override
public String apply(Class aClass) {
return getCommandName(aClass);
}
};
public static final Function<Class, Pair<String, Class>> GET_NAME_TO_CLASS_MAP = new Function<Class, Pair<String, Class>>() {
@Override
public Pair<String, Class> apply(Class aClass) {
return Pair.pair(getCommandName(aClass), aClass);
}
};
public static String getCommandName(Class aClass) {
return AnnotationHelper.getCommandAnnotation(aClass).name();
}
public static void run(Object command, String[] arguments) {
run(command, getArgumentList(arguments), getOptionMap(arguments));
}
public static Boolean run(Object command, List<String> argumentList, Map<String, String> optionMap) {
try {
Cli.Command commandAnnotation = AnnotationHelper.getCommandAnnotation(command);
if (commandAnnotation.subCommands().length == 0) {
runCommand(command, argumentList, optionMap);
} else {
runCompositeCommand(command, argumentList, optionMap);
}
return true;
} catch (ValueParseException e) {
System.err.println(HelpGenerator.generateHelp(command, e.getMessage()));
return false;
}
}
private static void runCommand(Object command, List<String> argumentList, Map<String, String> optionMap) {
handleOptions(command, optionMap);
handleArguments(command, argumentList);
CommandRunner.runCommand(command);
}
private static void runCompositeCommand(final Object command, final List<String> argumentList, final Map<String, String> optionMap) {
handleOptions(command, optionMap);
final Cli.Command commandAnnotation = AnnotationHelper.getCommandAnnotation(command);
final Function<String, Option<Class>> subCommandMapper = getSubCommandMapper(commandAnnotation);
final String subCommandArgument = argumentList.remove(0);
subCommandMapper.apply(subCommandArgument)
.map(InstantiatorSupplier.instantiate())
.map(new Function<Object, Boolean>() {
@Override
public Boolean apply(Object o) {
return run(o, argumentList, optionMap);
}
})
.or(new Supplier<Boolean>() {
@Override
public Boolean get() {
if (subCommandArgument.equals("help")) {
Object helpCommand = stream(argumentList)
.first()
.flatMap(new Function<String, Option<Object>>() {
@Override
public Option<Object> apply(String arg) {
return subCommandMapper.apply(arg).map(InstantiatorSupplier.instantiate());
}
})
.or(Supplier.of(command));
System.out.println(HelpGenerator.generateHelp(helpCommand));
} else {
String subCommandsString = stream(commandAnnotation.subCommands())
.map(GET_COMMAND_NAME)
.reduce(new Reduction<String>() {
@Override
public String apply(String s, String t) {
return s + ", " + t;
}
})
.or("");
throw new ValueParseException("Not a subcommand: '" + subCommandArgument + "', allowed are [" + subCommandsString + ']');
}
return true;
}
});
}
private static Function<String, Option<Class>> getSubCommandMapper(Cli.Command commandAnnotation) {
Map<String, Class> subCommandMap = stream(commandAnnotation.subCommands())
.toMap(GET_NAME_TO_CLASS_MAP);
return mapper(subCommandMap);
}
private static void setFieldValue(Object command, Field field, Object parsedValue) {
try {
field.setAccessible(true);
field.set(command, parsedValue);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static Option<String> getOptionValue(Map<String, String> optionMap, Field field) {
Cli.Option optionAnnotation = AnnotationHelper.getOptionAnnotation(field);
String name = FieldsProvider.getName(field, optionAnnotation.name());
Option<String> valueFromCommandLine = stream(
"--" + name,
"-" + optionAnnotation.shortName())
.map(mapper(optionMap))
.filterMap(Function.<Option<String>>identity())
.first();
if (valueFromCommandLine.isPresent()) {
return valueFromCommandLine;
} else {
return AnnotationHelper.fromEmpty(optionAnnotation.defaultValue());
}
}
private static List<String> getArgumentList(String[] arguments) {
return stream(arguments)
.filter(new Predicate<String>() {
@Override
public Boolean apply(String s) {
return !s.startsWith("-");
}
})
.to(new ArrayList<String>());
}
private static Map<String, String> getOptionMap(String[] arguments) {
return stream(arguments)
.filter(new Predicate<String>() {
@Override
public Boolean apply(String s) {
return s.startsWith("-");
}
})
.toMap(ActualOptionParser.optionKey(), ActualOptionParser.optionValue());
}
private static void handleArguments(Object command, List<String> argumentList) {
Class<?> commandClass = command.getClass();
List<Field> declaredArgumentList = FieldsProvider.getArgumentList(commandClass);
for (int i = 0; i < declaredArgumentList.size(); i++) {
final Field field = declaredArgumentList.get(i);
final Cli.Argument argumentAnnotation = AnnotationHelper.getArgumentAnnotation(field);
if (isLastArgument(declaredArgumentList, i)
&& ArgumentParserMatcher.argumentParserDoesNotMatchFieldType(field, argumentAnnotation)) {
List<Object> value = stream(argumentList)
.map(new Function<String, Object>() {
@Override
public Object apply(String a) {
return parseValue(field, a, argumentAnnotation.parser(), argumentAnnotation.values());
}
})
.to(new ArrayList<>());
argumentList.clear();
setFieldValue(command, field, value);
} else {
String value = argumentList.remove(0);
Object parsedValue = parseValue(field, value, argumentAnnotation.parser(), argumentAnnotation.values());
setFieldValue(command, field, parsedValue);
}
}
if (!argumentList.isEmpty()) {
throw new ValueParseException("Received unhandled arguments: " + argumentList);
}
}
private static boolean isLastArgument(List<Field> declaredArgumentList, int i) {
return i == declaredArgumentList.size() - 1;
}
private static void handleOptions(final Object command, final Map<String, String> optionMap) {
Class<?> commandClass = command.getClass();
FieldsProvider.getOptionStream(commandClass)
.forEach(new Consumer<Field>() {
@Override
public void consume(Field field) {
Cli.Option optionAnnotation = AnnotationHelper.getOptionAnnotation(field);
Option<String> value = getOptionValue(optionMap, field);
if (value.isPresent()) {
Object parsedValue = parseValue(field, value.get(), optionAnnotation.parser(), optionAnnotation.values());
setFieldValue(command, field, parsedValue);
}
}
});
}
private static Object parseValue(Field field, final String value, Class<? extends ValueParser> valueParserClass, final String[] values) {
final ValueParser valueParser = ValueParserProvider.getValueParser(field, valueParserClass);
return AnnotationHelper.checkedValue(value, values)
.map(new Function<String, Object>() {
@Override
public Object apply(String s) {
return valueParser.parse(s);
}
})
.orThrow(new Supplier<RuntimeException>() {
@Override
public RuntimeException get() {
return new ValueParseException("value '" + value + "' not allowed, allowed are '" + Arrays.asList(values) + "'");
}
});
}
} |
package nu.validator.checker;
import com.cybozu.labs.langdetect.Detector;
import com.cybozu.labs.langdetect.DetectorFactory;
import com.cybozu.labs.langdetect.LangDetectException;
import com.cybozu.labs.langdetect.Language;
import com.ibm.icu.util.ULocale;
import io.mola.galimatias.GalimatiasParseException;
import io.mola.galimatias.Host;
import io.mola.galimatias.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import nu.validator.checker.Checker;
import nu.validator.checker.LocatorImpl;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.apache.log4j.Logger;
public class LanguageDetectingChecker extends Checker {
private static final Logger log4j =
Logger.getLogger(LanguageDetectingChecker.class);
private static final String languageList =
"nu/validator/localentities/files/language-profiles-list.txt";
private static final String profilesDir =
"nu/validator/localentities/files/language-profiles/";
private static final Map<String, String[]> LANG_TAGS_BY_TLD =
new HashMap<>();
private String systemId;
private String tld;
private Locator htmlStartTagLocator;
private StringBuilder elementContent;
private StringBuilder documentContent;
private String httpContentLangHeader;
private String htmlElementLangAttrValue;
private String declaredLangCode;
private boolean htmlElementHasLang;
private String dirAttrValue;
private boolean hasDir;
private boolean inBody;
private int currentOpenElementsInDifferentLang;
private int currentOpenElementsWithSkipName = 0;
private int nonWhitespaceCharacterCount;
private static final int MAX_CHARS = 30720;
private static final int MIN_CHARS = 1024;
private static final double MIN_PROBABILITY = .90;
private static final String[] RTL_LANGS = { "ar", "azb", "ckb", "dv", "fa",
"he", "pnb", "ps", "sd", "ug", "ur" };
private static final String[] COMMON_LANGS = { "ar", "ca", "cs", "da", "de",
"el", "en", "es", "et", "fa", "fi", "fr", "he", "hi", "hu", "id",
"it", "ja", "ka", "ko", "lt", "lv", "ms", "nl", "no", "pl", "pt",
"ro", "ru", "sk", "sq", "sv", "th", "tr", "uk", "vi", "zh-hans",
"zh-hant" };
private static final String[] SKIP_NAMES = { "a", "figcaption", "form",
"li", "nav", "pre", "script", "select", "style", "td", "textarea" };
static {
LANG_TAGS_BY_TLD.put("ae", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("af", new String[] { "ps" });
LANG_TAGS_BY_TLD.put("am", new String[] { "hy" });
LANG_TAGS_BY_TLD.put("ar", new String[] { "es" });
LANG_TAGS_BY_TLD.put("at", new String[] { "de" });
LANG_TAGS_BY_TLD.put("az", new String[] { "az" });
LANG_TAGS_BY_TLD.put("ba", new String[] { "bs", "hr", "sr" });
LANG_TAGS_BY_TLD.put("bd", new String[] { "bn" });
LANG_TAGS_BY_TLD.put("be", new String[] { "de", "fr", "nl" });
LANG_TAGS_BY_TLD.put("bg", new String[] { "bg" });
LANG_TAGS_BY_TLD.put("bh", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("bo", new String[] { "es" });
LANG_TAGS_BY_TLD.put("br", new String[] { "pt" });
LANG_TAGS_BY_TLD.put("by", new String[] { "be" });
LANG_TAGS_BY_TLD.put("bz", new String[] { "es" });
LANG_TAGS_BY_TLD.put("ch", new String[] { "de", "fr", "it", "rm" });
LANG_TAGS_BY_TLD.put("cl", new String[] { "es" });
LANG_TAGS_BY_TLD.put("co", new String[] { "es" });
LANG_TAGS_BY_TLD.put("cu", new String[] { "es" });
LANG_TAGS_BY_TLD.put("cr", new String[] { "es" });
LANG_TAGS_BY_TLD.put("cz", new String[] { "cs" });
LANG_TAGS_BY_TLD.put("de", new String[] { "de" });
LANG_TAGS_BY_TLD.put("dk", new String[] { "da" });
LANG_TAGS_BY_TLD.put("do", new String[] { "es" });
LANG_TAGS_BY_TLD.put("ec", new String[] { "es" });
LANG_TAGS_BY_TLD.put("ee", new String[] { "et" });
LANG_TAGS_BY_TLD.put("eg", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("es", new String[] { "es" });
LANG_TAGS_BY_TLD.put("fi", new String[] { "fi" });
LANG_TAGS_BY_TLD.put("fr", new String[] { "fr" });
LANG_TAGS_BY_TLD.put("ge", new String[] { "ka" });
LANG_TAGS_BY_TLD.put("gr", new String[] { "el" });
LANG_TAGS_BY_TLD.put("gt", new String[] { "es" });
LANG_TAGS_BY_TLD.put("hn", new String[] { "es" });
LANG_TAGS_BY_TLD.put("hr", new String[] { "hr" });
LANG_TAGS_BY_TLD.put("hu", new String[] { "hu" });
LANG_TAGS_BY_TLD.put("id", new String[] { "id" });
LANG_TAGS_BY_TLD.put("is", new String[] { "is" });
LANG_TAGS_BY_TLD.put("it", new String[] { "it" });
LANG_TAGS_BY_TLD.put("il", new String[] { "iw" });
LANG_TAGS_BY_TLD.put("in", new String[] { "bn", "gu", "hi", "kn", "ml", "mr", "pa", "ta", "te" });
LANG_TAGS_BY_TLD.put("ja", new String[] { "jp" });
LANG_TAGS_BY_TLD.put("jo", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("ke", new String[] { "sw" });
LANG_TAGS_BY_TLD.put("kg", new String[] { "ky" });
LANG_TAGS_BY_TLD.put("kh", new String[] { "km" });
LANG_TAGS_BY_TLD.put("kr", new String[] { "ko" });
LANG_TAGS_BY_TLD.put("kw", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("kz", new String[] { "kk" });
LANG_TAGS_BY_TLD.put("la", new String[] { "lo" });
LANG_TAGS_BY_TLD.put("li", new String[] { "de" });
LANG_TAGS_BY_TLD.put("lb", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("lk", new String[] { "si", "ta" });
LANG_TAGS_BY_TLD.put("lt", new String[] { "lt" });
LANG_TAGS_BY_TLD.put("lu", new String[] { "de" });
LANG_TAGS_BY_TLD.put("lv", new String[] { "lv" });
LANG_TAGS_BY_TLD.put("md", new String[] { "mo" });
LANG_TAGS_BY_TLD.put("mk", new String[] { "mk" });
LANG_TAGS_BY_TLD.put("mn", new String[] { "mn" });
LANG_TAGS_BY_TLD.put("mx", new String[] { "es" });
LANG_TAGS_BY_TLD.put("my", new String[] { "ms" });
LANG_TAGS_BY_TLD.put("ni", new String[] { "es" });
LANG_TAGS_BY_TLD.put("nl", new String[] { "nl" });
LANG_TAGS_BY_TLD.put("no", new String[] { "nn", "no" });
LANG_TAGS_BY_TLD.put("np", new String[] { "ne" });
LANG_TAGS_BY_TLD.put("pa", new String[] { "es" });
LANG_TAGS_BY_TLD.put("pe", new String[] { "es" });
LANG_TAGS_BY_TLD.put("ph", new String[] { "tl" });
LANG_TAGS_BY_TLD.put("pl", new String[] { "pl" });
LANG_TAGS_BY_TLD.put("pk", new String[] { "ur" });
LANG_TAGS_BY_TLD.put("pr", new String[] { "es" });
LANG_TAGS_BY_TLD.put("pt", new String[] { "pt" });
LANG_TAGS_BY_TLD.put("py", new String[] { "es" });
LANG_TAGS_BY_TLD.put("qa", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("ro", new String[] { "ro" });
LANG_TAGS_BY_TLD.put("rs", new String[] { "sr" });
LANG_TAGS_BY_TLD.put("ru", new String[] { "ru" });
LANG_TAGS_BY_TLD.put("sa", new String[] { "ar" });
LANG_TAGS_BY_TLD.put("se", new String[] { "sv" });
LANG_TAGS_BY_TLD.put("si", new String[] { "sl" });
LANG_TAGS_BY_TLD.put("sk", new String[] { "sk" });
LANG_TAGS_BY_TLD.put("sv", new String[] { "es" });
LANG_TAGS_BY_TLD.put("th", new String[] { "th" });
LANG_TAGS_BY_TLD.put("tj", new String[] { "tg" });
LANG_TAGS_BY_TLD.put("tm", new String[] { "tk" });
LANG_TAGS_BY_TLD.put("ua", new String[] { "uk" });
LANG_TAGS_BY_TLD.put("uy", new String[] { "es" });
LANG_TAGS_BY_TLD.put("uz", new String[] { "uz" });
LANG_TAGS_BY_TLD.put("ve", new String[] { "es" });
LANG_TAGS_BY_TLD.put("vn", new String[] { "vi" });
LANG_TAGS_BY_TLD.put("za", new String[] { "af" });
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
LanguageDetectingChecker.class.getClassLoader().getResourceAsStream(
languageList)));
List<String> languageTags = new ArrayList<>();
String languageTagAndName = br.readLine();
while (languageTagAndName != null) {
languageTags.add(languageTagAndName.split("\t")[0]);
languageTagAndName = br.readLine();
}
List<String> profiles = new ArrayList<>();
for (String languageTag : languageTags) {
profiles.add((new BufferedReader(new InputStreamReader(
LanguageDetectingChecker.class.getClassLoader().getResourceAsStream(
profilesDir + languageTag)))).readLine());
}
DetectorFactory.clear();
DetectorFactory.loadProfile(profiles);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (LangDetectException e) {
}
}
private boolean shouldAppendToLangdetectContent() {
return (inBody && currentOpenElementsWithSkipName < 1
&& currentOpenElementsInDifferentLang < 1
&& nonWhitespaceCharacterCount < MAX_CHARS);
}
private void setDocumentLanguage(String languageTag) {
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/document-language",
languageTag);
}
}
private String getDetectedLanguageSerboCroatian() throws SAXException {
if ("hr".equals(declaredLangCode) || "hr".equals(tld)) {
return "hr";
}
if ("sr".equals(declaredLangCode) || ".rs".equals(tld)) {
return "sr-latn";
}
if ("bs".equals(declaredLangCode) || ".ba".equals(tld)) {
return "bs";
}
return "sh";
}
private void checkLangAttributeSerboCroatian() throws SAXException {
String lowerCaseLang = htmlElementLangAttrValue.toLowerCase();
String langWarning = "";
if (!htmlElementHasLang) {
langWarning = "This document appears to be written in either"
+ " Croatian, Serbian, or Bosnian. Consider adding either"
+ " \u201Clang=\"hr\"\u201D, \u201Clang=\"sr\"\u201D, or"
+ " \u201Clang=\"bs\"\u201D to the"
+ " \u201Chtml\u201D start tag.";
} else if (!("hr".equals(declaredLangCode)
|| "sr".equals(declaredLangCode)
|| "bs".equals(declaredLangCode))) {
langWarning = String.format(
"This document appears to be written in either Croatian,"
+ " Serbian, or Bosnian, but the \u201Chtml\u201D"
+ " start tag has %s. Consider using either"
+ " \u201Clang=\"hr\"\u201D,"
+ " \u201Clang=\"sr\"\u201D, or"
+ " \u201Clang=\"bs\"\u201D instead.",
getAttValueExpr("lang", lowerCaseLang));
}
if (!"".equals(langWarning)) {
warn(langWarning, htmlStartTagLocator);
}
}
private void checkLangAttributeNorwegian() throws SAXException {
String lowerCaseLang = htmlElementLangAttrValue.toLowerCase();
String langWarning = "";
if (!htmlElementHasLang) {
langWarning = "This document appears to be written in Norwegian"
+ " Consider adding either"
+ " \u201Clang=\"nn\"\u201D or \u201Clang=\"nb\"\u201D"
+ " (or variant) to the \u201Chtml\u201D start tag.";
} else if (!("no".equals(declaredLangCode)
|| "nn".equals(declaredLangCode)
|| "nb".equals(declaredLangCode))) {
langWarning = String.format(
"This document appears to be written in Norwegian, but the"
+ " \u201Chtml\u201D start tag has %s. Consider"
+ " using either \u201Clang=\"nn\"\u201D or"
+ " \u201Clang=\"nb\"\u201D (or variant) instead.",
getAttValueExpr("lang", lowerCaseLang));
}
if (!"".equals(langWarning)) {
warn(langWarning, htmlStartTagLocator);
}
}
private void checkContentLanguageHeaderNorwegian(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode)
throws SAXException {
if ("".equals(httpContentLangHeader)
|| httpContentLangHeader.contains(",")) {
return;
}
String lowerCaseContentLang = httpContentLangHeader.toLowerCase();
String contentLangCode = new ULocale(
lowerCaseContentLang).getLanguage();
if (!("no".equals(contentLangCode) || "nn".equals(contentLangCode)
|| "nb".equals(contentLangCode))) {
warn("This document appears to be written in"
+ " Norwegian but the value of the HTTP"
+ " \u201CContent-Language\u201D header is" + " \u201C"
+ lowerCaseContentLang + "\u201D. Consider"
+ " changing it to \u201Cnn\u201D or \u201Cnn\u201D"
+ " (or variant) instead.");
}
}
private void checkLangAttribute(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode,
String preferredLanguageCode) throws SAXException {
String langWarning = "";
String lowerCaseLang = htmlElementLangAttrValue.toLowerCase();
if (!htmlElementHasLang) {
langWarning = String.format(
"This document appears to be written in %s."
+ " Consider adding \u201Clang=\"%s\"\u201D"
+ " (or variant) to the \u201Chtml\u201D"
+ " start tag.",
detectedLanguageName, preferredLanguageCode);
} else {
if (request != null) {
if ("".equals(lowerCaseLang)) {
request.setAttribute(
"http://validator.nu/properties/lang-empty", true);
} else {
request.setAttribute(
"http://validator.nu/properties/lang-value",
lowerCaseLang);
}
}
if ("tl".equals(detectedLanguageCode)
&& ("ceb".equals(declaredLangCode)
|| "ilo".equals(declaredLangCode)
|| "pag".equals(declaredLangCode)
|| "war".equals(declaredLangCode))) {
return;
}
if ("id".equals(detectedLanguageCode)
&& "min".equals(declaredLangCode)) {
return;
}
if ("ms".equals(detectedLanguageCode)
&& "min".equals(declaredLangCode)) {
return;
}
if ("hr".equals(detectedLanguageCode)
&& ("sr".equals(declaredLangCode)
|| "bs".equals(declaredLangCode)
|| "sh".equals(declaredLangCode))) {
return;
}
if ("sr".equals(detectedLanguageCode)
&& ("hr".equals(declaredLangCode)
|| "bs".equals(declaredLangCode)
|| "sh".equals(declaredLangCode))) {
return;
}
if ("bs".equals(detectedLanguageCode)
&& ("hr".equals(declaredLangCode)
|| "sr".equals(declaredLangCode)
|| "sh".equals(declaredLangCode))) {
return;
}
if ("de".equals(detectedLanguageCode)
&& ("bar".equals(declaredLangCode)
|| "gsw".equals(declaredLangCode)
|| "lb".equals(declaredLangCode))) {
return;
}
if ("zh".equals(detectedLanguageCode)
&& "yue".equals(lowerCaseLang)) {
return;
}
if ("es".equals(detectedLanguageCode)
&& ("an".equals(declaredLangCode)
|| "ast".equals(declaredLangCode))) {
return;
}
if ("it".equals(detectedLanguageCode)
&& ("co".equals(declaredLangCode)
|| "pms".equals(declaredLangCode)
|| "vec".equals(declaredLangCode)
|| "lmo".equals(declaredLangCode)
|| "scn".equals(declaredLangCode)
|| "nap".equals(declaredLangCode))) {
return;
}
if ("rw".equals(detectedLanguageCode)
&& "rn".equals(declaredLangCode)) {
return;
}
if ("mhr".equals(detectedLanguageCode)
&& ("chm".equals(declaredLangCode)
|| "mrj".equals(declaredLangCode))) {
return;
}
if ("mrj".equals(detectedLanguageCode)
&& ("chm".equals(declaredLangCode)
|| "mhr".equals(declaredLangCode))) {
return;
}
if ("ru".equals(detectedLanguageCode)
&& "bg".equals(declaredLangCode)) {
return;
}
String message = "This document appears to be written in %s"
+ " but the \u201Chtml\u201D start tag has %s. Consider"
+ " using \u201Clang=\"%s\"\u201D (or variant) instead.";
if (zhSubtagMismatch(detectedLanguage, lowerCaseLang)
|| !declaredLangCode.equals(detectedLanguageCode)) {
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/lang-wrong", true);
}
langWarning = String.format(message, detectedLanguageName,
getAttValueExpr("lang", htmlElementLangAttrValue),
preferredLanguageCode);
}
}
if (!"".equals(langWarning)) {
warn(langWarning, htmlStartTagLocator);
}
}
private void checkContentLanguageHeader(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode,
String preferredLanguageCode) throws SAXException {
if ("".equals(httpContentLangHeader)
|| httpContentLangHeader.contains(",")) {
return;
}
String message = "";
String lowerCaseContentLang = httpContentLangHeader.toLowerCase();
String contentLangCode = new ULocale(
lowerCaseContentLang).getLanguage();
if ("tl".equals(detectedLanguageCode) && ("ceb".equals(contentLangCode)
|| "ilo".equals(contentLangCode)
|| "pag".equals(contentLangCode)
|| "war".equals(contentLangCode))) {
return;
}
if ("id".equals(detectedLanguageCode)
&& "min".equals(contentLangCode)) {
return;
}
if ("ms".equals(detectedLanguageCode)
&& "min".equals(contentLangCode)) {
return;
}
if ("hr".equals(detectedLanguageCode)
&& ("sr".equals(contentLangCode) || "bs".equals(contentLangCode)
|| "sh".equals(contentLangCode))) {
return;
}
if ("sr".equals(detectedLanguageCode)
&& ("hr".equals(contentLangCode) || "bs".equals(contentLangCode)
|| "sh".equals(contentLangCode))) {
return;
}
if ("bs".equals(detectedLanguageCode)
&& ("hr".equals(contentLangCode) || "sr".equals(contentLangCode)
|| "sh".equals(contentLangCode))) {
return;
}
if ("de".equals(detectedLanguageCode) && ("bar".equals(contentLangCode)
|| "gsw".equals(contentLangCode)
|| "lb".equals(contentLangCode))) {
return;
}
if ("zh".equals(detectedLanguageCode)
&& "yue".equals(lowerCaseContentLang)) {
return;
}
if ("es".equals(detectedLanguageCode) && ("an".equals(contentLangCode)
|| "ast".equals(contentLangCode))) {
return;
}
if ("it".equals(detectedLanguageCode) && ("co".equals(contentLangCode)
|| "pms".equals(contentLangCode)
|| "vec".equals(contentLangCode)
|| "lmo".equals(contentLangCode)
|| "scn".equals(contentLangCode)
|| "nap".equals(contentLangCode))) {
return;
}
if ("rw".equals(detectedLanguageCode) && "rn".equals(contentLangCode)) {
return;
}
if ("mhr".equals(detectedLanguageCode) && ("chm".equals(contentLangCode)
|| "mrj".equals(contentLangCode))) {
return;
}
if ("mrj".equals(detectedLanguageCode) && ("chm".equals(contentLangCode)
|| "mhr".equals(contentLangCode))) {
return;
}
if ("ru".equals(detectedLanguageCode) && "bg".equals(contentLangCode)) {
return;
}
if (zhSubtagMismatch(detectedLanguage, lowerCaseContentLang)
|| !contentLangCode.equals(detectedLanguageCode)) {
message = "This document appears to be written in %s but the value"
+ " of the HTTP \u201CContent-Language\u201D header is"
+ " \u201C%s\u201D. Consider changing it to"
+ " \u201C%s\u201D (or variant).";
warn(String.format(message, detectedLanguageName,
lowerCaseContentLang, preferredLanguageCode,
preferredLanguageCode));
}
if (htmlElementHasLang) {
message = "The value of the HTTP \u201CContent-Language\u201D"
+ " header is \u201C%s\u201D but it will be ignored because"
+ " the \u201Chtml\u201D start tag has %s.";
String lowerCaseLang = htmlElementLangAttrValue.toLowerCase();
if (htmlElementHasLang) {
if (zhSubtagMismatch(lowerCaseContentLang, lowerCaseLang)
|| !contentLangCode.equals(declaredLangCode)) {
warn(String.format(message, httpContentLangHeader,
getAttValueExpr("lang", htmlElementLangAttrValue)),
htmlStartTagLocator);
}
}
}
}
private void checkDirAttribute(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode,
String preferredLanguageCode) throws SAXException {
if (Arrays.binarySearch(RTL_LANGS, detectedLanguageCode) < 0) {
return;
}
String dirWarning = "";
if (!hasDir) {
dirWarning = String.format(
"This document appears to be written in %s."
+ " Consider adding \u201Cdir=\"rtl\"\u201D"
+ " to the \u201Chtml\u201D start tag.",
detectedLanguageName, preferredLanguageCode);
} else if (!"rtl".equals(dirAttrValue)) {
String message = "This document appears to be written in %s"
+ " but the \u201Chtml\u201D start tag has %s."
+ " Consider using \u201Cdir=\"rtl\"\u201D instead.";
dirWarning = String.format(message, detectedLanguageName,
getAttValueExpr("dir", dirAttrValue));
}
if (!"".equals(dirWarning)) {
warn(dirWarning, htmlStartTagLocator);
}
}
private boolean zhSubtagMismatch(String expectedLanguage,
String declaredLanguage) {
return (("zh-hans".equals(expectedLanguage)
&& (declaredLanguage.contains("zh-tw")
|| declaredLanguage.contains("zh-hant")))
|| ("zh-hant".equals(expectedLanguage)
&& (declaredLanguage.contains("zh-cn")
|| declaredLanguage.contains("zh-hans"))));
}
private String getAttValueExpr(String attName, String attValue) {
if ("".equals(attValue)) {
return String.format("an empty \u201c%s\u201d attribute", attName);
} else {
return String.format("\u201C%s=\"%s\"\u201D", attName, attValue);
}
}
public LanguageDetectingChecker() {
super();
}
private HttpServletRequest request;
public void setHttpContentLanguageHeader(String httpContentLangHeader) {
if (httpContentLangHeader != null) {
this.httpContentLangHeader = httpContentLangHeader;
}
}
/**
* @see nu.validator.checker.Checker#endDocument()
*/
@Override
public void endDocument() throws SAXException {
if (!"0".equals(System.getProperty(
"nu.validator.checker.enableLangDetection"))) {
detectLanguageAndCheckAgainstDeclaredLanguage();
}
}
private void warnIfMissingLang() throws SAXException {
if (!htmlElementHasLang) {
String message = "Consider adding a \u201Clang\u201D"
+ " attribute to the \u201Chtml\u201D"
+ " start tag to declare the language"
+ " of this document.";
warn(message, htmlStartTagLocator);
}
}
private void detectLanguageAndCheckAgainstDeclaredLanguage()
throws SAXException {
if (nonWhitespaceCharacterCount < MIN_CHARS) {
warnIfMissingLang();
return;
}
if ("zxx".equals(declaredLangCode) // "No Linguistic Content"
|| "eo".equals(declaredLangCode) // Esperanto
|| "la".equals(declaredLangCode) // Latin
) {
return;
}
if (LANG_TAGS_BY_TLD.containsKey(tld)
&& Arrays.binarySearch(LANG_TAGS_BY_TLD.get(tld),
declaredLangCode) >= 0) {
return;
}
try {
String textContent = documentContent.toString()
.replaceAll("\\s+", " ");
String detectedLanguage = "";
Detector detector = DetectorFactory.create();
detector.append(textContent);
detector.getProbabilities();
ArrayList<String> possibileLanguages = new ArrayList<>();
ArrayList<Language> possibilities = detector.getProbabilities();
for (Language possibility : possibilities) {
possibileLanguages.add(possibility.lang);
ULocale plocale = new ULocale(possibility.lang);
if (Arrays.binarySearch(COMMON_LANGS, possibility.lang) < 0
&& systemId != null) {
log4j.info(
String.format("%s %s %s", plocale.getDisplayName(),
possibility.prob, systemId));
}
if (possibility.prob > MIN_PROBABILITY) {
detectedLanguage = possibility.lang;
setDocumentLanguage(detectedLanguage);
} else if ((possibileLanguages.contains("hr")
&& (possibileLanguages.contains("sr-latn")
|| possibileLanguages.contains("bs")))
|| (possibileLanguages.contains("sr-latn")
&& (possibileLanguages.contains("hr")
|| possibileLanguages.contains("bs")))
|| (possibileLanguages.contains("bs")
&& (possibileLanguages.contains("hr")
|| possibileLanguages.contains(
"sr-latn")))) {
if (htmlElementHasLang || systemId != null) {
detectedLanguage = getDetectedLanguageSerboCroatian();
setDocumentLanguage(detectedLanguage);
}
if ("sh".equals(detectedLanguage)) {
checkLangAttributeSerboCroatian();
return;
}
}
}
if ("".equals(detectedLanguage)) {
warnIfMissingLang();
return;
}
String detectedLanguageName = "";
String preferredLanguageCode = "";
ULocale locale = new ULocale(detectedLanguage);
String detectedLanguageCode = locale.getLanguage();
if ("no".equals(detectedLanguage)) {
checkLangAttributeNorwegian();
checkContentLanguageHeaderNorwegian(detectedLanguage,
detectedLanguageName, detectedLanguageCode);
return;
}
if ("zh-hans".equals(detectedLanguage)) {
detectedLanguageName = "Simplified Chinese";
preferredLanguageCode = "zh-hans";
} else if ("zh-hant".equals(detectedLanguage)) {
detectedLanguageName = "Traditional Chinese";
preferredLanguageCode = "zh-hant";
} else if ("mhr".equals(detectedLanguage)) {
detectedLanguageName = "Meadow Mari";
preferredLanguageCode = "mhr";
} else if ("mrj".equals(detectedLanguage)) {
detectedLanguageName = "Hill Mari";
preferredLanguageCode = "mrj";
} else if ("nah".equals(detectedLanguage)) {
detectedLanguageName = "Nahuatl";
preferredLanguageCode = "nah";
} else if ("pnb".equals(detectedLanguage)) {
detectedLanguageName = "Western Panjabi";
preferredLanguageCode = "pnb";
} else if ("sr-cyrl".equals(detectedLanguage)) {
detectedLanguageName = "Serbian";
preferredLanguageCode = "sr";
} else if ("sr-latn".equals(detectedLanguage)) {
detectedLanguageName = "Serbian";
preferredLanguageCode = "sr";
} else if ("uz-cyrl".equals(detectedLanguage)) {
detectedLanguageName = "Uzbek";
preferredLanguageCode = "uz";
} else if ("uz-latn".equals(detectedLanguage)) {
detectedLanguageName = "Uzbek";
preferredLanguageCode = "uz";
} else if ("zxx".equals(detectedLanguage)) {
detectedLanguageName = "Lorem ipsum text";
preferredLanguageCode = "zxx";
} else {
detectedLanguageName = locale.getDisplayName();
preferredLanguageCode = detectedLanguageCode;
}
checkLangAttribute(detectedLanguage, detectedLanguageName,
detectedLanguageCode, preferredLanguageCode);
checkDirAttribute(detectedLanguage, detectedLanguageName,
detectedLanguageCode, preferredLanguageCode);
checkContentLanguageHeader(detectedLanguage, detectedLanguageName,
detectedLanguageCode, preferredLanguageCode);
} catch (LangDetectException e) {
}
}
/**
* @see nu.validator.checker.Checker#endElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
if (nonWhitespaceCharacterCount < MAX_CHARS) {
documentContent.append(elementContent);
elementContent.setLength(0);
}
if ("body".equals(localName)) {
inBody = false;
currentOpenElementsWithSkipName = 0;
}
if (currentOpenElementsInDifferentLang > 0) {
currentOpenElementsInDifferentLang
if (currentOpenElementsInDifferentLang < 0) {
currentOpenElementsInDifferentLang = 0;
}
} else {
if (Arrays.binarySearch(SKIP_NAMES, localName) >= 0) {
currentOpenElementsWithSkipName
if (currentOpenElementsWithSkipName < 0) {
currentOpenElementsWithSkipName = 0;
}
}
}
}
/**
* @see nu.validator.checker.Checker#startDocument()
*/
@Override
public void startDocument() throws SAXException {
httpContentLangHeader = "";
tld = "";
htmlStartTagLocator = null;
inBody = false;
currentOpenElementsInDifferentLang = 0;
currentOpenElementsWithSkipName = 0;
nonWhitespaceCharacterCount = 0;
elementContent = new StringBuilder();
documentContent = new StringBuilder();
htmlElementHasLang = false;
htmlElementLangAttrValue = "";
declaredLangCode = "";
hasDir = false;
dirAttrValue = "";
documentContent.setLength(0);
currentOpenElementsWithSkipName = 0;
try {
systemId = getDocumentLocator().getSystemId();
if (systemId != null && systemId.startsWith("http")) {
Host hostname = URL.parse(systemId).host();
if (hostname != null) {
String host = hostname.toString();
tld = host.substring(host.lastIndexOf(".") + 1);
}
}
} catch (GalimatiasParseException e) {
throw new RuntimeException(e);
}
}
/**
* @see nu.validator.checker.Checker#startElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
if ("html".equals(localName)) {
htmlStartTagLocator = new LocatorImpl(getDocumentLocator());
for (int i = 0; i < atts.getLength(); i++) {
if ("lang".equals(atts.getLocalName(i))) {
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/lang-found",
true);
}
htmlElementHasLang = true;
htmlElementLangAttrValue = atts.getValue(i);
declaredLangCode = new ULocale(
htmlElementLangAttrValue).getLanguage();
} else if ("dir".equals(atts.getLocalName(i))) {
hasDir = true;
dirAttrValue = atts.getValue(i);
}
}
} else if ("body".equals(localName)) {
inBody = true;
} else if (inBody) {
if (currentOpenElementsInDifferentLang > 0) {
currentOpenElementsInDifferentLang++;
} else {
for (int i = 0; i < atts.getLength(); i++) {
if ("lang".equals(atts.getLocalName(i))) {
if (!"".equals(htmlElementLangAttrValue)
&& !htmlElementLangAttrValue.equals(
atts.getValue(i))) {
currentOpenElementsInDifferentLang++;
}
}
}
}
}
if (Arrays.binarySearch(SKIP_NAMES, localName) >= 0) {
currentOpenElementsWithSkipName++;
}
}
/**
* @see nu.validator.checker.Checker#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (shouldAppendToLangdetectContent()) {
elementContent.append(ch, start, length);
}
for (int i = start; i < start + length; i++) {
char c = ch[i];
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
continue;
default:
if (shouldAppendToLangdetectContent()) {
nonWhitespaceCharacterCount++;
}
}
}
}
} |
package com.github.wovnio.wovnjava;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.IDN;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import nu.validator.htmlparser.dom.*;
class Interceptor {
private Store store;
Interceptor(FilterConfig config) {
store = new Store(config);
Logger.debugMode = store.settings.debugMode;
}
void call(HttpServletRequest request, ServletResponse response, FilterChain chain) {
if (!store.settings.isValid()) {
try {
chain.doFilter(request, response);
} catch (ServletException e) {
Logger.log.error("ServletException in chain.doFilter (invalid settings)", e);
} catch (IOException e) {
Logger.log.error("IOException in chain.doFilter (invalid settings)", e);
}
return;
}
Headers h = new Headers(request, store.settings);
if (store.settings.testMode && !store.settings.testUrl.equals(h.url)) {
if (Logger.isDebug()) {
Logger.log.info("test mode: " + h.url);
}
try {
chain.doFilter(request, response);
} catch (ServletException e) {
Logger.log.error("ServletException in chain.doFilter (test mode)", e);
} catch (IOException e) {
Logger.log.error("IOException in chain.doFilter (test mode)", e);
}
return;
}
if (h.getPathLang().equals(store.settings.defaultLang)) {
String redirectLocation = h.redirectLocation(store.settings.defaultLang);
if (Logger.isDebug()) {
Logger.log.info("Redirect to \"" + redirectLocation + "\"");
}
try {
((HttpServletResponse) response).sendRedirect(redirectLocation);
} catch (IOException e) {
Logger.log.error("IOException in response.sendRedirect", e);
}
return;
}
WovnHttpServletRequest wovnRequest = new WovnHttpServletRequest(
request, h
);
WovnHttpServletResponse wovnResponse = new WovnHttpServletResponse(
(HttpServletResponse)response, h
);
try {
chain.doFilter(wovnRequest, wovnResponse);
} catch (ServletException e) {
Logger.log.error("ServletExecption in chain.doFilter", e);
} catch (IOException e) {
Logger.log.error("ServletException in chain.doFilter", e);
}
String body = null;
// There is a possibility that response.getContentType() is null when the response is an image.
if (response.getContentType() != null && Pattern.compile("html").matcher(response.getContentType()).find()) {
String status = String.valueOf(wovnResponse.status);
if (!Pattern.compile("^1|302").matcher(status).find()) {
body = wovnResponse.toString();
if (!this.store.settings.strictHtmlCheck || isHtml(body)) {
if (Logger.isDebug()) {
if (wovnRequest.getQueryString() == null || wovnRequest.getQueryString().isEmpty()) {
Logger.log.info("Translating HTML: " + wovnRequest.getRequestURL());
} else {
Logger.log.info("Translating HTML: " + wovnRequest.getRequestURL() + "?" + wovnRequest.getQueryString());
}
}
String lang = h.langCode();
HashMap<String,String> url = new HashMap<String,String>();
url.put("protocol", h.protocol);
url.put("host", h.host);
url.put("pathname", h.pathName);
Values values = store.getValues(h.pageUrl);
body = this.switchLang(body, values, url, lang, h);
}
wovnResponse.setContentLength(body.getBytes().length);
}
}
if (body != null) {
// text
wovnResponse.setContentType("text/html; charset=utf-8");
try {
PrintWriter out = response.getWriter();
out.write(body);
out.close();
} catch (IOException e) {
Logger.log.error("IOException while writing text data", e);
}
} else {
// binary
try {
ServletOutputStream out = response.getOutputStream();
out.write(wovnResponse.getData());
out.close();
} catch (IOException e) {
Logger.log.error("IOException while writing binary data", e);
}
}
h.out(request, wovnResponse);
}
static boolean isHtml(String body) {
if (Logger.isDebug()) {
Logger.log.info("Checking HTML strictly.");
if (Logger.debugMode > 1) {
Logger.log.info("original HTML:\n" + body);
}
}
// Remove comments.
body = Pattern.compile("(?m)\\A(\\s*\\s*)+").matcher(body).replaceAll("");
// Remove spaces.
body = Pattern.compile("(?m)\\A\\s+").matcher(body).replaceAll("");
if (Logger.debugMode > 1) {
Logger.log.info("HTML after removing comment tags and spaces:\n" + body);
}
if (Pattern.compile("(?m)\\A<\\?xml\\b", Pattern.CASE_INSENSITIVE).matcher(body).find() // <?xml
|| Pattern.compile("(?m)\\A<!DOCTYPE\\b", Pattern.CASE_INSENSITIVE).matcher(body).find() // <!DOCTYPE
|| Pattern.compile("(?m)\\A<html\\b", Pattern.CASE_INSENSITIVE).matcher(body).find() // <html
) {
if (Logger.isDebug()) {
Logger.log.info("This data is HTML.");
}
return true;
} else {
if (Logger.isDebug()) {
Logger.log.info("This data is not HTML.");
}
return false;
}
}
private String addLangCode(String href, String pattern, String lang, Headers headers) {
if (href != null && href.length() > 0 && Pattern.compile("^(#.*)?$").matcher(href).find()) {
return href;
}
String newHref = href;
if ( href != null
&& href.length() > 0
&& Pattern.compile("^(https?:)?//", Pattern.CASE_INSENSITIVE).matcher(href).find()
) {
URL uri;
try {
uri = new URL(href);
} catch (MalformedURLException e) {
Logger.log.error("MalformedURLException in addLangCode", e);
return newHref;
}
if (uri.getHost().toLowerCase().equals(headers.host.toLowerCase())) {
if (pattern.equals("subdomain")) {
Matcher m = Pattern.compile("//([^\\.]*)\\.").matcher(href);
String subCode = Lang.getCode(m.group(1));
if (subCode != null
&& subCode.length() > 0
&& subCode.toLowerCase().equals(lang.toLowerCase())
) {
newHref = Pattern.compile(lang, Pattern.CASE_INSENSITIVE)
.matcher(href)
.replaceFirst(lang.toLowerCase());
} else {
newHref = href.replaceFirst("(//)([^\\.]*)", "$1" + lang.toLowerCase() + ".$2");
}
} else if (pattern.equals("query")) {
if (Pattern.compile("\\?").matcher(href).find()) {
newHref = href + "&wovn=" + lang;
} else {
newHref = href + "?wovn=" + lang;
}
} else {
newHref = addLangToPath(href, lang, headers.getPathLang());
}
}
} else if (href != null && href.length() > 0) {
String currentDir;
if (pattern.equals("subdomain")) {
String langUrl = headers.protocol + "://" + lang.toLowerCase() + headers.host;
currentDir = headers.pathName.replaceFirst("[^/]*\\.[^\\.]{2,6}$", "");
if (Pattern.compile("^\\.\\..*$").matcher(href).find()) {
newHref = langUrl + "/" + href.replaceAll("^\\.\\./", "");
} else if (Pattern.compile("^\\..*$").matcher(href).find()) {
newHref = langUrl + currentDir + "/" + href.replaceAll("^\\./", "");
} else if (Pattern.compile("^/.*$").matcher(href).find()) {
newHref = langUrl + href;
} else {
newHref = langUrl + currentDir + "/" + href;
}
} else if (pattern.equals("query")) {
if (Pattern.compile("\\?").matcher(href).find()) {
newHref = href + "&wovn=" + lang;
} else {
newHref = href + "?wovn=" + lang;
}
} else {
if (Pattern.compile("^/").matcher(href).find()) {
newHref = addLangToPath(href, lang, headers.getPathLang());
} else {
currentDir = headers.pathNameKeepTrailingSlash.replaceFirst("[^/]+$", "");
newHref = addLangToPath(currentDir + href, lang, headers.getPathLang());
}
}
}
return newHref;
}
private String addLangToPath(String path, String lang, String pathLang) {
if (lang == pathLang) {
return path;
}
String prefix = this.store.settings.sitePrefixPathWithSlash;
String newPath = prefix + lang + "/";
boolean hasPathLang = pathLang.length() > 0;
boolean hasPrefix = path.contains(prefix);
if (path.length() ==0) {
return newPath;
}
if (hasPrefix) {
if(hasPathLang) {
return path.replaceFirst(prefix + pathLang + "(/|$)", newPath);
} else {
return path.replaceFirst(prefix, newPath);
}
} else {
if(hasPathLang) {
return path.replaceFirst("/" + pathLang + "(/|$)", newPath);
} else {
return "/" + lang + "/" + path;
}
}
}
private boolean checkWovnIgnore(Node node) {
if (node.getAttributes() != null && node.getAttributes().getNamedItem("wovn-ignore") != null) {
return true;
} else if (node.getParentNode() == null) {
return false;
}
return this.checkWovnIgnore(node.getParentNode());
}
private static String getStringFromDocument(String body, Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.transform(domSource, result);
String html = writer.toString();
return DoctypeDetectation.addDoctypeIfNotExists(body, html);
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
private String switchLang(String body, Values values, HashMap<String, String> url, String lang, Headers headers) {
lang = Lang.getCode(lang);
HtmlDocumentBuilder builder = new HtmlDocumentBuilder();
StringReader reader = new StringReader(body);
Document doc;
try {
doc = builder.parse(new InputSource(reader));
} catch (org.xml.sax.SAXException e) {
Logger.log.error("SAXException while parsing HTML", e);
return body;
} catch (IOException e) {
Logger.log.error("IOException while parsing HTML", e);
return body;
}
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
if (doc.getDocumentElement().hasAttribute("wovn-ignore")) {
return getStringFromDocument(body, doc);
}
changeUrlToPunyCode(doc);
if (!lang.equals(this.store.settings.defaultLang)) {
NodeList anchors = null;
try { |
// Dataset.java
package imagej.model;
import mpicbg.imglib.container.Container;
import mpicbg.imglib.container.basictypecontainer.PlanarAccess;
import mpicbg.imglib.container.basictypecontainer.array.ArrayDataAccess;
import mpicbg.imglib.container.basictypecontainer.array.ByteArray;
import mpicbg.imglib.container.basictypecontainer.array.DoubleArray;
import mpicbg.imglib.container.basictypecontainer.array.FloatArray;
import mpicbg.imglib.container.basictypecontainer.array.IntArray;
import mpicbg.imglib.container.basictypecontainer.array.LongArray;
import mpicbg.imglib.container.basictypecontainer.array.ShortArray;
import mpicbg.imglib.container.planar.PlanarContainerFactory;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.image.ImageFactory;
import mpicbg.imglib.type.numeric.RealType;
/**
* TODO
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class Dataset {
private final Image<?> image;
private final Metadata metadata;
// FIXME TEMP - the current selection for this Dataset. Temporarily located
// here for plugin testing purposes. Really should be viewcentric.
private int selectionMinX, selectionMinY, selectionMaxX, selectionMaxY;
public int getSelectionMinX() { return selectionMinX; } // could define a nonAWT rect
public int getSelectionMinY() { return selectionMinY; } // and return it but lets
public int getSelectionMaxX() { return selectionMaxX; } // not pollute Dataset at
public int getSelectionMaxY() { return selectionMaxY; } // this time
public void setSelection(int minX, int minY, int maxX, int maxY)
{
selectionMinX = minX;
selectionMinY = minY;
selectionMaxX = maxX;
selectionMaxY = maxY;
}
// END FIXME TEMP
public Dataset(final Image<?> image) {
this(image, Metadata.createMetadata(image));
}
public Dataset(final Image<?> image, final Metadata metadata) {
this.image = image;
this.metadata = metadata;
}
public Image<?> getImage() {
return image;
}
public Metadata getMetadata() {
return metadata;
}
public Object getPlane(final int no) {
final Container<?> container = image.getContainer();
if (!(container instanceof PlanarAccess)) return null;
final Object plane = ((PlanarAccess<?>) container).getPlane(no);
if (!(plane instanceof ArrayDataAccess)) return null;
return ((ArrayDataAccess<?>) plane).getCurrentStorageArray();
}
@SuppressWarnings({"rawtypes","unchecked"})
public void setPlane(final int no, final Object plane) {
final Container<?> container = image.getContainer();
if (!(container instanceof PlanarAccess)) return;
final PlanarAccess planarAccess = (PlanarAccess) container;
ArrayDataAccess<?> array = null;
if (plane instanceof byte[]) {
array = new ByteArray((byte[]) plane);
}
else if (plane instanceof short[] ) {
array = new ShortArray((short[]) plane);
}
else if (plane instanceof int[] ) {
array = new IntArray((int[]) plane);
}
else if (plane instanceof float[] ) {
array = new FloatArray((float[]) plane);
}
else if (plane instanceof long[] ) {
array = new LongArray((long[]) plane);
}
else if (plane instanceof double[] ) {
array = new DoubleArray((double[]) plane);
}
planarAccess.setPlane(no, array);
}
// TEMP
public boolean isSigned() {
// HACK - imglib needs a way to query RealTypes for signedness
final String typeName = image.createType().getClass().getName();
return !typeName.startsWith("mpicbg.imglib.type.numeric.integer.Unsigned");
}
// TEMP
public boolean isFloat() {
// HACK - imglib needs a way to query RealTypes for integer vs. float
final String typeName = image.createType().getClass().getName();
return typeName.equals("mpicbg.imglib.type.numeric.real.FloatType")
|| typeName.equals("mpicbg.imglib.type.numeric.real.DoubleType");
}
// TODO - relocate this when its clear where it should go
public static <T extends RealType<T>> Image<T> createPlanarImage(final String name, final T type, final int[] dims)
{
final PlanarContainerFactory pcf = new PlanarContainerFactory();
final ImageFactory<T> imageFactory = new ImageFactory<T>(type, pcf);
return imageFactory.createImage(dims, name);
}
public static <T extends RealType<T>> Dataset create(final String name,
final T type, final int[] dims, final AxisLabel[] axes)
{
Image<T> image = createPlanarImage(name, type, dims);
final Metadata metadata = new Metadata();
metadata.setName(name);
metadata.setAxes(axes);
return new Dataset(image, metadata);
}
} |
package com.j256.ormlite.stmt.query;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.db.DatabaseType;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.stmt.ArgumentHolder;
import com.j256.ormlite.stmt.QueryBuilder.InternalQueryBuilderWrapper;
import com.j256.ormlite.stmt.Where;
/**
* Internal class handling the SQL 'in' query part. Used by {@link Where#in}.
*
* @author graywatson
*/
public class InSubQuery extends BaseComparison {
private final InternalQueryBuilderWrapper subQueryBuilder;
private final boolean in;
public InSubQuery(String columnName, FieldType fieldType, InternalQueryBuilderWrapper subQueryBuilder, boolean in)
throws SQLException {
super(columnName, fieldType, null, true);
this.subQueryBuilder = subQueryBuilder;
this.in = in;
}
@Override
public void appendOperation(StringBuilder sb) {
if (in) {
sb.append("IN ");
} else {
sb.append("NOT IN ");
}
}
@Override
public void appendValue(DatabaseType databaseType, StringBuilder sb, List<ArgumentHolder> argList)
throws SQLException {
sb.append('(');
subQueryBuilder.appendStatementString(sb, argList);
FieldType[] resultFieldTypes = subQueryBuilder.getResultFieldTypes();
if (resultFieldTypes == null) {
// we assume that if someone is doing a raw select, they know what they are doing
} else if (resultFieldTypes.length != 1) {
throw new SQLException("There must be only 1 result column in sub-query but we found "
+ resultFieldTypes.length);
} else if (fieldType.getSqlType() != resultFieldTypes[0].getSqlType()) {
throw new SQLException("Outer column " + fieldType + " is not the same type as inner column "
+ resultFieldTypes[0]);
}
sb.append(") ");
}
} |
package com.krux.kafka.consumer;
import com.krux.stdlib.KruxStdLib;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.common.errors.WakeupException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
public class ConsumerThread implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger( ConsumerThread.class );
private final AtomicBoolean closed = new AtomicBoolean(false);
private final MessageHandler<byte[]> _handler;
private final org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]> _consumer;
private String _topic;
private Long _consumerPollTimeout;
public ConsumerThread(org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]> consumer,
Long consumerPollTimeout, String topic, MessageHandler handler ) {
_consumer = consumer;
_consumerPollTimeout = consumerPollTimeout;
_topic = topic;
_handler = handler;
}
@Override
public void run() {
try {
// Subscribe to the topic
_consumer.subscribe( Arrays.asList(_topic) );
LOG.info( "Consuming thread subscribed - " + _topic);
while (!closed.get()) {
// Poll for messages in queue
ConsumerRecords<byte[], byte[]> records = _consumer.poll(_consumerPollTimeout);
for (ConsumerRecord<byte[], byte[]> record : records) {
long start = System.currentTimeMillis();
byte[] message = record.value();
LOG.debug("message received: {}", (new String(message)));
_handler.onMessage(message);
long time = System.currentTimeMillis() - start;
KruxStdLib.STATSD.time("message_received." + _topic, time);
}
}
} catch (WakeupException e) {
// Ignore exception if closing
if (!closed.get()) throw e;
} catch (Exception e) {
LOG.error("Consumer failure:", e);
} finally {
LOG.warn("Consumer shutting down");
_consumer.close();
}
}
// Shutdown hook which can be called from a separate thread
public void shutdown() {
closed.set(true);
_consumer.wakeup();
}
} |
package com.legendzero.lzlib.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class Database {
protected Connection connection;
protected Logger logger;
private String identifier;
private boolean enabled;
public Database(String identifier, String driverClass) {
this.connection = null;
this.logger = Logger.getLogger(identifier);
this.identifier = identifier;
this.enabled = this.checkClass(identifier, driverClass);
}
private boolean checkClass(String database, String driverClass) {
if (driverClass != null) {
try {
Class.forName(driverClass);
return true;
} catch (ClassNotFoundException e) {
this.logger.log(Level.SEVERE, "Error loading " + database + " driver.", e);
return false;
}
} else {
return true;
}
}
public final String getIdentifier() {
return this.identifier;
}
public final void setIdentifier(String identifier) {
this.logger = Logger.getLogger(identifier);
this.identifier = identifier;
}
public final boolean isEnabled() {
return this.enabled;
}
public final void setEnabled(boolean enabled) {
if (this.enabled != enabled) {
if (this.enabled) {
this.closeConnection();
}
this.enabled = enabled;
}
}
protected abstract Connection openConnection() throws SQLException;
protected final Connection getConnection() {
if (this.enabled) {
try {
if (this.connection == null || this.connection.isClosed()) {
this.connection = this.openConnection();
}
} catch (SQLException e) {
this.logger.log(Level.SEVERE, "Error opening connection", e);
}
return this.connection;
} else {
return null;
}
}
public boolean closeConnection() {
if (this.connection != null) {
try {
this.connection.close();
this.connection = null;
} catch (SQLException e) {
this.logger.log(Level.SEVERE, "Error closing connection", e);
return false;
}
}
return true;
}
protected final PreparedStatement prepareStatement(String query) throws SQLException {
return this.getConnection().prepareStatement(query);
}
protected final PreparedStatement map(PreparedStatement statement, Object[] mapping)
throws SQLException {
int index = 1;
for (Object object : mapping) {
statement.setObject(index++, object);
}
return statement;
}
public <T> T query(SQLQuery<T> query, Object... mappings) {
try (PreparedStatement statement = this.prepareStatement(query.getStatement())) {
try (ResultSet resultSet = this.map(statement, mappings).executeQuery()) {
return query.apply(resultSet);
}
} catch (SQLException e) {
this.logger.log(Level.WARNING, "Error querying database", e);
}
return null;
}
public Integer update(SQLUpdate update, Object... mapping) {
try (PreparedStatement statement = this.prepareStatement(update.getStatement())) {
return this.map(statement, mapping).executeUpdate();
} catch (SQLException e) {
this.logger.log(Level.WARNING, "Error querying database", e);
return -1;
}
}
public <T> int[] batch(SQLBatch<T> batch, Iterable<T> iterable) {
List<Function<? super T, Object>> mappingFunctions = batch.getMappingFunctions();
try (PreparedStatement statement = this.prepareStatement(batch.getStatement())) {
for (T object : iterable) {
Object[] parameters = new Object[mappingFunctions.size()];
for (int i = 0; i < parameters.length; i++) {
parameters[i] = mappingFunctions.get(i).apply(object);
}
this.map(statement, parameters).addBatch();
}
return statement.executeBatch();
} catch (SQLException e) {
this.logger.log(Level.WARNING, "Error querying database", e);
return null;
}
}
public <T> int[] batch(SQLBatch<T> batch, Iterator<T> iterator) {
List<Function<? super T, Object>> mappingFunctions = batch.getMappingFunctions();
try (PreparedStatement statement = this.prepareStatement(batch.getStatement())) {
while (iterator.hasNext()) {
T object = iterator.next();
Object[] parameters = new Object[mappingFunctions.size()];
for (int i = 0; i < parameters.length; i++) {
parameters[i] = mappingFunctions.get(i).apply(object);
}
this.map(statement, parameters).addBatch();
}
return statement.executeBatch();
} catch (SQLException e) {
this.logger.log(Level.WARNING, "Error querying database", e);
return null;
}
}
public <T> int[] batch(SQLBatch<T> batch, T... values) {
List<Function<? super T, Object>> mappingFunctions = batch.getMappingFunctions();
try (PreparedStatement statement = this.prepareStatement(batch.getStatement())) {
for (T object : values) {
Object[] parameters = new Object[mappingFunctions.size()];
for (int i = 0; i < parameters.length; i++) {
parameters[i] = mappingFunctions.get(i).apply(object);
}
this.map(statement, parameters).addBatch();
}
return statement.executeBatch();
} catch (SQLException e) {
this.logger.log(Level.WARNING, "Error querying database", e);
return null;
}
}
} |
package org.appwork.utils.ImageProvider;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import org.appwork.utils.Application;
import org.appwork.utils.logging.Log;
import sun.awt.image.ToolkitImage;
public class ImageProvider {
/**
* Hashcashmap to cache images.
*/
private static HashMap<String, BufferedImage> IMAGE_CACHE = new HashMap<String, BufferedImage>();
private static HashMap<String, ImageIcon> IMAGEICON_CACHE = new HashMap<String, ImageIcon>();
private static HashMap<Icon, Icon> DISABLED_ICON_CACHE = new HashMap<Icon, Icon>();
private static Object LOCK = new Object();
// stringbuilder die concat strings fast
private static StringBuilder SB = new StringBuilder();
/**
* @param bufferedImage
* @return
*/
public static BufferedImage convertToGrayScale(final BufferedImage bufferedImage) {
final BufferedImage dest = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(bufferedImage, 0, 0, null);
g2.dispose();
return dest;
}
/**
* Creates a dummy Icon
*
* @param string
* @param i
* @param j
* @return
*/
public static Image createIcon(final String string, final int width, final int height) {
final int w = width;
final int h = height;
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final BufferedImage image = gc.createCompatibleImage(w, h, Transparency.BITMASK);
final Graphics2D g = image.createGraphics();
int size = 1 + width / string.length();
// find max font size
int ww = 0;
int hh = 0;
while (size > 0) {
size
g.setFont(new Font("Arial", Font.BOLD, size));
ww = g.getFontMetrics().stringWidth(string);
hh = g.getFontMetrics().getAscent();
if (ww < w - 4 && hh < h - 2) {
break;
}
}
g.setColor(Color.WHITE);
g.fillRect(0, 0, w - 1, h - 1);
g.draw3DRect(0, 0, w - 1, h - 1, true);
g.setColor(Color.BLACK);
g.drawString(string, (w - ww) / 2, hh + (h - hh) / 2);
g.dispose();
return image;
}
/**
*
* @param name
* to the png file
* @param createDummy
* TODO
* @return
* @throws IOException
*/
public static Image getBufferedImage(final String name, final boolean createDummy) throws IOException {
synchronized (ImageProvider.LOCK) {
if (ImageProvider.IMAGE_CACHE.containsKey(name)) { return ImageProvider.IMAGE_CACHE.get(name); }
final File absolutePath = Application.getRessource("images/" + name + ".png");
try {
Log.L.info("Init Image: " + absolutePath.getAbsolutePath());
final BufferedImage image = ImageProvider.read(absolutePath);
ImageProvider.IMAGE_CACHE.put(name, image);
return image;
} catch (final IOException e) {
Log.L.severe("Could not Init Image: " + absolutePath.getAbsolutePath());
Log.L.severe("Image exists: " + absolutePath.exists());
try {
final File images = Application.getRessource("images/");
final String[] list = images.list();
if (list != null && list.length > 0) {
for (final String image : list) {
Log.L.severe("Existing images: " + image);
}
} else {
Log.L.severe("empty or not a folder: " + images);
}
} catch (final Throwable e2) {
}
if (createDummy) {
Log.exception(e);
return ImageProvider.createIcon(name.toUpperCase(), 48, 48);
} else {
throw e;
}
}
}
}
/**
* Uses the uimanager to get a grayscaled disabled Icon
*
* @param icon
* @return
*/
public static Icon getDisabledIcon(final Icon icon) {
if (icon == null) { return null; }
Icon ret = ImageProvider.DISABLED_ICON_CACHE.get(icon);
if (ret != null) { return ret; }
ret = UIManager.getLookAndFeel().getDisabledIcon(null, icon);
ImageProvider.DISABLED_ICON_CACHE.put(icon, ret);
return ret;
}
/**
* @param string
* @param i
* @param j
* @return
*/
public static ImageIcon getImageIcon(final String name, final int x, final int y) {
// TODO Auto-generated method stub
try {
return ImageProvider.getImageIcon(name, x, y, true);
} catch (final IOException e) {
// can not happen. true creates a dummyicon in case of io errors
Log.exception(e);
return null;
}
}
/**
* Loads the image, scales it to the desired size and returns it as an
* imageicon
*
* @param name
* @param width
* @param height
* @param createDummy
* TODO
* @return
* @throws IOException
*/
public static ImageIcon getImageIcon(final String name, int width, int height, final boolean createDummy) throws IOException {
synchronized (ImageProvider.LOCK) {
ImageProvider.SB.delete(0, ImageProvider.SB.capacity());
ImageProvider.SB.append(name);
ImageProvider.SB.append('_');
ImageProvider.SB.append(width);
ImageProvider.SB.append('_');
ImageProvider.SB.append(height);
String key;
if (ImageProvider.IMAGEICON_CACHE.containsKey(key = ImageProvider.SB.toString())) { return ImageProvider.IMAGEICON_CACHE.get(key); }
final Image image = ImageProvider.getBufferedImage(name, createDummy);
final double faktor = Math.max((double) image.getWidth(null) / width, (double) image.getHeight(null) / height);
width = (int) (image.getWidth(null) / faktor);
height = (int) (image.getHeight(null) / faktor);
final ImageIcon imageicon = new ImageIcon(image.getScaledInstance(width, height, Image.SCALE_SMOOTH));
ImageProvider.IMAGEICON_CACHE.put(key, imageicon);
return imageicon;
}
}
/**
* @param image
* @param imageIcon
* @param i
* @param j
*/
public static BufferedImage merge(final Image image, final Image b, final int xoffset, final int yoffset) {
final int width = Math.max(image.getWidth(null), xoffset + b.getWidth(null));
final int height = Math.max(image.getHeight(null), yoffset + b.getHeight(null));
final BufferedImage dest = new BufferedImage(width, height, Transparency.TRANSLUCENT);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.drawImage(b, xoffset, yoffset, null);
g2.dispose();
return dest;
}
/* copied from ImageIO, to close the inputStream */
public static BufferedImage read(final File input) throws IOException {
if (input == null) { throw new IllegalArgumentException("input == null!"); }
if (!input.canRead()) { throw new IIOException("Can't read input file!"); }
final ImageInputStream stream = ImageIO.createImageInputStream(input);
BufferedImage bi = null;
try {
if (stream == null) { throw new IIOException("Can't create an ImageInputStream!"); }
bi = ImageIO.read(stream);
} finally {
try {
stream.close();
} catch (final Throwable e) {
}
}
return bi;
}
/**
* @param scaleBufferedImage
* @param width
* @param height
* @return
*/
public static Image resizeWorkSpace(final Image scaleBufferedImage, final int width, final int height) {
// final GraphicsEnvironment ge =
// GraphicsEnvironment.getLocalGraphicsEnvironment();
// final GraphicsDevice gd = ge.getDefaultScreenDevice();
// final GraphicsConfiguration gc = gd.getDefaultConfiguration();
// final BufferedImage image = gc.createCompatibleImage(width, height,
// Transparency.BITMASK);
final BufferedImage image = new BufferedImage(width, height, Transparency.TRANSLUCENT);
final Graphics2D g = image.createGraphics();
g.drawImage(scaleBufferedImage, (width - scaleBufferedImage.getWidth(null)) / 2, (height - scaleBufferedImage.getHeight(null)) / 2, null);
g.dispose();
return image;
}
/**
* Scales a buffered Image to the given size. This method is NOT cached. so
* take care to cache it externally if you use it frequently
*
* @param img
* @param width
* @param height
* @return
*/
public static Image scaleBufferedImage(final BufferedImage img, int width, int height) {
if (img == null) { return null; }
final double faktor = Math.max((double) img.getWidth() / width, (double) img.getHeight() / height);
width = (int) (img.getWidth() / faktor);
height = (int) (img.getHeight() / faktor);
if (faktor == 1.0) { return img; }
return img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
}
/**
* Scales an imageicon to w x h.<br>
* like {@link #scaleBufferedImage(BufferedImage, int, int)}, this Function
* is NOT cached. USe an external cache if you use it frequently
*
* @param img
* @param w
* @param h
* @return
*/
public static ImageIcon scaleImageIcon(final ImageIcon img, final int w, final int h) {
// already has the desired size?
if (img.getIconHeight() == h && img.getIconWidth() == w) { return img; }
BufferedImage dest;
if (img.getImage() instanceof ToolkitImage) {
dest = new BufferedImage(w, h, Transparency.TRANSLUCENT);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(img.getImage(), 0, 0, null);
g2.dispose();
} else {
dest = (BufferedImage) img.getImage();
}
return new ImageIcon(ImageProvider.scaleBufferedImage(dest, w, h));
}
/**
* Converts an Icon to an Imageicon.
*
* @param icon
* @return
*/
public static ImageIcon toImageIcon(final Icon icon) {
if (icon == null) { return null; }
if (icon instanceof ImageIcon) {
return (ImageIcon) icon;
} else {
final int w = icon.getIconWidth();
final int h = icon.getIconHeight();
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final BufferedImage image = gc.createCompatibleImage(w, h, Transparency.BITMASK);
final Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return new ImageIcon(image);
}
}
} |
package com.mcmoddev.modernmetals;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mcmoddev.modernmetals.proxy.CommonProxy;
import com.mcmoddev.modernmetals.util.MMeConfig;
import com.mcmoddev.lib.data.SharedStrings;
import net.minecraft.launchwrapper.Launch;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLConstructionEvent;
import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
/**
* This is the entry point for this Mod.
*
* @author Jasmine Iwanek
*
*/
@Mod(
modid = ModernMetals.MODID,
name = ModernMetals.NAME,
version = ModernMetals.VERSION,
dependencies = "required-after:forge@[14.21.1.2387,);required-after:basemetals;after:tconstruct;after:conarm;before:buildingbricks",
acceptedMinecraftVersions = "[1.12,)",
certificateFingerprint = "@FINGERPRINT@",
updateJSON = ModernMetals.UPDATEJSON)
public class ModernMetals {
@Instance
public static ModernMetals instance;
/** ID of this Mod. */
public static final String MODID = "modernmetals";
/** Display name of this Mod. */
protected static final String NAME = "Modern Metals";
/**
* Version number, in Major.Minor.Build format. The minor number is
* increased whenever a change is made that has the potential to break
* compatibility with other mods that depend on this one.
*/
protected static final String VERSION = "2.5.0-beta7";
protected static final String UPDATEJSON = SharedStrings.UPDATE_JSON_URL + "ModernMetals/master/update.json";
private static final String PROXY_BASE = SharedStrings.MMD_PROXY_GROUP + MODID + SharedStrings.DOT_PROXY_DOT;
@SidedProxy(clientSide = PROXY_BASE + SharedStrings.CLIENTPROXY, serverSide = PROXY_BASE
+ SharedStrings.SERVERPROXY)
public static CommonProxy proxy;
public static final Logger logger = LogManager.getFormatterLogger(ModernMetals.MODID);
/**
*
* @param event The Event.
*/
@EventHandler
public void onFingerprintViolation(FMLFingerprintViolationEvent event) {
if (!(Boolean)Launch.blackboard.get("fml.deobfuscatedEnvironment")) {
// logger.warn("The Mod " + MODID + " is expecting signature " + event.getExpectedFingerprint() + " for source "+ event.getSource() + ", however there is no signature matching that description")
logger.warn(SharedStrings.INVALID_FINGERPRINT);
}
}
@EventHandler
public static void constructing(final FMLConstructionEvent event) {
MMeConfig.init();
}
/**
*
* @param event The Event.
*/
@EventHandler
public static void preInit(final FMLPreInitializationEvent event) {
proxy.preInit(event);
MinecraftForge.EVENT_BUS.register(com.mcmoddev.modernmetals.init.Items.class);
MinecraftForge.EVENT_BUS.register(com.mcmoddev.modernmetals.init.Blocks.class);
}
@EventHandler
public static void init(final FMLInitializationEvent event) {
proxy.init(event);
}
@EventHandler
public static void postInit(final FMLPostInitializationEvent event) {
proxy.postInit(event);
}
} |
package imagej;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
/**
* A classloader whose classpath can be augmented after instantiation.
*
* @author Johannes Schindelin
*/
public class ClassLoaderPlus extends URLClassLoader {
// A frozen ClassLoaderPlus will add only to the urls array
protected boolean frozen;
protected List<URL> urls = new ArrayList<URL>();
public static ClassLoaderPlus getInImageJDirectory(
final String... relativePaths)
{
try {
final File directory = new File(getImageJDir());
final URL[] urls = new URL[relativePaths.length];
for (int i = 0; i < urls.length; i++) {
urls[i] = new File(directory, relativePaths[i]).toURI().toURL();
}
return get(urls);
}
catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException("Uh oh: " + e.getMessage());
}
}
public static ClassLoaderPlus get(final File... files) {
try {
final URL[] urls = new URL[files.length];
for (int i = 0; i < urls.length; i++) {
urls[i] = files[i].toURI().toURL();
}
return get(urls);
}
catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException("Uh oh: " + e.getMessage());
}
}
public static ClassLoaderPlus get(final URL... urls) {
final ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
if (classLoader instanceof ClassLoaderPlus) {
final ClassLoaderPlus classLoaderPlus = (ClassLoaderPlus) classLoader;
for (final URL url : urls) {
classLoaderPlus.add(url);
}
return classLoaderPlus;
}
return new ClassLoaderPlus(urls);
}
public static ClassLoaderPlus getRecursivelyInImageJDirectory(
final String... relativePaths)
{
return getRecursivelyInImageJDirectory(false, relativePaths);
}
public static ClassLoaderPlus getRecursivelyInImageJDirectory(
final boolean onlyJars, final String... relativePaths)
{
try {
final File directory = new File(getImageJDir());
ClassLoaderPlus classLoader = null;
final File[] files = new File[relativePaths.length];
for (int i = 0; i < files.length; i++)
classLoader =
getRecursively(onlyJars, new File(directory, relativePaths[i]));
return classLoader;
}
catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException("Uh oh: " + e.getMessage());
}
}
public static ClassLoaderPlus getRecursively(final File directory) {
return getRecursively(false, directory);
}
public static ClassLoaderPlus getRecursively(final boolean onlyJars,
final File directory)
{
try {
ClassLoaderPlus classLoader = onlyJars ? null : get(directory);
final File[] list = directory.listFiles();
if (list != null) for (final File file : list)
if (file.isDirectory()) classLoader = getRecursively(onlyJars, file);
else if (file.getName().endsWith(".jar")) classLoader = get(file);
return classLoader;
}
catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException("Uh oh: " + e.getMessage());
}
}
public ClassLoaderPlus() {
this(new URL[0]);
}
public ClassLoaderPlus(final URL... urls) {
super(urls, Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(this);
}
public void addInImageJDirectory(final String relativePath) {
try {
add(new File(getImageJDir(), relativePath));
}
catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException("Uh oh: " + e.getMessage());
}
}
public void add(final String path) throws MalformedURLException {
add(new File(path));
}
public void add(final File file) throws MalformedURLException {
add(file.toURI().toURL());
}
public void add(final URL url) {
urls.add(url);
if (!frozen) addURL(url);
}
public void freeze() {
frozen = true;
}
public String getClassPath() {
final StringBuilder builder = new StringBuilder();
String sep = "";
for (final URL url : urls)
if (url.getProtocol().equals("file")) {
builder.append(sep).append(url.getPath());
sep = File.pathSeparator;
}
return builder.toString();
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(getClass().getName()).append("(");
for (final URL url : getURLs()) {
builder.append(" ").append(url.toString());
}
builder.append(" )");
return builder.toString();
}
public static String getImageJDir() throws ClassNotFoundException {
String path = System.getProperty("ij.dir");
if (path != null) return path;
final String prefix = "file:";
final String suffix = "/jars/ij-launcher.jar!/imagej/ClassLoaderPlus.class";
path =
Class.forName("imagej.ClassLoaderPlus")
.getResource("ClassLoaderPlus.class").getPath();
if (path.startsWith(prefix)) path = path.substring(prefix.length());
if (path.endsWith(suffix)) {
path = path.substring(0, path.length() - suffix.length());
}
return path;
}
public String getJarPath(final String className) {
try {
final Class clazz = loadClass(className);
String path =
clazz.getResource("/" + className.replace('.', '/') + ".class")
.getPath();
if (path.startsWith("file:")) path = path.substring(5);
final int bang = path.indexOf("!/");
if (bang > 0) path = path.substring(0, bang);
return path;
}
catch (final Throwable t) {
t.printStackTrace();
return null;
}
}
} |
package org.appwork.utils.swing.dialog;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.appwork.app.gui.MigPanel;
import org.appwork.resources.AWUTheme;
import org.appwork.storage.JSonStorage;
import org.appwork.utils.BinaryLogic;
import org.appwork.utils.locale._AWU;
import org.appwork.utils.logging.Log;
import org.appwork.utils.os.CrossSystem;
import org.appwork.utils.swing.EDTRunner;
import org.appwork.utils.swing.SwingUtils;
public abstract class AbstractDialog<T> extends TimerDialog implements ActionListener, WindowListener {
private static final long serialVersionUID = 1831761858087385862L;
private static final HashMap<String, Integer> SESSION_DONTSHOW_AGAIN = new HashMap<String, Integer>();
static Integer getSessionDontShowAgainValue(final String key) {
final Integer ret = AbstractDialog.SESSION_DONTSHOW_AGAIN.get(key);
if (ret == null) { return -1; }
return ret;
}
public static void resetDialogInformations() {
try {
AbstractDialog.SESSION_DONTSHOW_AGAIN.clear();
JSonStorage.getStorage("Dialogs").clear();
} catch (final Exception e) {
Log.exception(e);
}
}
protected JButton cancelButton;
private final String cancelOption;
private JPanel defaultButtons;
protected JCheckBox dontshowagain;
protected int flagMask;
private ImageIcon icon;
private boolean initialized = false;
protected JButton okButton;
private final String okOption;
protected JComponent panel;
protected int returnBitMask = 0;
private AbstractAction[] actions = null;
private final String title;
private JLabel iconLabel;
protected boolean doNotShowAgainSelected = false;
public AbstractDialog(final int flag, final String title, final ImageIcon icon, final String okOption, final String cancelOption) {
super();
this.title = title;
this.flagMask = flag;
this.icon = BinaryLogic.containsAll(flag, Dialog.STYLE_HIDE_ICON) ? null : icon;
this.okOption = okOption == null ? _AWU.T.ABSTRACTDIALOG_BUTTON_OK() : okOption;
this.cancelOption = cancelOption == null ? _AWU.T.ABSTRACTDIALOG_BUTTON_CANCEL() : cancelOption;
}
/**
* this function will init and show the dialog
*/
protected void _init() {
this.layoutDialog();
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_COUNTDOWN)) {
this.timerLbl.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
AbstractDialog.this.cancel();
AbstractDialog.this.timerLbl.removeMouseListener(this);
}
});
this.timerLbl.setToolTipText(_AWU.T.TIMERDIALOG_TOOLTIP_TIMERLABEL());
this.timerLbl.setIcon(AWUTheme.I().getIcon("dialog/cancel", 16));
}
/**
* this is very important so the new shown dialog will become root for
* all following dialogs! we save old parentWindow, then set current
* dialogwindow as new root and show dialog. after dialog has been
* shown, we restore old parentWindow
*/
final Component parentOwner = Dialog.getInstance().getParentOwner();
Dialog.getInstance().setParentOwner(this.getDialog());
try {
this.setTitle(this.title);
dont: if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
try {
final int i = BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT) ? AbstractDialog.getSessionDontShowAgainValue(this.getDontShowAgainKey()) : JSonStorage.getStorage("Dialogs").get(this.getDontShowAgainKey(), -1);
if (i >= 0) {
// filter saved return value
int ret = i & (Dialog.RETURN_OK | Dialog.RETURN_CANCEL);
// add flags
ret |= Dialog.RETURN_DONT_SHOW_AGAIN | Dialog.RETURN_SKIPPED_BY_DONT_SHOW;
/*
* if LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL or
* LOGIC_DONT_SHOW_AGAIN_IGNORES_OK are used, we check
* here if we should handle the dont show again feature
*/
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL) && BinaryLogic.containsAll(ret, Dialog.RETURN_CANCEL)) {
break dont;
}
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_OK) && BinaryLogic.containsAll(ret, Dialog.RETURN_OK)) {
break dont;
}
this.returnBitMask = ret;
return;
}
} catch (final Exception e) {
Log.exception(e);
}
}
if (parentOwner == null || !parentOwner.isShowing()) {
this.getDialog().setAlwaysOnTop(true);
}
// The Dialog Modal
this.getDialog().setModal(true);
// Layout manager
// Dispose dialog on close
this.getDialog().setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.getDialog().addWindowListener(this);
// create panel for the dialog's buttons
this.okButton = new JButton(this.okOption);
this.cancelButton = new JButton(this.cancelOption);
this.defaultButtons = this.getDefaultButtonPanel();
/*
* We set the focus on the ok button. if no ok button is shown, we
* set the focus on cancel button
*/
JButton focus = this.okButton;
// add listeners here
this.okButton.addActionListener(this);
this.cancelButton.addActionListener(this);
// add icon if available
if (this.icon != null) {
getDialog().setLayout(new MigLayout("ins 5,wrap 2","[][grow,fill]","[grow,fill][]"));
this.getDialog().add(this.iconLabel = new JLabel(this.icon), "gapright 10");
}else{
getDialog().setLayout(new MigLayout("ins 5,wrap 1","[grow,fill]","[grow,fill][]"));
}
// Layout the dialog content and add it to the contentpane
this.panel = this.layoutDialogContent();
this.getDialog().add(this.panel, "");
// add the countdown timer
MigPanel bottom = new MigPanel("ins 0", "[]20[grow,fill][]", "[]");
bottom.setOpaque(false);
bottom.add(this.timerLbl);
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
this.dontshowagain = new JCheckBox(_AWU.T.ABSTRACTDIALOG_STYLE_SHOW_DO_NOT_DISPLAY_AGAIN());
this.dontshowagain.setHorizontalAlignment(SwingConstants.TRAILING);
this.dontshowagain.setHorizontalTextPosition(SwingConstants.LEADING);
this.dontshowagain.setSelected(this.doNotShowAgainSelected);
bottom.add(this.dontshowagain, "alignx right");
} else {
bottom.add(Box.createHorizontalGlue());
}
bottom.add(this.defaultButtons);
if ((this.flagMask & Dialog.BUTTONS_HIDE_OK) == 0) {
// Set OK as defaultbutton
this.getDialog().getRootPane().setDefaultButton(this.okButton);
this.okButton.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(final HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
final JButton defaultButton = (JButton) e.getComponent();
final JRootPane root = SwingUtilities.getRootPane(defaultButton);
if (root != null) {
root.setDefaultButton(defaultButton);
}
}
}
});
focus = this.okButton;
this.defaultButtons.add(this.okButton, "alignx right,tag ok,sizegroup confirms");
}
if (!BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_CANCEL)) {
this.defaultButtons.add(this.cancelButton, "alignx right,tag cancel,sizegroup confirms");
if (BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_OK)) {
this.getDialog().getRootPane().setDefaultButton(this.cancelButton);
this.cancelButton.requestFocusInWindow();
// focus is on cancel if OK is hidden
focus = this.cancelButton;
}
}
this.addButtons(this.defaultButtons);
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_COUNTDOWN)) {
// show timer
this.initTimer(this.getCountdown());
} else {
this.timerLbl.setText(null);
}
getDialog().add(bottom,"spanx,growx,pushx");
// pack dialog
this.getDialog().invalidate();
// this.setMinimumSize(this.getPreferredSize());
if (!getDialog().isMinimumSizeSet()) {
this.getDialog().setMinimumSize(new Dimension(300, 80));
}
this.getDialog().setResizable(this.isResizable());
this.pack();
// minimum size foir a dialog
// // Dimension screenDim =
// Toolkit.getDefaultToolkit().getScreenSize();
// this.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize());
this.getDialog().toFront();
// if (this.getDesiredSize() != null) {
// this.setSize(this.getDesiredSize());
if (!this.getDialog().getParent().isDisplayable() || !this.getDialog().getParent().isVisible()) {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.getDialog().setLocation(new Point((int) (screenSize.getWidth() - this.getDialog().getWidth()) / 2, (int) (screenSize.getHeight() - this.getDialog().getHeight()) / 2));
} else if (this.getDialog().getParent() instanceof Frame && ((Frame) this.getDialog().getParent()).getExtendedState() == Frame.ICONIFIED) {
// dock dialog at bottom right if mainframe is not visible
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.getDialog().setLocation(new Point((int) (screenSize.getWidth() - this.getDialog().getWidth() - 20), (int) (screenSize.getHeight() - this.getDialog().getHeight() - 60)));
} else {
this.getDialog().setLocation(SwingUtils.getCenter(this.getDialog().getParent(), this.getDialog()));
}
// register an escape listener to cancel the dialog
final KeyStroke ks = KeyStroke.getKeyStroke("ESCAPE");
focus.getInputMap().put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "ESCAPE");
focus.getActionMap().put("ESCAPE", new AbstractAction() {
private static final long serialVersionUID = -6666144330707394562L;
public void actionPerformed(final ActionEvent e) {
Log.L.fine("Answer: Key<ESCAPE>");
AbstractDialog.this.setReturnmask(false);
AbstractDialog.this.dispose();
}
});
focus.requestFocus();
this.packed();
// System.out.println("NEW ONE "+this.getDialog());
/*
* workaround a javabug that forces the parentframe to stay always
* on top
*/
if (this.getDialog().getParent() != null && !CrossSystem.isMac()) {
((Window) this.getDialog().getParent()).setAlwaysOnTop(true);
((Window) this.getDialog().getParent()).setAlwaysOnTop(false);
}
this.setVisible(true);
} finally {
// System.out.println("SET OLD");
Dialog.getInstance().setParentOwner(this.getDialog().getParent());
}
/*
* workaround a javabug that forces the parentframe to stay always on
* top
*/
if (this.getDialog().getParent() != null && !CrossSystem.isMac()) {
((Window) this.getDialog().getParent()).setAlwaysOnTop(true);
((Window) this.getDialog().getParent()).setAlwaysOnTop(false);
}
}
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == this.okButton) {
Log.L.fine("Answer: Button<OK:" + this.okButton.getText() + ">");
this.setReturnmask(true);
} else if (e.getSource() == this.cancelButton) {
Log.L.fine("Answer: Button<CANCEL:" + this.cancelButton.getText() + ">");
this.setReturnmask(false);
}
this.dispose();
}
/**
* Overwrite this method to add additional buttons
*/
protected void addButtons(final JPanel buttonBar) {
}
/**
* called when user closes the window
*
* @return <code>true</code>, if and only if the dialog should be closeable
**/
public boolean closeAllowed() {
return true;
}
protected abstract T createReturnValue();
/**
* This method has to be called to display the dialog. make sure that all
* settings have beens et before, becvause this call very likly display a
* dialog that blocks the rest of the gui until it is closed
*/
public void displayDialog() {
if (this.initialized) { return; }
this.initialized = true;
this._init();
}
@Override
public void dispose() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
new EDTRunner() {
@Override
protected void runInEDT() {
AbstractDialog.super.dispose();
if (AbstractDialog.this.timer != null) {
AbstractDialog.this.timer.interrupt();
AbstractDialog.this.timer = null;
}
}
};
}
/**
* @return
*/
protected JPanel getDefaultButtonPanel() {
final JPanel ret = new JPanel(new MigLayout("ins 0", "[]", "0[]0"));
if (this.actions != null) {
for (final AbstractAction a : this.actions) {
String tag = (String) a.getValue("tag");
if (tag == null) {
tag = "help";
}
ret.add(new JButton(a), "tag " + tag + ",sizegroup confirms");
}
}
return ret;
}
/**
* Create the key to save the don't showmagain state in database. should be
* overwritten in same dialogs. by default, the dialogs get differed by
* their title and their classname
*
* @return
*/
protected String getDontShowAgainKey() {
return "ABSTRACTDIALOG_DONT_SHOW_AGAIN_" + this.getClass().getSimpleName() + "_" + this.toString();
}
public ImageIcon getIcon() {
return this.icon;
}
/**
* Return the returnbitmask
*
* @return
*/
public int getReturnmask() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.returnBitMask;
}
public T getReturnValue() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.createReturnValue();
}
/**
* @return
*/
public String getTitle() {
try {
return this.getDialog().getTitle();
} catch (final NullPointerException e) {
// not initialized yet
return this.title;
}
}
/**
* @return the initialized
*/
public boolean isInitialized() {
return this.initialized;
}
// /**
// * should be overwritten and return a Dimension of the dialog should have
// a
// * special size
// *
// * @return
// */
// protected Dimension getDesiredSize() {
// return null;
/**
* override to change default resizable flag
*
* @return
*/
protected boolean isResizable() {
// TODO Auto-generated method stub
return false;
}
/**
* This method has to be overwritten to implement custom content
*
* @return musst return a JComponent
*/
abstract public JComponent layoutDialogContent();
/**
* Handle timeout
*/
@Override
protected void onTimeout() {
this.setReturnmask(false);
this.returnBitMask |= Dialog.RETURN_TIMEOUT;
this.dispose();
}
/**
* may be overwritten to set focus to special components etc.
*/
protected void packed() {
}
/**
* @param b
*/
public void setDoNotShowAgainSelected(final boolean b) {
if (!BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) { throw new IllegalStateException("You have to set the Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN flag to use this method");
}
this.doNotShowAgainSelected = b;
}
public void setIcon(final ImageIcon icon) {
this.icon = icon;
if (this.iconLabel != null) {
new EDTRunner() {
@Override
protected void runInEDT() {
AbstractDialog.this.iconLabel.setIcon(AbstractDialog.this.icon);
}
};
}
}
/**
* Add Additional BUttons on the left side of ok and cancel button. You can
* add a "tag" property to the action in ordner to help the layouter,
*
* <pre>
* abstractActions[0].putValue("tag", "ok")
* </pre>
*
* @param abstractActions
* list
*/
public void setLeftActions(final AbstractAction... abstractActions) {
this.actions = abstractActions;
}
/**
* Sets the returnvalue and saves the don't show again states to the
* database
*
* @param b
*/
protected void setReturnmask(final boolean b) {
this.returnBitMask = b ? Dialog.RETURN_OK : Dialog.RETURN_CANCEL;
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
if (this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()) {
this.returnBitMask |= Dialog.RETURN_DONT_SHOW_AGAIN;
try {
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT)) {
AbstractDialog.SESSION_DONTSHOW_AGAIN.put(this.getDontShowAgainKey(), this.returnBitMask);
} else {
JSonStorage.getStorage("Dialogs").put(this.getDontShowAgainKey(), this.returnBitMask);
}
} catch (final Exception e) {
Log.exception(e);
}
}
}
}
/**
* @param title2
*/
protected void setTitle(final String title2) {
this.getDialog().setTitle(title2);
}
/**
* Returns an id of the dialog based on it's title;
*/
@Override
public String toString() {
return ("dialog-" + this.getTitle()).replaceAll("\\W", "_");
}
public void windowActivated(final WindowEvent arg0) {
}
public void windowClosed(final WindowEvent arg0) {
}
public void windowClosing(final WindowEvent arg0) {
if (this.closeAllowed()) {
Log.L.fine("Answer: Button<[X]>");
this.returnBitMask |= Dialog.RETURN_CLOSED;
this.dispose();
} else {
Log.L.fine("(Answer: Tried [X] bot not allowed)");
}
}
public void windowDeactivated(final WindowEvent arg0) {
}
public void windowDeiconified(final WindowEvent arg0) {
}
public void windowIconified(final WindowEvent arg0) {
}
public void windowOpened(final WindowEvent arg0) {
}
} |
package imagej.legacy;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import javassist.CannotCompileException;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.ConstPool;
import javassist.bytecode.InstructionPrinter;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.Opcode;
import javassist.expr.ConstructorCall;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.Handler;
import javassist.expr.MethodCall;
import javassist.expr.NewExpr;
import org.scijava.util.ClassUtils;
import org.scijava.util.FileUtils;
/**
* The code hacker provides a mechanism for altering the behavior of classes
* before they are loaded, for the purpose of injecting new methods and/or
* altering existing ones.
* <p>
* In ImageJ, this mechanism is used to provide new seams into legacy ImageJ1
* code, so that (e.g.) the modern UI is aware of legacy ImageJ events as they
* occur.
* </p>
*
* @author Curtis Rueden
* @author Rick Lentz
* @author Johannes Schindelin
*/
public class CodeHacker {
private static final String PATCH_PKG = "imagej.legacy.patches";
private static final String PATCH_SUFFIX = "Methods";
private final ClassPool pool;
protected final ClassLoader classLoader;
private final Set<CtClass> handledClasses = new LinkedHashSet<CtClass>();
public CodeHacker(final ClassLoader classLoader, final ClassPool classPool) {
this.classLoader = classLoader;
pool = classPool != null ? classPool : ClassPool.getDefault();
pool.appendClassPath(new ClassClassPath(getClass()));
pool.appendClassPath(new LoaderClassPath(classLoader));
// the CodeHacker offers the LegacyService instance, therefore it needs to add that field here
if (!hasField("ij.IJ", "_legacyService")) {
insertPrivateStaticField("ij.IJ", LegacyService.class, "_legacyService");
insertNewMethod("ij.IJ",
"public static imagej.legacy.LegacyService getLegacyService()",
"return _legacyService;");
}
}
public CodeHacker(ClassLoader classLoader) {
this(classLoader, null);
}
/**
* Modifies a class by injecting additional code at the end of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtBottomOfMethod(final String fullClass, final String methodSig)
{
insertAtBottomOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the end of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtBottomOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
getBehavior(fullClass, methodSig).insertAfter(expand(newCode));
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot modify method: " + methodSig,
e);
}
}
/**
* Modifies a class by injecting additional code at the start of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtTopOfMethod(final String fullClass, final String methodSig)
{
insertAtTopOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the start of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtTopOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
final CtBehavior behavior = getBehavior(fullClass, methodSig);
if (behavior instanceof CtConstructor) {
((CtConstructor)behavior).insertBeforeBody(expand(newCode));
} else {
behavior.insertBefore(expand(newCode));
}
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot modify method: " + methodSig,
e);
}
}
/**
* Modifies a class by injecting a new method.
* <p>
* The body of the method is defined in the imagej.legacy.patches package, as
* described in the {@link #insertNewMethod(String, String)} method
* documentation.
* <p>
* The new method implementation should be declared in the
* imagej.legacy.patches package, with the same name as the original class
* plus "Methods"; e.g., overridden ij.gui.ImageWindow methods should be
* placed in the imagej.legacy.patches.ImageWindowMethods class.
* </p>
* <p>
* New method implementations must be public static, with an additional first
* parameter: the instance of the class on which to operate.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void setVisible(boolean vis)"
*/
public void insertNewMethod(final String fullClass, final String methodSig) {
insertNewMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string as a new method.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertNewMethod(final String fullClass, final String methodSig,
final String newCode)
{
final CtClass classRef = getClass(fullClass);
final String methodBody = methodSig + " { " + expand(newCode) + " } ";
try {
final CtMethod methodRef = CtNewMethod.make(methodBody, classRef);
classRef.addMethod(methodRef);
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot add method: " + methodSig, e);
}
}
/*
* Works around a bug where the horizontal scroll wheel of the mighty mouse is mistaken for a popup trigger.
*/
public void handleMightyMousePressed(final String fullClass) {
ExprEditor editor = new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals("isPopupTrigger"))
call.replace("$_ = $0.isPopupTrigger() && $0.getButton() != 0;");
}
};
final CtClass classRef = getClass(fullClass);
for (final String methodName : new String[] { "mousePressed", "mouseDragged" }) try {
final CtMethod method = classRef.getMethod(methodName, "(Ljava/awt/event/MouseEvent;)V");
method.instrument(editor);
} catch (NotFoundException e) {
/* ignore */
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot instrument method: " + methodName, e);
}
}
public void insertPrivateStaticField(final String fullClass,
final Class<?> clazz, final String name) {
insertStaticField(fullClass, Modifier.PRIVATE, clazz, name, null);
}
public void insertPublicStaticField(final String fullClass,
final Class<?> clazz, final String name, final String initializer) {
insertStaticField(fullClass, Modifier.PUBLIC, clazz, name, initializer);
}
public void insertStaticField(final String fullClass, int modifiers,
final Class<?> clazz, final String name, final String initializer) {
final CtClass classRef = getClass(fullClass);
try {
final CtField field = new CtField(pool.get(clazz.getName()), name,
classRef);
field.setModifiers(modifiers | Modifier.STATIC);
classRef.addField(field);
if (initializer != null) {
addToClassInitializer(fullClass, name + " = " + initializer + ";");
}
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot add field " + name
+ " to " + fullClass, e);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Cannot add field " + name
+ " to " + fullClass, e);
}
}
public void addToClassInitializer(final String fullClass, final String code) {
final CtClass classRef = getClass(fullClass);
try {
CtConstructor method = classRef.getClassInitializer();
if (method != null) {
method.insertAfter(code);
} else {
method = CtNewConstructor.make(new CtClass[0], new CtClass[0], code, classRef);
method.getMethodInfo().setName("<clinit>");
method.setModifiers(Modifier.STATIC);
classRef.addConstructor(method);
}
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot add " + code
+ " to class initializer of " + fullClass, e);
}
}
public void addCatch(final String fullClass, final String methodSig, final String exceptionClassName, final String src) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.addCatch(src, getClass(exceptionClassName), "$e");
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot add catch for exception of type'"
+ exceptionClassName + " in " + fullClass + "'s " + methodSig, e);
}
}
public void insertAtTopOfExceptionHandlers(final String fullClass, final String methodSig, final String exceptionClassName, final String src) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(Handler handler) throws CannotCompileException {
try {
if (handler.getType().getName().equals(exceptionClassName)) {
handler.insertBefore(src);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot edit exception handler for type'"
+ exceptionClassName + " in " + fullClass + "'s " + methodSig, e);
}
}
/**
* Replaces the application name in the given method in the given parameter
* to the given constructor call.
*
* Fails silently if the specified method does not exist (e.g.
* CommandFinder's export() function just went away in 1.47i).
*
* @param fullClass
* Fully qualified name of the class to override.
* @param methodSig
* Method signature of the method to override; e.g.,
* "public void showMessage(String title, String message)"
* @param newClassName
* the name of the class which is to be constructed by the new
* operator
* @param parameterIndex
* the index of the parameter containing the application name
* @param replacement
* the code to use instead of the specified parameter
* @throws CannotCompileException
*/
protected void replaceParameterInNew(final String fullClass,
final String methodSig, final String newClassName,
final int parameterIndex, final String replacement) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(NewExpr expr) throws CannotCompileException {
if (expr.getClassName().equals(newClassName))
try {
final CtClass[] parameterTypes = expr
.getConstructor().getParameterTypes();
if (parameterTypes[parameterIndex] != CodeHacker.this
.getClass("java.lang.String")) {
throw new IllegalArgumentException("Parameter "
+ parameterIndex + " of "
+ expr.getConstructor() + " is not a String!");
}
final String replace = replaceParameter(
parameterIndex, parameterTypes.length, replacement);
expr.replace("$_ = new " + newClassName + replace
+ ";");
} catch (NotFoundException e) {
throw new IllegalArgumentException(
"Cannot find the parameters of the constructor of "
+ newClassName, e);
}
}
});
} catch (IllegalArgumentException e) {
// ignore: the method was not found
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot handle app name in " + fullClass
+ "'s " + methodSig, e);
}
}
/**
* Replaces the application name in the given method in the given parameter
* to the given method call.
*
* Fails silently if the specified method does not exist (e.g.
* CommandFinder's export() function just went away in 1.47i).
*
* @param fullClass
* Fully qualified name of the class to override.
* @param methodSig
* Method signature of the method to override; e.g.,
* "public void showMessage(String title, String message)"
* @param calledMethodName
* the name of the method to which the application name is passed
* @param parameterIndex
* the index of the parameter containing the application name
* @param replacement
* the code to use instead of the specified parameter
* @throws CannotCompileException
*/
protected void replaceParameterInCall(final String fullClass,
final String methodSig, final String calledMethodName,
final int parameterIndex, final String replacement) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals(calledMethodName)) try {
final boolean isSuper = call.isSuper();
final CtClass[] parameterTypes = isSuper ?
((ConstructorCall) call).getConstructor().getParameterTypes() :
call.getMethod().getParameterTypes();
if (parameterTypes.length < parameterIndex) {
throw new IllegalArgumentException("Index " + parameterIndex + " is outside of " + call.getMethod() + "'s parameter list!");
}
if (parameterTypes[parameterIndex - 1] != CodeHacker.this.getClass("java.lang.String")) {
throw new IllegalArgumentException("Parameter " + parameterIndex + " of "
+ call.getMethod() + " is not a String!");
}
final String replace = replaceParameter(
parameterIndex, parameterTypes.length, replacement);
call.replace((isSuper ? "" : "$0.") + calledMethodName + replace + ";");
} catch (NotFoundException e) {
throw new IllegalArgumentException(
"Cannot find the parameters of the method "
+ calledMethodName, e);
}
}
@Override
public void edit(final ConstructorCall call) throws CannotCompileException {
edit((MethodCall)call);
}
});
} catch (IllegalArgumentException e) {
// ignore: the method was not found
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot handle app name in " + fullClass
+ "'s " + methodSig, e);
}
}
private String replaceParameter(final int parameterIndex, final int parameterCount, final String replacement) {
final StringBuilder builder = new StringBuilder();
builder.append("(");
for (int i = 1; i <= parameterCount; i++) {
if (i > 1) {
builder.append(", ");
}
builder.append("$").append(i);
if (i == parameterIndex) {
builder.append(".replace(\"ImageJ\", " + replacement + ")");
}
}
builder.append(")");
return builder.toString();
}
/**
* Patches the bytecode of the given method to not return on a null check.
*
* This is needed to patch support for alternative editors into ImageJ 1.x.
*
* @param fullClass the class of the method to instrument
* @param methodSig the signature of the method to instrument
*/
public void dontReturnOnNull(final String fullClass, final String methodSig) {
final CtBehavior behavior = getBehavior(fullClass, methodSig);
final MethodInfo info = behavior.getMethodInfo();
final CodeIterator iterator = info.getCodeAttribute().iterator();
while (iterator.hasNext()) try {
int pos = iterator.next();
final int c = iterator.byteAt(pos);
if (c == Opcode.IFNONNULL && iterator.byteAt(pos + 3) == Opcode.RETURN) {
iterator.writeByte(Opcode.POP, pos++);
iterator.writeByte(Opcode.NOP, pos++);
iterator.writeByte(Opcode.NOP, pos++);
iterator.writeByte(Opcode.NOP, pos++);
return;
}
}
catch (BadBytecode e) {
throw new IllegalArgumentException(e);
}
throw new IllegalArgumentException("Method " + methodSig + " in " + fullClass + " does not return on null");
}
/**
* Replaces the given methods with stub methods.
*
* @param fullClass the class to patch
* @param methodNames the names of the methods to replace
* @throws NotFoundException
* @throws CannotCompileException
*/
public void replaceWithStubMethods(final String fullClass, final String... methodNames) {
final CtClass clazz = getClass(fullClass);
final Set<String> override = new HashSet<String>(Arrays.asList(methodNames));
for (final CtMethod method : clazz.getMethods())
if (override.contains(method.getName())) try {
final CtMethod stub = makeStubMethod(clazz, method);
method.setBody(stub, null);
} catch (NotFoundException e) {
// ignore
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot instrument method: " + method.getName(), e);
}
}
/**
* Replaces the superclass.
*
* @param fullClass
* @param fullNewSuperclass
* @throws NotFoundException
*/
public void replaceSuperclass(String fullClass, String fullNewSuperclass) {
final CtClass clazz = getClass(fullClass);
try {
CtClass originalSuperclass = clazz.getSuperclass();
clazz.setSuperclass(getClass(fullNewSuperclass));
for (final CtConstructor ctor : clazz.getConstructors())
ctor.instrument(new ExprEditor() {
@Override
public void edit(final ConstructorCall call) throws CannotCompileException {
if (call.getMethodName().equals("super"))
call.replace("super();");
}
});
letSuperclassMethodsOverride(clazz);
addMissingMethods(clazz, originalSuperclass);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Could not replace superclass of " + fullClass + " with " + fullNewSuperclass, e);
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Could not replace superclass of " + fullClass + " with " + fullNewSuperclass, e);
}
}
/**
* Replaces all instantiations of a subset of AWT classes with nulls.
*
* This is used by the partial headless support of legacy code.
*
* @param fullClass
* @throws CannotCompileException
* @throws NotFoundException
*/
public void skipAWTInstantiations(String fullClass) {
try {
skipAWTInstantiations(getClass(fullClass));
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Could not skip AWT class instantiations in " + fullClass, e);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Could not skip AWT class instantiations in " + fullClass, e);
}
}
/**
* Replaces every field write access to the specified field in the specified method.
*
* @param fullClass the full class
* @param methodSig the signature of the method to instrument
* @param fieldName the field whose write access to override
* @param newCode the code to run instead of the field access
*/
public void overrideFieldWrite(final String fullClass, final String methodSig, final String fieldName, final String newCode) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(final FieldAccess access) throws CannotCompileException {
if (access.getFieldName().equals(access)) {
access.replace(newCode);
}
}
});
} catch (IllegalArgumentException e) {
// ignore: the method was not found
} catch (CannotCompileException e) {
throw new IllegalArgumentException(
"Cannot override field access to " + fieldName + " in " + fullClass + "'s " + methodSig, e);
}
}
/**
* Replaces a call in the given method.
*
* @param fullClass the class of the method to edit
* @param methodSig the signature of the method to edit
* @param calledClass the class of the called method to replace
* @param calledMethodName the name of the called method to replace
* @param newCode the code to replace the call with
*/
public void replaceCallInMethod(final String fullClass,
final String methodSig, final String calledClass,
final String calledMethodName, final String newCode) {
replaceCallInMethod(fullClass, methodSig, calledClass, calledMethodName, newCode, -1);
}
/**
* Replaces a call in the given method.
*
* @param fullClass the class of the method to edit
* @param methodSig the signature of the method to edit
* @param calledClass the class of the called method to replace
* @param calledMethodName the name of the called method to replace
* @param newCode the code to replace the call with
* @param onlyNth if positive, only replace the <i>n</i>th call
*/
public void replaceCallInMethod(final String fullClass,
final String methodSig, final String calledClass,
final String calledMethodName, final String newCode, final int onlyNth) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
private int count = 0;
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals(calledMethodName)
&& call.getClassName().equals(calledClass)) {
if ( ++count != onlyNth && onlyNth > 0) return;
call.replace(newCode);
}
}
@Override
public void edit(NewExpr expr) throws CannotCompileException {
if ("<init>".equals(calledMethodName)
&& expr.getClassName().equals(calledClass)) {
if ( ++count != onlyNth && onlyNth > 0) return;
expr.replace(newCode);
}
}
});
} catch (IllegalArgumentException e) {
// ignore: the method was not found
} catch (CannotCompileException e) {
throw new IllegalArgumentException(
"Cannot handle replace call to " + calledMethodName
+ " in " + fullClass + "'s " + methodSig, e);
}
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param fullClass Fully qualified class name to load.
* @return the loaded class
*/
public Class<?> loadClass(final String fullClass) {
final CtClass classRef = getClass(fullClass);
return loadClass(classRef);
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param classRef class to load.
* @return the loaded class
*/
public Class<?> loadClass(final CtClass classRef) {
try {
return classRef.toClass(classLoader, null);
}
catch (final CannotCompileException e) {
// Cannot use LogService; it will not be initialized by the time the DefaultLegacyService
// class is loaded, which is when the CodeHacker is run
if (e.getCause() != null && e.getCause() instanceof LinkageError) {
final URL url = ClassUtils.getLocation(LegacyJavaAgent.class);
final String path = url != null && "file".equals(url.getProtocol()) && url.getPath().endsWith(".jar")?
url.getPath() : "/path/to/ij-legacy.jar";
throw new RuntimeException("Cannot load class: " + classRef.getName() + "\n"
+ "It appears that this class was already defined in the class loader!\n"
+ "Please make sure that you initialize the LegacyService before using\n"
+ "any ImageJ 1.x class. You can do that by adding this static initializer:\n\n"
+ "\tstatic {\n"
+ "\t\tDefaultLegacyService.preinit();\n"
+ "\t}\n\n"
+ "To debug this issue, start the JVM with the option:\n\n"
+ "\t-javaagent:" + path + "\n\n"
+ "To enforce pre-initialization, start the JVM with the option:\n\n"
+ "\t-javaagent:" + path + "=init\n", e.getCause());
}
System.err.println("Warning: Cannot load class: " + classRef.getName() + " into " + classLoader);
e.printStackTrace();
return null;
} finally {
classRef.freeze();
}
}
public void loadClasses() {
try {
LegacyJavaAgent.stop();
} catch (Throwable t) {
// ignore
}
final Iterator<CtClass> iter = handledClasses.iterator();
while (iter.hasNext()) {
final CtClass classRef = iter.next();
if (!classRef.isFrozen() && classRef.isModified()) {
loadClass(classRef);
}
iter.remove();
}
}
/** Gets the Javassist class object corresponding to the given class name. */
private CtClass getClass(final String fullClass) {
try {
final CtClass classRef = pool.get(fullClass);
if (classRef.getClassPool() == pool) handledClasses.add(classRef);
return classRef;
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such class: " + fullClass, e);
}
}
/**
* Gets the method or constructor of the specified class and signature.
*
* @param fullClass the class containing the method or constructor
* @param methodSig the method (or if the name is <code><init></code>, the constructor)
* @return the method or constructor
*/
private CtBehavior getBehavior(final String fullClass, final String methodSig) {
if (methodSig.indexOf("<init>") < 0) {
return getMethod(fullClass, methodSig);
} else {
return getConstructor(fullClass, methodSig);
}
}
/**
* Gets the Javassist method object corresponding to the given method
* signature of the specified class name.
*/
private CtMethod getMethod(final String fullClass, final String methodSig) {
final CtClass cc = getClass(fullClass);
final String name = getMethodName(methodSig);
final String[] argTypes = getMethodArgTypes(methodSig);
final CtClass[] params = new CtClass[argTypes.length];
for (int i = 0; i < params.length; i++) {
params[i] = getClass(argTypes[i]);
}
try {
return cc.getDeclaredMethod(name, params);
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such method: " + methodSig, e);
}
}
/**
* Gets the Javassist constructor object corresponding to the given constructor
* signature of the specified class name.
*/
private CtConstructor getConstructor(final String fullClass, final String constructorSig) {
final CtClass cc = getClass(fullClass);
final String[] argTypes = getMethodArgTypes(constructorSig);
final CtClass[] params = new CtClass[argTypes.length];
for (int i = 0; i < params.length; i++) {
params[i] = getClass(argTypes[i]);
}
try {
return cc.getDeclaredConstructor(params);
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such method: " + constructorSig, e);
}
}
/**
* Generates a new line of code calling the {@link imagej.legacy.patches}
* class and method corresponding to the given method signature.
*/
private String newCode(final String fullClass, final String methodSig) {
final int dotIndex = fullClass.lastIndexOf(".");
final String className = fullClass.substring(dotIndex + 1);
final String methodName = getMethodName(methodSig);
final boolean isStatic = isStatic(methodSig);
final boolean isVoid = isVoid(methodSig);
final String patchClass = PATCH_PKG + "." + className + PATCH_SUFFIX;
for (final CtMethod method : getClass(patchClass).getMethods()) try {
if ((method.getModifiers() & Modifier.STATIC) == 0) continue;
final CtClass[] types = method.getParameterTypes();
if (types.length == 0 || !types[0].getName().equals("imagej.legacy.LegacyService")) {
throw new UnsupportedOperationException("Method " + method + " of class " + patchClass + " has wrong type!");
}
} catch (NotFoundException e) {
e.printStackTrace();
}
final StringBuilder newCode =
new StringBuilder((isVoid ? "" : "return ") + patchClass + "." + methodName + "(");
newCode.append("$service");
if (!isStatic) {
newCode.append(", this");
}
final int argCount = getMethodArgTypes(methodSig).length;
for (int i = 1; i <= argCount; i++) {
newCode.append(", $" + i);
}
newCode.append(");");
return newCode.toString();
}
/** Patches in the current legacy service for '$service' */
private String expand(final String code) {
return code
.replace("$isLegacyMode()", "$service.isLegacyMode()")
.replace("$service", "ij.IJ.getLegacyService()");
}
/** Extracts the method name from the given method signature. */
private String getMethodName(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final int spaceIndex = methodSig.lastIndexOf(" ", parenIndex);
return methodSig.substring(spaceIndex + 1, parenIndex);
}
private String[] getMethodArgTypes(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodArgs =
methodSig.substring(parenIndex + 1, methodSig.length() - 1);
final String[] args =
methodArgs.equals("") ? new String[0] : methodArgs.split(",");
for (int i = 0; i < args.length; i++) {
args[i] = args[i].trim().split(" ")[0];
}
return args;
}
/** Returns true if the given method signature is static. */
private boolean isStatic(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
for (final String token : methodPrefix.split(" ")) {
if (token.equals("static")) return true;
}
return false;
}
/** Returns true if the given method signature returns void. */
private boolean isVoid(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
return methodPrefix.startsWith("void ") ||
methodPrefix.indexOf(" void ") > 0;
}
/**
* Determines whether the specified class has the specified field.
*
* @param fullName the class name
* @param fieldName the field name
* @return whether the field exists
*/
public boolean hasField(final String fullName, final String fieldName) {
final CtClass clazz = getClass(fullName);
try {
return clazz.getField(fieldName) != null;
} catch (NotFoundException e) {
return false;
}
}
/**
* Determines whether the specified class is known to Javassist.
*
* @param fullClass
* the class name
* @return whether the class exists
*/
public boolean existsClass(final String fullClass) {
try {
return pool.get(fullClass) != null;
} catch (NotFoundException e) {
return false;
}
}
public boolean hasSuperclass(final String fullClass, final String fullSuperclass) {
try {
final CtClass clazz = getClass(fullClass);
return fullSuperclass.equals(clazz.getSuperclass().getName());
} catch (final Throwable e) {
return false;
}
}
private static int verboseLevel = 0;
private static CtMethod makeStubMethod(CtClass clazz, CtMethod original) throws CannotCompileException, NotFoundException {
// add a stub
String prefix = "";
if (verboseLevel > 0) {
prefix = "System.err.println(\"Called " + original.getLongName() + "\\n\"";
if (verboseLevel > 1) {
prefix += "+ \"\\t(\" + fiji.Headless.toString($args) + \")\\n\"";
}
prefix += ");";
}
CtClass type = original.getReturnType();
String body = "{" +
prefix +
(type == CtClass.voidType ? "" : "return " + defaultReturnValue(type) + ";") +
"}";
CtClass[] types = original.getParameterTypes();
return CtNewMethod.make(type, original.getName(), types, new CtClass[0], body, clazz);
}
private static String defaultReturnValue(CtClass type) {
return (type == CtClass.booleanType ? "false" :
(type == CtClass.byteType ? "(byte)0" :
(type == CtClass.charType ? "'\0'" :
(type == CtClass.doubleType ? "0.0" :
(type == CtClass.floatType ? "0.0f" :
(type == CtClass.intType ? "0" :
(type == CtClass.longType ? "0l" :
(type == CtClass.shortType ? "(short)0" : "null"))))))));
}
private void addMissingMethods(CtClass fakeClass, CtClass originalClass) throws CannotCompileException, NotFoundException {
if (verboseLevel > 0)
System.err.println("adding missing methods from " + originalClass.getName() + " to " + fakeClass.getName());
Set<String> available = new HashSet<String>();
for (CtMethod method : fakeClass.getMethods())
available.add(stripPackage(method.getLongName()));
for (CtMethod original : originalClass.getDeclaredMethods()) {
if (available.contains(stripPackage(original.getLongName()))) {
if (verboseLevel > 1)
System.err.println("Skipping available method " + original);
continue;
}
CtMethod method = makeStubMethod(fakeClass, original);
fakeClass.addMethod(method);
if (verboseLevel > 1)
System.err.println("adding missing method " + method);
}
// interfaces
Set<CtClass> availableInterfaces = new HashSet<CtClass>();
for (CtClass iface : fakeClass.getInterfaces())
availableInterfaces.add(iface);
for (CtClass iface : originalClass.getInterfaces())
if (!availableInterfaces.contains(iface))
fakeClass.addInterface(iface);
CtClass superClass = originalClass.getSuperclass();
if (superClass != null && !superClass.getName().equals("java.lang.Object"))
addMissingMethods(fakeClass, superClass);
}
private void letSuperclassMethodsOverride(CtClass clazz) throws CannotCompileException, NotFoundException {
for (CtMethod method : clazz.getSuperclass().getDeclaredMethods()) {
CtMethod method2 = clazz.getMethod(method.getName(), method.getSignature());
if (method2.getDeclaringClass().equals(clazz)) {
method2.setBody(method, null); // make sure no calls/accesses to GUI components are remaining
method2.setName("narf" + method.getName());
}
}
}
private static String stripPackage(String className) {
int lastDot = -1;
for (int i = 0; ; i++) {
if (i >= className.length())
return className.substring(lastDot + 1);
char c = className.charAt(i);
if (c == '.' || c == '$')
lastDot = i;
else if (c >= 'A' && c <= 'Z')
; // continue
else if (c >= 'a' && c <= 'z')
; // continue
else if (i > lastDot + 1 && c >= '0' && c <= '9')
; // continue
else
return className.substring(lastDot + 1);
}
}
private void skipAWTInstantiations(CtClass clazz) throws CannotCompileException, NotFoundException {
clazz.instrument(new ExprEditor() {
@Override
public void edit(NewExpr expr) throws CannotCompileException {
String name = expr.getClassName();
if (name.startsWith("java.awt.Menu") || name.equals("java.awt.PopupMenu") ||
name.startsWith("java.awt.Checkbox") || name.equals("java.awt.Frame")) {
expr.replace("$_ = null;");
} else if (expr.getClassName().equals("ij.gui.StackWindow")) {
expr.replace("$1.show(); $_ = null;");
}
}
@Override
public void edit(MethodCall call) throws CannotCompileException {
final String className = call.getClassName();
final String methodName = call.getMethodName();
if (className.startsWith("java.awt.Menu") || className.equals("java.awt.PopupMenu") ||
className.startsWith("java.awt.Checkbox")) try {
CtClass type = call.getMethod().getReturnType();
if (type == CtClass.voidType) {
call.replace("");
} else {
call.replace("$_ = " + defaultReturnValue(type) + ";");
}
} catch (NotFoundException e) {
e.printStackTrace();
} else if (methodName.equals("put") && className.equals("java.util.Properties")) {
call.replace("if ($1 != null && $2 != null) $_ = $0.put($1, $2); else $_ = null;");
} else if (methodName.equals("get") && className.equals("java.util.Properties")) {
call.replace("$_ = $1 != null ? $0.get($1) : null;");
} else if (className.equals("java.lang.Integer") && methodName.equals("intValue")) {
call.replace("$_ = $0 == null ? 0 : $0.intValue();");
} else if (methodName.equals("addTextListener")) {
call.replace("");
} else if (methodName.equals("elementAt")) {
call.replace("$_ = $0 == null ? null : $0.elementAt($$);");
}
}
});
}
public void handleHTTPS(final String fullClass, final String methodSig) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
try {
if (call.getMethodName().equals("startsWith") &&
"http://".equals(getLastConstantArgument(call, 0)))
call.replace("$_ = $0.startsWith($1) || $0.startsWith(\"https:
} catch (BadBytecode e) {
e.printStackTrace();
}
}
});
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Could not handle HTTPS in " + methodSig + " in " + fullClass);
}
}
private String getLastConstantArgument(final MethodCall call, final int skip) throws BadBytecode {
final int[] indices = new int[skip + 1];
int counter = 0;
final MethodInfo info = ((CtMethod)call.where()).getMethodInfo();
final CodeIterator iterator = info.getCodeAttribute().iterator();
int currentPos = call.indexOfBytecode();
while (iterator.hasNext()) {
int pos = iterator.next();
if (pos >= currentPos)
break;
switch (iterator.byteAt(pos)) {
case Opcode.LDC:
indices[(counter++) % indices.length] = iterator.byteAt(pos + 1);
break;
case Opcode.LDC_W:
indices[(counter++) % indices.length] = iterator.u16bitAt(pos + 1);
break;
}
}
if (counter < skip) {
return null;
}
counter %= indices.length;
if (skip > 0) {
counter -= skip;
if (counter < 0) counter += indices.length;
}
return info.getConstPool().getStringInfo(indices[counter]);
}
/**
* Disassembles all methods of a class.
*
* @param fullName
* the class name
* @param out
* the output stream
*/
public void disassemble(final String fullName, final PrintStream out) {
disassemble(fullName, out, false);
}
/**
* Disassembles all methods of a class, optionally including superclass
* methods.
*
* @param fullName
* the class name
* @param out
* the output stream
* @param evenSuperclassMethods
* whether to disassemble methods defined in superclasses
*/
public void disassemble(final String fullName, final PrintStream out, final boolean evenSuperclassMethods) {
CtClass clazz = getClass(fullName);
out.println("Class " + clazz.getName());
for (CtConstructor ctor : clazz.getConstructors()) {
disassemble(ctor, out);
}
for (CtMethod method : clazz.getDeclaredMethods())
if (evenSuperclassMethods || method.getDeclaringClass().equals(clazz))
disassemble(method, out);
}
private void disassemble(CtBehavior method, PrintStream out) {
out.println(method.getLongName());
MethodInfo info = method.getMethodInfo2();
ConstPool pool = info.getConstPool();
CodeAttribute code = info.getCodeAttribute();
if (code == null)
return;
CodeIterator iterator = code.iterator();
while (iterator.hasNext()) {
int pos;
try {
pos = iterator.next();
} catch (BadBytecode e) {
throw new RuntimeException(e);
}
out.println(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool));
}
out.println("");
}
/**
* Writes a .jar file with the modified classes.
*
* <p>
* This comes in handy e.g. when ImageJ is to be run in an environment where
* redefining classes is not allowed. If users need to run, say, the legacy
* headless support in such an environment, they need to generate a
* <i>headless.jar</i> file using this method and prepend it to the class
* path (so that the classes of <i>ij.jar</i> are overridden by
* <i>headless.jar</i>'s classes).
* </p>
*
* @param path
* the <i>.jar</i> file to write to
* @throws IOException
*/
public void writeJar(final File path) throws IOException {
final JarOutputStream jar = new JarOutputStream(new FileOutputStream(path));
final DataOutputStream dataOut = new DataOutputStream(jar);
for (final CtClass clazz : handledClasses) {
final ZipEntry entry = new ZipEntry(clazz.getName().replace('.', '/') + ".class");
jar.putNextEntry(entry);
clazz.getClassFile().write(dataOut);
dataOut.flush();
}
jar.close();
}
private void verify(CtClass clazz, PrintWriter output) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(stream);
clazz.getClassFile().write(out);
out.flush();
out.close();
verify(stream.toByteArray(), output);
} catch(Exception e) {
e.printStackTrace();
}
}
private void verify(byte[] bytecode, PrintWriter out) {
try {
Collection<URL> urls;
urls = FileUtils.listContents(new File(System.getProperty("user.home"), "fiji/jars/").toURI().toURL());
if (urls.size() == 0) {
urls = FileUtils.listContents(new File(System.getProperty("user.home"), "Fiji.app/jars/").toURI().toURL());
if (urls.size() == 0) {
urls = FileUtils.listContents(new File("/Applications/Fiji.app/jars/").toURI().toURL());
}
}
ClassLoader loader = new java.net.URLClassLoader(urls.toArray(new URL[urls.size()]));
Class<?> readerClass = null, checkerClass = null;
for (final String prefix : new String[] { "org.", "jruby.", "org.jruby.org." }) try {
readerClass = loader.loadClass(prefix + "objectweb.asm.ClassReader");
checkerClass = loader.loadClass(prefix + "objectweb.asm.util.CheckClassAdapter");
break;
} catch (ClassNotFoundException e) { /* ignore */ }
java.lang.reflect.Constructor<?> ctor = readerClass.getConstructor(new Class[] { bytecode.getClass() });
Object reader = ctor.newInstance(bytecode);
java.lang.reflect.Method verify = checkerClass.getMethod("verify", new Class[] { readerClass, Boolean.TYPE, PrintWriter.class });
verify.invoke(null, new Object[] { reader, false, out });
} catch (Throwable e) {
if (e.getClass().getName().endsWith(".AnalyzerException")) {
final Pattern pattern = Pattern.compile("Error at instruction (\\d+): Argument (\\d+): expected L([^ ,;]+);, but found L(.*);");
final Matcher matcher = pattern.matcher(e.getMessage());
if (matcher.matches()) {
final CtClass clazz1 = getClass(matcher.group(3));
final CtClass clazz2 = getClass(matcher.group(4));
try {
if (clazz2.subtypeOf(clazz1)) return;
} catch (NotFoundException e1) {
e1.printStackTrace();
}
}
}
e.printStackTrace();
}
}
protected void verify(PrintWriter out) {
out.println("Verifying " + handledClasses.size() + " classes");
for (final CtClass clazz : handledClasses) {
out.println("Verifying class " + clazz.getName());
out.flush();
verify(clazz, out);
}
}
/**
* Applies legacy patches, optionally including the headless ones.
*
* <p>
* Intended to be used in unit tests only, for newly-created class loaders,
* via reflection.
* </p>
*
* @param forceHeadless
* also apply the headless patches
*/
@SuppressWarnings("unused")
private static void patch(final boolean forceHeadless) {
final ClassLoader loader = CodeHacker.class.getClassLoader();
final CodeHacker hacker = new CodeHacker(loader, new ClassPool(false));
if (forceHeadless) {
new LegacyHeadless(hacker).patch();
}
new LegacyInjector().injectHooks(hacker);
hacker.loadClasses();
}
} |
package org.biojava.bio.search;
import org.biojava.bio.seq.StrandedFeature.Strand;
import org.biojava.bio.symbol.Alignment;
import org.biojava.utils.ChangeListener;
import org.biojava.utils.ObjectUtil;
import org.biojava.utils.contract.Contract;
/**
* <code>SequenceDBSearchSubHit</code> objects.
*
* @author <a href="mailto:kdj@sanger.ac.uk">Keith James</a>
* @since 1.1
* @see SeqSimilaritySearchSubHit
*/
public class SequenceDBSearchSubHit implements SeqSimilaritySearchSubHit
{
private double score;
private double pValue;
private double eValue;
private int queryStart;
private int queryEnd;
private Strand queryStrand;
private int subjectStart;
private int subjectEnd;
private Strand subjectStrand;
private Alignment alignment;
/**
* Creates a new <code>SequenceDBSearchSubHit</code> object.
*
* @param queryStart an <code>int</code> value indicating the
* start coordinate of the hit on the query sequence.
* @param queryEnd an <code>int</code> value indicating the end
* coordinate of the hit on the query sequence.
* @param queryStrand a <code>Strand</code> object indicating the
* strand of the hit with respect to the query sequence, which may
* be null for protein similarities.
* @param subjectStart an <code>int</code> value indicating the
* start coordinate of the hit on the subject sequence.
* @param subjectEnd an <code>int</code> value indicating the end
* coordinate of the hit on the query sequence.
* @param subjectStrand a <code>Strand</code> object indicating
* the strand of the hit with respect to the query sequence, which
* may be null for protein similarities.
* @param score a <code>double</code> value; the score of the
* subhit, which may not be NaN.
* @param eValue a <code>double</code> the E-value of the
* subhit, which may be NaN.
* @param pValue a <code>double</code> value; the P-value of the
* hit, which may be NaN.
* @param alignment an <code>Alignment</code> object containing
* the alignment described by the subhit region, which may not be
* null.
*/
public SequenceDBSearchSubHit(final double score,
final double eValue,
final double pValue,
final int queryStart,
final int queryEnd,
final Strand queryStrand,
final int subjectStart,
final int subjectEnd,
final Strand subjectStrand,
final Alignment alignment)
{
Contract.pre(! Double.isNaN(score), "score was NaN");
// pValue may be NaN
// eValue may be NaN
Contract.pre(alignment != null, "alignment was null");
this.score = score;
this.eValue = eValue;
this.pValue = pValue;
this.queryStart = queryStart;
this.queryEnd = queryEnd;
this.queryStrand = queryStrand;
this.subjectStart = subjectStart;
this.subjectEnd = subjectEnd;
this.subjectStrand = subjectStrand;
this.alignment = alignment;
// Lock alignment by vetoing all changes
this.alignment.addChangeListener(ChangeListener.ALWAYS_VETO);
}
public double getScore()
{
return score;
}
public double getPValue()
{
return pValue;
}
public double getEValue()
{
return eValue;
}
public int getQueryStart()
{
return queryStart;
}
public int getQueryEnd()
{
return queryEnd;
}
public Strand getQueryStrand()
{
return queryStrand;
}
public int getSubjectStart()
{
return subjectStart;
}
public int getSubjectEnd()
{
return subjectEnd;
}
public Strand getSubjectStrand()
{
return subjectStrand;
}
public Alignment getAlignment()
{
return alignment;
}
public String toString()
{
return "SequenceDBSearchSubHit with score " + getScore();
}
public boolean equals(final Object other)
{
if (other == this) return true;
if (other == null) return false;
// Eliminate other if its class is not the same
if (! other.getClass().equals(this.getClass())) return false;
// Downcast and compare fields
SequenceDBSearchSubHit that = (SequenceDBSearchSubHit) other;
if (! ObjectUtil.equals(this.score, that.score))
return false;
if (! ObjectUtil.equals(this.pValue, that.pValue))
return false;
if (! ObjectUtil.equals(this.eValue, that.eValue))
return false;
if (! ObjectUtil.equals(this.queryStart, that.queryStart))
return false;
if (! ObjectUtil.equals(this.queryEnd, that.queryEnd))
return false;
if (! ObjectUtil.equals(this.queryStrand, that.queryStrand))
return false;
if (! ObjectUtil.equals(this.subjectStart, that.subjectStart))
return false;
if (! ObjectUtil.equals(this.subjectEnd, that.subjectEnd))
return false;
if (! ObjectUtil.equals(this.subjectStrand, that.subjectStrand))
return false;
return true;
}
public int hashCode()
{
int hc = 0;
hc = ObjectUtil.hashCode(hc, score);
hc = ObjectUtil.hashCode(hc, pValue);
hc = ObjectUtil.hashCode(hc, eValue);
hc = ObjectUtil.hashCode(hc, queryStart);
hc = ObjectUtil.hashCode(hc, queryEnd);
hc = ObjectUtil.hashCode(hc, queryStrand);
hc = ObjectUtil.hashCode(hc, subjectStart);
hc = ObjectUtil.hashCode(hc, subjectEnd);
hc = ObjectUtil.hashCode(hc, subjectStrand);
return hc;
}
} |
package org.broad.igv.renderer;
import org.apache.log4j.Logger;
import org.broad.igv.feature.*;
import org.broad.igv.track.FeatureTrack;
import org.broad.igv.track.RenderContext;
import org.broad.igv.ui.FontManager;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.GeneralPath;
import java.util.List;
/**
* Renderer for splice junctions. Draws a filled-in arc for each junction, with the width of the
* arc representing the depth of coverage
*
* @author dhmay
*/
public class SpliceJunctionRenderer extends IGVFeatureRenderer {
private static Logger log = Logger.getLogger(SpliceJunctionRenderer.class);
//color for drawing all arcs
Color ARC_COLOR_POS = new Color(50, 50, 150, 140); //transparent dull blue
Color ARC_COLOR_NEG = new Color(150, 50, 50, 140); //transparent dull red
//maximum depth that can be displayed, due to track height limitations. Junctions with
//this depth and deeper will all look the same
protected int MAX_DEPTH = 50;
/**
* Note: assumption is that featureList is sorted by pStart position.
*
* @param featureList
* @param context
* @param trackRectangle
* @param track
*/
public void renderFeatures(List<IGVFeature> featureList,
RenderContext context,
Rectangle trackRectangle,
FeatureTrack track) {
double origin = context.getOrigin();
double locScale = context.getScale();
// Clear values
lastFeatureLineMaxY = 0;
lastFeatureBoundsMaxY = 0;
lastRegionMaxY = 0;
// TODO -- use enum instead of string "Color"
if ((featureList != null) && (featureList.size() > 0)) {
// Create a graphics object to draw font names. Graphics are not cached
// by font, only by color, so its neccessary to create a new one to prevent
// affecting other tracks.
font = FontManager.getScalableFont(track.getFontSize());
Graphics2D fontGraphics = (Graphics2D) context.getGraphic2DForColor(Color.BLACK).create();
fontGraphics.setFont(font);
// Track coordinates
double trackRectangleX = trackRectangle.getX();
double trackRectangleMaxX = trackRectangle.getMaxX();
double trackRectangleMaxY = trackRectangle.getMaxY();
// Draw the lines that represent the bounds of
// a feature's region
// TODO -- bugs in "Line Placement" style -- hardocde to fishbone
int lastPixelEnd = -1;
int occludedCount = 0;
int maxOcclusions = 2;
IGVFeature featureArray[] = featureList.toArray(new IGVFeature[featureList.size()]);
for (IGVFeature feature : featureArray) {
// Get the pStart and pEnd of the entire feature. at extreme zoom levels the
// virtual pixel value can be too large for an int, so the computation is
// done in double precision and cast to an int only when its confirmed its
// within the field of view.
double virtualPixelStart = Math.round((feature.getStart() - origin) / locScale);
double virtualPixelEnd = Math.round((feature.getEnd() - origin) / locScale);
// If the any part of the feature fits in the
// Track rectangle draw it
if ((virtualPixelEnd >= trackRectangleX) && (virtualPixelStart <= trackRectangleMaxX)) {
int displayPixelEnd = (int) Math.min(trackRectangleMaxX, virtualPixelEnd);
int displayPixelStart = (int) Math.max(trackRectangleX, virtualPixelStart);
if (displayPixelEnd <= lastPixelEnd) {
if (occludedCount >= maxOcclusions) {
continue;
} else {
occludedCount++;
}
} else {
occludedCount = 0;
lastPixelEnd = displayPixelEnd;
}
// Junction read depth is modeled as score in BasicFeature
float depth = 1;
if (feature instanceof BasicFeature) {
BasicFeature bf = (BasicFeature) feature;
depth = bf.getScore();
}
//Transform the depth into a number of pixels to use as the arc width
int pixelDepth = Math.max(1,(int)
((Math.min(depth, MAX_DEPTH) / MAX_DEPTH) * trackRectangle.getHeight()));
drawFeatureFilledArc((int) virtualPixelStart, (int) virtualPixelEnd, pixelDepth,
trackRectangle, context, feature.getStrand());
// Determine the y offset of features based on strand type
// If the width is < 3 there isn't room to draw the
// feature, or orientation. If the feature has any exons
// at all indicate by filling a small rect
int pixelYCenter = trackRectangle.y + NORMAL_STRAND_Y_OFFSET / 2;
// If this is the highlight feature highlight it
if (getHighlightFeature() == feature) {
int yStart = pixelYCenter - BLOCK_HEIGHT / 2 - 1;
Graphics2D highlightGraphics = context.getGraphic2DForColor(Color.cyan);
highlightGraphics.drawRect(displayPixelStart - 1, yStart,
(displayPixelEnd - displayPixelStart + 2), BLOCK_HEIGHT + 2);
}
}
}
if (drawBoundary) {
Graphics2D g2D = context.getGraphic2DForColor(Color.LIGHT_GRAY);
g2D.drawLine((int) trackRectangleX, (int) trackRectangleMaxY - 1,
(int) trackRectangleMaxX, (int) trackRectangleMaxY - 1);
}
}
}
/**
* Draw a filled arc representing a single feature
* @param pixelStart the starting position of the feature, whether on-screen or not
* @param pixelEnd the ending position of the feature, whether on-screen or not
* @param pixelDepth the width of the arc, in pixels
* @param trackRectangle
*/
final private void drawFeatureFilledArc(int pixelStart, int pixelEnd, int pixelDepth,
Rectangle trackRectangle, RenderContext context, Strand strand) {
boolean isPositiveStrand = true;
// Get the feature's direction, color appropriately
if (strand != null && strand.equals(Strand.NEGATIVE))
isPositiveStrand = false;
Color color = isPositiveStrand ? ARC_COLOR_POS : ARC_COLOR_NEG;
Graphics2D g2D = context.getGraphic2DForColor(color);
//Create a path describing the arc, using Bezier curves. The Bezier control points for the top and
//bottom arcs are simply the boundary points of the rectangles containing the arcs
//Height of top of the arc
int outerArcHeight = trackRectangle.height;
//Height of bottom of the arc
int innerArcHeight = Math.max(Math.max(1,outerArcHeight / 10), outerArcHeight - pixelDepth);
int arcBeginY = isPositiveStrand ?
(int) trackRectangle.getMaxY() :
(int) trackRectangle.getMinY();
int outerArcPeakY = isPositiveStrand ?
arcBeginY - outerArcHeight :
arcBeginY + outerArcHeight;
int innerArcPeakY = isPositiveStrand ?
arcBeginY - innerArcHeight :
arcBeginY + innerArcHeight;
GeneralPath arcPath = new GeneralPath();
arcPath.moveTo(pixelStart, arcBeginY);
arcPath.curveTo(pixelStart, outerArcPeakY, //Bezier 1
pixelEnd, outerArcPeakY, //Bezier 2
pixelEnd, arcBeginY); //Arc end
arcPath.curveTo(pixelEnd, innerArcPeakY, //Bezier 1
pixelStart, innerArcPeakY, //Bezier 2
pixelStart, arcBeginY); //Arc end
//Draw the arc, to ensure outline is drawn completely (fill won't do it, necessarily). This will also
//give the arc a darker outline
g2D.draw(arcPath);
//Fill the arc
g2D.fill(arcPath);
lastFeatureLineMaxY = Math.max(outerArcPeakY, arcBeginY);
}
} |
package org.encog.neural.networks.layers;
import org.encog.neural.activation.ActivationFunction;
import org.encog.neural.activation.ActivationTANH;
import org.encog.neural.data.NeuralData;
import org.encog.neural.data.basic.BasicNeuralData;
import org.encog.neural.networks.ContextClearable;
import org.encog.persist.Persistor;
import org.encog.persist.persistors.ContextLayerPersistor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implements a context layer. A context layer is used to implement a simple
* recurrent neural network, such as an Elman or Jordan neural network. The
* context layer has a short-term memory. The context layer accept input, and
* provide the same data as output on the next cycle. This continues, and the
* context layer's output "one step" out of sync with the input.
*
* @author jheaton
*
*/
public class ContextLayer extends BasicLayer implements ContextClearable {
/**
* The serial id.
*/
private static final long serialVersionUID = -5588659547177460637L;
/**
* The context data that this layer will store.
*/
private final NeuralData context;
/**
* The logging object.
*/
private static final transient Logger LOGGER =
LoggerFactory.getLogger(ContextLayer.class);
/**
* Default constructor, mainly so the workbench can easily create a default
* layer.
*/
public ContextLayer() {
this(1);
}
/**
* Construct a context layer with the parameters specified.
*
* @param thresholdFunction
* The threshold function to use.
* @param hasThreshold
* Does this layer have thresholds?
* @param neuronCount
* The neuron count to use.
*/
public ContextLayer(final ActivationFunction thresholdFunction,
final boolean hasThreshold, final int neuronCount) {
super(thresholdFunction, hasThreshold, neuronCount);
this.context = new BasicNeuralData(neuronCount);
}
/**
* Construct a default context layer that has the TANH activation function
* and the specified number of neurons. Use threshold values.
*
* @param neuronCount
* The number of neurons on this layer.
*/
public ContextLayer(final int neuronCount) {
this(new ActivationTANH(), true, neuronCount);
}
/**
* Create a persistor for this layer.
*
* @return The new persistor.
*/
@Override
public Persistor createPersistor() {
return new ContextLayerPersistor();
}
/**
* @return The context, or memory of this layer. These will be the values
* that were just output.
*/
public NeuralData getContext() {
return this.context;
}
/**
* Called to process input from the previous layer. Simply store the output
* in the context.
*
* @param pattern
* The pattern to store in the context.
*/
@Override
public void process(final NeuralData pattern) {
double[] s = pattern.getData();
double[] t = this.context.getData();
System.arraycopy(s, 0, t, 0, s.length);
if (ContextLayer.LOGGER.isDebugEnabled()) {
ContextLayer.LOGGER.debug("Updated ContextLayer to {}", pattern);
}
}
/**
* Called to get the output from this layer when called in a recurrent
* manor. Simply return the context that was kept from the last iteration.
*
* @return The recurrent output.
*/
@Override
public NeuralData recur() {
return this.context;
}
/**
* Reset the context values back to zero.
*/
public void clearContext() {
for(int i =0;i<this.context.size();i++ ) {
this.context.setData(i, 0);
}
}
} |
package com.ame.bus3.common.packetsorters;
import com.ame.bus3.common.Connection;
import com.ame.bus3.common.Coordinate;
import com.ame.bus3.common.PacketSorterTracker;
import com.ame.bus3.common.Tile;
import com.ame.bus3.common.Tiles.Wall;
import com.ame.bus3.common.Variables;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
* Gets a tile from the server.
* @author Amelorate
*/
public class GetTile implements PacketSorter {
public GetTile() {
PacketSorterTracker.register("GetTile", this);
}
@Override
public void sort(JSONObject packet, Connection sending) {
try {
Coordinate location = new Coordinate((JSONObject) packet.get("location"));
Tile getting;
while (true) {
getting = Variables.map.get(location);
if (getting == null && location.z != 0)
break;
else if (getting == null && location.z == 0) { // TODO: Replace placing a wall tile with a gamemodecontroler place tile call when that is added.
Variables.map.place(new Wall(), location);
}
SorterList.placeTile.send(sending, getting);
location.z++;
}
SorterList.waitUntill.send(sending, "got");
}
catch (ClassCastException e) {
System.out.println("[Error] Malformed packet. Full packet text: \n" + packet.toString());
}
}
/**
* Gets a tile from the server.
*/
@SuppressWarnings("unchecked")
public void send(Connection connection, Coordinate location) {
JSONArray packet = new JSONArray();
JSONObject innerPacket = new JSONObject();
innerPacket.put("sorter", "GetTile");
innerPacket.put("location", location);
packet.add(innerPacket);
connection.send(packet);
}
} |
package org.exist.xquery.functions.util;
import org.apache.log4j.Logger;
import org.exist.dom.QName;
import org.exist.xquery.Cardinality;
import org.exist.xquery.Function;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.LocalVariable;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
/**
* @author wolf
*/
public class CatchFunction extends Function {
protected static final Logger logger = Logger.getLogger(CatchFunction.class);
public final static FunctionSignature signature =
new FunctionSignature(
new QName("catch", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"This function corresponds to a try-catch statement in Java. The code block " +
"in $try-code-blocks will be put inside a try-catch statement. If an exception " +
"is thrown while executing $try-code-blocks, the function checks the name of " +
"the exception and calls $catch-code-blocks if it matches one of " +
"the fully qualified Java class names specified in $java-classnames. " +
"A value of \"*\" in $java-classnames will catch all java exceptions",
new SequenceType[] {
new FunctionParameterSequenceType("java-classnames", Type.STRING, Cardinality.ONE_OR_MORE, "The list of one or more fully qualified Java class names. An entry of '*' will catch all java exceptions."),
new FunctionParameterSequenceType("try-code-blocks", Type.ITEM, Cardinality.ZERO_OR_MORE, "The code blocks that will be put inside of a the try part of the try-catch statement."),
new FunctionParameterSequenceType("catch-code-blocks", Type.ITEM, Cardinality.ZERO_OR_MORE, "The code blocks that will be will called if the catch matches one of the $java-classnames")
},
new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE, "the results from the try-catch"));
/**
* @param context
*/
public CatchFunction(XQueryContext context) {
super(context, signature);
}
/* (non-Javadoc)
* @see org.exist.xquery.Function#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
*/
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
Sequence exceptionClasses = getArgument(0).eval(contextSequence, contextItem);
try {
context.pushDocumentContext();
LocalVariable mark = context.markLocalVariables(false);
try {
return getArgument(1).eval(contextSequence, contextItem);
} finally {
context.popDocumentContext();
context.popLocalVariables(mark);
}
} catch(Exception e) {
logger.debug("Caught exception in util:catch: " + e.getMessage());
if (!(e instanceof XPathException)) {
logger.warn("Exception: " + e.getMessage(), e);
}
// context.popDocumentContext();
context.getWatchDog().reset();
for(SequenceIterator i = exceptionClasses.iterate(); i.hasNext(); ) {
Item next = i.nextItem();
try {
String exClassName = next.getStringValue();
Class exClass = null;
if( !exClassName.equals( "*" ) ) {
exClass = Class.forName(next.getStringValue());
}
if( exClassName.equals( "*" ) || exClass.getName().equals( e.getClass().getName() ) || exClass.isInstance(e) ) {
logger.debug("Calling exception handler to process " + e.getClass().getName());
UtilModule myModule =
(UtilModule) context.getModule(UtilModule.NAMESPACE_URI);
myModule.declareVariable(UtilModule.EXCEPTION_QNAME, new StringValue(e.getClass().getName()));
myModule.declareVariable(UtilModule.EXCEPTION_MESSAGE_QNAME, new StringValue(e.getMessage()));
return getArgument(2).eval(contextSequence, contextItem);
}
} catch (Exception e2) {
if (e2 instanceof XPathException) {
throw (XPathException) e2;
} else {
throw new XPathException(this, "Error in exception handler: " + e2.getMessage(), e);
}
}
}
// this type of exception is not caught: throw again
if(e instanceof XPathException)
throw (XPathException)e;
throw new XPathException(this, e.getMessage(), e);
}
}
/* (non-Javadoc)
* @see org.exist.xquery.Function#returnsType()
*/
public int returnsType() {
return getArgument(1).returnsType();
}
/* (non-Javadoc)
* @see org.exist.xquery.Function#getCardinality()
*/
public int getCardinality() {
return getArgument(1).getCardinality();
}
} |
package com.github.mizool.core;
import java.time.Duration;
import javax.annotation.concurrent.ThreadSafe;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import com.google.common.base.Stopwatch;
/**
* Helper class to allow for something to happen at regular intervals. A common use case might be invalidation of
* in-memory data.<br>
* <br>
* Example to invalidate a cache every minute:
* <pre>
* {@code
* private final Interval cacheInvalidationInterval = new Interval(Duration.ofMinutes(1));
*
* ...
*
* cacheInvalidationInterval.runIfDue(this::invalidateCache);
* }
* </pre>
*/
@ThreadSafe
@RequiredArgsConstructor
public class Interval
{
private final Stopwatch stopwatch = Stopwatch.createStarted();
private final Duration duration;
/**
* Executes the {@code runnable} if the interval is due or <i>past due</i>. The next full interval is started after
* completion of the runnable.
*
* @return {@code true} if the operation was due and the runnable completed.
*/
@Synchronized
public boolean runIfDue(Runnable runnable)
{
boolean isReached = stopwatch.elapsed()
.compareTo(duration) > 0;
if (isReached)
{
stopwatch.reset();
runnable.run();
stopwatch.start();
}
return isReached;
}
} |
package com.s24.redjob.worker;
import org.springframework.util.Assert;
/**
* Wrapper for job runners which do not implement {@link Runnable}.
*/
public abstract class WrappingRunnable implements Runnable {
/**
* Job runner.
*/
private final Object runner;
/**
* Constructor.
*
* @param runner
* Job runner.
*/
public WrappingRunnable(Object runner) {
Assert.notNull(runner, "Pre-condition violated: runner != null.");
this.runner = runner;
}
/**
* Job runner.
*/
@SuppressWarnings("unchecked")
public <R> R unwrap() {
return (R) runner;
}
} |
package org.jitsi.videobridge.influxdb;
import org.ice4j.ice.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.util.*;
import org.jitsi.videobridge.*;
import org.jitsi.videobridge.eventadmin.*;
import org.json.simple.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Allows logging of {@link InfluxDBEvent}s using an
* <tt>InfluxDB</tt> instance.
*
* @author Boris Grozev
* @author George Politis
*/
public class LoggingHandler
implements EventHandler
{
/**
* The names of the columns of a "conference created" event.
*/
private static final String[] CONFERENCE_CREATED_COLUMNS
= new String[] {"conference_id", "focus"};
/**
* The names of the columns of a "conference expired" event.
*/
private static final String[] CONFERENCE_EXPIRED_COLUMNS
= new String[] {"conference_id"};
/**
* The names of the columns of a "content created" event.
*/
private static final String[] CONTENT_CREATED_COLUMNS
= new String[] {"name", "conference_id"};
/**
* The names of the columns of a "content expired" event.
*/
private static final String[] CONTENT_EXPIRED_COLUMNS
= new String[] {"name", "conference_id"};
/**
* The names of the columns of a "channel created" event.
*/
private static final String[] CHANNEL_CREATED_COLUMNS
= new String[]
{
"channel_id",
"content_name",
"conference_id",
"endpoint_id",
"lastn"
};
/**
* The names of the columns of a "rtp channel expired" event.
*/
private static final String[] RTP_CHANNEL_EXPIRED_COLUMNS
= new String[]
{
"channel_id",
"content_name",
"conference_id",
"stats.local_ip",
"stats.local_port",
"stats.remote_ip",
"stats.remote_port",
"stats.nb_received_bytes",
"stats.nb_sent_bytes",
"stats.nb_received_packets",
"stats.nb_received_packets_lost",
"stats.nb_sent_packets",
"stats.nb_sent_packets_lost",
"stats.min_download_jitter_ms",
"stats.max_download_jitter_ms",
"stats.avg_download_jitter_ms",
"stats.min_upload_jitter_ms",
"stats.max_upload_jitter_ms",
"stats.avg_upload_jitter_ms"
};
/**
* The names of the columns of a "channel expired" event.
*/
private static final String[] CHANNEL_EXPIRED_COLUMNS
= new String[]
{
"channel_id",
"content_name",
"conference_id",
};
/**
* The names of the columns of a "transport created" event.
*/
private static final String[] TRANSPORT_CREATED_COLUMNS
= new String[]
{
"hash_code",
"conference_id",
"num_components",
"ufrag",
"is_controlling"
};
/**
* The names of the columns of a "transport manager channel added" event.
*/
private static final String[] TRANSPORT_CHANNEL_ADDED_COLUMNS
= new String[]
{
"hash_code",
"conference_id",
"channel_id",
};
/**
* The names of the columns of a "transport manager channel removed" event.
*/
private static final String[] TRANSPORT_CHANNEL_REMOVED_COLUMNS
= new String[]
{
"hash_code",
"conference_id",
"channel_id",
};
/**
* The names of the columns of a "transport manager connected" event.
*/
private static final String[] TRANSPORT_CONNECTED_COLUMNS
= new String[]
{
"hash_code",
"conference_id",
"selected_pairs"
};
/**
* The names of the columns of a "transport manager connected" event.
*/
private static final String[] TRANSPORT_STATE_CHANGED_COLUMNS
= new String[]
{
"hash_code",
"conference_id",
"old_state",
"new_state"
};
/**
* The names of the columns of an "endpoint created" event.
*/
private static final String[] ENDPOINT_CREATED_COLUMNS
= new String[]
{
"conference_id",
"endpoint_id",
};
/**
* The names of the columns of an "endpoint display name" event.
*/
private static final String[] ENDPOINT_DISPLAY_NAME_COLUMNS
= new String[]
{
"conference_id",
"endpoint_id",
"display_name"
};
/**
* The name of the property which specifies whether logging to an
* <tt>InfluxDB</tt> is enabled.
*/
public static final String ENABLED_PNAME
= "org.jitsi.videobridge.log.INFLUX_DB_ENABLED";
/**
* The name of the property which specifies the protocol, hostname and
* port number (in URL format) to use to connect to <tt>InfluxDB</tt>.
*/
public static final String URL_BASE_PNAME
= "org.jitsi.videobridge.log.INFLUX_URL_BASE";
/**
* The name of the property which specifies the name of the
* <tt>InfluxDB</tt> database.
*/
public static final String DATABASE_PNAME
= "org.jitsi.videobridge.log.INFLUX_DATABASE";
/**
* The name of the property which specifies the username to use to connect
* to <tt>InfluxDB</tt>.
*/
public static final String USER_PNAME
= "org.jitsi.videobridge.log.INFLUX_USER";
/**
* The name of the property which specifies the password to use to connect
* to <tt>InfluxDB</tt>.
*/
public static final String PASS_PNAME
= "org.jitsi.videobridge.log.INFLUX_PASS";
/**
* The <tt>Logger</tt> used by the <tt>LoggingHandler</tt> class
* and its instances to print debug information.
*/
private static final Logger logger
= Logger.getLogger(LoggingHandler.class);
/**
* The <tt>Executor</tt> which is to perform the task of sending data to
* <tt>InfluxDB</tt>.
*/
private final Executor executor
= ExecutorUtils
.newCachedThreadPool(true, LoggingHandler.class.getName());
/**
* The <tt>URL</tt> to be used to POST to <tt>InfluxDB</tt>. Besides the
* protocol, host and port also encodes the database name, user name and
* password.
*/
private final URL url;
/**
* Initializes a new <tt>LoggingHandler</tt> instance, by reading
* its configuration from <tt>cfg</tt>.
* @param cfg the <tt>ConfigurationService</tt> to use.
*
* @throws Exception if initialization fails
*/
public LoggingHandler(ConfigurationService cfg)
throws Exception
{
if (cfg == null)
throw new NullPointerException("cfg");
String s = "Required property not set: ";
String urlBase = cfg.getString(URL_BASE_PNAME, null);
if (urlBase == null)
throw new Exception(s + URL_BASE_PNAME);
String database = cfg.getString(DATABASE_PNAME, null);
if (database == null)
throw new Exception(s + DATABASE_PNAME);
String user = cfg.getString(USER_PNAME, null);
if (user == null)
throw new Exception(s + USER_PNAME);
String pass = cfg.getString(PASS_PNAME, null);
if (pass == null)
throw new Exception(s + PASS_PNAME);
String urlStr
= urlBase + "/db/" + database + "/series?u=" + user +"&p=" +pass;
url = new URL(urlStr);
logger.info("Initialized InfluxDBLoggingService for " + urlBase
+ ", database \"" + database + "\"");
}
/**
* Logs an <tt>InfluxDBEvent</tt> to an <tt>InfluxDB</tt> database. This
* method returns without blocking, the blocking operations are performed
* by a thread from {@link #executor}.
*
* @param e the <tt>Event</tt> to log.
*/
@SuppressWarnings("unchecked")
protected void logEvent(InfluxDBEvent e)
{
// The following is a sample JSON message in the format used by InfluxDB
// "name": "series_name",
// "columns": ["column1", "column2"],
// "points": [
// ["value1", 1234],
// ["value2", 5678]
boolean useLocalTime = e.useLocalTime();
long now = System.currentTimeMillis();
boolean multipoint = false;
int pointCount = 1;
JSONArray columns = new JSONArray();
JSONArray points = new JSONArray();
Object[] values = e.getValues();
if (useLocalTime)
columns.add("time");
Collections.addAll(columns, e.getColumns());
if (values[0] instanceof Object[])
{
multipoint = true;
pointCount = values.length;
}
if (multipoint)
{
for (int i = 0; i < pointCount; i++)
{
if (!(values[i] instanceof Object[]))
continue;
JSONArray point = new JSONArray();
if (useLocalTime)
point.add(now);
Collections.addAll(point, (Object[]) values[i]);
points.add(point);
}
}
else
{
JSONArray point = new JSONArray();
if (useLocalTime)
point.add(now);
Collections.addAll(point, values);
points.add(point);
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", e.getName());
jsonObject.put("columns", columns);
jsonObject.put("points", points);
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObject);
// TODO: this is probably a good place to optimize by grouping multiple
// events in a single POST message and/or multiple points for events
// of the same type together).
final String jsonString = jsonArray.toJSONString();
executor.execute(new Runnable()
{
@Override
public void run()
{
sendPost(jsonString);
}
});
}
/**
* Sends the string <tt>s</tt> as the contents of an HTTP POST request to
* {@link #url}.
* @param s the content of the POST request.
*/
private void sendPost(final String s)
{
try
{
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type",
"application/json");
connection.setDoOutput(true);
DataOutputStream outputStream
= new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(s);
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode != 200)
throw new IOException("HTTP response code: "
+ responseCode);
}
catch (IOException ioe)
{
logger.info("Failed to post to influxdb: " + ioe);
}
}
/**
*
* @param conference
*/
private void conferenceCreated(Conference conference)
{
if (conference == null)
{
logger.debug("Could not log conference created event because " +
"the conference is null.");
return;
}
String focus = conference.getFocus();
logEvent(new InfluxDBEvent("conference_created",
CONFERENCE_CREATED_COLUMNS,
new Object[]{
conference.getID(),
focus != null ? focus : "null"
}));
}
/**
*
* @param conference
*/
private void conferenceExpired(Conference conference)
{
if (conference == null)
{
logger.debug("Could not log conference expired event because " +
"the conference is null.");
return;
}
logEvent(new InfluxDBEvent("conference_expired",
CONFERENCE_EXPIRED_COLUMNS,
new Object[]{
conference.getID()
}));
}
/**
*
* @param endpoint
*/
private void endpointCreated(Endpoint endpoint)
{
if (endpoint == null)
{
logger.debug("Could not log endpoint created event because " +
"the endpoint is null.");
return;
}
Conference conference = endpoint.getConference();
if (conference == null)
{
logger.debug("Could not log endpoint created event because " +
"the conference is null.");
return;
}
logEvent(new InfluxDBEvent("endpoint_created",
ENDPOINT_CREATED_COLUMNS,
new Object[]{
conference.getID(),
endpoint.getID()
}));
}
/**
*
* @param endpoint
*/
private void endpointDisplayNameChanged(Endpoint endpoint)
{
if (endpoint == null)
{
logger.debug("Could not log endpoint display name changed" +
" event because the endpoint is null.");
return;
}
Conference conference = endpoint.getConference();
if (conference == null)
{
logger.debug("Could not log endpoint display name changed " +
" event because the conference is null.");
return;
}
logEvent(new InfluxDBEvent("endpoint_display_name",
ENDPOINT_DISPLAY_NAME_COLUMNS,
new Object[]{
conference.getID(),
endpoint.getID(),
endpoint.getDisplayName()
}));
}
/**
*
* @param content
*/
private void contentCreated(Content content)
{
if (content == null)
{
logger.debug("Could not log content created event because " +
"the content is null.");
return;
}
Conference conference = content.getConference();
if (conference == null)
{
logger.debug("Could not log content created event because " +
"the conference is null.");
return;
}
logEvent(new InfluxDBEvent("content_created",
CONTENT_CREATED_COLUMNS,
new Object[] {
content.getName(),
conference.getID()
}));
}
/**
*
* @param content
*/
private void contentExpired(Content content)
{
if (content == null)
{
logger.debug("Could not log content expired event because " +
"the content is null.");
return;
}
Conference conference = content.getConference();
if (conference == null)
{
logger.debug("Could not log content expired event because " +
"the conference is null.");
return;
}
logEvent(new InfluxDBEvent("content_expired",
CONTENT_EXPIRED_COLUMNS,
new Object[] {
content.getName(),
conference.getID()
}));
}
private void transportChannelAdded(Channel channel)
{
TransportManager transportManager;
try
{
transportManager = channel.getTransportManager();
}
catch (IOException e)
{
logger.error("Could not log the transport channel added event " +
"because of an error.", e);
return;
}
Content content = channel.getContent();
if (content == null)
{
logger.debug("Could not log the transport channel added event " +
"because the content is null.");
return;
}
Conference conference = content.getConference();
if (conference == null)
{
logger.debug("Could not log the transport channel added event " +
"because the conference is null.");
return;
}
logEvent(new InfluxDBEvent("transport_channel_added",
TRANSPORT_CHANNEL_ADDED_COLUMNS,
new Object[]{
String.valueOf(transportManager.hashCode()),
conference.getID(),
channel.getID()
}));
}
/**
*
* @param channel
*/
private void transportChannelRemoved(Channel channel)
{
TransportManager transportManager;
try
{
transportManager = channel.getTransportManager();
}
catch (IOException e)
{
logger.error("Could not log the transport channel removed event " +
"because of an error.", e);
return;
}
Content content = channel.getContent();
if (content == null)
{
logger.debug("Could not log the transport channel removed event " +
"because the content is null.");
return;
}
Conference conference = content.getConference();
if (conference == null)
{
logger.debug("Could not log the transport channel removed event " +
"because the conference is null.");
return;
}
logEvent(new InfluxDBEvent("transport_channel_removed",
TRANSPORT_CHANNEL_REMOVED_COLUMNS,
new Object[] {
String.valueOf(transportManager.hashCode()),
conference.getID(),
channel.getID()
}));
}
/**
*
* @param transportManager
* @param oldState
* @param newState
*/
private void transportStateChanged(
IceUdpTransportManager transportManager,
IceProcessingState oldState,
IceProcessingState newState)
{
Conference conference = transportManager.getConference();
if (conference == null)
{
logger.debug("Could not log the transport state changed event " +
"because the conference is null.");
return;
}
logEvent(new InfluxDBEvent("transport_state_changed",
TRANSPORT_STATE_CHANGED_COLUMNS,
new Object[]{
String.valueOf(transportManager.hashCode()),
conference.getID(),
oldState == null ? "null" : oldState.toString(),
newState == null ? "null" : newState.toString()
}));
}
/**
*
* @param transportManager
*/
private void transportCreated(IceUdpTransportManager transportManager)
{
Conference conference = transportManager.getConference();
if (conference == null)
{
logger.debug("Could not log the transport created event " +
"because the conference is null.");
return;
}
Agent agent = transportManager.getAgent();
if (agent == null)
{
logger.debug("Could not log the transport created event " +
"because the agent is null.");
return;
}
logEvent(new InfluxDBEvent("transport_created",
TRANSPORT_CREATED_COLUMNS,
new Object[]{
String.valueOf(transportManager.hashCode()),
conference.getID(),
transportManager.getNumComponents(),
agent.getLocalUfrag(),
Boolean.valueOf(transportManager.isControlling()).toString()
}));
}
/**
*
* @param transportManager
*/
private void transportConnected(IceUdpTransportManager transportManager)
{
Conference conference = transportManager.getConference();
if (conference == null)
{
logger.debug("Could not log the transport connected event " +
"because the conference is null.");
return;
}
IceMediaStream iceStream = transportManager.getIceStream();
if (iceStream == null)
{
logger.debug("Could not log the transport connected event " +
"because the iceStream is null.");
return;
}
StringBuilder s = new StringBuilder();
for (Component component : iceStream.getComponents())
{
CandidatePair pair = component.getSelectedPair();
if (pair == null)
continue;
Candidate localCandidate = pair.getLocalCandidate();
Candidate remoteCandidate = pair.getRemoteCandidate();
s.append((localCandidate == null)
? "unknown" : localCandidate.getTransportAddress())
.append(" -> ")
.append((remoteCandidate == null)
? "unknown" : remoteCandidate.getTransportAddress())
.append("; ");
}
logEvent(new InfluxDBEvent("transport_connected",
TRANSPORT_CONNECTED_COLUMNS,
new Object[]{
String.valueOf(transportManager.hashCode()),
conference.getID(),
s.toString()
}));
}
/**
*
* @param channel
*/
private void channelCreated(Channel channel)
{
if (channel == null)
{
logger.debug("Could not log the channel created event " +
"because the channel is null.");
return;
}
Content content = channel.getContent();
if (content == null)
{
logger.debug("Could not log the channel created event " +
"because the content is null.");
return;
}
Conference conference = content.getConference();
if (conference == null)
{
logger.debug("Could not log the channel created event " +
"because the conference is null.");
return;
}
String endpointID = "";
Endpoint endpoint = channel.getEndpoint();
if (endpoint != null)
{
endpointID = endpoint.getID();
}
int lastN = -1;
if (channel instanceof VideoChannel)
{
lastN = ((VideoChannel)channel).getLastN();
}
logEvent(new InfluxDBEvent("channel_created",
CHANNEL_CREATED_COLUMNS,
new Object[] {
channel.getID(),
content.getName(),
conference.getID(),
endpointID,
lastN
}));
}
/**
*
* @param channel
*/
private void channelExpired(Channel channel)
{
if (channel == null)
{
logger.debug("Could not log the channel expired event " +
"because the channel is null.");
return;
}
Content content = channel.getContent();
if (content == null)
{
logger.debug("Could not log the channel expired event " +
"because the content is null.");
return;
}
Conference conference = content.getConference();
if (conference == null)
{
logger.debug("Could not log the channel expired event " +
"because the conference is null.");
return;
}
MediaStreamStats stats = null;
if (channel instanceof RtpChannel)
{
RtpChannel rtpChannel = (RtpChannel) channel;
MediaStream stream = rtpChannel.getStream();
if (stream != null)
{
stats = stream.getMediaStreamStats();
}
}
if (stats != null)
{
Object[] values = new Object[] {
channel.getID(),
content.getName(),
conference.getID(),
stats.getLocalIPAddress(),
stats.getLocalPort(),
stats.getRemoteIPAddress(),
stats.getRemotePort(),
stats.getNbReceivedBytes(),
stats.getNbSentBytes(),
// Number of packets sent from the other side
stats.getNbPacketsReceived() + stats.getDownloadNbPacketLost(),
stats.getDownloadNbPacketLost(),
stats.getNbPacketsSent(),
stats.getUploadNbPacketLost(),
stats.getMinDownloadJitterMs(),
stats.getMaxDownloadJitterMs(),
stats.getAvgDownloadJitterMs(),
stats.getMinUploadJitterMs(),
stats.getMaxUploadJitterMs(),
stats.getAvgUploadJitterMs()
};
logEvent(new InfluxDBEvent(
"channel_expired", RTP_CHANNEL_EXPIRED_COLUMNS, values));
}
else
{
Object[] values = new Object[] {
channel.getID(),
content.getName(),
conference.getID(),
};
logEvent(new InfluxDBEvent(
"channel_expired", CHANNEL_EXPIRED_COLUMNS, values));
}
}
@Override
public void handleEvent(Event event)
{
if (event == null)
{
logger.debug("Could not handle the event because it was null.");
return;
}
String topic = event.getTopic();
if (EventFactory.CHANNEL_CREATED_TOPIC.equals(topic))
{
Channel channel
= (Channel) event.getProperty(EventFactory.EVENT_SOURCE);
channelCreated(channel);
}
else if (EventFactory.CHANNEL_EXPIRED_TOPIC.equals(topic))
{
Channel channel
= (Channel) event.getProperty(EventFactory.EVENT_SOURCE);
channelExpired(channel);
}
else if (
EventFactory.CONFERENCE_CREATED_TOPIC.equals(topic))
{
Conference conference
= (Conference) event.getProperty(EventFactory.EVENT_SOURCE);
conferenceCreated(conference);
}
else if (EventFactory.CONFERENCE_EXPIRED_TOPIC.equals(topic))
{
Conference conference
= (Conference) event.getProperty(EventFactory.EVENT_SOURCE);
conferenceExpired(conference);
}
else if (EventFactory.CONTENT_CREATED_TOPIC.equals(topic))
{
Content content
= (Content) event.getProperty(EventFactory.EVENT_SOURCE);
contentCreated(content);
}
else if (EventFactory.CONTENT_EXPIRED_TOPIC.equals(topic))
{
Content content
= (Content) event.getProperty(EventFactory.EVENT_SOURCE);
contentExpired(content);
}
else if (EventFactory.ENDPOINT_CREATED_TOPIC.equals(topic))
{
Endpoint endpoint
= (Endpoint) event.getProperty(EventFactory.EVENT_SOURCE);
endpointCreated(endpoint);
}
else if (EventFactory.ENDPOINT_DISPLAY_NAME_CHANGED_TOPIC.equals(topic))
{
Endpoint endpoint
= (Endpoint) event.getProperty(EventFactory.EVENT_SOURCE);
endpointDisplayNameChanged(endpoint);
}
else if (EventFactory.TRANSPORT_CHANNEL_ADDED_TOPIC.equals(topic))
{
Channel channel
= (Channel) event.getProperty(EventFactory.EVENT_SOURCE);
transportChannelAdded(channel);
}
else if (EventFactory.TRANSPORT_CHANNEL_REMOVED_TOPIC.equals(topic))
{
Channel channel
= (Channel) event.getProperty(EventFactory.EVENT_SOURCE);
transportChannelRemoved(channel);
}
else if (EventFactory.TRANSPORT_CONNECTED_TOPIC.equals(topic))
{
IceUdpTransportManager transportManager
= (IceUdpTransportManager) event.getProperty(
EventFactory.EVENT_SOURCE);
transportConnected(transportManager);
}
else if (EventFactory.TRANSPORT_CREATED_TOPIC.equals(topic))
{
IceUdpTransportManager transportManager
= (IceUdpTransportManager) event.getProperty(
EventFactory.EVENT_SOURCE);
transportCreated(transportManager);
}
else if (EventFactory.TRANSPORT_STATE_CHANGED_TOPIC.equals(topic))
{
IceUdpTransportManager transportManager
= (IceUdpTransportManager) event.getProperty(
EventFactory.EVENT_SOURCE);
IceProcessingState oldState
= (IceProcessingState) event.getProperty("oldState");
IceProcessingState newState
= (IceProcessingState) event.getProperty("newState");
transportStateChanged(transportManager, oldState, newState);
}
}
} |
package com.sandwell.JavaSimulation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import com.jaamsim.basicsim.ErrorException;
import com.jaamsim.input.InputErrorException;
import com.jaamsim.ui.LogBox;
/**
* Class encapsulating file input/output methods and file access.
*/
public class FileEntity {
public static int ALIGNMENT_LEFT = 0;
public static int ALIGNMENT_RIGHT = 1;
private File backingFileObject;
private BufferedWriter outputStream;
private DecimalFormat formatter;
public FileEntity(String fileName) {
this(fileName, false);
}
public FileEntity(String fileName, boolean append) {
backingFileObject = new File( fileName);
formatter = new DecimalFormat( "##0.00" );
try {
backingFileObject.createNewFile();
outputStream = new BufferedWriter( new FileWriter( backingFileObject, append ) );
}
catch( IOException e ) {
throw new InputErrorException( "IOException thrown trying to open FileEntity: " + e );
}
catch( IllegalArgumentException e ) {
throw new InputErrorException( "IllegalArgumentException thrown trying to open FileEntity (Should not happen): " + e );
}
catch( SecurityException e ) {
throw new InputErrorException( "SecurityException thrown trying to open FileEntity: " + e );
}
}
public void close() {
try {
if( outputStream != null ) {
outputStream.flush();
outputStream.close();
outputStream = null;
}
}
catch( IOException e ) {
outputStream = null;
LogBox.logLine( "Unable to close FileEntity: " + backingFileObject.getName() );
}
}
public void flush() {
try {
if( outputStream != null ) {
outputStream.flush();
}
}
catch( IOException e ) {
throw new ErrorException( "Unable to flush FileEntity: " + e );
}
}
public void putString( String string ) {
write(string);
}
public void format(String format, Object... args) {
write(String.format(format, args));
}
/**
* Prints the given string for the specified number of times.
*/
public void putString( String string, int count ) {
try {
for ( int i =0; i < count; i++ ) {
outputStream.write( string );
}
}
catch( IOException e ) {
return;
}
}
/**
* Generic string writing method. All other methods will wrap this class.
*/
private void putString( String string, int putLength, int alignment ) {
String spaces = "";
for( int i = 0; i < putLength - string.length(); i++ ) {
spaces = " " + spaces;
}
try {
if( alignment == ALIGNMENT_LEFT ) {
outputStream.write( string + spaces );
}
if( alignment == ALIGNMENT_RIGHT ) {
outputStream.write( spaces + string );
}
outputStream.flush();
}
catch( IOException e ) {
return;
}
}
public void putDoublePadRight( double putDouble, int decimalPlaces, int putLength ) {
StringBuilder pattern = new StringBuilder("
if( decimalPlaces > 0 ) {
pattern.append(".");
for( int i = 0; i < decimalPlaces; i++ ) {
pattern.append("0");
}
}
formatter.applyPattern(pattern.toString());
putString( formatter.format( putDouble ), putLength, ALIGNMENT_RIGHT );
}
public void putDoubleWithDecimals( double putDouble, int decimalPlaces ) {
StringBuilder pattern = new StringBuilder("
if( decimalPlaces > 0 ) {
pattern.append(".");
for( int i = 0; i < decimalPlaces; i++ ) {
pattern.append("0");
}
}
formatter.applyPattern(pattern.toString());
putString( formatter.format( putDouble ), formatter.format( putDouble ).length(), ALIGNMENT_LEFT );
}
public void putDoubleWithDecimalsTabs( double putDouble, int decimalPlaces, int tabs ) {
StringBuilder pattern = new StringBuilder("
if( decimalPlaces > 0 ) {
pattern.append(".");
for( int i = 0; i < decimalPlaces; i++ ) {
pattern.append("0");
}
}
formatter.applyPattern(pattern.toString());
putString( formatter.format( putDouble ), formatter.format( putDouble ).length(), ALIGNMENT_LEFT );
putTabs( tabs );
}
public void newLine() {
try {
outputStream.newLine();
}
catch( IOException e ) {
return;
}
}
public void newLine( int numLines ) {
for( int i = 0; i < numLines; i++ ) {
newLine();
}
}
public void putTab() {
try {
outputStream.write( "\t" );
}
catch( IOException e ) {
return;
}
}
public void putTabs( int numTabs ) {
try {
for( int i = 0; i < numTabs; i++ ) {
outputStream.write( "\t" );
}
}
catch( IOException e ) {
return;
}
}
public void write( String text ) {
try {
outputStream.write( text );
}
catch( IOException e ) {
return;
}
}
public void putStringTabs( String input, int tabs ) {
putString( input );
putTabs( tabs );
}
/**
* Delete the file
*/
public void delete() {
try {
if( backingFileObject.exists() ) {
if( !backingFileObject.delete() ) {
throw new ErrorException( "Failed to delete " + backingFileObject.getName() );
}
}
}
catch( SecurityException e ) {
throw new ErrorException( "Unable to delete " + backingFileObject.getName() + "(" + e.getMessage() + ")" );
}
}
} |
package de.hft_stuttgart.swp2.model;
import java.util.ArrayList;
import java.util.List;
public class Building extends MeshInterface {
private String id;
private double volume;
private List<Vertex> polygon;
private ArrayList<ShadowTriangle> shadowTriangles = new ArrayList<>();
private Vertex center;
public Building() {
}
public Building(String id, List<Vertex> polygon) {
this.id = id;
this.polygon = polygon;
}
public Building(String bid, ArrayList<Triangle> polyTriangles) {
// TODO Auto-generated constructor stub
this.id=id;
for (int i=0; i<polyTriangles.size();i++) {
this.addTriangle(polyTriangles.get(i));
}
}
public void setVolume(double volume) {
this.volume = volume;
}
public double getVolume() {
return volume;
}
public String getId() {
return id;
}
public List<Vertex> getPolygon() {
return polygon;
}
public void addShadowTriangle(ShadowTriangle t) {
shadowTriangles.add(t);
}
public ArrayList<ShadowTriangle> getShadowTriangles() {
return shadowTriangles;
}
public void translate(float x, float y, float z) {
for (Triangle t : getTriangles()) {
for (Vertex v : t.getVertices()) {
v.resetVisit();
}
}
for (Triangle t : getTriangles()) {
for (Vertex v : t.getVertices()) {
if (!v.wasVisited()) {
v.visit();
v.translate(x, y, z);
}
}
}
for (ShadowTriangle t : shadowTriangles) {
for (Vertex v : t.getVertices()) {
if (!v.wasVisited()) {
v.visit();
v.translate(x, y, z);
}
}
}
}
/**
* This method must be called be before calculateShadow(), otherwise the
* shadow triangles can be too big or too small.
* The values are multiplied to the vertices so for keeping the original size
* the scaling has to be 1.
*
* @param x scaling in x
* @param y scaling in y
* @param z scaling in z
*/
public void scale(float x, float y, float z) {
for (Triangle t : getTriangles()) {
for (Vertex v : t.getVertices()) {
v.resetVisit();
}
}
for (Triangle t : getTriangles()) {
for (Vertex v : t.getVertices()) {
if (!v.wasVisited()) {
v.visit();
v.scale(x, y, z);
}
}
}
}
public Vertex getCenter() {
return center;
}
public void setCenter(Vertex center) {
this.center = center;
}
} |
package org.jmist.framework.services;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.UUID;
import org.jmist.framework.IJob;
import org.jmist.framework.IParallelizableJob;
import org.jmist.framework.IProgressMonitor;
/**
* @author bkimmel
*
*/
public final class ServiceSubmitJob implements IJob {
/* (non-Javadoc)
* @see org.jmist.framework.IJob#go(org.jmist.framework.IProgressMonitor)
*/
@Override
public void go(IProgressMonitor monitor) {
try {
monitor.notifyStatusChanged("Submitting job...");
Registry registry = LocateRegistry.getRegistry(this.masterHost);
IJobMasterService service = (IJobMasterService) registry.lookup("IJobMasterService");
UUID jobId = service.submitJob(this.job, this.priority);
if (jobId.compareTo(new UUID(0, 0)) != 0) {
monitor.notifyStatusChanged(String.format("Submitted, ID=%s.", jobId.toString()));
monitor.notifyComplete();
} else {
monitor.notifyStatusChanged("Failed to submit job.");
monitor.notifyCancelled();
}
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
monitor.notifyStatusChanged(String.format("Failed to submit job: %s.", e.toString()));
monitor.notifyCancelled();
}
}
private String masterHost;
private IParallelizableJob job;
private int priority;
} |
package com.sdl.selenium.web.table;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
import com.sdl.selenium.web.form.SimpleCheckBox;
import org.apache.log4j.Logger;
public class SimpleTable extends WebLocator implements ITable <TableRow, TableCell>{
private static final Logger logger = Logger.getLogger(SimpleTable.class);
private int timeout = 30;
public SimpleTable() {
setClassName("SimpleTable");
setTag("table");
}
public SimpleTable(WebLocator container) {
this();
setContainer(container);
}
@Override
public boolean rowSelect(String searchText) {
return rowSelect(searchText, SearchType.EQUALS);
}
@Override
public boolean rowSelect(String searchText, SearchType searchType) {
ready(true);
TableCell cell = getTableCell(searchText, searchType);
return doCellSelect(cell);
}
@Deprecated
private boolean doCellSelect(TableCell tableCell) {
return doCellAction(tableCell, null);
}
@Deprecated
private boolean doCellDoubleClickAt(TableCell tableCell) {
return doCellAction(tableCell, "doubleClickAt");
}
@Deprecated
private boolean doCellAction(WebLocator cell, String action) {
boolean selected;
if ("doubleClickAt".equals(action)) {
selected = cell.doubleClickAt();
} else {
selected = cell.click();
}
if (selected) {
logger.info("The element '" + cell + "' has been located.");
} else {
logger.warn("The element '" + cell + "' is not present in the list.");
if (logger.isDebugEnabled()) {
logger.debug("Path's element is: " + cell.getPath());
logger.debug("Total Rows: " + getCount());
}
}
return selected;
}
/**
* returns if a table contains a certain element
*
* @param searchElement the searchElement of the table element on which the search is done
* @return
* @throws Exception
*/
public boolean isRowPresent(String searchElement) {
ready();
boolean found;
WebLocator cell = getTableCell(searchElement, SearchType.EQUALS);
found = cell.isElementPresent();
return found;
}
public Number getRowCount(String searchElement, SearchType searchType) {
ready();
String rowPath = getTableCell(searchElement, searchType).getPath();
return new WebLocator(null, rowPath).size();
}
public Number getRowCount(String searchElement) {
return getRowCount(searchElement, SearchType.STARTS_WITH);
}
@Override
public int getCount() {
if (ready()) {
WebLocator body = new WebLocator(this).setTag("tbody");
return new TableRow(body).size();
} else {
logger.warn("table is not ready to be used");
// TODO could try to verify row count with mask on table or when is disabled also.
return -1;
}
}
@Override
public TableRow getRowLocator(int rowIndex) {
return new TableRow(this, rowIndex).setInfoMessage("row - Table");
}
public TableRow getTableRow(String searchElement) {
return new TableRow(this, searchElement, SearchType.EQUALS);
}
public TableRow getTableRow(String searchElement, SearchType searchType) {
return new TableRow(this, searchElement, searchType);
}
private String getSearchTypePath(String searchElement, SearchType searchType) {
String selector = "";
if (SearchType.EQUALS.equals(searchType)) {
selector += "text()='" + searchElement + "'";
} else if (SearchType.CONTAINS.equals(searchType)) {
selector += "contains(text(),'" + searchElement + "')";
} else if (SearchType.STARTS_WITH.equals(searchType)) {
selector += "starts-with(text(),'" + searchElement + "')";
} else {
logger.warn("searchType did not math to any accepted values");
selector = "";
}
/**
* TODO improve *reuse searchType from WebLocator
*
* @param searchElement
* @param searchType accepted values are: {"equals", "starts-with", "contains"}
* @return
*/
public TableCell getTableCell(String searchElement, SearchType searchType) {
String selector = getSearchTypePath(searchElement, searchType);
return new TableCell(this).setElPath("//tr//td[" + selector + "]");
}
/**
* @deprecated use getTableCell(String searchElement, SearchType searchType)
* @param searchElement
* @param startWidth
* @return
*/
public TableCell getTableCell(String searchElement, Boolean startWidth) {
return getTableCell(searchElement, startWidth ? SearchType.STARTS_WITH : SearchType.EQUALS);
}
public TableCell getTableCell(int rowIndex, int columnIndex, String text) {
Row row = getRowLocator(rowIndex);
return new TableCell(row).setElPath("//td[" + getSearchTypePath(text, SearchType.EQUALS) + "][" + columnIndex + "]");
}
public TableCell getTableCell(String searchElement, String columnText, SearchType searchType) {
TableRow tableRow = getTableRow(searchElement, SearchType.CONTAINS);
return getTableCellWithText(tableRow, columnText, searchType);
}
public TableCell getTableCell(String searchElement, int columnIndex, SearchType searchType) {
return new TableCell(new TableRow(this, searchElement, searchType), columnIndex);
}
private TableCell getTableCellWithText(TableRow tableRow, String columnText, SearchType searchType) {
return new TableCell(tableRow).setElPath("//td[" + getSearchTypePath(columnText, searchType) + "]");
}
@Override
public TableRow getRow(TableCell... byCells) {
return new TableRow(this, byCells).setInfoMessage("-TableRow");
}
public TableCell getTableCell(int columnIndex, TableCell... byCells) {
return new TableCell(getRow(byCells), columnIndex);
}
public TableCell getTableCell(int columnIndex, String text, TableCell... byCells) {
return new TableCell(getRow(byCells), columnIndex, text, SearchType.EQUALS);
}
/**
* returns all text elements from a table
*
* @param searchText
* @return
*/
@Deprecated //TODO fix it
public String[] getRow(String searchText) {
String[] rowElements = null;
String text = getTableRow(searchText).getHtmlText();
if (text != null) {
rowElements = text.split("\n");
}
return rowElements;
}
/**
* get all strings as array from specified columnIndex
*
* @param columnIndex
* @return
*/
public String[] getCollTexts(int columnIndex) {
int count = getCount();
if (count > 0) {
String[] texts = new String[count];
for (int i = 1; i <= count; i++) {
texts[i - 1] = getText(i, columnIndex);
}
return texts;
} else {
return null;
}
}
public String getText(String searchText, int columnId) {
String text = null;
TableRow tableRow = new TableRow(this, searchText, SearchType.EQUALS);
if (tableRow.ready()) {
text = new TableCell(tableRow, columnId).getHtmlText();
} else {
logger.warn("searchText was not found in table: " + searchText);
}
return text;
}
public String getText(int rowIndex, int columnIndex) {
return getCell(rowIndex, columnIndex).getHtmlText();
}
/**
* returns if a specific Table contains a certain element
*
* @param searchText the element that is already part of the table
* @param columnIndex the column index where the comparison is done (STARTS AT 0)
* @param compareText the text to which the element found is compared to
* @return
*/
public boolean isTextPresent(String searchText, int columnIndex, String compareText) {
String text = getText(searchText, columnIndex);
return text != null && text.trim().equals(compareText);
}
public boolean checkboxColumnSelect(String searchText, int columnIndex) {
return checkboxColumnSelect(searchText, columnIndex, SearchType.EQUALS);
}
public boolean checkboxColumnSelect(String searchText, int columnIndex, SearchType searchType) {
boolean selected = false;
if (ready(true)) {
SimpleCheckBox simpleCheckBox = new SimpleCheckBox().setContainer(getTableCell(searchText, columnIndex, searchType));
selected = simpleCheckBox.isSelected() || simpleCheckBox.click();
}
return selected;
}
public boolean checkboxColumnDeselect(String searchText, int columnIndex) {
return checkboxColumnDeselect(searchText, columnIndex, SearchType.EQUALS);
}
public boolean checkboxColumnDeselect(String searchText, int columnIndex, SearchType searchType) {
boolean selected = false;
if (ready(true)) {
SimpleCheckBox simpleCheckBox = new SimpleCheckBox().setContainer(getTableCell(searchText, columnIndex, searchType));
selected = !simpleCheckBox.isSelected() || simpleCheckBox.click();
}
return selected;
}
public boolean waitToPopulate() {
return waitToPopulate(timeout);
}
public boolean waitToPopulate(int seconds) {
Row row = getRowLocator(1).setInfoMessage("first row");
return row.waitToRender(seconds);
}
public boolean ready(boolean waitRows) {
return ready() && (!waitRows || waitToPopulate());
}
} |
package org.ojalgo.optimisation;
import static org.ojalgo.constant.BigMath.*;
import static org.ojalgo.function.BigFunction.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
import org.ojalgo.ProgrammingError;
import org.ojalgo.access.Access1D;
import org.ojalgo.access.Structure1D.IntIndex;
import org.ojalgo.access.Structure2D.IntRowColumn;
import org.ojalgo.array.Array1D;
import org.ojalgo.array.Primitive64Array;
import org.ojalgo.constant.BigMath;
import org.ojalgo.netio.BasicLogger;
import org.ojalgo.netio.BasicLogger.Printer;
import org.ojalgo.optimisation.convex.ConvexSolver;
import org.ojalgo.optimisation.integer.IntegerSolver;
import org.ojalgo.optimisation.linear.LinearSolver;
import org.ojalgo.type.context.NumberContext;
/**
* <p>
* Lets you construct optimisation problems by combining (mathematical) expressions in terms of variables.
* Each expression or variable can be a constraint and/or contribute to the objective function. An expression
* or variable is turned into a constraint by setting a lower and/or upper limit. Use
* {@linkplain Expression#lower(Number)}, {@linkplain Expression#upper(Number)} or
* {@linkplain Expression#level(Number)}. An expression or variable is made part of (contributing to) the
* objective function by setting a contribution weight. Use {@linkplain Expression#weight(Number)}.
* </p>
* <p>
* You may think of variables as simple (the simplest possible) expressions, and of expressions as weighted
* combinations of variables. They are both model entities and it is as such they can be turned into
* constraints and set to contribute to the objective function. Alternatively you may choose to disregard the
* fact that variables are model entities and simply treat them as index values. In this case everything
* (constraints and objective) needs to be defined using expressions.
* </p>
* <p>
* Basic instructions:
* </p>
* <ol>
* <li>Define (create) a set of variables. Set contribution weights and lower/upper limits as needed.</li>
* <li>Create a model using that set of variables.</li>
* <li>Add expressions to the model. The model is the expression factory. Set contribution weights and
* lower/upper limits as needed.</li>
* <li>Solve your problem using either minimise() or maximise()</li>
* </ol>
* <p>
* When using this class you do not need to worry about which solver will actually be used. The docs of the
* various solvers describe requirements on input formats and similar. This is handled for you and should
* absolutely NOT be considered here! Compared to using the various solvers directly this class actually does
* something for you:
* </p>
* <ol>
* <li>You can model your problems without worrying about specific solver requirements.</li>
* <li>It knows which solver to use.</li>
* <li>It knows how to use that solver.</li>
* <li>It has a presolver that tries to simplify the problem before invoking a solver (sometimes it turns out
* there is no need to invoke a solver at all).</li>
* <li>When/if needed it scales problem parameters, before creating solver specific data structures, to
* minimize numerical problems in the solvers.</li>
* <li>It's the only way to access the integer solver.</li>
* </ol>
* <p>
* Different solvers can be used, and ojAlgo comes with collection built in. The default built-in solvers can
* handle anythimng you can model with a couple of restrictions:
* </p>
* <ul>
* <li>No quadratic constraints (The plan is that future versions should not have this limitation.)</li>
* <li>If you use quadratic expressions make sure they're convex. This is most likely a requirement even with
* 3:d party solvers.</li>
* </ul>
*
* @author apete
*/
public final class ExpressionsBasedModel extends AbstractModel<GenericSolver> {
public static abstract class Integration<S extends Optimisation.Solver> implements Optimisation.Integration<ExpressionsBasedModel, S> {
/**
* @see org.ojalgo.optimisation.Optimisation.Integration#extractSolverState(org.ojalgo.optimisation.Optimisation.Model)
*/
public final Result extractSolverState(final ExpressionsBasedModel model) {
return this.toSolverState(model.getVariableValues(), model);
}
public Result toModelState(final Result solverState, final ExpressionsBasedModel model) {
final int numbVariables = model.countVariables();
if (this.isSolutionMapped()) {
final List<Variable> freeVariables = model.getFreeVariables();
final Set<IntIndex> fixedVariables = model.getFixedVariables();
if (solverState.count() != freeVariables.size()) {
throw new IllegalStateException();
}
final Primitive64Array modelSolution = Primitive64Array.make(numbVariables);
for (final IntIndex fixedIndex : fixedVariables) {
modelSolution.set(fixedIndex.index, model.getVariable(fixedIndex.index).getValue());
}
for (int f = 0; f < freeVariables.size(); f++) {
final int freeIndex = model.indexOf(freeVariables.get(f));
modelSolution.set(freeIndex, solverState.doubleValue(f));
}
return new Result(solverState.getState(), modelSolution);
} else {
if (solverState.count() != numbVariables) {
throw new IllegalStateException();
}
return solverState;
}
}
public Result toSolverState(final Result modelState, final ExpressionsBasedModel model) {
if (this.isSolutionMapped()) {
final List<Variable> tmpFreeVariables = model.getFreeVariables();
final int numbFreeVars = tmpFreeVariables.size();
final Primitive64Array solverSolution = Primitive64Array.make(numbFreeVars);
for (int i = 0; i < numbFreeVars; i++) {
final Variable variable = tmpFreeVariables.get(i);
final int modelIndex = model.indexOf(variable);
solverSolution.set(i, modelState.doubleValue(modelIndex));
}
return new Result(modelState.getState(), solverSolution);
} else {
return modelState;
}
}
/**
* @param model
* @param variable
* @return The index with which one can reference parameters related to this variable in the solver.
*/
protected int getIndexInSolver(final ExpressionsBasedModel model, final Variable variable) {
return model.indexOfFreeVariable(variable);
}
/**
* @return true if the set of variables present in the solver is not precisely the same as in the
* model. If fixed variables are omitted or if variables are split into a positive and
* negative part, then this method must return true
*/
protected abstract boolean isSolutionMapped();
protected boolean update(Variable variable, ExpressionsBasedModel model, S solver) {
return false;
}
}
public static final class Intermediate implements Optimisation.Solver {
private transient ExpressionsBasedModel.Integration<?> myIntegration = null;
private final ExpressionsBasedModel myModel;
private transient Optimisation.Solver mySolver = null;
Intermediate(final ExpressionsBasedModel model) {
super();
myModel = model;
myIntegration = null;
mySolver = null;
}
public void dispose() {
Solver.super.dispose();
if (mySolver != null) {
mySolver.dispose();
mySolver = null;
}
myIntegration = null;
}
public ExpressionsBasedModel getModel() {
return myModel;
}
public Variable getVariable(final int globalIndex) {
return myModel.getVariable(globalIndex);
}
public Variable getVariable(final IntIndex globalIndex) {
return myModel.getVariable(globalIndex);
}
public Optimisation.Result solve(final Optimisation.Result candidate) {
if (mySolver == null) {
myModel.presolve();
}
if (myModel.isInfeasible()) {
final Optimisation.Result solution = candidate != null ? candidate : myModel.getVariableValues();
return new Optimisation.Result(State.INFEASIBLE, solution);
} else if (myModel.isUnbounded()) {
if ((candidate != null) && myModel.validate(candidate)) {
return new Optimisation.Result(State.UNBOUNDED, candidate);
}
final Optimisation.Result derivedSolution = myModel.getVariableValues();
if (derivedSolution.getState().isFeasible()) {
return new Optimisation.Result(State.UNBOUNDED, derivedSolution);
}
} else if (myModel.isFixed()) {
final Optimisation.Result derivedSolution = myModel.getVariableValues();
if (derivedSolution.getState().isFeasible()) {
return new Optimisation.Result(State.DISTINCT, derivedSolution);
} else {
return new Optimisation.Result(State.INVALID, derivedSolution);
}
}
final ExpressionsBasedModel.Integration<?> integration = this.getIntegration();
final Optimisation.Solver solver = this.getSolver();
Optimisation.Result retVal = candidate != null ? candidate : myModel.getVariableValues();
retVal = integration.toSolverState(retVal, myModel);
retVal = solver.solve(retVal);
retVal = integration.toModelState(retVal, myModel);
return retVal;
}
public void update(final int index) {
this.update(myModel.getVariable(index));
}
public void update(final IntIndex index) {
this.update(myModel.getVariable(index));
}
public void update(final Variable variable) {
if (mySolver != null) {
if (variable.isFixed() && (mySolver instanceof UpdatableSolver) && ((UpdatableSolver) mySolver)
.fixVariable(this.getIntegration().getIndexInSolver(myModel, variable), variable.getUnadjustedLowerLimit())) {
// Solver updated in-place
} else {
// Solver needs to be regenerated
mySolver = null;
}
}
}
public boolean validate(final Result solution) {
return myModel.validate(solution);
}
ExpressionsBasedModel.Integration<?> getIntegration() {
if (myIntegration == null) {
myIntegration = myModel.getIntegration();
}
return myIntegration;
}
Optimisation.Solver getSolver() {
if (mySolver == null) {
mySolver = this.getIntegration().build(myModel);
}
return mySolver;
}
}
public static abstract class Presolver extends Simplifier<Expression, Presolver> {
protected Presolver(final int executionOrder) {
super(executionOrder);
}
/**
* @param expression
* @param fixedVariables
* @param fixedValue TODO
* @param variableResolver TODO
* @param precision TODO
* @return True if any model entity was modified so that a re-run of the presolvers is necessary -
* typically when/if a variable was fixed.
*/
public abstract boolean simplify(Expression expression, Set<IntIndex> fixedVariables, BigDecimal fixedValue,
Function<IntIndex, Variable> variableResolver, NumberContext precision);
@Override
boolean isApplicable(final Expression target) {
return target.isConstraint() && !target.isInfeasible() && !target.isRedundant() && (target.countQuadraticFactors() == 0);
}
}
static abstract class Simplifier<ME extends ModelEntity<?>, S extends Simplifier<?, ?>> implements Comparable<S> {
private final int myExecutionOrder;
private final UUID myUUID = UUID.randomUUID();
Simplifier(final int executionOrder) {
super();
myExecutionOrder = executionOrder;
}
public final int compareTo(final S reference) {
return Integer.compare(myExecutionOrder, reference.getExecutionOrder());
}
@Override
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Simplifier)) {
return false;
}
final Simplifier<?, ?> other = (Simplifier<?, ?>) obj;
if (myUUID == null) {
if (other.myUUID != null) {
return false;
}
} else if (!myUUID.equals(other.myUUID)) {
return false;
}
return true;
}
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((myUUID == null) ? 0 : myUUID.hashCode());
return result;
}
final int getExecutionOrder() {
return myExecutionOrder;
}
abstract boolean isApplicable(final ME target);
}
static abstract class VariableAnalyser extends Simplifier<Variable, VariableAnalyser> {
protected VariableAnalyser(final int executionOrder) {
super(executionOrder);
}
public abstract boolean simplify(Variable variable, ExpressionsBasedModel model);
@Override
boolean isApplicable(final Variable target) {
return true;
}
}
private static final ConvexSolver.ModelIntegration CONVEX_INTEGRATION = new ConvexSolver.ModelIntegration();
private static final IntegerSolver.ModelIntegration INTEGER_INTEGRATION = new IntegerSolver.ModelIntegration();
private static final List<ExpressionsBasedModel.Integration<?>> INTEGRATIONS = new ArrayList<>();
private static final LinearSolver.ModelIntegration LINEAR_INTEGRATION = new LinearSolver.ModelIntegration();
private static final String NEW_LINE = "\n";
private static final String OBJ_FUNC_AS_CONSTR_KEY = UUID.randomUUID().toString();
private static final String OBJECTIVE = "Generated/Aggregated Objective";
private static final TreeSet<Presolver> PRESOLVERS = new TreeSet<>();
private static final String START_END = "
static {
ExpressionsBasedModel.addPresolver(Presolvers.ZERO_ONE_TWO);
ExpressionsBasedModel.addPresolver(Presolvers.OPPOSITE_SIGN);
// ExpressionsBasedModel.addPresolver(Presolvers.BINARY_VALUE);
// ExpressionsBasedModel.addPresolver(Presolvers.BIGSTUFF);
}
public static boolean addIntegration(final Integration<?> integration) {
return INTEGRATIONS.add(integration);
}
public static boolean addPresolver(final Presolver presolver) {
return PRESOLVERS.add(presolver);
}
public static void clearIntegrations() {
INTEGRATIONS.clear();
}
public static void clearPresolvers() {
PRESOLVERS.clear();
}
public static boolean removeIntegration(final Integration<?> integration) {
return INTEGRATIONS.remove(integration);
}
public static boolean removePresolver(final Presolver presolver) {
return PRESOLVERS.remove(presolver);
}
private final HashMap<String, Expression> myExpressions = new HashMap<>();
private final HashSet<IntIndex> myFixedVariables = new HashSet<>();
private transient int[] myFreeIndices = null;
private final List<Variable> myFreeVariables = new ArrayList<>();
private transient int[] myIntegerIndices = null;
private final List<Variable> myIntegerVariables = new ArrayList<>();
private transient int[] myNegativeIndices = null;
private final List<Variable> myNegativeVariables = new ArrayList<>();
private transient int[] myPositiveIndices = null;
private final List<Variable> myPositiveVariables = new ArrayList<>();
private final ArrayList<Variable> myVariables = new ArrayList<>();
private final boolean myWorkCopy;
public ExpressionsBasedModel() {
super();
myWorkCopy = false;
}
public ExpressionsBasedModel(final Collection<? extends Variable> variables) {
super();
for (final Variable tmpVariable : variables) {
this.addVariable(tmpVariable);
}
myWorkCopy = false;
}
public ExpressionsBasedModel(final Optimisation.Options someOptions) {
super(someOptions);
myWorkCopy = false;
}
public ExpressionsBasedModel(final Variable... variables) {
super();
for (final Variable tmpVariable : variables) {
this.addVariable(tmpVariable);
}
myWorkCopy = false;
}
ExpressionsBasedModel(final ExpressionsBasedModel modelToCopy, final boolean workCopy, final boolean allEntities) {
super(modelToCopy.options);
this.setMinimisation(modelToCopy.isMinimisation());
for (final Variable tmpVariable : modelToCopy.getVariables()) {
this.addVariable(tmpVariable.copy());
}
for (final Expression tmpExpression : modelToCopy.getExpressions()) {
if (allEntities || tmpExpression.isObjective() || (tmpExpression.isConstraint() && !tmpExpression.isRedundant())) {
myExpressions.put(tmpExpression.getName(), tmpExpression.copy(this, !workCopy));
} else {
// BasicLogger.DEBUG.println("Discarding expression: {}", tmpExpression);
}
}
myWorkCopy = workCopy;
}
public Expression addExpression() {
return this.addExpression("EXPR" + myExpressions.size());
}
public Expression addExpression(final String name) {
final Expression retVal = new Expression(name, this);
myExpressions.put(name, retVal);
return retVal;
}
/**
* Creates a special ordered set (SOS) presolver instance and links that to the supplied expression.
* When/if the presolver concludes that the SOS "constraints" are not possible the linked expression is
* marked as infeasible.
*/
public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int type, final Expression linkedTo) {
if (type <= 0) {
throw new ProgrammingError("Invalid SOS type!");
}
if (!linkedTo.isConstraint()) {
throw new ProgrammingError("The linked to expression needs to be a constraint!");
}
final IntIndex[] sequence = new IntIndex[orderedSet.size()];
int index = 0;
for (final Variable variable : orderedSet) {
if ((variable == null) || (variable.getIndex() == null)) {
throw new ProgrammingError("Variables must be already inserted in the model!");
} else {
sequence[index++] = variable.getIndex();
}
}
ExpressionsBasedModel.addPresolver(new SpecialOrderedSet(sequence, type, linkedTo));
}
/**
* Calling this method will create 2 things:
* <ol>
* <li>A simple expression meassuring the sum of the (binary) variable values (the number of binary
* variables that are "ON"). The upper, and optionally lower, limits are set as defined by the
* <code>max</code> and <code>min</code> parameter values.</li>
* <li>A custom presolver (specific to this SOS) to be used by the MIP solver. This presolver help to keep
* track of which combinations of variable values or feasible, and is the only thing that enforces the
* order.</li>
* </ol>
*
* @param orderedSet The set members in correct order. Each of these variables must be binary.
* @param min The minimum number of binary varibales in the set that must be "ON" (Set this to 0 if there
* is no minimum.)
* @param max The SOS type or maximum number of binary varibales in the set that may be "ON"
*/
public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int min, final int max) {
if ((max <= 0) || (min > max)) {
throw new ProgrammingError("Invalid min/max number of ON variables!");
}
final String name = "SOS" + max + "-" + orderedSet.toString();
final Expression expression = this.addExpression(name);
for (final Variable variable : orderedSet) {
if ((variable == null) || (variable.getIndex() == null) || !variable.isBinary()) {
throw new ProgrammingError("Variables must be binary and already inserted in the model!");
} else {
expression.set(variable.getIndex(), ONE);
}
}
expression.upper(BigDecimal.valueOf(max));
if (min > 0) {
expression.lower(BigDecimal.valueOf(min));
}
this.addSpecialOrderedSet(orderedSet, max, expression);
}
public Variable addVariable() {
return this.addVariable("X" + myVariables.size());
}
public Variable addVariable(final String name) {
final Variable retVal = new Variable(name);
this.addVariable(retVal);
return retVal;
}
public void addVariable(final Variable variable) {
if (myWorkCopy) {
throw new IllegalStateException("This model is a work copy - its set of variables cannot be modified!");
} else {
myVariables.add(variable);
variable.setIndex(new IntIndex(myVariables.size() - 1));
}
}
public void addVariables(final Collection<? extends Variable> variables) {
for (final Variable tmpVariable : variables) {
this.addVariable(tmpVariable);
}
}
public void addVariables(final Variable[] variables) {
for (final Variable tmpVariable : variables) {
this.addVariable(tmpVariable);
}
}
/**
* @return A stream of variables that are constraints and not fixed
*/
public Stream<Variable> bounds() {
return this.variables().filter((final Variable v) -> v.isConstraint());
}
/**
* @return A prefiltered stream of expressions that are constraints and have not been markes as redundant
*/
public Stream<Expression> constraints() {
return myExpressions.values().stream().filter(c -> c.isConstraint() && !c.isRedundant());
}
public ExpressionsBasedModel copy() {
return new ExpressionsBasedModel(this, false, true);
}
public int countExpressions() {
return myExpressions.size();
}
public int countVariables() {
return myVariables.size();
}
@Override
public void dispose() {
for (final Expression tmpExprerssion : myExpressions.values()) {
tmpExprerssion.destroy();
}
myExpressions.clear();
for (final Variable tmpVariable : myVariables) {
tmpVariable.destroy();
}
myVariables.clear();
myFixedVariables.clear();
myFreeVariables.clear();
myFreeIndices = null;
myPositiveVariables.clear();
myPositiveIndices = null;
myNegativeVariables.clear();
myNegativeIndices = null;
myIntegerVariables.clear();
myIntegerIndices = null;
}
public Expression generateCut(final Expression constraint, final Optimisation.Result solution) {
return null;
}
public Expression getExpression(final String name) {
return myExpressions.get(name);
}
public Collection<Expression> getExpressions() {
return Collections.unmodifiableCollection(myExpressions.values());
}
public Set<IntIndex> getFixedVariables() {
myFixedVariables.clear();
for (final Variable tmpVar : myVariables) {
if (tmpVar.isFixed()) {
myFixedVariables.add(tmpVar.getIndex());
}
}
return Collections.unmodifiableSet(myFixedVariables);
}
/**
* @return A list of the variables that are not fixed at a specific value
*/
public List<Variable> getFreeVariables() {
if (myFreeIndices == null) {
this.categoriseVariables();
}
return Collections.unmodifiableList(myFreeVariables);
}
/**
* @return A list of the variables that are not fixed at a specific value and are marked as integer
* variables
*/
public List<Variable> getIntegerVariables() {
if (myIntegerIndices == null) {
this.categoriseVariables();
}
return Collections.unmodifiableList(myIntegerVariables);
}
/**
* @return A list of the variables that are not fixed at a specific value and whos range include negative
* values
*/
public List<Variable> getNegativeVariables() {
if (myNegativeIndices == null) {
this.categoriseVariables();
}
return Collections.unmodifiableList(myNegativeVariables);
}
/**
* @return A list of the variables that are not fixed at a specific value and whos range include positive
* values and/or zero
*/
public List<Variable> getPositiveVariables() {
if (myPositiveIndices == null) {
this.categoriseVariables();
}
return Collections.unmodifiableList(myPositiveVariables);
}
public Variable getVariable(final int index) {
return myVariables.get(index);
}
public Variable getVariable(final IntIndex index) {
return myVariables.get(index.index);
}
public List<Variable> getVariables() {
return Collections.unmodifiableList(myVariables);
}
public Optimisation.Result getVariableValues() {
return this.getVariableValues(options.feasibility);
}
/**
* Null variable values are replaced with 0.0. If any variable value is null the state is set to
* INFEASIBLE even if zero would actually be a feasible value. The objective function value is not
* calculated for infeasible variable values.
*/
public Optimisation.Result getVariableValues(final NumberContext validationContext) {
final int tmpNumberOfVariables = myVariables.size();
State retState = State.UNEXPLORED;
double retValue = Double.NaN;
final Array1D<BigDecimal> retSolution = Array1D.BIG.makeZero(tmpNumberOfVariables);
boolean tmpAllVarsSomeInfo = true;
for (int i = 0; i < tmpNumberOfVariables; i++) {
final Variable tmpVariable = myVariables.get(i);
if (tmpVariable.getValue() != null) {
retSolution.set(i, tmpVariable.getValue());
} else {
if (tmpVariable.isEqualityConstraint()) {
retSolution.set(i, tmpVariable.getLowerLimit());
} else if (tmpVariable.isLowerLimitSet() && tmpVariable.isUpperLimitSet()) {
retSolution.set(i, DIVIDE.invoke(tmpVariable.getLowerLimit().add(tmpVariable.getUpperLimit()), TWO));
} else if (tmpVariable.isLowerLimitSet()) {
retSolution.set(i, tmpVariable.getLowerLimit());
} else if (tmpVariable.isUpperLimitSet()) {
retSolution.set(i, tmpVariable.getUpperLimit());
} else {
retSolution.set(i, ZERO);
tmpAllVarsSomeInfo = false; // This var no info
}
}
}
if (tmpAllVarsSomeInfo) {
if (this.validate(retSolution, validationContext)) {
retState = State.FEASIBLE;
retValue = this.objective().evaluate(retSolution).doubleValue();
} else {
retState = State.APPROXIMATE;
}
} else {
retState = State.INFEASIBLE;
}
return new Optimisation.Result(retState, retValue, retSolution);
}
public int indexOf(final Variable variable) {
return variable.getIndex().index;
}
/**
* @param globalIndex General, global, variable index
* @return Local index among the free variables. -1 indicates the variable is not a positive variable.
*/
public int indexOfFreeVariable(final int globalIndex) {
return myFreeIndices[globalIndex];
}
public int indexOfFreeVariable(final IntIndex variableIndex) {
return this.indexOfFreeVariable(variableIndex.index);
}
public int indexOfFreeVariable(final Variable variable) {
return this.indexOfFreeVariable(this.indexOf(variable));
}
/**
* @param globalIndex General, global, variable index
* @return Local index among the integer variables. -1 indicates the variable is not an integer variable.
*/
public int indexOfIntegerVariable(final int globalIndex) {
return myIntegerIndices[globalIndex];
}
public int indexOfIntegerVariable(final IntIndex variableIndex) {
return this.indexOfIntegerVariable(variableIndex.index);
}
public int indexOfIntegerVariable(final Variable variable) {
return this.indexOfIntegerVariable(variable.getIndex().index);
}
/**
* @param globalIndex General, global, variable index
* @return Local index among the negative variables. -1 indicates the variable is not a negative variable.
*/
public int indexOfNegativeVariable(final int globalIndex) {
return myNegativeIndices[globalIndex];
}
public int indexOfNegativeVariable(final IntIndex variableIndex) {
return this.indexOfNegativeVariable(variableIndex.index);
}
public int indexOfNegativeVariable(final Variable variable) {
return this.indexOfNegativeVariable(this.indexOf(variable));
}
/**
* @param globalIndex General, global, variable index
* @return Local index among the positive variables. -1 indicates the variable is not a positive variable.
*/
public int indexOfPositiveVariable(final int globalIndex) {
return myPositiveIndices[globalIndex];
}
public int indexOfPositiveVariable(final IntIndex variableIndex) {
return this.indexOfPositiveVariable(variableIndex.index);
}
public int indexOfPositiveVariable(final Variable variable) {
return this.indexOfPositiveVariable(this.indexOf(variable));
}
public boolean isAnyConstraintQuadratic() {
boolean retVal = false;
for (final Expression value : myExpressions.values()) {
retVal |= (value.isAnyQuadraticFactorNonZero() && value.isConstraint() && !value.isRedundant());
}
return retVal;
}
/**
* Objective or any constraint has quadratic part.
*
* @deprecated v45 Use {@link #isAnyConstraintQuadratic()} or {@link #isAnyObjectiveQuadratic()} instead
*/
@Deprecated
public boolean isAnyExpressionQuadratic() {
boolean retVal = false;
for (final Expression value : myExpressions.values()) {
retVal |= value.isAnyQuadraticFactorNonZero() && (value.isConstraint() || value.isObjective());
}
return retVal;
}
public boolean isAnyObjectiveQuadratic() {
boolean retVal = false;
for (final Expression value : myExpressions.values()) {
retVal |= (value.isAnyQuadraticFactorNonZero() && value.isObjective());
}
return retVal;
}
public boolean isAnyVariableFixed() {
return myVariables.stream().anyMatch(v -> v.isFixed());
}
public boolean isAnyVariableInteger() {
boolean retVal = false;
final int tmpLength = myVariables.size();
for (int i = 0; !retVal && (i < tmpLength); i++) {
retVal |= myVariables.get(i).isInteger();
}
return retVal;
}
public boolean isWorkCopy() {
return myWorkCopy;
}
public void limitObjective(final BigDecimal lower, final BigDecimal upper) {
Expression constrExpr = myExpressions.get(OBJ_FUNC_AS_CONSTR_KEY);
if (constrExpr == null) {
final Expression objExpr = this.objective();
if (!objExpr.isAnyQuadraticFactorNonZero()) {
constrExpr = objExpr.copy(this, false);
myExpressions.put(OBJ_FUNC_AS_CONSTR_KEY, constrExpr);
}
}
if (constrExpr != null) {
// int maxScale = 0;
// for (final Entry<IntIndex, BigDecimal> entry : constrExpr.getLinearEntrySet()) {
// maxScale = Math.max(maxScale, entry.getValue().scale());
// long gcd = -1L;
// for (final Entry<IntIndex, BigDecimal> entry : constrExpr.getLinearEntrySet()) {
// final long tmpLongValue = Math.abs(entry.getValue().setScale(maxScale).unscaledValue().longValue());
// if (gcd == -1L) {
// gcd = tmpLongValue;
// } else {
// gcd = RationalNumber.gcd(gcd, tmpLongValue);
// if (upper != null) {
// final BigDecimal tmpSetScale = upper.setScale(maxScale, RoundingMode.FLOOR);
// final long tmpLongValue = tmpSetScale.unscaledValue().longValue();
// upper = new BigDecimal(tmpLongValue).divide(new BigDecimal(gcd), maxScale, RoundingMode.FLOOR);
constrExpr.lower(lower).upper(upper);
}
}
public Optimisation.Result maximise() {
this.setMaximisation();
return this.optimise();
}
public Optimisation.Result minimise() {
this.setMinimisation();
return this.optimise();
}
public Expression objective() {
final Expression retVal = new Expression(OBJECTIVE, this);
Variable tmpVariable;
for (int i = 0; i < myVariables.size(); i++) {
tmpVariable = myVariables.get(i);
if (tmpVariable.isObjective()) {
retVal.set(i, tmpVariable.getContributionWeight());
}
}
BigDecimal tmpOldVal = null;
BigDecimal tmpDiff = null;
BigDecimal tmpNewVal = null;
for (final Expression tmpExpression : myExpressions.values()) {
if (tmpExpression.isObjective()) {
final BigDecimal tmpContributionWeight = tmpExpression.getContributionWeight();
final boolean tmpNotOne = tmpContributionWeight.compareTo(ONE) != 0; // To avoid multiplication by 1.0
if (tmpExpression.isAnyLinearFactorNonZero()) {
for (final IntIndex tmpKey : tmpExpression.getLinearKeySet()) {
tmpOldVal = retVal.get(tmpKey);
tmpDiff = tmpExpression.get(tmpKey);
tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff);
final Number value = tmpNewVal;
retVal.set(tmpKey, value);
}
}
if (tmpExpression.isAnyQuadraticFactorNonZero()) {
for (final IntRowColumn tmpKey : tmpExpression.getQuadraticKeySet()) {
tmpOldVal = retVal.get(tmpKey);
tmpDiff = tmpExpression.get(tmpKey);
tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff);
final Number value = tmpNewVal;
retVal.set(tmpKey, value);
}
}
}
}
return retVal;
}
/**
* <p>
* The general recommendation is to NOT call this method directly. Instead you should use/call
* {@link #maximise()} or {@link #minimise()}.
* </P>
* <p>
* The primary use case for this method is as a callback method for solvers that iteratively modifies the
* model and solves at each iteration point.
* </P>
* <p>
* With direct usage of this method:
* </P>
* <ul>
* <li>Maximisation/Minimisation is undefined (you don't know which it is)</li>
* <li>The solution is not written back to the model</li>
* <li>The solution is not validated by the model</li>
* </ul>
*/
public ExpressionsBasedModel.Intermediate prepare() {
return new ExpressionsBasedModel.Intermediate(this);
}
public ExpressionsBasedModel relax(final boolean inPlace) {
final ExpressionsBasedModel retVal = inPlace ? this : new ExpressionsBasedModel(this, true, true);
for (final Variable tmpVariable : retVal.getVariables()) {
tmpVariable.relax();
}
return retVal;
}
public ExpressionsBasedModel simplify() {
this.scanEntities();
this.presolve();
final ExpressionsBasedModel retVal = new ExpressionsBasedModel(this, true, false);
return retVal;
}
/**
* <p>
* Most likely you should NOT have been using this method directly. Instead you should have used/called
* {@link #maximise()} or {@link #minimise()}.
* </P>
* <p>
* In case you believe it was correct to use this method, you should now use {@link #prepare()} and then
* {@link Intermediate#solve(Optimisation.Result)} instead.
* </P>
*
* @deprecated v46
*/
@Deprecated
public Optimisation.Result solve(final Optimisation.Result candidate) {
return this.prepare().solve(candidate);
}
@Override
public String toString() {
final StringBuilder retVal = new StringBuilder(START_END);
for (final Variable tmpVariable : myVariables) {
tmpVariable.appendToString(retVal);
retVal.append(NEW_LINE);
}
for (final Expression tmpExpression : myExpressions.values()) {
// if ((tmpExpression.isConstraint() && !tmpExpression.isRedundant()) || tmpExpression.isObjective()) {
tmpExpression.appendToString(retVal, this.getVariableValues());
retVal.append(NEW_LINE);
}
return retVal.append(START_END).toString();
}
/**
* This methods validtes model construction only. All the other validate(...) method validates the
* solution (one way or another).
*
* @see org.ojalgo.optimisation.Optimisation.Model#validate()
*/
public boolean validate() {
final Printer appender = options.logger_detailed ? options.logger_appender : BasicLogger.NULL;
boolean retVal = true;
for (final Variable tmpVariable : myVariables) {
retVal &= tmpVariable.validate(appender);
}
for (final Expression tmpExpression : myExpressions.values()) {
retVal &= tmpExpression.validate(appender);
}
return retVal;
}
public boolean validate(final Access1D<BigDecimal> solution) {
final NumberContext context = options.feasibility;
final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL;
return this.validate(solution, context, appender);
}
public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context) {
final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL;
return this.validate(solution, context, appender);
}
public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context, final Printer appender) {
ProgrammingError.throwIfNull(solution, context, appender);
final int size = myVariables.size();
boolean retVal = size == solution.count();
for (int i = 0; retVal && (i < size); i++) {
final Variable tmpVariable = myVariables.get(i);
final BigDecimal value = solution.get(i);
retVal &= tmpVariable.validate(value, context, appender);
}
if (retVal) {
for (final Expression tmpExpression : myExpressions.values()) {
final BigDecimal value = tmpExpression.evaluate(solution);
retVal &= tmpExpression.validate(value, context, appender);
}
}
return retVal;
}
public boolean validate(final Access1D<BigDecimal> solution, final Printer appender) {
final NumberContext context = options.feasibility;
return this.validate(solution, context, appender);
}
public boolean validate(final NumberContext context) {
final Result solution = this.getVariableValues(context);
final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL;
return this.validate(solution, context, appender);
}
public boolean validate(final NumberContext context, final Printer appender) {
final Access1D<BigDecimal> solution = this.getVariableValues(context);
return this.validate(solution, context, appender);
}
public boolean validate(final Printer appender) {
final NumberContext context = options.feasibility;
final Result solution = this.getVariableValues(context);
return this.validate(solution, context, appender);
}
/**
* @return A stream of variables that are not fixed
*/
public Stream<Variable> variables() {
return myVariables.stream().filter((final Variable v) -> (!v.isEqualityConstraint()));
}
private void categoriseVariables() {
final int tmpLength = myVariables.size();
myFreeVariables.clear();
myFreeIndices = new int[tmpLength];
Arrays.fill(myFreeIndices, -1);
myPositiveVariables.clear();
myPositiveIndices = new int[tmpLength];
Arrays.fill(myPositiveIndices, -1);
myNegativeVariables.clear();
myNegativeIndices = new int[tmpLength];
Arrays.fill(myNegativeIndices, -1);
myIntegerVariables.clear();
myIntegerIndices = new int[tmpLength];
Arrays.fill(myIntegerIndices, -1);
for (int i = 0; i < tmpLength; i++) {
final Variable tmpVariable = myVariables.get(i);
if (!tmpVariable.isFixed()) {
myFreeVariables.add(tmpVariable);
myFreeIndices[i] = myFreeVariables.size() - 1;
if (!tmpVariable.isUpperLimitSet() || (tmpVariable.getUpperLimit().signum() == 1)) {
myPositiveVariables.add(tmpVariable);
myPositiveIndices[i] = myPositiveVariables.size() - 1;
}
if (!tmpVariable.isLowerLimitSet() || (tmpVariable.getLowerLimit().signum() == -1)) {
myNegativeVariables.add(tmpVariable);
myNegativeIndices[i] = myNegativeVariables.size() - 1;
}
if (tmpVariable.isInteger()) {
myIntegerVariables.add(tmpVariable);
myIntegerIndices[i] = myIntegerVariables.size() - 1;
}
}
}
}
/**
* @param constraints Linear constraints with all binary variables
*/
private void generateCuts(final Set<Expression> constraints) {
if ((constraints != null) && (constraints.size() > 0)) {
final List<Variable> posBinVar = new ArrayList<>();
final List<Variable> negBinVar = new ArrayList<>();
final Set<IntIndex> indices = new HashSet<>();
final Set<IntIndex> fixedVariables = this.getFixedVariables();
for (final Expression tmpExpression : constraints) {
posBinVar.clear();
negBinVar.clear();
indices.clear();
indices.addAll(tmpExpression.getLinearKeySet());
final int countExprVars = indices.size();
indices.removeAll(fixedVariables);
for (final IntIndex tmpIndex : indices) {
final Variable tmpVariable = this.getVariable(tmpIndex);
if (tmpVariable.isBinary()) {
final BigDecimal tmpFactor = tmpExpression.get(tmpIndex);
if (tmpFactor.signum() == 1) {
posBinVar.add(tmpVariable);
} else if (tmpFactor.signum() == -1) {
negBinVar.add(tmpVariable);
}
}
}
if ((posBinVar.size() == indices.size()) && (posBinVar.size() != countExprVars) && (posBinVar.size() != 0)) {
// All remaining (not fixed) variables are binary with positive constraint factors
final BigDecimal ul = tmpExpression.getUpperLimit();
if ((ul != null) && (ul.signum() != -1)) {
posBinVar.sort((v1, v2) -> tmpExpression.get(v1.getIndex()).compareTo(tmpExpression.get(v2.getIndex())));
BigDecimal accum = BigMath.ZERO;
int count = 0;
for (final Variable tmpVariable : posBinVar) {
accum = accum.add(tmpExpression.get(tmpVariable));
if (accum.compareTo(ul) > 0) {
final Expression tmpNewCut = this.addExpression("Cut-" + tmpExpression.getName());
tmpNewCut.setLinearFactorsSimple(posBinVar);
tmpNewCut.upper(new BigDecimal(count));
break;
}
count++;
}
}
}
if (posBinVar.size() == indices.size()) {
// All remaining (not fixed) variables are binary with negative constraint factors
}
}
}
}
private void scanEntities() {
final Set<IntIndex> fixedVariables = Collections.emptySet();
final BigDecimal fixedValue = BigMath.ZERO;
for (final Expression tmpExpression : myExpressions.values()) {
Presolvers.LINEAR_OBJECTIVE.simplify(tmpExpression, fixedVariables, fixedValue, this::getVariable, options.feasibility);
if (tmpExpression.isConstraint()) {
Presolvers.ZERO_ONE_TWO.simplify(tmpExpression, fixedVariables, fixedValue, this::getVariable, options.feasibility);
}
}
for (final Variable tmpVariable : myVariables) {
Presolvers.FIXED_OR_UNBOUNDED.simplify(tmpVariable, this);
}
}
Stream<Expression> expressions() {
return myExpressions.values().stream();
}
ExpressionsBasedModel.Integration<?> getIntegration() {
ExpressionsBasedModel.Integration<?> retVal = null;
for (final ExpressionsBasedModel.Integration<?> tmpIntegration : INTEGRATIONS) {
if (tmpIntegration.isCapable(this)) {
retVal = tmpIntegration;
break;
}
}
if (retVal == null) {
if (this.isAnyVariableInteger()) {
if (INTEGER_INTEGRATION.isCapable(this)) {
retVal = INTEGER_INTEGRATION;
}
} else {
if (CONVEX_INTEGRATION.isCapable(this)) {
retVal = CONVEX_INTEGRATION;
} else if (LINEAR_INTEGRATION.isCapable(this)) {
retVal = LINEAR_INTEGRATION;
}
}
}
if (retVal == null) {
throw new ProgrammingError("No solver integration available that can handle this model!");
}
return retVal;
}
boolean isFixed() {
return myVariables.stream().allMatch(v -> v.isFixed());
}
boolean isInfeasible() {
for (final Expression tmpExpression : myExpressions.values()) {
if (tmpExpression.isInfeasible()) {
return true;
}
}
for (final Variable tmpVariable : myVariables) {
if (tmpVariable.isInfeasible()) {
return true;
}
}
return false;
}
boolean isUnbounded() {
return myVariables.stream().anyMatch(v -> v.isUnbounded());
}
Optimisation.Result optimise() {
if (PRESOLVERS.size() > 0) {
this.scanEntities();
}
final Optimisation.Result solver = this.prepare().solve(null);
for (int i = 0, limit = myVariables.size(); i < limit; i++) {
final Variable tmpVariable = myVariables.get(i);
if (!tmpVariable.isFixed()) {
tmpVariable.setValue(options.solution.enforce(solver.get(i)));
}
}
final Access1D<BigDecimal> retSolution = this.getVariableValues();
final Optimisation.State retState = solver.getState();
final double retValue = this.objective().evaluate(retSolution).doubleValue();
return new Optimisation.Result(retState, retValue, retSolution);
}
final void presolve() {
myExpressions.values().forEach(expr -> expr.setRedundant(false));
boolean needToRepeat = false;
do {
final Set<IntIndex> fixedVariables = this.getFixedVariables();
BigDecimal fixedValue;
needToRepeat = false;
for (final Expression expr : this.getExpressions()) {
if (!needToRepeat && expr.isConstraint() && !expr.isInfeasible() && !expr.isRedundant() && (expr.countQuadraticFactors() == 0)) {
fixedValue = options.solution.enforce(expr.calculateFixedValue(fixedVariables));
for (final Presolver presolver : PRESOLVERS) {
if (!needToRepeat) {
needToRepeat |= presolver.simplify(expr, fixedVariables, fixedValue, this::getVariable, options.solution);
}
}
}
}
} while (needToRepeat);
this.categoriseVariables();
}
} |
package hudson.tasks;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jenkins.model.Jenkins;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.Functions;
import hudson.model.User;
/**
* Infers avatar image URLs for users
*
* <p>
* This is an extension point of Jenkins. Plugins that contribute a new implementation
* of this class should put {@link Extension} on your implementation class, like this:
*
* <pre>
* @Extension
* class MyUserAvatarResolver extends {@link UserAvatarResolver} {
* ...
* }
* </pre>
*
* @author Erik Ramfelt
* @since 1.434
*/
public abstract class UserAvatarResolver implements ExtensionPoint {
/** Regex pattern for splitting up the icon size string that is used in jelly pages. */
static Pattern iconSizeRegex = Pattern.compile("(\\d+)x(\\d+)");
/**
* Finds an avatar image URL string for a user.
*
* <p>
* This method is called when a web page is going to show an avatar for a {@link User}.
*
* <p>
* When multiple resolvers are installed, they are consulted in order and
* the search will be over when an avatar is found by someoene.
*
* <p>
* Since {@link UserAvatarResolver} is singleton, this method can be invoked concurrently
* from multiple threads.
* @param u the user
* @param width the preferred width of the avatar
* @param height the preferred height of the avatar.
*
* @return null if the inference failed.
*/
public abstract String findAvatarFor(User u, int width, int height);
/**
* Resolve an avatar image URL string for the user
* @param u user
* @param avatarSize the preferred image size, "[width]x[height]"
* @return a URL string for a user Avatar image.
*/
public static String resolve(User u, String avatarSize) {
Matcher matcher = iconSizeRegex.matcher(avatarSize);
if (matcher.matches() && matcher.groupCount() == 2) {
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
for (UserAvatarResolver r : all()) {
String name = r.findAvatarFor(u, width, height);
if(name!=null) return name;
}
} else {
LOGGER.warning(String.format("Could not split up the avatar size (%s) into a width and height.", avatarSize));
}
return Jenkins.getInstance().getRootUrl() + Functions.getResourcePath() + "/images/" + avatarSize + "/user.png";
}
/**
* Returns all the registered {@link UserAvatarResolver} descriptors.
*/
public static ExtensionList<UserAvatarResolver> all() {
return Jenkins.getInstance().getExtensionList(UserAvatarResolver.class);
}
private static final Logger LOGGER = Logger.getLogger(UserAvatarResolver.class.getName());
} |
// obtaining a copy of this software and associated documentation /
// files (the "Software"), to deal in the Software without /
// restriction, including without limitation the rights to use, /
// sell copies of the Software, and to permit persons to whom the /
// Software is furnished to do so, subject to the following /
// conditions: /
// included in all copies or substantial portions of the Software. /
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES /
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND /
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, /
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE /
// OR OTHER DEALINGS IN THE SOFTWARE. /
package org.asn1s.core;
import org.apache.commons.lang3.StringUtils;
import org.asn1s.api.Scope;
import org.asn1s.api.TemplateParameter;
import org.asn1s.api.Validation;
import org.asn1s.api.exception.ResolutionException;
import org.asn1s.api.exception.ValidationException;
import org.asn1s.api.type.Type;
import org.asn1s.api.value.ByteArrayValue;
import org.asn1s.api.value.Value;
import org.asn1s.api.value.Value.Kind;
import org.asn1s.api.value.x680.NamedValue;
import org.asn1s.core.type.DefinedTypeTemplate;
import org.asn1s.core.value.x680.ByteArrayValueImpl;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
@SuppressWarnings( {"UtilityClassCanBeEnum", "UtilityClass"} )
public final class CoreUtils
{
private static final int BYTE_MASK = 0xFF;
private static final Pattern CLEAR_HEX_PATTERN = Pattern.compile( "[^A-Za-z0-9]" );
private static final Pattern CLEAR_BIN_PATTERN = Pattern.compile( "[^0-1]" );
private static final byte[] EMPTY_ARRAY = new byte[0];
private static final int HEX_RADIX = 16;
private static final int BIN_RADIX = 2;
public static final String CORE_MODULE_NAME = "ASN14J-CORE-MODULE";
private CoreUtils()
{
}
private static final Pattern BIN_HEX_PATTERN = Pattern.compile( "^'([A-Za-z0-9]'H|[01]'B)$" );
public static boolean isConvertibleToByteArrayValue( CharSequence content )
{
return BIN_HEX_PATTERN.matcher( content ).matches();
}
public static int compareNumberToNamed( Value lhs, NamedValue rhs )
{
assert lhs.getKind() == Kind.Real || lhs.getKind() == Kind.Integer;
Kind kind = rhs.getReferenceKind();
if( kind == Kind.Real || kind == Kind.Integer )
{
assert rhs.getValueRef() instanceof Value;
return lhs.compareTo( (Value)rhs.getValueRef() );
}
throw new UnsupportedOperationException( "Unable to compare number value to " + kind );
}
public static void assertParameterMap( Scope scope, Map<String, TemplateParameter> parameterMap ) throws ValidationException, ResolutionException
{
if( parameterMap.isEmpty() )
throw new ValidationException( "No parameters for template type" );
for( TemplateParameter parameter : parameterMap.values() )
{
assertReference( parameter );
assertGovernor( scope, parameter );
}
}
private static void assertReference( TemplateParameter parameter ) throws ValidationException
{
if( parameter.isTypeRef() )
return;
if( parameter.isValueRef() && parameter.getGovernor() == null )
throw new ValidationException( "Governor type must be present for value parameter" );
}
private static void assertGovernor( Scope scope, TemplateParameter parameter ) throws ResolutionException, ValidationException
{
if( parameter.getGovernor() == null )
return;
Type type = parameter.getGovernor().resolve( scope );
if( type instanceof DefinedTypeTemplate )
throw new ValidationException( "Unable to use Type template as governor" );
}
@NotNull
public static ByteArrayValue byteArrayFromBitString( @NotNull String content )
{
content = normalizeBitString( content );
try( ByteArrayOutputStream os = new ByteArrayOutputStream() )
{
return convertBitString( content, os );
} catch( IOException e )
{
throw new IllegalStateException( e );
}
}
private static String normalizeBitString( @NotNull String content )
{
if( !content.startsWith( "'" ) && content.endsWith( "'B" ) )
throw new IllegalArgumentException( "Not BString: " + content );
return CLEAR_BIN_PATTERN.matcher( content.substring( 1, content.length() - 2 ) ).replaceAll( "" );
}
@NotNull
private static ByteArrayValue convertBitString( @NotNull String content, ByteArrayOutputStream os )
{
for( int i = 0; i * 8 < content.length(); i++ )
writeOctetFromBits( content, os, i );
byte[] bytes = os.toByteArray();
int usedBits = content.length();
return usedBits > 0
? new ByteArrayValueImpl( usedBits, bytes )
: new ByteArrayValueImpl( 0, EMPTY_ARRAY );
}
private static void writeOctetFromBits( @NotNull String content, ByteArrayOutputStream os, int i )
{
String value = content.substring( i * 8, Math.min( i * 8 + 8, content.length() ) );
int size = value.length();
if( size < 8 )
{
StringBuilder sb = new StringBuilder();
sb.append( value );
for( int k = size; k < 8; k++ )
sb.append( '0' );
value = sb.toString();
}
os.write( Integer.parseInt( value, BIN_RADIX ) & BYTE_MASK );
}
@NotNull
public static ByteArrayValue byteArrayFromHexString( @NotNull String content )
{
content = normalizeHexString( content );
try( ByteArrayOutputStream os = new ByteArrayOutputStream() )
{
return convertHexString( content, os );
} catch( IOException e )
{
throw new IllegalStateException( e );
}
}
private static String normalizeHexString( @NotNull String content )
{
if( !content.startsWith( "'" ) && content.endsWith( "'H" ) )
throw new IllegalArgumentException( "Not HString: " + content );
return CLEAR_HEX_PATTERN.matcher( content.substring( 1, content.length() - 2 ) ).replaceAll( "" );
}
@NotNull
private static ByteArrayValue convertHexString( @NotNull String content, ByteArrayOutputStream os )
{
for( int i = 0; i * 2 < content.length(); i++ )
writeOctet( content, os, i );
byte[] bytes = os.toByteArray();
int usedBits = content.length() * 4;
return usedBits > 0
? new ByteArrayValueImpl( usedBits, bytes )
: new ByteArrayValueImpl( 0, EMPTY_ARRAY );
}
private static void writeOctet( @NotNull String content, ByteArrayOutputStream os, int i )
{
int size = Math.min( i * 2 + 2, content.length() );
//noinspection NonConstantStringShouldBeStringBuffer
String value = content.substring( i * 2, size );
if( value.length() == 1 )
value += "0";
os.write( Integer.parseInt( value, HEX_RADIX ) & BYTE_MASK );
}
public static String paramMapToString( Map<String, TemplateParameter> parameterMap )
{
List<TemplateParameter> parameters = new ArrayList<>( parameterMap.values() );
parameters.sort( Comparator.comparingInt( TemplateParameter:: getIndex ) );
return StringUtils.join( parameters, ", " );
}
public static void resolutionValidate( Scope scope, Validation copy ) throws ResolutionException
{
try
{
copy.validate( scope );
} catch( ValidationException e )
{
throw new ResolutionException( "Unable to create new template type instance", e );
}
}
} |
package VASSAL.chat.node;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import VASSAL.Info;
import VASSAL.build.GameModule;
import VASSAL.chat.Compressor;
import VASSAL.chat.InviteCommand;
import VASSAL.chat.InviteEncoder;
import VASSAL.chat.LockableChatServerConnection;
import VASSAL.chat.LockableRoom;
import VASSAL.chat.MainRoomChecker;
import VASSAL.chat.Player;
import VASSAL.chat.PlayerEncoder;
import VASSAL.chat.PrivateChatEncoder;
import VASSAL.chat.PrivateChatManager;
import VASSAL.chat.Room;
import VASSAL.chat.SimplePlayer;
import VASSAL.chat.SimpleRoom;
import VASSAL.chat.SimpleStatus;
import VASSAL.chat.SoundEncoder;
import VASSAL.chat.SynchEncoder;
import VASSAL.chat.WelcomeMessageServer;
import VASSAL.chat.ui.ChatControlsInitializer;
import VASSAL.chat.ui.ChatServerControls;
import VASSAL.chat.ui.InviteAction;
import VASSAL.chat.ui.KickAction;
import VASSAL.chat.ui.LockableRoomTreeRenderer;
import VASSAL.chat.ui.PrivateMessageAction;
import VASSAL.chat.ui.RoomInteractionControlsInitializer;
import VASSAL.chat.ui.SendSoundAction;
import VASSAL.chat.ui.ShowProfileAction;
import VASSAL.chat.ui.SimpleStatusControlsInitializer;
import VASSAL.chat.ui.SynchAction;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.i18n.Resources;
import VASSAL.tools.PropertiesEncoder;
import VASSAL.tools.SequenceEncoder;
/**
* @author rkinney
*/
public class NodeClient implements LockableChatServerConnection,
PlayerEncoder, ChatControlsInitializer, SocketWatcher {
public static final String ZIP_HEADER = "!ZIP!"; //$NON-NLS-1$
protected PropertyChangeSupport propSupport = new PropertyChangeSupport(this);
protected NodePlayer me;
protected SimpleRoom currentRoom;
protected String defaultRoomName = DEFAULT_ROOM_NAME; //$NON-NLS-1$
protected NodeRoom[] allRooms = new NodeRoom[0];
protected String moduleName;
protected String playerId;
protected MainRoomChecker checker = new MainRoomChecker();
protected int compressionLimit = 1000;
protected CommandEncoder encoder;
protected RoomInteractionControlsInitializer roomControls;
protected SimpleStatusControlsInitializer playerStatusControls;
protected SoundEncoder soundEncoder;
protected PrivateChatEncoder privateChatEncoder;
protected SynchEncoder synchEncoder;
protected InviteEncoder inviteEncoder;
protected PropertyChangeListener nameChangeListener;
protected PropertyChangeListener profileChangeListener;
protected NodeRoom pendingSynchToRoom;
private SocketHandler sender;
protected final String host;
protected final int port;
protected final WelcomeMessageServer welcomer;
public NodeClient(String moduleName, String playerId, CommandEncoder encoder, String host, int port, WelcomeMessageServer welcomer) {
this.host = host;
this.port = port;
this.encoder = encoder;
this.welcomer = welcomer;
this.playerId = playerId;
this.moduleName = moduleName;
me = new NodePlayer(playerId);
roomControls = new LockableNodeRoomControls(this);
roomControls.addPlayerActionFactory(ShowProfileAction.factory());
roomControls.addPlayerActionFactory(SynchAction.factory(this));
final PrivateChatManager privateChatManager = new PrivateChatManager(this);
roomControls.addPlayerActionFactory(PrivateMessageAction.factory(this,
privateChatManager));
roomControls.addPlayerActionFactory(SendSoundAction.factory(this, Resources
.getString("Chat.send_wakeup"), "wakeUpSound", "phone1.wav")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
roomControls.addPlayerActionFactory(InviteAction.factory(this));
roomControls.addPlayerActionFactory(KickAction.factory(this));
playerStatusControls = new SimpleStatusControlsInitializer(this);
synchEncoder = new SynchEncoder(this, this);
privateChatEncoder = new PrivateChatEncoder(this, privateChatManager);
soundEncoder = new SoundEncoder(this);
inviteEncoder = new InviteEncoder(this);
nameChangeListener = e -> {
final SimplePlayer p = (SimplePlayer) getUserInfo();
p.setName((String) e.getNewValue());
setUserInfo(p);
};
profileChangeListener = e -> {
final SimplePlayer p = (SimplePlayer) getUserInfo();
SimpleStatus s = (SimpleStatus) p.getStatus();
s = new SimpleStatus(
s.isLooking(),
s.isAway(),
(String) e.getNewValue(),
s.getClient(),
s.getIp(),
s.getModuleVersion(),
s.getCrc()
);
p.setStatus(s);
setUserInfo(p);
};
}
@Override
public void setConnected(boolean connect) {
if (connect) {
if (!isConnected()) {
try {
final NodePlayer oldPlayer = me;
me = new NodePlayer(playerId);
setUserInfo(oldPlayer);
initializeConnection();
final Command welcomeMessage = welcomer.getWelcomeMessage();
if (welcomeMessage != null) {
welcomeMessage.execute();
}
registerNewConnection();
}
// FIXME: review error message
catch (final IOException e) {
propSupport.firePropertyChange(STATUS, null, Resources.getString(
"Chat.unable_to_establish", e.getMessage())); //$NON-NLS-1$
}
}
}
else {
if (isConnected()) {
closeConnection();
}
currentRoom = null;
allRooms = new NodeRoom[0];
}
propSupport.firePropertyChange(CONNECTED, null,
isConnected() ? Boolean.TRUE : Boolean.FALSE);
}
protected void registerNewConnection() {
synchronized (this) {
if (sender == null) { // If already hung up
return;
}
final String path = new SequenceEncoder(moduleName, '/').append(defaultRoomName)
.getValue();
send(Protocol.encodeRegisterCommand(me.getId(), path,
new PropertiesEncoder(me.toProperties()).getStringValue()));
if (GameModule.getGameModule() != null) {
final String username = (String) GameModule.getGameModule().getPrefs()
.getValue("Login"); //$NON-NLS-1$
if (username != null) {
send(Protocol.encodeLoginCommand(username));
}
}
}
}
protected void initializeConnection() throws UnknownHostException, IOException {
final Socket s = new Socket(host, port);
synchronized (this) {
sender = new SocketHandler(s, this);
sender.start();
}
}
protected void closeConnection() {
final SocketHandler s;
synchronized (this) {
s = sender;
sender = null;
}
s.close();
}
@Override
public boolean isConnected() {
synchronized (this) {
return sender != null;
}
}
@Override
public void socketClosed(SocketHandler handler) {
synchronized (this) {
if (sender != null) {
propSupport.firePropertyChange(STATUS, null, Resources.getString("Server.lost_connection")); //$NON-NLS-1$
propSupport.firePropertyChange(CONNECTED, null, Boolean.FALSE);
sender = null;
}
}
}
public void send(String command) {
synchronized (this) {
sender.writeLine(command);
}
}
public void setDefaultRoomName(String defaultRoomName) {
this.defaultRoomName = defaultRoomName;
}
@Override
public String getDefaultRoomName() {
return defaultRoomName;
}
@Override
public boolean isDefaultRoom(Room r) {
return r != null && r.getName().equals(getDefaultRoomName());
}
protected void sendStats() {
if (isConnected()) {
send(Protocol.encodeStatsCommand(new PropertiesEncoder(me.toProperties())
.getStringValue()));
}
}
@Override
public void sendToOthers(Command c) {
sendToOthers(encoder.encode(c));
}
public void sendToAll(String msg) {
if (currentRoom != null) {
final String path = new SequenceEncoder(moduleName, '/').append(
currentRoom.getName()).getValue();
forward(path, msg);
}
}
public void forward(String receipientPath, String msg) {
if (isConnected() && currentRoom != null && msg != null) {
msg = checker.filter(msg, defaultRoomName, currentRoom.getName());
if (msg.length() > compressionLimit) {
try {
msg = ZIP_HEADER + Base64.encodeBase64String(
Compressor.compress(msg.getBytes(StandardCharsets.UTF_8))
);
}
// FIXME: review error message
catch (final IOException e) {
e.printStackTrace();
}
}
send(Protocol.encodeForwardCommand(receipientPath, msg));
}
}
public void sendToOthers(String msg) {
if (currentRoom != null) {
final String path = new SequenceEncoder(moduleName, '/').append(
currentRoom.getName()).append("~" + me.getId()).getValue(); //$NON-NLS-1$
forward(path, msg);
}
}
@Override
public void sendTo(Player recipient, Command c) {
final String path = new SequenceEncoder(moduleName, '/')
.append("*").append(recipient.getId()).getValue(); //$NON-NLS-1$
forward(path, encoder.encode(c));
}
@Override
public void doKick(Player kickee) {
send(Protocol.encodeKickCommand(kickee.getId()));
}
@Override
public boolean isKickable(Player kickee) {
if (kickee != null) {
final Room room = getRoom();
// Is this a locked room?
if (room instanceof LockableRoom && ((LockableRoom) room).isLocked()) {
if (room instanceof NodeRoom) {
// Is the target player in the same room?
if (((NodeRoom) room).contains(kickee)) {
final String owner = ((NodeRoom) room).getOwner();
// Do I own this room and the target is not me?
if (owner != null && owner.equals(getUserInfo().getId())
&& !owner.equals(kickee.getId())) {
return true;
}
}
}
}
}
return false;
}
@Override
public boolean isInvitable(Player invitee) {
if (invitee != null) {
final Room room = getRoom();
if (room instanceof NodeRoom) {
// Is the target player in a different room?
if (!((NodeRoom) room).contains(invitee)) {
final String owner = ((NodeRoom) room).getOwner();
// Do I own this room and the target is not me?
if (owner != null && owner.equals(getUserInfo().getId())
&& !owner.equals(invitee.getId())) {
return true;
}
}
}
}
return false;
}
/**
* Send Invitation to another player to join the current room
*
* @param invitee
* Player to invite
*/
@Override
public void sendInvite(Player invitee) {
sendTo(invitee, new InviteCommand(me.getName(), me.getId(), getRoom()
.getName()));
}
/**
* Process an invitation request from a player to join a room
*
* @param playerId Inviting player name
* @param roomName Inviting room
*/
@Override
public void doInvite(String playerId, String roomName) {
for (final Room room : getAvailableRooms()) {
if (room.getName().equals(roomName)) {
if (room instanceof NodeRoom) {
final String owner = ((NodeRoom) room).getOwner();
if (owner != null && owner.equals(playerId)) {
setRoom(room, playerId);
return;
}
}
}
}
}
@Override
public Room getRoom() {
return currentRoom;
}
@Override
public Room[] getAvailableRooms() {
return allRooms;
}
@Override
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener l) {
propSupport.addPropertyChangeListener(propertyName, l);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propSupport.addPropertyChangeListener(l);
}
@Override
public Player getUserInfo() {
return me;
}
public NodePlayer getMyInfo() {
return me;
}
@Override
public void setUserInfo(Player p) {
me.setName(p.getName());
me.setStatus(p.getStatus());
sendStats();
propSupport.firePropertyChange(PLAYER_INFO, null, me);
}
@Override
public void lockRoom(LockableRoom r) {
if (r instanceof NodeRoom) {
final NodeRoom n = (NodeRoom) r;
if (n.getOwner().equals(me.getId())) {
n.toggleLock();
sendRoomInfo(n);
propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
}
}
public void sendRoomInfo(NodeRoom r) {
final Node dummy = new Node(null, r.getName(), new PropertiesEncoder(r.getInfo())
.getStringValue());
if (isConnected()) {
final String msg = Protocol.encodeRoomsInfo(new Node[] { dummy });
send(msg);
}
}
@Override
public void setRoom(Room r) {
setRoom(r, null);
}
public void setRoom(Room r, String password) {
if (isConnected()) {
final String newRoom = r.getName();
final String newPath = new SequenceEncoder(moduleName, '/').append(
newRoom).getValue();
final String msg = Protocol.encodeJoinCommand(newPath, password);
send(msg);
// Request a synch if we are not the owner
if (r instanceof NodeRoom) {
final NodeRoom room = (NodeRoom) r;
if (newRoom.equals(defaultRoomName)) {
GameModule.getGameModule().setGameFileMode(GameModule.GameFileMode.NEW_GAME);
GameModule.getGameModule().getGameState().setup(false);
}
else if (!room.isOwner(me)) {
// We are not actually recorded as being in the new room until we get
// an update back from
// the server. Record a Synch required to the new room.
pendingSynchToRoom = room;
GameModule.getGameModule().warn(
Resources.getString("Chat.synchronize_pending"));
}
}
}
}
/**
* Process a message received from the server
*
* @param msg
* Encoded message
*/
public void handleMessageFromServer(String msg) {
final Node n;
final Properties p;
if ((n = Protocol.decodeListCommand(msg)) != null) {
final Node mod = n.getChild(moduleName);
if (mod != null) {
updateRooms(mod);
}
// Rooms have been updated with any new players (including us), so perform
// a Synchronize
// for a move to a new room if needed.
if (pendingSynchToRoom != null) {
new SynchAction(pendingSynchToRoom.getOwningPlayer(), this)
.actionPerformed(null);
pendingSynchToRoom = null;
GameModule.getGameModule().warn(
Resources.getString("Chat.synchronize_complete"));
}
}
else if ((p = Protocol.decodeRoomsInfo(msg)) != null) {
for (final NodeRoom aRoom : allRooms) {
final String infoString = p.getProperty(aRoom.getName());
if (infoString != null && infoString.length() > 0) {
try {
final Properties info = new PropertiesEncoder(infoString).getProperties();
aRoom.setInfo(info);
}
// FIXME: review error message
catch (final IOException e) {
e.printStackTrace();
}
}
}
propSupport.firePropertyChange(ROOM, null, currentRoom);
propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
else if (Protocol.decodeRegisterRequest(msg)) {
registerNewConnection();
}
else {
if (msg.startsWith(ZIP_HEADER)) {
try {
msg = new String(
Compressor.decompress(
Base64.decodeBase64(
msg.substring(ZIP_HEADER.length())
)
),
StandardCharsets.UTF_8
);
}
// FIXME: review error message
catch (final IOException e) {
e.printStackTrace();
}
}
propSupport.firePropertyChange(INCOMING_MSG, null, msg);
}
}
@Override
public void handleMessage(String msg) {
handleMessageFromServer(msg);
}
protected void updateRooms(Node module) {
final Node[] roomNodes = module.getChildren();
final NodeRoom[] rooms = new NodeRoom[roomNodes.length];
int defaultRoomIndex = -1;
for (int i = 0; i < roomNodes.length; ++i) {
final Node[] playerNodes = roomNodes[i].getChildren();
final NodePlayer[] players = new NodePlayer[playerNodes.length];
boolean containsMe = false;
for (int j = 0; j < playerNodes.length; ++j) {
players[j] = new NodePlayer(playerNodes[j].getId());
if (players[j].equals(me)) {
containsMe = true;
}
try {
final Properties p = new PropertiesEncoder(playerNodes[j].getInfo())
.getProperties();
players[j].setInfo(p);
if (players[j].equals(me)) {
me.setInfo(p);
}
}
// FIXME: review error message
catch (final IOException e) {
e.printStackTrace();
}
}
rooms[i] = new NodeRoom(roomNodes[i].getId(), players);
// Lock room to start with. The ROOM_INFO message will unlock
// any rooms that are not locked. Prevents unwanted clients from
// connecting while room is in an undefined state.
if (!rooms[i].getName().equals(defaultRoomName)) {
rooms[i].lock();
}
try {
if (roomNodes[i].getInfo() != null) {
rooms[i].setInfo(new PropertiesEncoder(roomNodes[i].getInfo())
.getProperties());
}
}
// FIXME: review error message
catch (final IOException e) {
e.printStackTrace();
}
if (containsMe) {
currentRoom = rooms[i];
}
if (defaultRoomName.equals(rooms[i].getName())) {
defaultRoomIndex = i;
}
}
if (defaultRoomIndex < 0) {
allRooms = ArrayUtils.addFirst(rooms, new NodeRoom(defaultRoomName));
}
else {
allRooms = rooms;
final NodeRoom swap = allRooms[0];
allRooms[0] = allRooms[defaultRoomIndex];
allRooms[defaultRoomIndex] = swap;
}
// Do not fire a PropertyChange request, The server will be following
// immediately
// with a Room List refresh which can cause Icons to flash unexpectedly.
// propSupport.firePropertyChange(ROOM, null, currentRoom);
// propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
@Override
public Player stringToPlayer(String s) {
NodePlayer p = null;
try {
final PropertiesEncoder propEncoder = new PropertiesEncoder(s);
p = new NodePlayer(null);
p.setInfo(propEncoder.getProperties());
}
// FIXME: review error message
catch (final IOException e) {
e.printStackTrace();
}
return p;
}
@Override
public String playerToString(Player p) {
final Properties props = ((NodePlayer) p).toProperties();
return new PropertiesEncoder(props).getStringValue();
}
@Override
public void initializeControls(ChatServerControls controls) {
playerStatusControls.initializeControls(controls);
roomControls.initializeControls(controls);
controls.setRoomControlsVisible(true);
final GameModule g = GameModule.getGameModule();
g.addCommandEncoder(synchEncoder);
g.addCommandEncoder(privateChatEncoder);
g.addCommandEncoder(soundEncoder);
g.addCommandEncoder(inviteEncoder);
me.setName((String) g.getPrefs().getValue(GameModule.REAL_NAME));
g.getPrefs().getOption(GameModule.REAL_NAME).addPropertyChangeListener(
nameChangeListener);
SimpleStatus s = (SimpleStatus) me.getStatus();
s = new SimpleStatus(s.isLooking(), s.isAway(), (String) g.getPrefs()
.getValue(GameModule.PERSONAL_INFO), Info.getVersion(), s.getIp(), g
.getGameVersion()
+ ((g.getArchiveWriter() == null) ? "" : " " + Resources.getString("Editor.NodeClient.editing")), Long
.toHexString(g.getCrc()));
me.setStatus(s);
g.getPrefs().getOption(GameModule.PERSONAL_INFO).addPropertyChangeListener(
profileChangeListener);
controls.getRoomTree().setCellRenderer(new LockableRoomTreeRenderer());
}
@Override
public void uninitializeControls(ChatServerControls controls) {
roomControls.uninitializeControls(controls);
playerStatusControls.uninitializeControls(controls);
final GameModule g = GameModule.getGameModule();
g.removeCommandEncoder(synchEncoder);
g.removeCommandEncoder(privateChatEncoder);
g.removeCommandEncoder(soundEncoder);
g.removeCommandEncoder(inviteEncoder);
g.getPrefs().getOption(GameModule.REAL_NAME)
.removePropertyChangeListener(nameChangeListener);
g.getPrefs().getOption(GameModule.PERSONAL_INFO)
.removePropertyChangeListener(profileChangeListener);
}
} |
package com.showka.domain;
import java.time.LocalDate;
import com.showka.kubun.NyukinHohoKubun;
import com.showka.kubun.NyukinTsukiKubun;
import com.showka.system.exception.SystemException;
import com.showka.value.TheDate;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Doman
*
* @author ShowKa
*
*/
@AllArgsConstructor
@Getter
public class NyukinKakeInfoDomain extends DomainBase {
// private member
private String kokyakuId = STRING_EMPTY;
private Integer shimeDate = INTEGER_EMPTY;
private NyukinTsukiKubun nyukinTsukiKubun = NyukinTsukiKubun.EMPTY;
private NyukinHohoKubun nyukinHohoKubun = NyukinHohoKubun.EMPTY;
private Integer nyukinDate = INTEGER_EMPTY;
private Integer version = INTEGER_EMPTY;
/**
*
*
* <pre>
* =
* </pre>
*
* @return
*/
public Integer getNyukinSight() {
return (30 * nyukinTsukiKubun.getMonthSpan()) + (nyukinDate - shimeDate);
}
/**
*
*
* @param date
*
* @return
*/
public TheDate getNextSeikyuSimeDate(TheDate date) {
LocalDate _d = date.getDate();
LocalDate shimeDateOfThisMonth = _d.withDayOfMonth(shimeDate);
if (shimeDateOfThisMonth.getDayOfMonth() > shimeDate) {
return new TheDate(shimeDateOfThisMonth);
}
return new TheDate(shimeDateOfThisMonth.plusMonths(1));
}
/**
*
*
*
* @param date
*
* @return
*/
public TheDate getNyukinYoteiDate(TheDate date) {
TheDate nextShimeDate = getNextSeikyuSimeDate(date);
LocalDate nyukinMonth = nextShimeDate.getDate().plusMonths(nyukinTsukiKubun.getMonthSpan());
return new TheDate(nyukinMonth.withDayOfMonth(nyukinDate));
}
/**
* .
*
* <pre>
* false
* </pre>
*
* @return
*/
public boolean shimeDateBeforeNyukinDate() {
if (this.nyukinTsukiKubun.isIncludedIn(NyukinTsukiKubun., NyukinTsukiKubun.)) {
return true;
}
if (nyukinDate.compareTo(shimeDate) > 0) {
return true;
}
return false;
}
@Override
protected boolean equals(DomainBase other) {
NyukinKakeInfoDomain o = (NyukinKakeInfoDomain) other;
return kokyakuId.equals(o.kokyakuId);
}
@Override
public int hashCode() {
return kokyakuId.hashCode();
}
@Override
public void validate() throws SystemException {
}
} |
package net.time4j.engine;
import java.util.Comparator;
import java.util.Locale;
/**
* <p>Represents a chronological element which refers to a partial value of
* the whole temporal value and mainly serves for formatting purposes (as
* a carrier of a chronological information). </p>
*
* <p>Each chronological system knows a set of elements whose values
* compose the total temporal value, usually the associated time coordinates
* on a time axis. Each element can be associated with a value of type V.
* Normally this value is an integer or an enum. Examples are the hour on
* a clock or the month of a calendar date. </p>
*
* <p>The associated values are often defined as continuum without any
* gaps as integer within a given value range. However, there is no
* guarantee for such a continuum, for example daylight-saving-jumps or
* hebrew leap months. </p>
*
* @param <V> generic type of element values, usually extending the interface
* {@code java.lang.Comparable} (or it can be converted to any other
* sortable form)
* @author Meno Hochschild
* @see ChronoEntity#get(ChronoElement)
* @doctags.spec All implementations must be immutable and serializable.
*/
/*[deutsch]
* <p>Repräsentiert ein chronologisches Element, das einen Teil eines
* Zeitwerts referenziert und als Träger einer chronologischen Information
* in erster Linie Formatierzwecken dient. </p>
*
* <p>Jedes chronologische System kennt einen Satz von Elementen, deren Werte
* zusammen den Gesamtzeitwert festlegen, in der Regel die zugehörige Zeit
* als Punkt auf einem Zeitstrahl. Jedes Element kann mit einem Wert vom Typ V
* assoziiert werden. Normalerweise handelt es sich um einen Integer-Wert oder
* einen Enum-Wert. Beispiele sind die Stunde einer Uhrzeit oder der Monat
* eines Datums. </p>
*
* <p>Die zugehörigen Werte sind, wenn vorhanden, oft als Kontinuum
* ohne Lücken als Integer im angegebenen Wertebereich definiert.
* Garantiert ist ein Kontinuum aber nicht, siehe zum Beispiel
* Sommerzeit-Umstellungen oder hebräische Schaltmonate. </p>
*
* @param <V> generic type of element values, usually extending the interface
* {@code java.lang.Comparable} (or it can be converted to any other
* sortable form)
* @author Meno Hochschild
* @see ChronoEntity#get(ChronoElement)
* @doctags.spec All implementations must be immutable and serializable.
*/
public interface ChronoElement<V>
extends Comparator<ChronoDisplay> {
/**
* <p>Returns the name which is unique within the context of a given
* chronology. </p>
*
* <p>The name can also serve as resource key together with the name of
* a chronology for a localized description. </p>
*
* @return name of element, unique within a chronology
*/
/*[deutsch]
* <p>Liefert den innerhalb einer Chronologie eindeutigen Namen. </p>
*
* <p>Zusammen mit dem Namen der zugehörigen Chronologie kann
* der Name des chronologischen Elements auch als Ressourcenschlüssel
* für eine lokalisierte Beschreibung dienen. </p>
*
* @return name of element, unique within a chronology
*/
String name();
/**
* <p>Yields the reified value type. </p>
*
* @return type of associated values
*/
/*[deutsch]
* <p>Liefert die Wertklasse. </p>
*
* @return type of associated values
*/
Class<V> getType();
/**
* <p>Defines the default format symbol which is used in format patterns
* to refer to this element. </p>
*
* <p>In most cases the symbol should closely match the symbol-mapping
* as defined by the CLDR-standard of unicode-organization. Is the
* element not designed for formatting using patterns then this method
* just yields the ASCII-char "\u0000" (Codepoint 0). </p>
*
* @return format symbol as char
* @see FormattableElement
*/
/*[deutsch]
* <p>Definiert das Standard-Formatsymbol, mit dem diese Instanz in
* Formatmustern referenziert wird. </p>
*
* <p>So weit wie möglich handelt es sich um ein Symbol nach der
* CLDR-Norm des Unicode-Konsortiums. Ist das Element nicht für
* Formatierungen per Formatmuster vorgesehen, liefert diese Methode das
* ASCII-Zeichen "\u0000" (Codepoint 0). </p>
*
* @return format symbol as char
* @see FormattableElement
*/
char getSymbol();
/**
* <p>Applies an element-orientated sorting of any chronological
* entities. </p>
*
* <p>The value type V is usually a subtype of the interface
* {@code Comparable} so that this method will usually be based on
* the expression {@code o1.get(this).compareTo(o2.get(this))}. In
* other words, this method compares the element values of given
* chronological entities. It is even permitted to compare entities
* of different chronological types as long as the entities both
* support this element. </p>
*
* <p>It should be noted however that a element value comparison does
* often not induce any temporal (complete) order. Counter examples
* are the year of gregorian BC-era (reversed temporal order before
* Jesu birth) or the clock display of hours (12 is indeed the begin
* at midnight). </p>
*
* @param o1 the first object to be compared
* @param o2 the second object to be compared
* @return a negative integer, zero, or a positive integer as the first
* argument is less than, equal to, or greater than the second
* @throws ChronoException if this element is not registered in any entity
* and/or if no element rule exists to extract the element value
*/
/*[deutsch]
* <p>Führt eine elementorientierte Sortierung von beliebigen
* chronologischen Objekten bezüglich dieses Elements ein . </p>
*
* <p>Der Werttyp V ist typischerweise eine Implementierung des Interface
* {@code Comparable}, so daß diese Methode oft auf dem Ausdruck
* {@code o1.get(this).compareTo(o2.get(this))} beruhen wird. Mit anderen
* Worten, im Normalfall werden in den angegebenen chronologischen Objekten
* die Werte bezüglich dieses Elements verglichen. Es dürfen
* anders als im {@code Comparable}-Interface möglich hierbei auch
* Objekte verschiedener chronologischer Typen miteinander verglichen
* werden solange die zu vergleichenden Objekte dieses Element
* unterstützen. </p>
*
* <p>Es ist zu betonen, daß ein Elementwertvergleich im allgemeinen
* keine (vollständige) zeitliche Sortierung indiziert. Gegenbeispiele
* sind das Jahr innerhalb der gregorianischen BC-Ära (umgekehrte
* zeitliche Reihenfolge vor Christi Geburt) oder die Ziffernblattanzeige
* von Stunden (die Zahl 12 ist eigentlich der Beginn zu Mitternacht). </p>
*
* @param o1 the first object to be compared
* @param o2 the second object to be compared
* @return a negative integer, zero, or a positive integer as the first
* argument is less than, equal to, or greater than the second
* @throws ChronoException if this element is not registered in any entity
* and/or if no element rule exists to extract the element value
*/
@Override
int compare(
ChronoDisplay o1,
ChronoDisplay o2
);
/**
* <p>Returns the default minimum of this element which is not dependent
* on the chronological context. </p>
*
* <p>Note: This minimum does not necessarily define a minimum for all
* possible circumstances but only the default minimum under normal
* conditions such that the default minimum always exists and can be
* used as prototypical value. An example is the start of day which
* is usually midnight in ISO-8601 and can only deviate in specialized
* timezone context. </p>
*
* @return default minimum value of element
* @see #getDefaultMaximum()
*/
/*[deutsch]
* <p>Gibt das übliche chronologieunabhängige Minimum des
* assoziierten Elementwerts zurück. </p>
*
* <p>Hinweis: Dieses Minimum definiert keineswegs eine untere Schranke
* für alle gültigen Elementwerte, sondern nur das Standardminimum
* unter chronologischen Normalbedingungen, unter denen es immer existiert
* und daher als prototypischer Wert verwendet werden kann. Ein Beispiel
* ist der Start des Tages in ISO-8601, welcher nur unter bestimmten
* Zeitzonenkonfigurationen von Mitternacht abweichen kann. </p>
*
* @return default minimum value of element
* @see #getDefaultMaximum()
*/
V getDefaultMinimum();
/**
* <p>Returns the default maximum of this element which is not dependent
* on the chronological context. </p>
*
* <p>Note: This maximum does not necessarily define a maximum for all
* possible circumstances but only the default maximum under normal
* conditions. An example is the second of minute whose default maximum
* is {@code 59} while the largest maximum can be {@code 60} in context
* of UTC-leapseconds. </p>
*
* @return default maximum value of element
* @see #getDefaultMinimum()
*/
/*[deutsch]
* <p>Gibt das übliche chronologieunabhängige Maximum des
* assoziierten Elementwerts zurück. </p>
*
* <p>Hinweis: Dieses Maximum definiert keineswegs eine obere Schranke
* für alle gültigen Elementwerte, sondern nur das Standardmaximum
* unter chronologischen Normalbedingungen . Ein Beispiel ist das
* Element SECOND_OF_MINUTE, dessen Standardmaximum {@code 59} ist,
* während das größte Maximum bedingt durch
* UTC-Schaltsekunden {@code 60} sein kann. </p>
*
* @return default maximum value of element
* @see #getDefaultMinimum()
*/
V getDefaultMaximum();
/**
* <p>Queries if this element represents a calendar date element. </p>
*
* @return boolean
* @see #isTimeElement()
*/
/*[deutsch]
* <p>Ist dieses Element eine Teilkomponente, die ein Datumselement
* darstellt? </p>
*
* @return boolean
* @see #isTimeElement()
*/
boolean isDateElement();
/**
* <p>Queries if this element represents a wall time element. </p>
*
* @return boolean
* @see #isDateElement()
*/
/*[deutsch]
* <p>Ist dieses Element eine Teilkomponente, die ein Uhrzeitelement
* darstellt? </p>
*
* @return boolean
* @see #isDateElement()
*/
boolean isTimeElement();
/**
* <p>Queries if setting of element values is performed in a lenient
* way. </p>
*
* @return {@code true} if lenient else {@code false} (standard)
* @see ElementRule#withValue(Object, Object, boolean)
* ElementRule.withValue(T, V, boolean)
*/
/*[deutsch]
* <p>Soll das Setzen von Werten fehlertolerant ausgeführt werden? </p>
*
* @return {@code true} if lenient else {@code false} (standard)
* @see ElementRule#withValue(Object, Object, boolean)
* ElementRule.withValue(T, V, boolean)
*/
boolean isLenient();
/**
* <p>Obtains a localized name for display purposes if possible. </p>
*
* <p>Most elements have no localized names, but in case the i18n-module is loaded then elements
* like eras, years, quarters, months, weeks, day-of-month, day-of-week, am/pm, hour, minute and second
* do have localization support. The default implementation falls back to the technical element name. </p>
*
* <p>Note that the displayed name does not need to be unique for different elements. For example the
* localized names of {@code PlainDate.MONTH_OF_YEAR} and {@code PlainDate.MONTH_AS_NUMBER} are equal. </p>
*
* @param language language setting
* @return localized name or if not available then {@link #name() a technical name} will be chosen
* @since 3.22/4.18
*/
/*[deutsch]
* <p>Ermittelt einen lokalisierten Anzeigenamen wenn möglich. </p>
*
* <p>Die meisten Elemente haben keine lokalisierten Namen, aber falls das i18n-Modul geladen ist,
* haben Elemente wie Äras, Jahre, Quartale, Monate, Wochen, Tag, Wochentag, AM/PM, Stunde,
* Minute und Sekunde lokalisierte Namen. Die Standardimplementierung fällt auf den technischen
* Elementnamen zurück. </p>
*
* <p>Hinweis: Der Anzeigename muß nicht eindeutig sein. Zum Beispiel sind die Anzeigenamen
* von {@code PlainDate.MONTH_OF_YEAR} und {@code PlainDate.MONTH_AS_NUMBER} in der Regel gleich. </p>
*
* @param language language setting
* @return localized name or if not available then {@link #name() a technical name} will be chosen
* @since 3.22/4.18
*/
default String getDisplayName(Locale language) {
return this.name();
}
} |
package VASSAL.counters;
import VASSAL.build.GameModule;
import VASSAL.build.module.Map;
import VASSAL.command.AddPiece;
import VASSAL.tools.ReflectionUtils;
/**
* Utility class for cloning {@link GamePiece}s
*/
public class PieceCloner {
private static PieceCloner instance = new PieceCloner();
// For use by subclasses
protected PieceCloner() {}
public static PieceCloner getInstance() {
return instance;
}
/**
* Create a new instance that is a clone of the given piece.
*
* @return the new instance
*/
public GamePiece clonePiece(GamePiece piece) {
GamePiece clone = null;
if (piece instanceof BasicPiece) {
clone = GameModule.getGameModule().createPiece(piece.getType());
final Map m = piece.getMap();
// Temporarily set map to null so that clone won't be added to map
piece.setMap(null);
clone.setState(piece.getState());
piece.setMap(m);
}
else if (piece instanceof UsePrototype) {
clone = clonePiece(((UsePrototype)piece).getExpandedInner());
}
else if (piece instanceof EditablePiece && piece instanceof Decorator) {
try {
clone = piece.getClass().getConstructor().newInstance();
final Decorator dclone = (Decorator) clone;
final Decorator dpiece = (Decorator) piece;
dclone.setInner(clonePiece(dpiece.getInner()));
((EditablePiece)clone).mySetType(dpiece.myGetType());
dclone.mySetState(dpiece.myGetState());
}
catch (Throwable t) {
ReflectionUtils.handleNewInstanceFailure(t, piece.getClass());
}
}
else {
clone = ((AddPiece) GameModule.getGameModule().decode(
GameModule.getGameModule().encode(new AddPiece(piece)))).getTarget();
final Map m = piece.getMap();
// Temporarily set map to null so that clone won't be added to map
piece.setMap(null);
clone.setState(piece.getState());
piece.setMap(m);
}
return clone;
}
} |
package com.braintreegateway;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.braintreegateway.util.NodeWrapperFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.braintreegateway.SandboxValues.CreditCardNumber;
import com.braintreegateway.SandboxValues.TransactionAmount;
import com.braintreegateway.exceptions.ForgedQueryStringException;
import com.braintreegateway.exceptions.NotFoundException;
public class TransactionTest {
private BraintreeGateway gateway;
@Before
public void createGateway() {
this.gateway = new BraintreeGateway(Environment.DEVELOPMENT, "integration_merchant_id", "integration_public_key", "integration_private_key");
}
@SuppressWarnings("deprecation")
@Test
public void transparentRedirectURLForCreate() {
Assert.assertEquals(gateway.baseMerchantURL() + "/transactions/all/create_via_transparent_redirect_request",
gateway.transaction().transparentRedirectURLForCreate());
}
@Test
public void trData() {
String trData = gateway.trData(new TransactionRequest(), "http://example.com");
TestHelper.assertValidTrData(gateway.getConfiguration(), trData);
}
@Test
public void saleTrData() {
String trData = gateway.transaction().saleTrData(new TransactionRequest(), "http://example.com");
TestHelper.assertValidTrData(gateway.getConfiguration(), trData);
Assert.assertTrue(trData.contains("sale"));
}
@Test
public void creditTrData() {
String trData = gateway.transaction().creditTrData(new TransactionRequest(), "http://example.com");
TestHelper.assertValidTrData(gateway.getConfiguration(), trData);
Assert.assertTrue(trData.contains("credit"));
}
@SuppressWarnings("deprecation")
@Test
public void createViaTransparentRedirect() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
options().
storeInVault(true).
done();
TransactionRequest trParams = new TransactionRequest().
type(Transaction.Type.SALE);
String queryString = TestHelper.simulateFormPostForTR(gateway, trParams, request, gateway.transaction().transparentRedirectURLForCreate());
Result<Transaction> result = gateway.transaction().confirmTransparentRedirect(queryString);
Assert.assertTrue(result.isSuccess());
}
@SuppressWarnings("deprecation")
@Test(expected = ForgedQueryStringException.class)
public void createViaTransparentRedirectThrowsWhenQueryStringHasBeenTamperedWith() {
String queryString = TestHelper.simulateFormPostForTR(gateway, new TransactionRequest(), new TransactionRequest(), gateway.transaction().transparentRedirectURLForCreate());
gateway.transaction().confirmTransparentRedirect(queryString + "this make it invalid");
}
@Test
public void cloneTransaction() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
orderId("123").
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
customer().
firstName("Dan").
done().
billingAddress().
firstName("Carl").
done().
shippingAddress().
firstName("Andrew").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
TransactionCloneRequest cloneRequest = new TransactionCloneRequest().amount(new BigDecimal("123.45")).options().submitForSettlement(false).done();
Result<Transaction> cloneResult = gateway.transaction().cloneTransaction(transaction.getId(), cloneRequest);
Assert.assertTrue(cloneResult.isSuccess());
Transaction cloneTransaction = result.getTarget();
Assert.assertEquals("123", cloneTransaction.getOrderId());
Assert.assertEquals("411111******1111", cloneTransaction.getCreditCard().getMaskedNumber());
Assert.assertEquals("Dan", cloneTransaction.getCustomer().getFirstName());
Assert.assertEquals("Carl", cloneTransaction.getBillingAddress().getFirstName());
Assert.assertEquals("Andrew", cloneTransaction.getShippingAddress().getFirstName());
}
@Test
public void cloneTransactionAndSubmitForSettlement() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
orderId("123").
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
TransactionCloneRequest cloneRequest = new TransactionCloneRequest().amount(new BigDecimal("123.45")).options().submitForSettlement(true).done();
Result<Transaction> cloneResult = gateway.transaction().cloneTransaction(transaction.getId(), cloneRequest);
Assert.assertTrue(cloneResult.isSuccess());
Transaction cloneTransaction = cloneResult.getTarget();
Assert.assertEquals(Transaction.Status.SUBMITTED_FOR_SETTLEMENT, cloneTransaction.getStatus());
}
@Test
public void cloneTransactionWithValidationErrors() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().credit(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
TransactionCloneRequest cloneRequest = new TransactionCloneRequest().amount(new BigDecimal("123.45"));
Result<Transaction> cloneResult = gateway.transaction().cloneTransaction(transaction.getId(), cloneRequest);
Assert.assertFalse(cloneResult.isSuccess());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_CANNOT_CLONE_CREDIT,
cloneResult.getErrors().forObject("transaction").onField("base").get(0).getCode());
}
@Test
public void sale() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(new BigDecimal("1000.00"), transaction.getAmount());
Assert.assertEquals("USD", transaction.getCurrencyIsoCode());
Assert.assertNotNull(transaction.getProcessorAuthorizationCode());
Assert.assertEquals(Transaction.Type.SALE, transaction.getType());
Assert.assertEquals(Transaction.Status.AUTHORIZED, transaction.getStatus());
Assert.assertEquals(Calendar.getInstance().get(Calendar.YEAR), transaction.getCreatedAt().get(Calendar.YEAR));
Assert.assertEquals(Calendar.getInstance().get(Calendar.YEAR), transaction.getUpdatedAt().get(Calendar.YEAR));
CreditCard creditCard = transaction.getCreditCard();
Assert.assertEquals("411111", creditCard.getBin());
Assert.assertEquals("1111", creditCard.getLast4());
Assert.assertEquals("05", creditCard.getExpirationMonth());
Assert.assertEquals("2009", creditCard.getExpirationYear());
Assert.assertEquals("05/2009", creditCard.getExpirationDate());
}
@Test
public void saleWithAllAttributes() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
orderId("123").
creditCard().
cardholderName("The Cardholder").
number(CreditCardNumber.VISA.number).
cvv("321").
expirationDate("05/2009").
done().
customer().
firstName("Dan").
lastName("Smith").
company("Braintree Payment Solutions").
email("dan@example.com").
phone("419-555-1234").
fax("419-555-1235").
website("http://braintreepayments.com").
done().
billingAddress().
firstName("Carl").
lastName("Jones").
company("Braintree").
streetAddress("123 E Main St").
extendedAddress("Suite 403").
locality("Chicago").
region("IL").
postalCode("60622").
countryName("United States of America").
countryCodeAlpha2("US").
countryCodeAlpha3("USA").
countryCodeNumeric("840").
done().
shippingAddress().
firstName("Andrew").
lastName("Mason").
company("Braintree Shipping").
streetAddress("456 W Main St").
extendedAddress("Apt 2F").
locality("Bartlett").
region("MA").
postalCode("60103").
countryName("Mexico").
countryCodeAlpha2("MX").
countryCodeAlpha3("MEX").
countryCodeNumeric("484").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(new BigDecimal("1000.00"), transaction.getAmount());
Assert.assertEquals(Transaction.Status.AUTHORIZED, transaction.getStatus());
Assert.assertEquals("123", transaction.getOrderId());
Assert.assertNull(transaction.getVaultCreditCard(gateway));
Assert.assertNull(transaction.getVaultCustomer(gateway));
Assert.assertNull(transaction.getAvsErrorResponseCode());
Assert.assertEquals("M", transaction.getAvsPostalCodeResponseCode());
Assert.assertEquals("M", transaction.getAvsStreetAddressResponseCode());
Assert.assertEquals("M", transaction.getCvvResponseCode());
Assert.assertFalse(transaction.isTaxExempt());
Assert.assertNull(transaction.getVaultCreditCard(gateway));
CreditCard creditCard = transaction.getCreditCard();
Assert.assertEquals("411111", creditCard.getBin());
Assert.assertEquals("1111", creditCard.getLast4());
Assert.assertEquals("05", creditCard.getExpirationMonth());
Assert.assertEquals("2009", creditCard.getExpirationYear());
Assert.assertEquals("05/2009", creditCard.getExpirationDate());
Assert.assertEquals("The Cardholder", creditCard.getCardholderName());
Assert.assertNull(transaction.getVaultCustomer(gateway));
Customer customer = transaction.getCustomer();
Assert.assertEquals("Dan", customer.getFirstName());
Assert.assertEquals("Smith", customer.getLastName());
Assert.assertEquals("Braintree Payment Solutions", customer.getCompany());
Assert.assertEquals("dan@example.com", customer.getEmail());
Assert.assertEquals("419-555-1234", customer.getPhone());
Assert.assertEquals("419-555-1235", customer.getFax());
Assert.assertEquals("http://braintreepayments.com", customer.getWebsite());
Assert.assertNull(transaction.getVaultBillingAddress(gateway));
Address billing = transaction.getBillingAddress();
Assert.assertEquals("Carl", billing.getFirstName());
Assert.assertEquals("Jones", billing.getLastName());
Assert.assertEquals("Braintree", billing.getCompany());
Assert.assertEquals("123 E Main St", billing.getStreetAddress());
Assert.assertEquals("Suite 403", billing.getExtendedAddress());
Assert.assertEquals("Chicago", billing.getLocality());
Assert.assertEquals("IL", billing.getRegion());
Assert.assertEquals("60622", billing.getPostalCode());
Assert.assertEquals("United States of America", billing.getCountryName());
Assert.assertEquals("US", billing.getCountryCodeAlpha2());
Assert.assertEquals("USA", billing.getCountryCodeAlpha3());
Assert.assertEquals("840", billing.getCountryCodeNumeric());
Assert.assertNull(transaction.getVaultShippingAddress(gateway));
Address shipping = transaction.getShippingAddress();
Assert.assertEquals("Andrew", shipping.getFirstName());
Assert.assertEquals("Mason", shipping.getLastName());
Assert.assertEquals("Braintree Shipping", shipping.getCompany());
Assert.assertEquals("456 W Main St", shipping.getStreetAddress());
Assert.assertEquals("Apt 2F", shipping.getExtendedAddress());
Assert.assertEquals("Bartlett", shipping.getLocality());
Assert.assertEquals("MA", shipping.getRegion());
Assert.assertEquals("60103", shipping.getPostalCode());
Assert.assertEquals("Mexico", shipping.getCountryName());
Assert.assertEquals("MX", shipping.getCountryCodeAlpha2());
Assert.assertEquals("MEX", shipping.getCountryCodeAlpha3());
Assert.assertEquals("484", shipping.getCountryCodeNumeric());
}
@Test
public void saleWithSpecifyingMerchantAccountId() {
TransactionRequest request = new TransactionRequest().
merchantAccountId(MerchantAccount.NON_DEFAULT_MERCHANT_ACCOUNT_ID).
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(MerchantAccount.NON_DEFAULT_MERCHANT_ACCOUNT_ID, transaction.getMerchantAccountId());
}
@Test
public void saleWithoutSpecifyingMerchantAccountIdFallsBackToDefault() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(MerchantAccount.DEFAULT_MERCHANT_ACCOUNT_ID, transaction.getMerchantAccountId());
}
@Test
public void saleWithStoreInVaultAndSpecifyingToken() {
String customerId = String.valueOf(new Random().nextInt());
String paymentToken = String.valueOf(new Random().nextInt());
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
token(paymentToken).
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
customer().
id(customerId).
firstName("Jane").
done().
options().
storeInVault(true).
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
CreditCard creditCard = transaction.getCreditCard();
Assert.assertEquals(paymentToken, creditCard.getToken());
Assert.assertEquals("05/2009", transaction.getVaultCreditCard(gateway).getExpirationDate());
Customer customer = transaction.getCustomer();
Assert.assertEquals(customerId, customer.getId());
Assert.assertEquals("Jane", transaction.getVaultCustomer(gateway).getFirstName());
}
@Test
public void saleWithStoreInVaultWithoutSpecifyingToken() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
customer().
firstName("Jane").
done().
options().
storeInVault(true).
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
CreditCard creditCard = transaction.getCreditCard();
Assert.assertNotNull(creditCard.getToken());
Assert.assertEquals("05/2009", transaction.getVaultCreditCard(gateway).getExpirationDate());
Customer customer = transaction.getCustomer();
Assert.assertNotNull(customer.getId());
Assert.assertEquals("Jane", transaction.getVaultCustomer(gateway).getFirstName());
}
@Test
public void saleWithStoreInVaultOnSuccessWhenTransactionSucceeds() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
customer().
firstName("Jane").
done().
options().
storeInVaultOnSuccess(true).
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
CreditCard creditCard = transaction.getCreditCard();
Assert.assertNotNull(creditCard.getToken());
Assert.assertEquals("05/2009", transaction.getVaultCreditCard(gateway).getExpirationDate());
Customer customer = transaction.getCustomer();
Assert.assertNotNull(customer.getId());
Assert.assertEquals("Jane", transaction.getVaultCustomer(gateway).getFirstName());
}
@Test
public void saleWithStoreInVaultOnSuccessWhenTransactionFails() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.DECLINE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
customer().
firstName("Jane").
done().
options().
storeInVaultOnSuccess(true).
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Transaction transaction = result.getTransaction();
CreditCard creditCard = transaction.getCreditCard();
Assert.assertNull(creditCard.getToken());
Assert.assertNull(transaction.getVaultCreditCard(gateway));
Customer customer = transaction.getCustomer();
Assert.assertNull(customer.getId());
Assert.assertNull(transaction.getVaultCustomer(gateway));
}
@Test
public void saleWithStoreInVaultForBillingAndShipping() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
billingAddress().
firstName("Carl").
done().
shippingAddress().
firstName("Andrew").
done().
options().
storeInVault(true).
addBillingAddressToPaymentMethod(true).
storeShippingAddressInVault(true).
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
CreditCard creditCard = transaction.getVaultCreditCard(gateway);
Assert.assertEquals("Carl", creditCard.getBillingAddress().getFirstName());
Assert.assertEquals("Carl", transaction.getVaultBillingAddress(gateway).getFirstName());
Assert.assertEquals("Andrew", transaction.getVaultShippingAddress(gateway).getFirstName());
Customer customer = transaction.getVaultCustomer(gateway);
Assert.assertEquals(2, customer.getAddresses().size());
List<Address> addresses = new ArrayList<Address>(customer.getAddresses());
Collections.sort(addresses, new Comparator<Address>() {
public int compare(Address left, Address right) {
return left.getFirstName().compareTo(right.getFirstName());
}
});
Assert.assertEquals("Andrew", addresses.get(0).getFirstName());
Assert.assertEquals("Carl", addresses.get(1).getFirstName());
Assert.assertNotNull(transaction.getBillingAddress().getId());
Assert.assertNotNull(transaction.getShippingAddress().getId());
}
@Test
public void saleWithVaultCustomerAndNewCreditCard() {
Customer customer = gateway.customer().create(new CustomerRequest().
firstName("Michael").
lastName("Angelo").
company("Some Company")
).getTarget();
TransactionRequest request = new TransactionRequest().
amount(SandboxValues.TransactionAmount.AUTHORIZE.amount).
customerId(customer.getId()).
creditCard().
cardholderName("Bob the Builder").
number(SandboxValues.CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals("Bob the Builder", transaction.getCreditCard().getCardholderName());
Assert.assertNull(transaction.getVaultCreditCard(gateway));
}
@Test
public void saleWithVaultCustomerAndNewCreditCardStoresInVault() {
Customer customer = gateway.customer().create(new CustomerRequest().
firstName("Michael").
lastName("Angelo").
company("Some Company")
).getTarget();
TransactionRequest request = new TransactionRequest().
amount(SandboxValues.TransactionAmount.AUTHORIZE.amount).
customerId(customer.getId()).
creditCard().
cardholderName("Bob the Builder").
number(SandboxValues.CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
options().
storeInVault(true).
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals("Bob the Builder", transaction.getCreditCard().getCardholderName());
Assert.assertEquals("Bob the Builder", transaction.getVaultCreditCard(gateway).getCardholderName());
}
@Test
public void saleDeclined() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.DECLINE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Transaction transaction = result.getTransaction();
Assert.assertEquals(new BigDecimal("2000.00"), transaction.getAmount());
Assert.assertEquals(Transaction.Status.PROCESSOR_DECLINED, transaction.getStatus());
Assert.assertEquals("2000", transaction.getProcessorResponseCode());
Assert.assertNotNull(transaction.getProcessorResponseText());
CreditCard creditCard = transaction.getCreditCard();
Assert.assertEquals("411111", creditCard.getBin());
Assert.assertEquals("1111", creditCard.getLast4());
Assert.assertEquals("05", creditCard.getExpirationMonth());
Assert.assertEquals("2009", creditCard.getExpirationYear());
Assert.assertEquals("05/2009", creditCard.getExpirationDate());
}
@Test
public void saleWithCustomFields() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
customField("storeMe", "custom value").
customField("another_stored_field", "custom value2").
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Map<String, String> expected = new HashMap<String, String>();
expected.put("store_me", "custom value");
expected.put("another_stored_field", "custom value2");
Assert.assertEquals(expected, transaction.getCustomFields());
}
@Test
public void saleWithValidationErrorsOnAddress() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.DECLINE.amount).
customField("unkown_custom_field", "custom value").
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
billingAddress().
countryName("No such country").
countryCodeAlpha2("zz").
countryCodeAlpha3("zzz").
countryCodeNumeric("000").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryName").get(0).getCode());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryCodeAlpha2").get(0).getCode());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryCodeAlpha3").get(0).getCode());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryCodeNumeric").get(0).getCode());
}
@Test
public void saleWithUnregisteredCustomField() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.DECLINE.amount).
customField("unkown_custom_field", "custom value").
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_CUSTOM_FIELD_IS_INVALID,
result.getErrors().forObject("transaction").onField("customFields").get(0).getCode());
}
@Test
public void saleWithMultipleValidationErrorsOnSameField() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
paymentMethodToken("foo").
customerId("5").
creditCard().
number(CreditCardNumber.VISA.number).
cvv("321").
expirationDate("04/2009").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
List<ValidationError> errros = result.getErrors().forObject("transaction").onField("base");
Assert.assertNull(result.getTransaction());
Assert.assertNull(result.getCreditCardVerification());
Assert.assertEquals(2, errros.size());
List<ValidationErrorCode> validationErrorCodes = new ArrayList<ValidationErrorCode>();
validationErrorCodes.add(errros.get(0).getCode());
validationErrorCodes.add(errros.get(1).getCode());
Assert.assertTrue(validationErrorCodes.contains(ValidationErrorCode.TRANSACTION_PAYMENT_METHOD_CONFLICT));
Assert.assertTrue(validationErrorCodes.contains(ValidationErrorCode.TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_CUSTOMER));
}
@Test
public void saleWithCustomerId() {
Customer customer = gateway.customer().create(new CustomerRequest()).getTarget();
CreditCardRequest creditCardRequest = new CreditCardRequest().
customerId(customer.getId()).
cvv("123").
number("5105105105105100").
expirationDate("05/12");
CreditCard creditCard = gateway.creditCard().create(creditCardRequest).getTarget();
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
paymentMethodToken(creditCard.getToken());
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(creditCard.getToken(), transaction.getCreditCard().getToken());
Assert.assertEquals("510510", transaction.getCreditCard().getBin());
Assert.assertEquals("05/2012", transaction.getCreditCard().getExpirationDate());
}
@Test
public void saleWithPaymentMethodTokenAndCvv() {
Customer customer = gateway.customer().create(new CustomerRequest()).getTarget();
CreditCardRequest creditCardRequest = new CreditCardRequest().
customerId(customer.getId()).
number("5105105105105100").
expirationDate("05/12");
CreditCard creditCard = gateway.creditCard().create(creditCardRequest).getTarget();
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
paymentMethodToken(creditCard.getToken()).
creditCard().cvv("301").done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(creditCard.getToken(), transaction.getCreditCard().getToken());
Assert.assertEquals("510510", transaction.getCreditCard().getBin());
Assert.assertEquals("05/2012", transaction.getCreditCard().getExpirationDate());
Assert.assertEquals("S", transaction.getCvvResponseCode());
}
@Test
public void saleUsesShippingAddressFromVault() {
Customer customer = gateway.customer().create(new CustomerRequest()).getTarget();
gateway.creditCard().create(new CreditCardRequest().
customerId(customer.getId()).
cvv("123").
number("5105105105105100").
expirationDate("05/12")).getTarget();
Address shippingAddress = gateway.address().create(customer.getId(),
new AddressRequest().firstName("Carl")).getTarget();
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
customerId(customer.getId()).
shippingAddressId(shippingAddress.getId());
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(shippingAddress.getId(), transaction.getShippingAddress().getId());
Assert.assertEquals("Carl", transaction.getShippingAddress().getFirstName());
}
@Test
public void saleWithValidationError() {
TransactionRequest request = new TransactionRequest().
amount(null).
creditCard().
expirationMonth("05").
expirationYear("2010").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Assert.assertNull(result.getTarget());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_AMOUNT_IS_REQUIRED, result.getErrors().forObject("transaction").onField("amount").get(0).getCode());
Map<String, String> parameters = result.getParameters();
Assert.assertEquals(null, parameters.get("transaction[amount]"));
Assert.assertEquals("05", parameters.get("transaction[credit_card][expiration_month]"));
Assert.assertEquals("2010", parameters.get("transaction[credit_card][expiration_year]"));
}
@Test
public void saleWithSubmitForSettlement() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
options().
submitForSettlement(true).
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(Transaction.Status.SUBMITTED_FOR_SETTLEMENT, transaction.getStatus());
}
@Test
public void saleWithDescriptor() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
descriptor().
name("123*123456789012345678").
phone("3334445555").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals("123*123456789012345678", transaction.getDescriptor().getName());
Assert.assertEquals("3334445555", transaction.getDescriptor().getPhone());
}
@Test
public void saleWithDescriptorValidation() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
descriptor().
name("badcompanyname12*badproduct12").
phone("%bad4445555").
done();
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.DESCRIPTOR_NAME_FORMAT_IS_INVALID,
result.getErrors().forObject("transaction").forObject("descriptor").onField("name").get(0).getCode());
Assert.assertEquals(ValidationErrorCode.DESCRIPTOR_PHONE_FORMAT_IS_INVALID,
result.getErrors().forObject("transaction").forObject("descriptor").onField("phone").get(0).getCode());
}
@Test
public void saleWithLevel2() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
taxAmount(new BigDecimal("10.00")).
taxExempt(true).
purchaseOrderNumber("12345");
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(new BigDecimal("10.00"), transaction.getTaxAmount());
Assert.assertTrue(transaction.isTaxExempt());
Assert.assertEquals("12345", transaction.getPurchaseOrderNumber());
}
@Test
public void saleWithLevel2Validations() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
purchaseOrderNumber("aaaaaaaaaaaaaaaaaa");
Result<Transaction> result = gateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_PURCHASE_ORDER_NUMBER_IS_TOO_LONG,
result.getErrors().forObject("transaction").onField("purchaseOrderNumber").get(0).getCode());
}
@Test
public void createTransactionFromTransparentRedirectWithAddress() {
TransactionRequest request = new TransactionRequest();
TransactionRequest trParams = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
type(Transaction.Type.SALE).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
billingAddress().
countryName("United States of America").
countryCodeAlpha2("US").
countryCodeAlpha3("USA").
countryCodeNumeric("840").
done();
String queryString = TestHelper.simulateFormPostForTR(gateway, trParams, request, gateway.transparentRedirect().url());
Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals("United States of America", transaction.getBillingAddress().getCountryName());
Assert.assertEquals("US", transaction.getBillingAddress().getCountryCodeAlpha2());
Assert.assertEquals("USA", transaction.getBillingAddress().getCountryCodeAlpha3());
Assert.assertEquals("840", transaction.getBillingAddress().getCountryCodeNumeric());
}
@Test
public void createTransactionFromTransparentRedirectWithAddressWithErrors() {
TransactionRequest request = new TransactionRequest();
TransactionRequest trParams = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
type(Transaction.Type.SALE).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done().
billingAddress().
countryName("Foo bar!").
countryCodeAlpha2("zz").
countryCodeAlpha3("zzz").
countryCodeNumeric("000").
done();
String queryString = TestHelper.simulateFormPostForTR(gateway, trParams, request, gateway.transparentRedirect().url());
Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryName").get(0).getCode());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryCodeAlpha2").get(0).getCode());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryCodeAlpha3").get(0).getCode());
Assert.assertEquals(ValidationErrorCode.ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED,
result.getErrors().forObject("transaction").forObject("billing").onField("countryCodeNumeric").get(0).getCode());
}
@Test
public void credit() {
TransactionRequest request = new TransactionRequest().
amount(SandboxValues.TransactionAmount.AUTHORIZE.amount).
creditCard().
number(SandboxValues.CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().credit(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(new BigDecimal("1000.00"), transaction.getAmount());
Assert.assertEquals(Transaction.Type.CREDIT, transaction.getType());
Assert.assertEquals(Transaction.Status.SUBMITTED_FOR_SETTLEMENT, transaction.getStatus());
CreditCard creditCard = transaction.getCreditCard();
Assert.assertEquals("411111", creditCard.getBin());
Assert.assertEquals("1111", creditCard.getLast4());
Assert.assertEquals("05", creditCard.getExpirationMonth());
Assert.assertEquals("2009", creditCard.getExpirationYear());
Assert.assertEquals("05/2009", creditCard.getExpirationDate());
}
@Test
public void creditWithSpecifyingMerchantAccountId() {
TransactionRequest request = new TransactionRequest().
amount(SandboxValues.TransactionAmount.AUTHORIZE.amount).
merchantAccountId(MerchantAccount.NON_DEFAULT_MERCHANT_ACCOUNT_ID).
creditCard().
number(SandboxValues.CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().credit(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(MerchantAccount.NON_DEFAULT_MERCHANT_ACCOUNT_ID, transaction.getMerchantAccountId());
}
@Test
public void creditWithoutSpecifyingMerchantAccountIdFallsBackToDefault() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().credit(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Assert.assertEquals(MerchantAccount.DEFAULT_MERCHANT_ACCOUNT_ID, transaction.getMerchantAccountId());
}
@Test
public void creditWithCustomFields() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
customField("store_me", "custom value").
customField("another_stored_field", "custom value2").
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = gateway.transaction().credit(request);
Assert.assertTrue(result.isSuccess());
Transaction transaction = result.getTarget();
Map<String, String> expected = new HashMap<String, String>();
expected.put("store_me", "custom value");
expected.put("another_stored_field", "custom value2");
Assert.assertEquals(expected, transaction.getCustomFields());
}
@Test
public void creditWithValidationError() {
TransactionRequest request = new TransactionRequest().
amount(null).
creditCard().
expirationMonth("05").
expirationYear("2010").
done();
Result<Transaction> result = gateway.transaction().credit(request);
Assert.assertFalse(result.isSuccess());
Assert.assertNull(result.getTarget());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_AMOUNT_IS_REQUIRED, result.getErrors().forObject("transaction").onField("amount").get(0).getCode());
Map<String, String> parameters = result.getParameters();
Assert.assertEquals(null, parameters.get("transaction[amount]"));
Assert.assertEquals("05", parameters.get("transaction[credit_card][expiration_month]"));
Assert.assertEquals("2010", parameters.get("transaction[credit_card][expiration_year]"));
}
@Test
public void find() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Transaction foundTransaction = gateway.transaction().find(transaction.getId());
Assert.assertEquals(transaction.getId(), foundTransaction.getId());
Assert.assertEquals(Transaction.Status.AUTHORIZED, foundTransaction.getStatus());
Assert.assertEquals("05/2008", foundTransaction.getCreditCard().getExpirationDate());
}
@Test(expected = NotFoundException.class)
public void findWithBadId() {
gateway.transaction().find("badId");
}
@Test
public void voidVoidsTheTransaction() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Result<Transaction> result = gateway.transaction().voidTransaction(transaction.getId());
Assert.assertTrue(result.isSuccess());
Assert.assertEquals(transaction.getId(), result.getTarget().getId());
Assert.assertEquals(Transaction.Status.VOIDED, result.getTarget().getStatus());
}
@Test(expected = NotFoundException.class)
public void voidWithBadId() {
gateway.transaction().voidTransaction("badId");
}
@Test
public void voidWithBadStatus() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
gateway.transaction().voidTransaction(transaction.getId());
Result<Transaction> result = gateway.transaction().voidTransaction(transaction.getId());
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_CANNOT_BE_VOIDED,
result.getErrors().forObject("transaction").onField("base").get(0).getCode());
}
@Test
public void statusHistoryReturnsCorrectStatusEvents() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Transaction settledTransaction = gateway.transaction().submitForSettlement(transaction.getId()).getTarget();
Assert.assertEquals(2, settledTransaction.getStatusHistory().size());
Assert.assertEquals(Transaction.Status.AUTHORIZED, settledTransaction.getStatusHistory().get(0).getStatus());
Assert.assertEquals(Transaction.Status.SUBMITTED_FOR_SETTLEMENT, settledTransaction.getStatusHistory().get(1).getStatus());
}
@Test
public void submitForSettlementWithoutAmount() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Result<Transaction> result = gateway.transaction().submitForSettlement(transaction.getId());
Assert.assertTrue(result.isSuccess());
Assert.assertEquals(Transaction.Status.SUBMITTED_FOR_SETTLEMENT, result.getTarget().getStatus());
Assert.assertEquals(TransactionAmount.AUTHORIZE.amount, result.getTarget().getAmount());
}
@Test
public void submitForSettlementWithAmount() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Result<Transaction> result = gateway.transaction().submitForSettlement(transaction.getId(), new BigDecimal("50.00"));
Assert.assertTrue(result.isSuccess());
Assert.assertEquals(Transaction.Status.SUBMITTED_FOR_SETTLEMENT, result.getTarget().getStatus());
Assert.assertEquals(new BigDecimal("50.00"), result.getTarget().getAmount());
}
@Test
public void submitForSettlementWithBadStatus() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
gateway.transaction().submitForSettlement(transaction.getId());
Result<Transaction> result = gateway.transaction().submitForSettlement(transaction.getId());
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_CANNOT_SUBMIT_FOR_SETTLEMENT,
result.getErrors().forObject("transaction").onField("base").get(0).getCode());
}
@Test(expected = NotFoundException.class)
public void submitForSettlementWithBadId() {
gateway.transaction().submitForSettlement("badId");
}
@Test
public void searchOnAllTextFields()
{
String creditCardToken = String.valueOf(new Random().nextInt());
String firstName = String.valueOf(new Random().nextInt());
TransactionRequest request = new TransactionRequest().
amount(new BigDecimal("1000")).
creditCard().
number("4111111111111111").
expirationDate("05/2012").
cardholderName("Tom Smith").
token(creditCardToken).
done().
billingAddress().
company("Braintree").
countryName("United States of America").
extendedAddress("Suite 123").
firstName(firstName).
lastName("Smith").
locality("Chicago").
postalCode("12345").
region("IL").
streetAddress("123 Main St").
done().
customer().
company("Braintree").
email("smith@example.com").
fax("5551231234").
firstName("Tom").
lastName("Smith").
phone("5551231234").
website("http://example.com").
done().
options().
storeInVault(true).
submitForSettlement(true).
done().
orderId("myorder").
shippingAddress().
company("Braintree P.S.").
countryName("Mexico").
extendedAddress("Apt 456").
firstName("Thomas").
lastName("Smithy").
locality("Braintree").
postalCode("54321").
region("MA").
streetAddress("456 Road").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TestHelper.settle(gateway, transaction.getId());
transaction = gateway.transaction().find(transaction.getId());
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
billingCompany().is("Braintree").
billingCountryName().is("United States of America").
billingExtendedAddress().is("Suite 123").
billingFirstName().is(firstName).
billingLastName().is("Smith").
billingLocality().is("Chicago").
billingPostalCode().is("12345").
billingRegion().is("IL").
billingStreetAddress().is("123 Main St").
creditCardCardholderName().is("Tom Smith").
creditCardExpirationDate().is("05/2012").
creditCardNumber().is(CreditCardNumber.VISA.number).
currency().is("USD").
customerCompany().is("Braintree").
customerEmail().is("smith@example.com").
customerFax().is("5551231234").
customerFirstName().is("Tom").
customerId().is(transaction.getCustomer().getId()).
customerLastName().is("Smith").
customerPhone().is("5551231234").
customerWebsite().is("http://example.com").
orderId().is("myorder").
paymentMethodToken().is(creditCardToken).
processorAuthorizationCode().is(transaction.getProcessorAuthorizationCode()).
settlementBatchId().is(transaction.getSettlementBatchId()).
shippingCompany().is("Braintree P.S.").
shippingCountryName().is("Mexico").
shippingExtendedAddress().is("Apt 456").
shippingFirstName().is("Thomas").
shippingLastName().is("Smithy").
shippingLocality().is("Braintree").
shippingPostalCode().is("54321").
shippingRegion().is("MA").
shippingStreetAddress().is("456 Road");
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
Assert.assertEquals(transaction.getId(), collection.getFirst().getId());
}
@Test
public void searchOnTextNodeOperators() {
TransactionRequest request = new TransactionRequest().
amount(new BigDecimal("1000")).
creditCard().
number("4111111111111111").
expirationDate("05/2012").
cardholderName("Tom Smith").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardholderName().startsWith("Tom");
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardholderName().endsWith("Smith");
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardholderName().contains("m Sm");
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardholderName().isNot("Tom Smith");
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(0, collection.getMaximumSize());
}
@Test
public void searchOnNullValue() {
TransactionRequest request = new TransactionRequest().
amount(new BigDecimal("1000")).
creditCard().
number("4111111111111111").
expirationDate("05/2012").
cardholderName("Tom Smith").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardholderName().is(null);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
}
@Test
public void searchOnCreatedUsing() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdUsing().is(Transaction.CreatedUsing.FULL_INFORMATION);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdUsing().in(Transaction.CreatedUsing.FULL_INFORMATION, Transaction.CreatedUsing.TOKEN);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdUsing().is(Transaction.CreatedUsing.TOKEN);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(0, collection.getMaximumSize());
}
@Test
public void searchOnCreditCardCustomerLocation() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCustomerLocation().is(CreditCard.CustomerLocation.US);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCustomerLocation().in(CreditCard.CustomerLocation.US, CreditCard.CustomerLocation.INTERNATIONAL);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCustomerLocation().is(CreditCard.CustomerLocation.INTERNATIONAL);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(0, collection.getMaximumSize());
}
@Test
public void searchOnMerchantAccountId() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
merchantAccountId().is(transaction.getMerchantAccountId());
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
merchantAccountId().in(transaction.getMerchantAccountId(), "badmerchantaccountid");
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
merchantAccountId().is("badmerchantaccountid");
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(0, collection.getMaximumSize());
}
@Test
public void searchOnCreditCardType() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardType().is(CreditCard.CardType.VISA);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardType().in(CreditCard.CardType.VISA, CreditCard.CardType.MASTER_CARD);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
creditCardCardType().is(CreditCard.CardType.MASTER_CARD);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(0, collection.getMaximumSize());
}
@Test
public void searchOnStatus() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
status().is(Transaction.Status.AUTHORIZED);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
status().in(Transaction.Status.AUTHORIZED, Transaction.Status.GATEWAY_REJECTED);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
status().is(Transaction.Status.GATEWAY_REJECTED);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(0, collection.getMaximumSize());
}
@Test
public void searchOnAuthorizationExpiredStatus() {
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
status().is(Transaction.Status.AUTHORIZATION_EXPIRED);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertTrue(collection.getMaximumSize() > 0);
Assert.assertEquals(Transaction.Status.AUTHORIZATION_EXPIRED, collection.getFirst().getStatus());
}
@Test
public void searchOnSource() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
source().is(Transaction.Source.API);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
source().in(Transaction.Source.API, Transaction.Source.CONTROL_PANEL);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
source().is(Transaction.Source.CONTROL_PANEL);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(0, collection.getMaximumSize());
}
@Test
public void searchOnType() {
String name = String.valueOf(new Random().nextInt());
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
cardholderName(name).
done().
options().
submitForSettlement(true).
done();
Transaction creditTransaction = gateway.transaction().credit(request).getTarget();
Transaction saleTransaction = gateway.transaction().sale(request).getTarget();
TestHelper.settle(gateway, saleTransaction.getId());
Transaction refundTransaction = gateway.transaction().refund(saleTransaction.getId()).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
creditCardCardholderName().is(name).
type().is(Transaction.Type.CREDIT);
ResourceCollection<Transaction> collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(2, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
creditCardCardholderName().is(name).
type().is(Transaction.Type.SALE);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
searchRequest = new TransactionSearchRequest().
creditCardCardholderName().is(name).
type().is(Transaction.Type.CREDIT).
refund().is(true);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
Assert.assertEquals(refundTransaction.getId(), collection.getFirst().getId());
searchRequest = new TransactionSearchRequest().
creditCardCardholderName().is(name).
type().is(Transaction.Type.CREDIT).
refund().is(false);
collection = gateway.transaction().search(searchRequest);
Assert.assertEquals(1, collection.getMaximumSize());
Assert.assertEquals(creditTransaction.getId(), collection.getFirst().getId());
}
@Test
public void searchOnAmount() {
TransactionRequest request = new TransactionRequest().
amount(new BigDecimal("1000")).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
amount().between(new BigDecimal("500"), new BigDecimal("1500"));
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
amount().greaterThanOrEqualTo(new BigDecimal("500"));
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
amount().lessThanOrEqualTo(new BigDecimal("1500"));
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
amount().between(new BigDecimal("1300"), new BigDecimal("1500"));
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnCreatedAt() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Calendar createdAt = transaction.getCreatedAt();
Calendar threeDaysEarlier = ((Calendar)createdAt.clone());
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = ((Calendar)createdAt.clone());
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = ((Calendar)createdAt.clone());
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnCreatedAtUsingLocalTime() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
createdAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnAuthorizationExpiredAt() {
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
authorizationExpiredAt().between(oneDayEarlier, oneDayLater);
ResourceCollection<Transaction> results = gateway.transaction().search(searchRequest);
Assert.assertTrue(results.getMaximumSize() > 0);
Assert.assertEquals(Transaction.Status.AUTHORIZATION_EXPIRED, results.getFirst().getStatus());
searchRequest = new TransactionSearchRequest().
authorizationExpiredAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnAuthorizedAt() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
authorizedAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
authorizedAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
authorizedAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
authorizedAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnFailedAt() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.FAILED.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTransaction();
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
failedAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
failedAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
failedAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
failedAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnGatewayRejectedAt() {
BraintreeGateway processingRulesGateway = new BraintreeGateway(Environment.DEVELOPMENT, "processing_rules_merchant_id", "processing_rules_public_key", "processing_rules_private_key");
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
cvv("200").
done();
Transaction transaction = processingRulesGateway.transaction().sale(request).getTransaction();
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
gatewayRejectedAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, processingRulesGateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
gatewayRejectedAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, processingRulesGateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
gatewayRejectedAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, processingRulesGateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
gatewayRejectedAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, processingRulesGateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnProcessorDeclinedAt() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.DECLINE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTransaction();
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
processorDeclinedAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
processorDeclinedAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
processorDeclinedAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
processorDeclinedAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnSettledAt() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done().
options().
submitForSettlement(true).
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TestHelper.settle(gateway, transaction.getId());
transaction = gateway.transaction().find(transaction.getId());
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
settledAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
settledAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
settledAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
settledAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnSubmittedForSettlementAt() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done().
options().
submitForSettlement(true).
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
submittedForSettlementAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
submittedForSettlementAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
submittedForSettlementAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
submittedForSettlementAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnVoidedAt() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
transaction = gateway.transaction().voidTransaction(transaction.getId()).getTarget();
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
voidedAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
voidedAt().greaterThanOrEqualTo(oneDayEarlier);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
voidedAt().lessThanOrEqualTo(oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
voidedAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
public void searchOnMultipleStatusAtFields() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2010").
done().
options().
submitForSettlement(true).
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Calendar threeDaysEarlier = Calendar.getInstance();
threeDaysEarlier.add(Calendar.DAY_OF_MONTH, -3);
Calendar oneDayEarlier = Calendar.getInstance();
oneDayEarlier.add(Calendar.DAY_OF_MONTH, -1);
Calendar oneDayLater = Calendar.getInstance();
oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
TransactionSearchRequest searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
authorizedAt().between(oneDayEarlier, oneDayLater).
submittedForSettlementAt().between(oneDayEarlier, oneDayLater);
Assert.assertEquals(1, gateway.transaction().search(searchRequest).getMaximumSize());
searchRequest = new TransactionSearchRequest().
id().is(transaction.getId()).
authorizedAt().between(threeDaysEarlier, oneDayEarlier).
submittedForSettlementAt().between(threeDaysEarlier, oneDayEarlier);
Assert.assertEquals(0, gateway.transaction().search(searchRequest).getMaximumSize());
}
@Test
@SuppressWarnings("deprecation")
public void refundTransaction() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done().
options().
submitForSettlement(true).
done();
String transactionId = gateway.transaction().sale(request).getTarget().getId();
TestHelper.settle(gateway, transactionId);
Result<Transaction> result = gateway.transaction().refund(transactionId);
Assert.assertTrue(result.isSuccess());
Transaction refund = result.getTarget();
Transaction originalTransaction = gateway.transaction().find(transactionId);
Assert.assertEquals(Transaction.Type.CREDIT, refund.getType());
Assert.assertEquals(originalTransaction.getAmount(), refund.getAmount());
Assert.assertEquals(refund.getId(), originalTransaction.getRefundId());
Assert.assertEquals(originalTransaction.getId(), refund.getRefundedTransactionId());
}
@Test
public void refundTransactionWithPartialAmount() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done().
options().
submitForSettlement(true).
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TestHelper.settle(gateway, transaction.getId());
Result<Transaction> result = gateway.transaction().refund(transaction.getId(), TransactionAmount.AUTHORIZE.amount.divide(new BigDecimal(2)));
Assert.assertTrue(result.isSuccess());
Assert.assertEquals(Transaction.Type.CREDIT, result.getTarget().getType());
Assert.assertEquals(TransactionAmount.AUTHORIZE.amount.divide(new BigDecimal(2)), result.getTarget().getAmount());
}
@Test
public void refundMultipleTransactionsWithPartialAmounts() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done().
options().
submitForSettlement(true).
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
TestHelper.settle(gateway, transaction.getId());
Transaction refund1 = gateway.transaction().refund(transaction.getId(), TransactionAmount.AUTHORIZE.amount.divide(new BigDecimal(2))).getTarget();
Assert.assertEquals(Transaction.Type.CREDIT, refund1.getType());
Assert.assertEquals(TransactionAmount.AUTHORIZE.amount.divide(new BigDecimal(2)), refund1.getAmount());
Transaction refund2 = gateway.transaction().refund(transaction.getId(), TransactionAmount.AUTHORIZE.amount.divide(new BigDecimal(2))).getTarget();
Assert.assertEquals(Transaction.Type.CREDIT, refund2.getType());
Assert.assertEquals(TransactionAmount.AUTHORIZE.amount.divide(new BigDecimal(2)), refund2.getAmount());
transaction = gateway.transaction().find(transaction.getId());
Assert.assertTrue(TestHelper.listIncludes(transaction.getRefundIds(), refund1.getId()));
Assert.assertTrue(TestHelper.listIncludes(transaction.getRefundIds(), refund1.getId()));
}
@Test
public void refundFailsWithNonSettledTransaction() {
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2008").
done();
Transaction transaction = gateway.transaction().sale(request).getTarget();
Assert.assertEquals(Transaction.Status.AUTHORIZED, transaction.getStatus());
Result<Transaction> result = gateway.transaction().refund(transaction.getId());
Assert.assertFalse(result.isSuccess());
Assert.assertEquals(ValidationErrorCode.TRANSACTION_CANNOT_REFUND_UNLESS_SETTLED,
result.getErrors().forObject("transaction").onField("base").get(0).getCode());
}
@Test
public void unrecognizedStatus() {
String xml = "<transaction><status>foobar</status><billing/><credit-card/><customer/><descriptor/><shipping/><subscription/><type>sale</type></transaction>";
Transaction transaction = new Transaction(NodeWrapperFactory.instance.create(xml));
Assert.assertEquals(Transaction.Status.UNRECOGNIZED, transaction.getStatus());
}
@Test
public void unrecognizedType() {
String xml = "<transaction><type>foobar</type><billing/><credit-card/><customer/><descriptor/><shipping/><subscription/><type>sale</type></transaction>";
Transaction transaction = new Transaction(NodeWrapperFactory.instance.create(xml));
Assert.assertEquals(Transaction.Type.UNRECOGNIZED, transaction.getType());
}
@Test
public void gatewayRejectedOnCvv() {
BraintreeGateway processingRulesGateway = new BraintreeGateway(Environment.DEVELOPMENT, "processing_rules_merchant_id", "processing_rules_public_key", "processing_rules_private_key");
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
cvv("200").
done();
Result<Transaction> result = processingRulesGateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Transaction transaction = result.getTransaction();
Assert.assertEquals(Transaction.GatewayRejectionReason.CVV, transaction.getGatewayRejectionReason());
}
@Test
public void gatewayRejectedOnAvs() {
BraintreeGateway processingRulesGateway = new BraintreeGateway(Environment.DEVELOPMENT, "processing_rules_merchant_id", "processing_rules_public_key", "processing_rules_private_key");
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
billingAddress().
postalCode("20001").
done().
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
done();
Result<Transaction> result = processingRulesGateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Transaction transaction = result.getTransaction();
Assert.assertEquals(Transaction.GatewayRejectionReason.AVS, transaction.getGatewayRejectionReason());
}
@Test
public void gatewayRejectedOnAvsAndCvv() {
BraintreeGateway processingRulesGateway = new BraintreeGateway(Environment.DEVELOPMENT, "processing_rules_merchant_id", "processing_rules_public_key", "processing_rules_private_key");
TransactionRequest request = new TransactionRequest().
amount(TransactionAmount.AUTHORIZE.amount).
billingAddress().
postalCode("20001").
done().
creditCard().
number(CreditCardNumber.VISA.number).
expirationDate("05/2009").
cvv("200").
done();
Result<Transaction> result = processingRulesGateway.transaction().sale(request);
Assert.assertFalse(result.isSuccess());
Transaction transaction = result.getTransaction();
Assert.assertEquals(Transaction.GatewayRejectionReason.AVS_AND_CVV, transaction.getGatewayRejectionReason());
}
@Test
public void snapshotAddOnsAndDiscountsFromSubscription() {
CustomerRequest customerRequest = new CustomerRequest().
creditCard().
number("5105105105105100").
expirationDate("05/12").
done();
CreditCard creditCard = gateway.customer().create(customerRequest).getTarget().getCreditCards().get(0);
SubscriptionRequest request = new SubscriptionRequest().
paymentMethodToken(creditCard.getToken()).
planId(PlanFixture.PLAN_WITHOUT_TRIAL.getId()).
addOns().
add().
amount(new BigDecimal("11.00")).
inheritedFromId("increase_10").
numberOfBillingCycles(5).
quantity(2).
done().
add().
amount(new BigDecimal("21.00")).
inheritedFromId("increase_20").
numberOfBillingCycles(6).
quantity(3).
done().
done().
discounts().
add().
amount(new BigDecimal("7.50")).
inheritedFromId("discount_7").
neverExpires(true).
quantity(2).
done().
done();
Transaction transaction = gateway.subscription().create(request).getTarget().getTransactions().get(0);
List<AddOn> addOns = transaction.getAddOns();
Collections.sort(addOns, new TestHelper.CompareModificationsById());
Assert.assertEquals(2, addOns.size());
Assert.assertEquals("increase_10", addOns.get(0).getId());
Assert.assertEquals(new BigDecimal("11.00"), addOns.get(0).getAmount());
Assert.assertEquals(new Integer(5), addOns.get(0).getNumberOfBillingCycles());
Assert.assertEquals(new Integer(2), addOns.get(0).getQuantity());
Assert.assertFalse(addOns.get(0).neverExpires());
Assert.assertEquals("increase_20", addOns.get(1).getId());
Assert.assertEquals(new BigDecimal("21.00"), addOns.get(1).getAmount());
Assert.assertEquals(new Integer(6), addOns.get(1).getNumberOfBillingCycles());
Assert.assertEquals(new Integer(3), addOns.get(1).getQuantity());
Assert.assertFalse(addOns.get(1).neverExpires());
List<Discount> discounts = transaction.getDiscounts();
Assert.assertEquals(1, discounts.size());
Assert.assertEquals("discount_7", discounts.get(0).getId());
Assert.assertEquals(new BigDecimal("7.50"), discounts.get(0).getAmount());
Assert.assertNull(discounts.get(0).getNumberOfBillingCycles());
Assert.assertEquals(new Integer(2), discounts.get(0).getQuantity());
Assert.assertTrue(discounts.get(0).neverExpires());
}
} |
package com.sun.glass.ui.monocle;
import dagger.Module;
import dagger.Provides;
import org.freedesktop.wayland.client.WlDisplayProxy;
import javax.inject.Singleton;
@Module
public class WaylandModule {
@Provides
@Singleton
WlDisplayProxy providesWlDisplayProxy() {
//TODO from config
return WlDisplayProxy.connect("wayland-0");
}
} |
package org.plasmarobotics.jim.controls;
import edu.wpi.first.wpilibj.Joystick;
/**
*
* @author Allek
*/
public class PlasmaGamepad extends Joystick {
private final ToggleableButton aButton = new ToggleableButton(this, 1),
bButton = new ToggleableButton(this, 2),
xButton = new ToggleableButton(this, 3),
yButton = new ToggleableButton(this, 4),
leftBumper = new ToggleableButton(this, 5),
rightBumper = new ToggleableButton(this, 6),
backButton = new ToggleableButton(this, 7),
startButton = new ToggleableButton(this, 8),
leftJoystickButton = new ToggleableButton(this, 9),
rightJoystickButton = new ToggleableButton(this, 10);
private final GhettoButton rightDPadButton = new GhettoButton(this, 6, false),
leftDPadButton = new GhettoButton(this, 6, true),
rightTriggerButton = new GhettoButton(this, 3, true),
leftTriggerButton = new GhettoButton(this, 3, true);
public PlasmaGamepad(int port) {
super(port);
}
public ToggleableButton getAButton() {
return this.aButton;
}
public ToggleableButton getBButton() {
return this.bButton;
}
public ToggleableButton getXButton() {
return this.xButton;
}
public ToggleableButton getYButton() {
return this.yButton;
}
public ToggleableButton getLeftBumper() {
return this.leftBumper;
}
public ToggleableButton getRightBumper() {
return this.rightBumper;
}
public ToggleableButton getBackButton() {
return this.backButton;
}
public ToggleableButton getStartButton() {
return this.startButton;
}
/**
* Get left joystick button (pressed in or not).
**/
public ToggleableButton getLeftJoystickButton() {
return this.leftJoystickButton;
}
/**
* Get right joystick button (pressed in or not).
**/
public ToggleableButton getRightJoystickButton() {
return this.rightJoystickButton;
}
/**
* Get left joystick x-axis (left-right).
* Full left = -1, full right = +1.
**/
public double getLeftJoystickXAxis() {
return super.getRawAxis(1);
}
/**
* Get left joystick y-axis (up-down).
* Full up = -1, full down = +1.
**/
public double getLeftJoystickYAxis() {
return super.getRawAxis(2);
}
/**
* Get right joystick x-axis (left-right).
* Full left = -1, full right = +1.
**/
public double getRightJoystickXAxis() {
return super.getRawAxis(4);
}
/**
* Get right joystick y-axis (up-down).
* Full up = -1, full down = +1.
**/
public double getRightJoystickYAxis() {
return super.getRawAxis(5);
}
/**
* Get trigger axis.
* Right depressed -> -1
* Left depressed -> +1
* Both fully depressed/neither touched = 0
* @return Trigger axis value
**/
public double getTriggerAxis() {
return super.getRawAxis(3);
}
/**
* Check if right trigger is pressed (trigger axis < 0).
* @deprecated Prone to looping issues. Use
* PlasmaGamepad.getRightTriggerButton().get() instead.
* @return True if pressed
**/
public boolean rightTriggerPressed() {
return (getTriggerAxis() < 0);
}
/**
* Check if left trigger is pressed (trigger axis > 0).
* @deprecated Prone to looping issues. Use
* PlasmaGamepad.getLeftTriggerButton().get() instead.
* @return True if pressed
**/
public boolean leftTriggerPressed() {
return (getTriggerAxis() > 0);
}
/**
* Get DPad axis.
* Right = 1
* Left = -1
* @return DPad axis
**/
public int getDPadXAxis() {
return (int) (super.getRawAxis(6));
}
/**
* Check if D-Pad is pressed right.
* @deprecated Prone to looping issues. Use
* PlasmaGamepad.getRightDPadButton().get() instead.
* @return True if pressed
**/
public boolean rightDPadPressed() {
return (getDPadXAxis() == 1);
}
/**
* Check if D-Pad is pressed left.
* @deprecated Prone to looping issues. Use
* PlasmaGamepad.getLeftDPadButton().get() instead.
* @return True if pressed
**/
public boolean leftDPadPressed() {
return (getDPadXAxis() == -1);
}
public GhettoButton getRightDPadButton() {
return this.rightDPadButton;
}
public GhettoButton getLeftDPadButton() {
return this.leftDPadButton;
}
public GhettoButton getRightTriggerButton() {
return this.rightTriggerButton;
}
public GhettoButton getLeftTriggerButton() {
return this.leftTriggerButton;
}
} |
package se.tfiskgul.mux2fs.fs.mux;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toList;
import static se.tfiskgul.mux2fs.Constants.BUG;
import static se.tfiskgul.mux2fs.Constants.KILOBYTE;
import static se.tfiskgul.mux2fs.Constants.MEGABYTE;
import static se.tfiskgul.mux2fs.Constants.MUX_WAIT_LOOP_MS;
import static se.tfiskgul.mux2fs.Constants.SUCCESS;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalCause;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import cyclops.control.Try;
import ru.serce.jnrfuse.ErrorCodes;
import se.tfiskgul.mux2fs.fs.base.DirectoryFiller;
import se.tfiskgul.mux2fs.fs.base.FileChannelCloser;
import se.tfiskgul.mux2fs.fs.base.FileHandleFiller;
import se.tfiskgul.mux2fs.fs.base.FileHandleFiller.Recorder;
import se.tfiskgul.mux2fs.fs.base.FileInfo;
import se.tfiskgul.mux2fs.fs.base.Sleeper;
import se.tfiskgul.mux2fs.fs.base.StatFiller;
import se.tfiskgul.mux2fs.fs.mirror.MirrorFs;
import se.tfiskgul.mux2fs.mux.MuxedFile;
import se.tfiskgul.mux2fs.mux.Muxer;
import se.tfiskgul.mux2fs.mux.Muxer.MuxerFactory;
import se.tfiskgul.mux2fs.mux.Muxer.State;
public class MuxFs extends MirrorFs {
private static final Logger logger = LoggerFactory.getLogger(MuxFs.class);
private final Path tempDir;
private final MuxerFactory muxerFactory;
private final Sleeper sleeper;
private final ConcurrentMap<FileInfo, Muxer> muxFiles = new ConcurrentHashMap<>(10, 0.75f, 2);
private final ConcurrentMap<Integer, MuxedFile> openMuxFiles = new ConcurrentHashMap<>(10, 0.75f, 2);
private final RemovalListener<FileInfo, MuxedFile> closedMuxlistener = new RemovalListener<FileInfo, MuxedFile>() {
@Override
public void onRemoval(RemovalNotification<FileInfo, MuxedFile> notification) {
if (notification.getCause() != RemovalCause.EXPLICIT) {
MuxedFile muxedFile = notification.getValue();
// This is racy, at worst we will re-trigger muxing for unlucky files being re-opened
if (!openMuxFiles.containsValue(muxedFile)) {
muxFiles.remove(muxedFile.getInfo(), muxedFile.getMuxer());
logger.info("Expired {}: {} deleted = {}", notification.getCause(), muxedFile, safeDelete(muxedFile));
} else {
logger.warn("BUG: Expired {}: {}, but is still open!", notification.getCause(), muxedFile);
}
}
}
};
private final Cache<FileInfo, MuxedFile> closedMuxFiles = CacheBuilder.newBuilder()
.maximumWeight(50 * KILOBYTE) // FIXME: Mount parameter
.removalListener(closedMuxlistener)
.weigher((info, path) -> (int) (info.getSize() / MEGABYTE)) // Weigher can only take integer, so divide down into MBs
.expireAfterWrite(20, MINUTES) // FIXME: Mount parameter
.build();
private final Cache<FileInfo, Long> muxedSizeCache = CacheBuilder.newBuilder().build();
private final LoadingCache<Path, Long> extraSizeCache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, MINUTES)
.build(new CacheLoader<Path, Long>() {
@Override
public Long load(Path key)
throws Exception {
return getExtraSizeOf(key);
}
});
private final ScheduledThreadPoolExecutor cleaningPool = new ScheduledThreadPoolExecutor(1);
private final ExecutorService executorService;
public MuxFs(Path mirroredPath, Path tempDir) {
super(mirroredPath);
this.tempDir = tempDir;
this.muxerFactory = MuxerFactory.defaultFactory();
this.sleeper = (millis) -> Thread.sleep(millis);
executorService = Executors.newCachedThreadPool();
cleaningPool.scheduleAtFixedRate(() -> {
closedMuxFiles.cleanUp();
extraSizeCache.cleanUp();
muxedSizeCache.cleanUp();
}, 10, 10, SECONDS);
}
@VisibleForTesting
MuxFs(Path mirroredPath, Path tempDir, MuxerFactory muxerFactory, Sleeper sleeper, FileChannelCloser fileChannelCloser, ExecutorService executorService) {
super(mirroredPath, fileChannelCloser);
this.tempDir = tempDir;
this.muxerFactory = muxerFactory;
this.sleeper = sleeper;
this.executorService = executorService;
}
@Override
public String getFSName() {
return "mux2fs";
}
@Override
public int readdir(String path, DirectoryFiller filler) {
logger.debug(path);
Path real = readdirInitial(path, filler);
return tryCatch.apply(() -> {
List<Path> muxFiles = null;
List<Path> subFiles = null;
// Read the directory, saving all .mkv and .srt files for further matching
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(real)) {
for (Path entry : directoryStream) {
String fileName = entry.getFileName().toString();
if (fileName.endsWith(".mkv")) {
if (muxFiles == null) {
muxFiles = new ArrayList<>();
}
muxFiles.add(entry);
continue;
}
if (fileName.endsWith(".srt")) {
if (subFiles == null) {
subFiles = new ArrayList<>();
}
subFiles.add(entry);
continue;
}
if (!add(filler, entry)) {
return SUCCESS;
}
}
}
// Hide matching .srt files from listing
if (muxFiles != null) {
for (Path muxFile : muxFiles) {
long extraSize = 0;
String muxFileNameLower = muxFile.getFileName().toString().toLowerCase();
muxFileNameLower = muxFileNameLower.substring(0, muxFileNameLower.length() - 4);
if (subFiles != null) {
Iterator<Path> subIterator = subFiles.iterator();
while (subIterator.hasNext()) {
Path subFile = subIterator.next();
String subFileNameLower = subFile.getFileName().toString().toLowerCase();
if (subFileNameLower.startsWith(muxFileNameLower)) {
subIterator.remove();
extraSize += subFile.toFile().length();
logger.debug("Hiding {} due to match with {}", subFile, muxFile);
}
}
}
if (!addWithExtraSize(filler, muxFile, extraSize)) {
return SUCCESS;
}
}
}
// List the non-matching .srt files
if (subFiles != null) {
for (Path subFile : subFiles) {
if (!add(filler, subFile)) {
return SUCCESS;
}
}
}
return SUCCESS;
});
}
@Override
public int getattr(String path, StatFiller stat) {
logger.debug(path);
if (!path.endsWith(".mkv")) {
return super.getattr(path, stat);
}
Path muxFile = real(path);
return tryCatchRunnable.apply(() -> {
stat.statWithSize(muxFile, info -> Optional.ofNullable(muxedSizeCache.getIfPresent(info)),
() -> Try.withCatch(() -> extraSizeCache.get(muxFile)).get());
});
}
@Override
// TODO: Multiple SRT file support
public int open(String path, FileHandleFiller filler) {
if (!path.endsWith(".mkv")) {
return super.open(path, filler);
}
logger.info(path);
Path muxFile = real(path);
List<Path> subFiles = getMatchingSubFiles(muxFile);
if (subFiles.isEmpty()) { // It doesn't need to be muxed, open normally
logger.debug("{} doesn't need muxing", path);
return super.open(path, filler);
}
return Try.withCatch(() -> FileInfo.of(muxFile), Exception.class).map(info ->
open(path, filler, muxFile, subFiles, info)).recover(this::translateOrThrow).get();
}
@Override
public int read(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle) {
MuxedFile muxedFile = openMuxFiles.get(fileHandle);
if (muxedFile == null) { // Not a muxed file
return super.read(path, buf, size, offset, fileHandle);
}
Muxer muxer = muxedFile.getMuxer();
State state = muxer.state();
switch (state) {
case SUCCESSFUL:
return super.read(path, buf, size, offset, fileHandle);
case FAILED:
return muxingFailed(fileHandle, muxedFile, muxer);
case RUNNING:
return readRunningMuxer(path, buf, size, offset, fileHandle, muxedFile, muxer);
default:
logger.error("BUG: Unhandled state {} in muxer {}", state, muxer);
return BUG;
}
}
@Override
public int release(String path, int fileHandle) {
logger.info("release({}, {})", fileHandle, path);
MuxedFile muxed = openMuxFiles.remove(fileHandle);
if (muxed != null && !openMuxFiles.containsValue(muxed)) {
// Muxed file is no longer open, save it in cache for quick re-open
closedMuxFiles.put(muxed.getInfo(), muxed);
}
return super.release(path, fileHandle);
}
@Override
public void destroy() {
super.destroy();
logger.info("Cleaning up");
cleaningPool.shutdownNow();
executorService.shutdownNow();
closedMuxFiles.asMap().forEach((info, muxed) -> muxed.getMuxer().getOutput().map(this::safeDelete));
closedMuxFiles.invalidateAll();
closedMuxFiles.cleanUp();
openMuxFiles.forEach((fh, muxed) -> safeDelete(muxed));
openMuxFiles.clear();
muxFiles.forEach((fi, muxer) -> muxer.getOutput().map(this::safeDelete));
muxFiles.clear();
}
private int open(String path, FileHandleFiller filler, Path muxFile, List<Path> subFiles, FileInfo info) {
closedMuxFiles.invalidate(info);
Muxer muxer = muxerFactory.from(muxFile, subFiles.get(0), tempDir);
Muxer previous = muxFiles.putIfAbsent(info, muxer); // Others might be racing the same file
if (previous != null) { // They won the race
muxer = previous;
}
try {
muxer.start();
muxer.waitForOutput();
} catch (IOException e) {
// Something dun goofed. Second best thing is to open the original file then.
logger.warn("Muxing failed, falling back to unmuxed file {}", muxFile, e);
// Invalidate the broken muxer. This means the next open will try again, which might not be a good strategy.
muxFiles.remove(info, muxer);
return super.open(path, filler);
}
Optional<Path> optionalOutput = muxer.getOutput();
if (!optionalOutput.isPresent()) {
logger.warn("Muxing failed! muxer.getOutput().isPresent() == false, falling back to unmuxed file {}", muxFile);
// Invalidate the broken muxer. This means the next open will try again, which might not be a good strategy.
muxFiles.remove(info, muxer);
return super.open(path, filler); // Fall back to original if no result
}
Path output = optionalOutput.get();
Recorder recorder = FileHandleFiller.Recorder.wrap(filler);
int result = super.openReal(output, recorder);
if (result == SUCCESS) {
updateMuxCaches(info, muxer, output, recorder);
} else {
logger.warn("Failed to open muxed file {}, falling back to unmuxed file {}", output, muxFile);
muxFiles.remove(info, muxer);
safeDelete(output);
result = super.openReal(muxFile, filler);
}
return result;
}
private void updateMuxCaches(FileInfo info, final Muxer muxer, Path output, Recorder recorder) {
openMuxFiles.put(recorder.getFileHandle(), new MuxedFile(info, muxer));
if (!muxedSizeCache.asMap().containsKey(info)) { // Race, but fine.
executorService.submit(() -> {
try {
muxer.waitFor();
} catch (Exception e) { // Ignored
}
if (muxer.state() == State.SUCCESSFUL) {
long length = output.toFile().length();
if (length > 0) {
muxedSizeCache.put(info, length);
}
}
});
}
}
private boolean safeDelete(MuxedFile file) {
if (file != null) {
return file.getMuxer().getOutput().map(this::safeDelete).orElse(false);
}
return false;
}
private int readRunningMuxer(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle, MuxedFile muxedFile, Muxer muxer) {
long maxPosition = offset + size; // This could overflow for really big files / sizes, close to 8388608 TB.
FileChannel channelFor = getChannelFor(fileHandle);
if (channelFor == null) {
logger.error("BUG: FileChannel for file handle {} open {} not found", fileHandle, muxedFile);
return BUG;
}
try {
long muxSize = channelFor.size();
if (maxPosition >= muxSize) { // Read beyond current mux progress
logger.debug("{}: read @ {} with mux progress {}, sleeping...", path, maxPosition, muxSize);
int result = waitForMuxing(muxer, maxPosition, channelFor, fileHandle, muxedFile);
if (result != 0) {
return result;
}
}
return super.read(path, buf, size, offset, fileHandle);
} catch (IOException e) {
logger.warn("IOException for {}", muxedFile, e);
return -ErrorCodes.EIO();
} catch (InterruptedException e) {
logger.warn("Interrupted while waiting for {}", muxedFile, e);
return -ErrorCodes.EINTR();
}
}
/**
* At this point, we are still muxing, and trying to read beyond muxed data.
*
* We park here and wait until it is available.
*/
private int waitForMuxing(Muxer muxer, long maxPosition, FileChannel fileChannel, int fileHandle, MuxedFile muxedFile)
throws IOException, InterruptedException {
long currentSize = 0;
while (maxPosition >= (currentSize = fileChannel.size())) {
State state = muxer.state();
switch (state) {
case RUNNING:
logger.debug("Want to read @ {} (file is {}), so waiting for {}", maxPosition, currentSize, muxer);
sleeper.sleep(MUX_WAIT_LOOP_MS);
break;
case SUCCESSFUL:
logger.debug("Done waiting to read @ {}", maxPosition, muxer);
return SUCCESS;
case FAILED:
return muxingFailed(fileHandle, muxedFile, muxer);
default:
logger.error("BUG: Unhandled state {} in muxer {}", state, muxer);
return BUG;
}
}
logger.debug("Done waiting to read @ {}", maxPosition, muxer);
return SUCCESS;
}
private int muxingFailed(int fileHandle, MuxedFile muxedFile, Muxer muxer) {
logger.info("Muxing failed for {}", muxer);
muxFiles.remove(muxedFile.getInfo(), muxer);
openMuxFiles.remove(fileHandle, muxedFile);
return -ErrorCodes.EIO();
}
private boolean safeDelete(Path path) {
if (path != null) {
try {
return path.toFile().delete();
} catch (Exception e) {
logger.warn("Failed to delete {} ", path, e);
}
}
return false;
}
private long getExtraSizeOf(Path mkv) {
return getMatchingSubFiles(mkv).stream().reduce(0L, (buf, path) -> buf + path.toFile().length(), (a, b) -> a + b);
}
private List<Path> getMatchingSubFiles(Path muxFile) {
return getFileName(muxFile).map(name -> getMatchingSubFiles(muxFile.getParent(), name)).orElse(Collections.emptyList());
}
private List<Path> getMatchingSubFiles(Path parent, String muxName) {
String muxFileNameLower = muxName.toLowerCase().substring(0, muxName.length() - 4);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(parent)) {
return StreamSupport.stream(directoryStream.spliterator(), false).filter(entry -> {
String entryName = entry.getFileName().toString();
return entryName.endsWith(".srt") && entryName.toLowerCase().startsWith(muxFileNameLower);
}).collect(toList());
} catch (IOException e) { // Ignored, non-critical
logger.trace("", e);
return Collections.emptyList();
}
}
private boolean addWithExtraSize(DirectoryFiller filler, Path entry, long extraSize) {
return add(entry, (fileName) -> filler.addWithExtraSize(fileName, entry, extraSize));
}
} |
package com.tspooner.histogram;
// Import statements
import java.text.DecimalFormat;
import java.util.List;
import java.util.ArrayList;
public class AdaptiveStorage extends HistogramStorage {
private Tree<Bin> tree;
public AdaptiveStorage(double min, double max) {
tree = new Tree<Bin>(new Bin(0, min, max));
}
public AdaptiveStorage() { tree = new Tree<Bin>(new Bin()); }
public void reset() {
Bin old = tree.getValue();
tree.reset(); old.reset();
tree.setValue(old);
}
public void add(double value) {
List<Tree<Bin>> fringe = tree.fringe();
boolean counted = false;
for (Tree<Bin> leaf : fringe) {
if (counted) return;
Bin bin = leaf.getValue();
if (bin.contains(value)) {
counted = true;
total++;
bin.increment();
if (bin.count >= getSplitLimit() && bin.min != bin.max) {
List<Bin> newBins;
if (value > bin.getCentre())
newBins = bin.split();
else
newBins = bin.split();
leaf.setLeft(new Tree<Bin>(newBins.get(0)));
leaf.setRight(new Tree<Bin>(newBins.get(1)));
if (bin.count % 2 != 0) {
if (leaf.getLeft().getValue().contains(value))
leaf.getLeft().getValue().increment();
else
leaf.getRight().getValue().increment();
}
}
}
}
Bin toExtend;
if (!counted) {
if (fringe.get(0).getValue().min > value)
toExtend = fringe.get(0).getValue();
else
toExtend = fringe.get((fringe.size()-1)).getValue();
toExtend.extend(value);
toExtend.increment();
}
}
public int getCount(double value) {
Bin bin = getBin(value);
return (null != bin) ? bin.count : 0;
}
public int getCount(int index) {
List<Tree<T>> leaves = tree.fringe();
if (index < leaves.size())
return leaves.get(index).getValue().count;
else
return 0;
}
public int getAccumCount(double value) {
int sum = 0;
for (Tree<Bin> leaf : tree) {
sum += leaf.getValue().count;
if (leaf.getValue().contains(value)) break;
}
return sum;
}
public double getDensity(double value) {
Bin bin = getBin(value);
return (null != bin) ? bin.getDensity(getTotal()) : 0;
}
public double getValueAtPercentile(int perc) {
int pSum = (int) getTotal(tree) * perc / 100;
int cSum = 0;
Bin bin = null;
for (Tree<Bin> leaf : tree) {
cSum += leaf.getValue().count;
if (cSum >= pSum) {
bin = leaf.getValue();
break;
}
}
return (null != bin) ? bin.getCentre() : 100;
}
private int getTotal(Tree<Bin> node) {
int sum = 0;
for (Tree<Bin> leaf : node.fringe())
sum += leaf.getValue().count;
return sum;
}
private Bin getBin(double value) {
for (Tree<Bin> leaf : tree)
if (leaf.getValue().contains(value)) return leaf.getValue();
return null;
}
private int getSplitLimit() {
return (total == 1) ? 1 : total / 10;
}
// Export methods
public String toCsv() {
String csv = "bin_centre,bin_width,bin_count,bin_unit_density\n";
for (Tree<Bin> f : tree) {
Bin bin = f.getValue();
csv += bin.getCentre() + "," +
bin.getWidth() + "," +
bin.count + "," +
bin.getDensity(total) + "\n";
}
return csv;
}
public int[] toArray() {
List<Tree<Bin>> fringe = tree.fringe();
int[] arr = new int[fringe.size()];
for (int i = 0; i < arr.length; i++)
arr[i] = (int) fringe.get(i).getValue().getDensity(total);
return arr;
}
public String toPrettyString() {
StringBuilder sb = new StringBuilder();
String sep = System.getProperty("line.separator");
DecimalFormat df = new DecimalFormat("#0.00");
DecimalFormat dfMore = new DecimalFormat("#0.0000");
sb.append(sep);
// Add all the leaf nodes
for (Tree<Bin> node : tree.fringe()) {
Bin bin = node.getValue();
sb.append(
"Bin @ " + dfMore.format(bin.getCentre()) + ": " + bin.getCount() +
"\t[\u03c3 = " + df.format(error(bin.getCount())) + "]" +
"\t(" + dfMore.format(bin.max - bin.min) + ")" + sep
); // U+03C3 is a sigma character
}
return sb.toString();
}
} |
package org.tepi.filtertable.demo;
import java.text.DateFormat;
import java.util.Locale;
import org.tepi.filtertable.FilterDecorator;
import org.tepi.filtertable.demo.FiltertabledemoApplication.State;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.DateField;
class DemoFilterDecorator implements FilterDecorator {
public String getEnumFilterDisplayName(Object propertyId, Object value) {
if ("state".equals(propertyId)) {
State state = (State) value;
switch (state) {
case CREATED:
return "Order has been created";
case PROCESSING:
return "Order is being processed";
case PROCESSED:
return "Order has been processed";
case FINISHED:
return "Order is delivered";
}
}
// returning null will output default value
return null;
}
public Resource getEnumFilterIcon(Object propertyId, Object value) {
if ("state".equals(propertyId)) {
State state = (State) value;
switch (state) {
case CREATED:
return new ThemeResource("../runo/icons/16/document.png");
case PROCESSING:
return new ThemeResource("../runo/icons/16/reload.png");
case PROCESSED:
return new ThemeResource("../runo/icons/16/ok.png");
case FINISHED:
return new ThemeResource("../runo/icons/16/globe.png");
}
}
return null;
}
public String getBooleanFilterDisplayName(Object propertyId, boolean value) {
if ("validated".equals(propertyId)) {
return value ? "Validated" : "Not validated";
}
// returning null will output default value
return null;
}
public Resource getBooleanFilterIcon(Object propertyId, boolean value) {
if ("validated".equals(propertyId)) {
return value ? new ThemeResource("../runo/icons/16/ok.png")
: new ThemeResource("../runo/icons/16/cancel.png");
}
return null;
}
public String getFromCaption() {
return "Start date:";
}
public String getToCaption() {
return "End date:";
}
public String getSetCaption() {
// use default caption
return null;
}
public String getClearCaption() {
// use default caption
return null;
}
public boolean isTextFilterImmediate(Object propertyId) {
// use text change events for all the text fields
return true;
}
public int getTextChangeTimeout(Object propertyId) {
// use the same timeout for all the text fields
return 500;
}
public String getAllItemsVisibleString() {
return "Show all";
}
public int getDateFieldResolution(Object propertyId) {
return DateField.RESOLUTION_DAY;
}
public DateFormat getDateFormat(Object propertyId) {
return DateFormat.getDateInstance(DateFormat.SHORT, new Locale("fi",
"FI"));
}
} |
// MainServlet.java
// blogwt
package com.willshex.blogwt.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.SilentCssErrorHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.spacehopperstudios.utility.StringUtils;
import com.willshex.blogwt.server.service.PersistenceService;
import com.willshex.blogwt.server.service.permission.PermissionServiceProvider;
import com.willshex.blogwt.server.service.property.IPropertyService;
import com.willshex.blogwt.server.service.property.PropertyServiceProvider;
import com.willshex.blogwt.server.service.role.RoleServiceProvider;
import com.willshex.blogwt.server.service.session.ISessionService;
import com.willshex.blogwt.server.service.session.SessionServiceProvider;
import com.willshex.blogwt.server.service.user.UserServiceProvider;
import com.willshex.blogwt.shared.api.datatype.Property;
import com.willshex.blogwt.shared.api.datatype.Session;
import com.willshex.blogwt.shared.api.helper.PropertyHelper;
import com.willshex.service.ContextAwareServlet;
/**
* @author William Shakour (billy1380)
*
*/
public class MainServlet extends ContextAwareServlet {
private static final long serialVersionUID = 3007918530671674098L;
private static String PAGE_FORMAT = null;
private static final long TIMEOUT_MILLIS = 5000;
private static final long JS_TIMEOUT_MILLIS = 2000;
private static final long PAGE_WAIT_MILLIS = 100;
private static final long MAX_LOOP_CHECKS = 2;
private static final String CHAR_ENCODING = "UTF-8";
static {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
MainServlet.class.getResourceAsStream("res/index.html")))) {
StringBuffer contents = new StringBuffer();
int length;
char string[] = new char[1024];
while ((length = reader.read(string)) != -1) {
contents.append(string, 0, length);
}
PAGE_FORMAT = contents.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
*
* @see com.willshex.service.ContextAwareServlet#doGet() */
@Override
protected void doGet () throws ServletException, IOException {
super.doGet();
HttpServletRequest request = REQUEST.get();
String fragmentParameter = request.getParameter("_escaped_fragment_");
boolean isStatic = fragmentParameter != null;
if (isStatic) {
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String uri = request.getRequestURI();
String url = scheme + "://" + serverName + ":" + serverPort + uri
+ "#!" + StringUtils.urldecode(fragmentParameter);
HttpServletResponse response = RESPONSE.get();
response.setCharacterEncoding(CHAR_ENCODING);
response.setHeader("Content-Type", "text/plain; charset="
+ CHAR_ENCODING);
response.getOutputStream().print(staticContent(url));
} else {
IPropertyService propertyService = PropertyServiceProvider
.provide();
ISessionService sessionService = SessionServiceProvider.provide();
Property title = null, extendedTitle = null, copyrightHolder = null, copyrightUrl = null;
StringBuffer scriptVariables = new StringBuffer();
List<Property> properties = null;
title = propertyService.getNamedProperty(PropertyHelper.TITLE);
Session userSession = null;
if (title != null) {
extendedTitle = propertyService
.getNamedProperty(PropertyHelper.EXTENDED_TITLE);
copyrightHolder = propertyService
.getNamedProperty(PropertyHelper.COPYRIGHT_HOLDER);
copyrightUrl = propertyService
.getNamedProperty(PropertyHelper.COPYRIGHT_URL);
properties = Arrays.asList(new Property[] { title,
extendedTitle, copyrightHolder, copyrightUrl });
Cookie[] cookies = request.getCookies();
String sessionId = null;
if (cookies != null) {
for (Cookie currentCookie : cookies) {
if ("session.id".equals(currentCookie.getName())) {
sessionId = currentCookie.getValue();
break;
}
}
if (sessionId != null) {
userSession = sessionService.getSession(Long
.valueOf(sessionId));
if (userSession != null) {
if (userSession.expires.getTime() > new Date()
.getTime()) {
userSession = sessionService
.extendSession(
userSession,
Long.valueOf(ISessionService.MILLIS_MINUTES));
userSession.user = UserServiceProvider
.provide().getUser(
userSession.userKey.getId());
userSession.user.password = null;
if (userSession.user.roleKeys != null) {
userSession.user.roles = RoleServiceProvider
.provide()
.getIdRolesBatch(
PersistenceService
.keysToIds(userSession.user.roleKeys));
}
if (userSession.user.permissionKeys != null) {
userSession.user.permissions = PermissionServiceProvider
.provide()
.getIdPermissionsBatch(
PersistenceService
.keysToIds(userSession.user.permissionKeys));
}
} else {
sessionService.deleteSession(userSession);
userSession = null;
}
}
}
}
if (properties != null) {
scriptVariables.append("\nvar properties='[");
boolean first = true;
for (Property property : properties) {
if (first) {
first = false;
} else {
scriptVariables.append(",");
}
scriptVariables.append(property.toString().replace("'",
"\\'"));
}
scriptVariables.append("]';\n");
}
if (userSession != null) {
scriptVariables.append("var session='"
+ userSession.toString().replace("'", "\\'")
+ "';\n");
}
}
RESPONSE.get()
.getOutputStream()
.print(String.format(PAGE_FORMAT, (title == null ? "Blogwt"
: title.value), scriptVariables.toString()));
}
}
/**
* This method as far as I can tell does not work with the gwt version of htmlunit
* will probably either need to use GWTP crawler service or restructure this project
* to use modules and roll my own again either with GWTP or just the method below
* @return
* @throws IOException
* @throws FailingHttpStatusCodeException
*/
private String staticContent (String url)
throws FailingHttpStatusCodeException, IOException {
WebClient webClient = new WebClient();
webClient.getCache().clear();
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setRedirectEnabled(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController() {
private static final long serialVersionUID = 2875888832992558703L;
/* (non-Javadoc)
*
* @see com.gargoylesoftware.htmlunit.
* NicelyResynchronizingAjaxController #processSynchron(com
* .gargoylesoftware.htmlunit.html.HtmlPage,
* com.gargoylesoftware.htmlunit.WebRequest, boolean) */
@Override
public boolean processSynchron (HtmlPage page, WebRequest settings,
boolean async) {
return true;
}
});
webClient.setCssErrorHandler(new SilentCssErrorHandler());
WebRequest webRequest = new WebRequest(new URL(url), "text/html");
HtmlPage page = webClient.getPage(webRequest);
webClient.getJavaScriptEngine().pumpEventLoop(TIMEOUT_MILLIS);
int waitForBackgroundJavaScript = webClient
.waitForBackgroundJavaScript(JS_TIMEOUT_MILLIS);
int loopCount = 0;
while (waitForBackgroundJavaScript > 0 && loopCount < MAX_LOOP_CHECKS) {
++loopCount;
waitForBackgroundJavaScript = webClient
.waitForBackgroundJavaScript(JS_TIMEOUT_MILLIS);
if (waitForBackgroundJavaScript == 0) {
break;
}
synchronized (page) {
try {
page.wait(PAGE_WAIT_MILLIS);
} catch (InterruptedException e) {}
}
}
webClient.closeAllWindows();
return Pattern
.compile("<style>.*?</style>", Pattern.DOTALL)
.matcher(
page.asXml().replace(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"")).replaceAll("");
}
} |
package net.katsuster.strview.media;
import net.katsuster.strview.util.*;
import net.katsuster.strview.io.*;
public class BitBuffer {
private long position = 0;
private long limit;
private long capacity;
protected LargeBitList buf;
/**
* <p>
* position <= limit <= capacity
* </p>
*
* @param pos
* @param lim
* @param cap
*/
protected BitBuffer(long pos, long lim, long cap) {
this(pos, lim, cap, null);
}
/**
* <p>
* position <= limit <= capacity
* </p>
*
* @param pos
* @param lim
* @param cap
* @param b
*/
protected BitBuffer(long pos, long lim, long cap, LargeBitList b) {
super();
if (cap < 0) {
throw new IllegalArgumentException(
"capacity is negative(" + cap + ").");
}
if (b.length() < (cap)) {
throw new IndexOutOfBoundsException(
"capacity(" + cap + ") is too large"
+ "(b.length: " + b.length() + ").");
}
capacity = cap;
limit(lim);
position(pos);
buf = b;
}
/**
* <p>
*
* </p>
*
* @param capacity
* @return
*/
public static BitBuffer allocate(long capacity) {
BitBuffer b;
if (capacity < 0) {
throw new IllegalArgumentException(
"capacity is negative(" + capacity + ").");
}
if (capacity > Integer.MAX_VALUE) {
throw new IndexOutOfBoundsException(
"capacity is too large(" + capacity + ").");
}
b = new BitBuffer(0, capacity, capacity,
new MemoryBitList(capacity));
return b;
}
/**
* <p>
*
* </p>
*
* @param array
* @param length
* @return
*/
public static BitBuffer wrap(LargeBitList array, long length) {
return new BitBuffer(0, length, length,
array);
}
/**
* <p>
*
* </p>
*
* @param array
* @return
*/
public static BitBuffer wrap(LargeBitList array) {
return wrap(array, array.length());
}
/**
* <p>
*
* </p>
*
* @param array
* @param length
* @return
*/
public static BitBuffer wrap(LargeByteList array, long length) {
return new BitBuffer(0, length, length,
new ByteToBitList(array));
}
/**
* <p>
*
* </p>
*
* @param array
* @return
*/
public static BitBuffer wrap(LargeByteList array) {
return wrap(array, (array.length() << 3));
}
/**
* <p>
* byte
* </p>
*
* @param array byte
* @param length
* @return
*/
public static BitBuffer wrap(byte[] array, long length) {
return new BitBuffer(0, length, length,
new ByteToBitList(new MemoryByteList(array)));
}
/**
* <p>
* byte
* </p>
*
* @param array byte
* @return
*/
public static BitBuffer wrap(byte[] array) {
return wrap(new MemoryByteList(array), (array.length << 3));
}
/**
* <p>
*
* </p>
*
* <p>
*
*
* 2
* </p>
*
* <p>
*
*
* </p>
*
* @return
*/
public BitBuffer duplicate() {
return new BitBuffer(position, limit, capacity,
buf);
}
protected long getIndex(long i) {
if ((0 <= i) && (i < limit)) {
return i;
} else {
throw new IndexOutOfBoundsException(
"index(" + i + ") is exceeded "
+ "limit(" + limit + ").");
}
}
protected long getIndex(long i, int n) {
if ((0 <= i) || (n + i <= limit)) {
return i;
} else {
throw new IndexOutOfBoundsException(
"index(" + i + " - " + (i + n) + ") is exceeded "
+ "limit(" + limit + ").");
}
}
/**
* <p>
*
*
* </p>
*
* @return
*/
protected String invariantToString() {
return "position(" + position + ")"
+ "<= limit(" + limit + ")"
+ "<= capacity(" + capacity + ")";
}
/**
* <p>
*
* </p>
*
* @return
*/
public long capacity() {
return capacity;
}
/**
* <p>
*
* </p>
*
* @return
*/
public long position() {
return position;
}
public BitBuffer position(long newPosition) {
if (newPosition < 0) {
throw new IllegalArgumentException(
"new position is negative(" + newPosition + ").");
}
if (newPosition > limit) {
throw new IndexOutOfBoundsException(
"new position does not hold invariant. "
+ invariantToString());
}
position = newPosition;
return this;
}
/**
* <p>
*
* </p>
*
* @return
*/
public long limit() {
return limit;
}
public BitBuffer limit(long newLimit) {
if (newLimit < 0) {
throw new IllegalArgumentException(
"new limit is negative(" + newLimit + ").");
}
if (newLimit > capacity) {
throw new IndexOutOfBoundsException(
"new limit does not hold invariant."
+ invariantToString());
}
limit = newLimit;
if (position > limit) {
position = limit;
}
return this;
}
/**
* <p>
*
* 0
* </p>
*
* <p>
*
* java.nio.Buffer clear()
* </p>
*
* @return
* @see java.nio.Buffer#clear()
*/
public BitBuffer clear() {
limit = capacity;
position = 0;
return this;
}
/**
* <p>
*
*
* 0
* </p>
*
* <p>
*
* java.nio.Buffer flip()
* </p>
*
* @return
* @see java.nio.Buffer#flip()
*/
public BitBuffer flip() {
limit = position;
position = 0;
return this;
}
/**
* <p>
*
* 0
* </p>
*
* <p>
*
* java.nio.Buffer rewind()
* </p>
*
* @return
* @see java.nio.Buffer#rewind()
*/
public BitBuffer rewind() {
position = 0;
return this;
}
/**
* <p>
*
* </p>
*
* @return
*/
public long remaining() {
return (limit - position);
}
/**
* <p>
* 1
* </p>
*
* @return true
* 1 false
*/
public boolean hasRemaining() {
return (position < limit);
}
/**
* <p>
*
* </p>
*
* @return true false
*/
public boolean isReadOnly() {
return false;
}
/**
* <p>
*
* Java
* </p>
*
* <p>
* true array
* arrayOffset
* </p>
*
* @return Java
* true
* false
*/
public boolean hasArray() {
return true;
}
/**
* <p>
*
* </p>
*
* <p>
*
*
* </p>
*
* <p>
* hasArray
*
* </p>
*
* @return
* @throws UnsupportedOperationException
*
*/
public LargeBitList array() {
return buf;
}
/**
* <p>
*
* </p>
*
* @return true
* false
*/
public boolean isDirect() {
return false;
}
/**
* <p>
* p
* </p>
*
* @return true false
*/
public boolean isAlignedByte() {
return ((position & 0x07) == 0);
}
/**
* <p>
* p
* </p>
*
* @return
*/
public BitBuffer alignByte() {
return position((position + 0x7) & ~0x7);
}
/**
* <p>
* p 2
* </p>
*
* @return 2 true false
*/
public boolean isAlignedShort() {
return ((position & 0x0f) == 0);
}
/**
* <p>
* p 2
* </p>
*
* @return
*/
public BitBuffer alignShort() {
return position((position + 0xf) & ~0xf);
}
/**
* <p>
* p 4
* </p>
*
* @return 4 true false
*/
public boolean isAlignedInt() {
return ((position & 0x1f) == 0);
}
/**
* <p>
* p 4
* </p>
*
* @return
*/
public BitBuffer alignInt() {
return position((position + 0x1f) & ~0x1f);
}
/**
* <p>
* p 8
* </p>
*
* @return 8 true false
*/
public boolean isAlignedLong() {
return ((position & 0x3f) == 0);
}
/**
* <p>
* p 8
* </p>
*
* @return
*/
public BitBuffer alignLong() {
return position((position + 0x3f) & ~0x3f);
}
public int get() {
int result;
result = peek32Inner(1, getIndex(position));
position += 1;
return result;
}
public int get(long index) {
int result;
result = peek32Inner(1, getIndex(index));
return result;
}
public BitBuffer get(byte[] dst, int off, int length) {
return get(new MemoryByteList(dst), off, length);
}
public BitBuffer get(byte[] dst) {
return get(dst, 0, (dst.length << 3));
}
public BitBuffer get(LargeByteList dst, int off, int length) {
//bits
long index;
int len, n;
//bytes
int dst_off;
if (off < 0) {
throw new IllegalArgumentException(
"offset is negative"
+ "(offset: " + off + ").");
}
if (length < 0) {
throw new IllegalArgumentException(
"length is negative"
+ "(length: " + length + ").");
}
if ((off + length) > (dst.length() << 3)) {
throw new IndexOutOfBoundsException(
"offset + length is too large"
+ "(offset: " + off + ", "
+ "(length: " + length + ", "
+ "(dst.length: " + (dst.length() << 3) + ")");
}
if (length > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is underflow, "
+ "required(" + length + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
index = getIndex(position, length);
len = length;
dst_off = (off >>> 3);
if (len > 8) {
//use for-loop
n = 8 - (off & 0x07);
off = 0;
//1st byte
dst.set(dst_off, (byte)peek32Inner(n, index));
index += n;
len -= n;
dst_off += 1;
//mid bytes
while (len >= 8) {
dst.set(dst_off, (byte)peek32Inner(8, index));
index += 8;
len -= 8;
dst_off += 1;
}
}
//last byte
if (len > 0) {
dst.set(dst_off,
(byte)(peek32Inner(len, index) << (8 - len - (off & 0x07))));
}
position += length;
return this;
}
public BitBuffer get(LargeByteList dst) {
return get(dst, 0, (int)dst.getLength());
}
public Float32 getF32(int n, Float32 val) {
long p = position();
if (val == null) {
val = new Float32();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(get32(n));
return val;
}
public SFixed8_8 getSF8_8(int n, SFixed8_8 val) {
long p = position();
if (n != 16) {
throw new IllegalArgumentException(
"getSF8_8() cannot get not equal 16 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new SFixed8_8();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue((short)(get32(n)));
return val;
}
public UFixed8_8 getUF8_8(int n, UFixed8_8 val) {
long p = position();
if (n != 16) {
throw new IllegalArgumentException(
"getUF8_8() cannot get not equal 16 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new UFixed8_8();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue((short)(get32(n)));
return val;
}
public SFixed16_16 getSF16_16(int n, SFixed16_16 val) {
long p = position();
if (n != 32) {
throw new IllegalArgumentException(
"getSF16_16() cannot get not equal 32 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new SFixed16_16();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(get32(n));
return val;
}
public UFixed16_16 getUF16_16(int n, UFixed16_16 val) {
long p = position();
if (n != 32) {
throw new IllegalArgumentException(
"getUF16_16() cannot get not equal 32 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new UFixed16_16();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(get32(n));
return val;
}
public SInt getS16r(int n, SInt val) {
long p = position();
if (n != 16) {
throw new IllegalArgumentException(
"getS16r() cannot get not equal 16 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new SInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Short.reverseBytes((short)(get32(n))));
return val;
}
public SInt getS32r(int n, SInt val) {
long p = position();
if (n != 32) {
throw new IllegalArgumentException(
"getS32r() cannot get not equal 32 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new SInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Integer.reverseBytes(get32(n)));
return val;
}
public UInt getU16r(int n, UInt val) {
long p = position();
if (n != 16) {
throw new IllegalArgumentException(
"getU16r() cannot get not equal 16 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new UInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Short.reverseBytes((short)(get32(n))) & 0xffffL);
return val;
}
public UInt getU32r(int n, UInt val) {
long p = position();
if (n != 32) {
throw new IllegalArgumentException(
"getU32r() cannot get not equal 32 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new UInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Integer.reverseBytes(get32(n)) & 0xffffffffL);
return val;
}
public Float32 getF32r(int n, Float32 val) {
long p = position();
if (n != 32) {
throw new IllegalArgumentException(
"getF32r() cannot get not equal 32 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new Float32();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Integer.reverseBytes(get32(n)));
return val;
}
public int peek32(int n) {
int result;
if (n < 0 || 32 < n) {
throw new IllegalArgumentException(
"peek32() cannot get more than 32 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is underflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
result = peek32Inner(n, getIndex(position, n));
return result;
}
public int get32(int n) {
int result;
if (n < 0 || 32 < n) {
throw new IllegalArgumentException(
"get32() cannot get more than 32 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is underflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
result = peek32Inner(n, getIndex(position, n));
position += n;
return result;
}
/**
* <p>
* 1 32
* </p>
*
* @param n 32
* @param index
* @return n
*/
protected int peek32Inner(int n, long index) {
return buf.getPackedInt(index, n);
}
public SInt getSInt(int n, SInt val) {
long p = position();
if (val == null) {
val = new SInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(get64(n));
return val;
}
public UInt getUInt(int n, UInt val) {
long p = position();
if (val == null) {
val = new UInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(get64(n));
return val;
}
public Float64 getF64(int n, Float64 val) {
long p = position();
if (val == null) {
val = new Float64();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(get64(n));
return val;
}
public SInt getS64r(int n, SInt val) {
long p = position();
if (n != 64) {
throw new IllegalArgumentException(
"getS64r() cannot get not equal 64 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new SInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Long.reverseBytes(get64(n)));
return val;
}
public UInt getU64r(int n, UInt val) {
long p = position();
if (n != 64) {
throw new IllegalArgumentException(
"getU64r() cannot get not equal 64 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new UInt();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Long.reverseBytes(get64(n)));
return val;
}
public Float64 getF64r(int n, Float64 val) {
long p = position();
if (n != 64) {
throw new IllegalArgumentException(
"getF64r() cannot get not equal 64 bits."
+ "(" + n + "bits)");
}
if (val == null) {
val = new Float64();
}
val.setStart(p);
val.setLength(n);
val.setBitsValue(Long.reverseBytes(get64(n)));
return val;
}
/**
* <p>
*
*
* </p>
*
* @param n
* @return n
*/
public LargeBitList getBitList(int n) {
LargeBitList b;
b = buf.subLargeList(position(), position() + n);
position += n;
return b;
}
public LargeByteList getByteArray(int n) {
LargeByteList a = new MemoryByteList(
new byte[(n + 7) >>> 3], n, position());
get(a);
return a;
}
public long peek64(int n) {
long result;
if (n < 0 || 64 < n) {
throw new IllegalArgumentException(
"peek64() cannot get more than 64 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is underflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
result = peek64Inner(n, getIndex(position, n));
return result;
}
public long get64(int n) {
long result;
if (n < 0 || 64 < n) {
throw new IllegalArgumentException(
"get64() cannot get more than 64 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is underflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
result = peek64Inner(n, getIndex(position, n));
position += n;
return result;
}
/**
* <p>
* 1 64
* </p>
*
* @param n 64
* @param index
* @return n
*/
protected long peek64Inner(int n, long index) {
return buf.getPackedLong(index, n);
}
/**
* <p>
* 1
* </p>
*
* @param val 1
* @return
*/
public BitBuffer put(int val) {
poke32Inner(1, val, getIndex(position));
position += 1;
return this;
}
/**
* <p>
* 1
* </p>
*
* @param index
* @param val 1
* @return
*/
public BitBuffer put(long index, int val) {
poke32Inner(1, val, getIndex(index));
return this;
}
public BitBuffer put(byte[] src, int off, int length) {
return put(new MemoryByteList(src), off, length);
}
public BitBuffer put(byte[] src) {
return put(src, 0, (src.length << 3));
}
public BitBuffer put(LargeByteList src, int off, int length) {
//bits
long index;
int len, n;
//bytes
int src_off;
if (off < 0) {
throw new IllegalArgumentException(
"offset is negative"
+ "(offset: " + off + ").");
}
if (length < 0) {
throw new IllegalArgumentException(
"length is negative"
+ "(length: " + length + ").");
}
if ((off + length) > (src.length() << 3)) {
throw new IndexOutOfBoundsException(
"offset + length is too large"
+ "(offset: " + off + ", "
+ "(length: " + length + ", "
+ "(src.length: " + (src.length() << 3) + ")");
}
if (length > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is overflow, "
+ "required(" + length + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
index = getIndex(position, length);
len = length;
src_off = (off >>> 3);
if (len > 8) {
//use for-loop
n = 8 - (off & 0x07);
off = 0;
//1st byte
poke32Inner(n, src.get(src_off), index);
index += n;
len -= n;
src_off += 1;
//mid bytes
while (len >= 8) {
poke32Inner(8, src.get(src_off), index);
index += 8;
len -= 8;
src_off += 1;
}
}
//last byte
if (len > 0) {
poke32Inner(len, src.get(src_off) >>> (8 - len - (off & 0x07)), index);
}
position += length;
return this;
}
public BitBuffer put(LargeByteList src) {
return put(src, 0, (int)src.getLength());
}
public BitBuffer putF32(int n, Float32 val) {
return put32(n, (int)val.getBitsValue());
}
public BitBuffer putSF8_8(int n, SFixed8_8 val) {
return put32(n, (int)val.getBitsValue());
}
public BitBuffer putUF8_8(int n, UFixed8_8 val) {
return put32(n, (int)val.getBitsValue());
}
public BitBuffer putSF16_16(int n, SFixed16_16 val) {
return put32(n, (int)val.getBitsValue());
}
public BitBuffer putUF16_16(int n, UFixed16_16 val) {
return put32(n, (int)val.getBitsValue());
}
public BitBuffer putS16r(int n, SInt val) {
if (n != 16) {
throw new IllegalArgumentException(
"putS16r() cannot put not equal 16 bits."
+ "(" + n + "bits)");
}
return put32(n, Short.reverseBytes((short)val.getBitsValue()));
}
public BitBuffer putS32r(int n, SInt val) {
if (n != 32) {
throw new IllegalArgumentException(
"putS32r() cannot put not equal 32 bits."
+ "(" + n + "bits)");
}
return put32(n, Integer.reverseBytes((int)val.getBitsValue()));
}
public BitBuffer putU16r(int n, UInt val) {
if (n != 16) {
throw new IllegalArgumentException(
"putU16r() cannot put not equal 16 bits."
+ "(" + n + "bits)");
}
return put32(n, Short.reverseBytes((short)val.getBitsValue()));
}
public BitBuffer putU32r(int n, UInt val) {
if (n != 32) {
throw new IllegalArgumentException(
"putU32r() cannot put not equal 32 bits."
+ "(" + n + "bits)");
}
return put32(n, Integer.reverseBytes((int)val.getBitsValue()));
}
public BitBuffer putF32r(int n, Float32 val) {
return put32(n, Integer.reverseBytes((int)val.getBitsValue()));
}
public BitBuffer poke32(int n, int val) {
if (n < 0 || 32 < n) {
throw new IllegalArgumentException(
"poke32() cannot put more than 32 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is overflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
poke32Inner(n, val, getIndex(position, n));
return this;
}
public BitBuffer put32(int n, int val) {
if (n < 0 || 32 < n) {
throw new IllegalArgumentException(
"put32() cannot put more than 32 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is overflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
poke32Inner(n, val, getIndex(position, n));
position += n;
return this;
}
/**
* <p>
* val 1 32
*
* </p>
*
* @param n 32
* @param val
* @param index
*/
protected void poke32Inner(int n, int val, long index) {
buf.setPackedInt(index, n, val);
}
public BitBuffer putSInt(int n, SInt val) {
return put64(n, val.getBitsValue());
}
public BitBuffer putUInt(int n, UInt val) {
return put64(n, val.getBitsValue());
}
public BitBuffer putF64(int n, Float64 val) {
return put64(n, val.getBitsValue());
}
public BitBuffer putS64r(int n, SInt val) {
if (n != 64) {
throw new IllegalArgumentException(
"putS64r() cannot put not equal 64 bits."
+ "(" + n + "bits)");
}
return put64(n, Long.reverseBytes(val.getBitsValue()));
}
public BitBuffer putU64r(int n, UInt val) {
if (n != 64) {
throw new IllegalArgumentException(
"putU64r() cannot put not equal 64 bits."
+ "(" + n + "bits)");
}
return put64(n, Long.reverseBytes(val.getBitsValue()));
}
public BitBuffer putF64r(int n, Float64 val) {
return put64(n, Long.reverseBytes(val.getBitsValue()));
}
public BitBuffer poke64(int n, long val) {
if (n < 0 || 64 < n) {
throw new IllegalArgumentException(
"poke64() cannot put more than 64 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is overflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
poke64Inner(n, val, getIndex(position, n));
return this;
}
public BitBuffer put64(int n, long val) {
if (n < 0 || 64 < n) {
throw new IllegalArgumentException(
"put64() cannot put more than 64 bits."
+ "(" + n + "bits)");
}
if (n > remaining()) {
throw new IndexOutOfBoundsException(
"buffer is overflow, "
+ "required(" + n + ") is exceeded "
+ "remaining(" + remaining() + ").");
}
poke64Inner(n, val, getIndex(position, n));
position += n;
return this;
}
/**
* <p>
* val 1 64
*
* </p>
*
* @param n 64
* @param val
* @param index
*/
protected void poke64Inner(int n, long val, long index) {
buf.setPackedLong(index, n, val);
}
} |
package com.xtra.core.command.base;
import java.lang.reflect.Method;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.source.CommandBlockSource;
import org.spongepowered.api.command.source.ConsoleSource;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.TextMessageException;
import com.xtra.core.command.Command;
public abstract class CommandBase<T extends CommandSource> implements Command {
public abstract CommandResult executeCommand(T src, CommandContext args) throws Exception;
@Override
public final CommandResult execute(CommandSource source, CommandContext args) throws CommandException {
// Iterate through the methods to find executeCommand()
Class<?> type = null;
for (Method method : this.getClass().getMethods()) {
// Find our executeCommand method
if (method.getName().equals("executeCommand")) {
// Find one without type erasure :S
if (!method.getParameterTypes()[0].equals(CommandSource.class)) {
type = method.getParameterTypes()[0];
break;
}
}
}
// It is possible that CommandSource was specified, so if we didn't find
// one, then use CommandSource as a default.
if (type == null) {
type = CommandSource.class;
}
if (type.equals(Player.class) && !(source instanceof Player)) {
source.sendMessage(Text.of(TextColors.RED, "You must be a player to execute this command!"));
return CommandResult.empty();
} else if (type.equals(ConsoleSource.class) && !(source instanceof ConsoleSource)) {
source.sendMessage(Text.of(TextColors.RED, "You must be the console to execute this command!"));
return CommandResult.empty();
} else if (type.equals(CommandBlockSource.class) && !(source instanceof CommandBlockSource)) {
source.sendMessage(Text.of(TextColors.RED, "Only a command block may execute this command!"));
return CommandResult.empty();
}
@SuppressWarnings("unchecked")
T src = (T) source;
try {
return executeCommand(src, args);
} catch (TextMessageException e) {
src.sendMessage(e.getText());
} catch (Exception e2) {
e2.printStackTrace();
}
return CommandResult.empty();
}
} |
package com.zack6849.superlogger;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class EventsHandler implements Listener {
public static main plugin;
public static boolean debug;
public static boolean LOG_COMMANDS;
public static boolean LOG_JOIN;
public static boolean LOG_CHAT;
public static boolean LOG_JOIN_IP;
public static boolean COMMAND_WHITELIST;
public static boolean LOG_KICK;
public static boolean LOG_QUIT ;
public static boolean LOG_DEATH;
public static boolean LOG_DEATH_LOCATION;
public static boolean LOG_DISALLOWED_CONNECTIONS;
public EventsHandler(main main) {
plugin = main;
debug = false;
LOG_COMMANDS = plugin.getConfig().getBoolean("log-commands");
LOG_JOIN = plugin.getConfig().getBoolean("log-join");
LOG_CHAT = plugin.getConfig().getBoolean("log-chat");
LOG_JOIN_IP = plugin.getConfig().getBoolean("log-ip");
COMMAND_WHITELIST = plugin.getConfig().getBoolean("use-command-whitelist");
LOG_KICK = plugin.getConfig().getBoolean("log-kick");
LOG_QUIT = plugin.getConfig().getBoolean("log-quit");
LOG_DEATH = plugin.getConfig().getBoolean("log-death");
LOG_DEATH_LOCATION = plugin.getConfig().getBoolean("log-death-location");
LOG_DISALLOWED_CONNECTIONS = plugin.getConfig().getBoolean("log-disallowed-connections");
}
public static void reload(){
LOG_COMMANDS = plugin.getConfig().getBoolean("log-commands");
LOG_JOIN = plugin.getConfig().getBoolean("log-join");
LOG_CHAT = plugin.getConfig().getBoolean("log-chat");
LOG_JOIN_IP = plugin.getConfig().getBoolean("log-ip");
COMMAND_WHITELIST = plugin.getConfig().getBoolean("use-command-whitelist");
LOG_KICK = plugin.getConfig().getBoolean("log-kick");
LOG_QUIT = plugin.getConfig().getBoolean("log-quit");
LOG_DEATH = plugin.getConfig().getBoolean("log-death");
LOG_DEATH_LOCATION = plugin.getConfig().getBoolean("log-death-location");
LOG_DISALLOWED_CONNECTIONS = plugin.getConfig().getBoolean("log-disallowed-connections");
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent e) {
debug("command event");
if (LOG_COMMANDS && ((main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.command")) || !main.permissions)) {
debug("logging commands");
String command = e.getMessage().split(" ")[0].replaceFirst("/", "");
if(plugin.getServer().getPluginCommand(command) == null && !plugin.getConfig().getBoolean("check-commands")){
return;
}
if (COMMAND_WHITELIST && isWhitelisted(e.getMessage())) {
debug("command whitelisting enabled and command is whitelisted");
if (!main.oldlog) {
debug("old logging disabled");
plugin.log(main.commands, main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
}
debug("logging to log.txt");
plugin.logToFile(main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
return;
}
debug("whitelist wasn't enabled.");
if (!main.oldlog) {
debug("old logging wasnt enabled");
plugin.log(main.commands, main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
}
debug("logging to main file");
plugin.logToFile(main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
}
}
@EventHandler
public void onChat(AsyncPlayerChatEvent e) {
if (LOG_CHAT) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.chat")) {
if (!main.oldlog) {
plugin.log(main.chat, main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
}
plugin.logToFile(main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
return;
}
if (!main.oldlog) {
plugin.log(main.chat, main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
}
plugin.logToFile(main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
return;
}
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
if (LOG_JOIN) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.connection")) {
String log = main.getTime() + "[JOIN] " + e.getPlayer().getName() + " joined the server";
if (LOG_JOIN_IP) {
log += " from ip " + e.getPlayer().getAddress().toString().replaceFirst("/", "");
}
if (main.oldlog) {
//log to the main
plugin.logToFile(log);
}
plugin.logToAll(log);
return;
}
String log = main.getTime() + "[JOIN] " + e.getPlayer().getName() + " joined the server";
if (LOG_JOIN_IP) {
log += " from ip " + e.getPlayer().getAddress().toString().replaceFirst("/", "");
}
if (main.oldlog) {
plugin.logToFile(log);
}
plugin.log(main.connections, log);
}
}
@EventHandler
public void onKick(PlayerKickEvent e) {
if (LOG_KICK) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.connection")) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK]" + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
}
plugin.logToFile(main.getTime() + "[KICK] " + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
return;
}
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK]" + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
}
plugin.logToFile(main.getTime() + "[KICK] " + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
}
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
if (LOG_QUIT) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.connection")) {
plugin.logToFile(main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
}
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
return;
}
plugin.logToFile(main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
}
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
}
}
@EventHandler
public void onDeath(PlayerDeathEvent e) {
String info = main.getTime() + "[DEATH] " + e.getDeathMessage();
if (LOG_DEATH) {
if (main.permissions && !e.getEntity().hasPermission("superlogger.bypass.death")) {
if (LOG_DEATH_LOCATION) {
info += String.format(" at (%s,%s,%s) in world %s", e.getEntity().getLocation().getBlockX(), e.getEntity().getLocation().getBlockY(), e.getEntity().getLocation().getBlockZ(), e.getEntity().getWorld().getName());
}
if (main.oldlog) {
plugin.log(main.death, info);
}
plugin.logToFile(info);
return;
}
if (LOG_DEATH_LOCATION) {
info += String.format(" at (%s,%s,%s) in world %s", e.getEntity().getLocation().getBlockX(), e.getEntity().getLocation().getBlockY(), e.getEntity().getLocation().getBlockZ(), e.getEntity().getWorld().getName());
}
if (main.oldlog) {
plugin.log(main.death, info);
}
plugin.logToFile(info);
}
}
@EventHandler
public void onDisallow(PlayerLoginEvent e) {
if (LOG_DISALLOWED_CONNECTIONS) {
if (!e.getResult().equals(PlayerLoginEvent.Result.ALLOWED)) {
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_BANNED)) {
plugin.logToFile(main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
}
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_WHITELIST)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
plugin.logToFile(main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_FULL)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
plugin.logToFile(main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_OTHER)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
plugin.logToFile(main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
}
}
}
public boolean isFiltered(String s) {
boolean flag = false;
String msg = s.split(" ")[0].toLowerCase().replaceFirst("/", "");
for (String s1 : main.blocked) {
if (msg.equalsIgnoreCase(s1)) {
flag = true;
break;
}
}
return flag;
}
public boolean isWhitelisted(String s) {
boolean flag = false;
String msg = s.split(" ")[0].toLowerCase().replaceFirst("/", "");
for (String s1 : main.whitelist) {
if (msg.equalsIgnoreCase(s1)) {
flag = true;
break;
}
}
return flag;
}
public static void debug(String s) {
if (debug) {
plugin.log.log(Level.FINEST, s);
Bukkit.broadcastMessage("[SUPERLOGGER] DEBUG: " + s);
}
}
} |
package org.egordorichev.lasttry.item.block;
import com.badlogic.gdx.graphics.Texture;
import org.egordorichev.lasttry.Globals;
import org.egordorichev.lasttry.LastTry;
import org.egordorichev.lasttry.entity.drop.DroppedItem;
import org.egordorichev.lasttry.graphics.Graphics;
import org.egordorichev.lasttry.item.Item;
import org.egordorichev.lasttry.item.ItemHolder;
import org.egordorichev.lasttry.item.ItemID;
import org.egordorichev.lasttry.item.items.ToolPower;
import org.egordorichev.lasttry.util.Rectangle;
public class Block extends Item {
public static final int SIZE = 16;
public static final byte MAX_HP = 4;
/** Is the block solid */
protected boolean solid;
/** The tool type to use for the block */
protected ToolPower power;
/** The block spite-sheet */
protected Texture tiles;
/** Block width in tiles */
protected int width = 1;
/** Block height in tiles */
protected int height = 1;
public Block(short id, String name, boolean solid, ToolPower requiredPower, Texture texture, Texture tiles) {
super(id, name, texture);
this.power = requiredPower;
this.tiles = tiles;
this.solid = solid;
this.useSpeed = 30;
}
@Override
public boolean isAutoUse() {
return true;
}
/**
* Calculates a number based on the edges that have blocks of the same type.
*
* @param top Top edge matches current type.
* @param right Right edge matches current type.
* @param bottom Bottom edge matches current type.
* @param left Left edge matches current type.
* @return
*/
public static byte calculateBinary(boolean top, boolean right, boolean bottom, boolean left) {
byte result = 0;
if (top)
result += 1;
if (right)
result += 2;
if (bottom)
result += 4;
if (left)
result += 8;
return result;
}
/**
* Updates the block at given coordinates
*
* @param x X-position in the world.
* @param y Y-position in the world.
*/
public void updateBlockStyle(int x, int y) {
/* TODO: if block has animation, update it */
}
public void updateBlock(int x, int y) {
}
public void onNeighborChange(int x, int y, int nx, int ny) {
}
public void die(int x, int y) {
Globals.entityManager.spawn(new DroppedItem(new ItemHolder(this, 1)), Block.SIZE * x, Block.SIZE * y);
}
public boolean canBePlaced(int x, int y) {
int dx = (int) Globals.player.physics.getCenterX() / Block.SIZE - x;
int dy = (int) Globals.player.physics.getCenterY() / Block.SIZE - y;
double length = Math.abs(Math.sqrt(dx * dx + dy * dy));
if (length > Globals.player.getItemUseRadius()) {
return false;
}
Block t = Globals.world.blocks.get(x, y + 1);
Block b = Globals.world.blocks.get(x, y - 1);
Block l = Globals.world.blocks.get(x + 1, y);
Block r = Globals.world.blocks.get(x - 1, y);
if ((t == null || !t.isSolid()) && (b == null || !b.isSolid()) &&
(r == null || !r.isSolid()) && (l == null || !l.isSolid())) {
return false;
}
return true;
}
public void place(int x, int y) {
Globals.world.blocks.set(this.id, x, y);
}
/**
* Renders the block at the given coordinates.
*
* @param x X-position in the world.
* @param y Y-position in the world.
*/
public void renderBlock(int x, int y) {
boolean t = Globals.world.blocks.getID(x, y + 1) == this.id;
boolean r = Globals.world.blocks.getID(x + 1, y) == this.id;
boolean b = Globals.world.blocks.getID(x, y - 1) == this.id;
boolean l = Globals.world.blocks.getID(x - 1, y) == this.id;
// TODO: FIXME: replace with var
short variant = 1;
byte binary = Block.calculateBinary(t, r, b, l);
if (binary == 15) {
Graphics.batch.draw(this.tiles, x * Block.SIZE,
y * Block.SIZE, Block.SIZE, Block.SIZE,
Block.SIZE * (binary), 48 + variant * Block.SIZE, Block.SIZE,
Block.SIZE, false, false);
} else {
Graphics.batch.draw(this.tiles, x * Block.SIZE,
y * Block.SIZE, Block.SIZE, Block.SIZE,
Block.SIZE * (binary), variant * Block.SIZE, Block.SIZE,
Block.SIZE, false, false);
}
if (this.renderCracks()) {
byte hp = Globals.world.blocks.getHP(x, y);
if (hp < Block.MAX_HP) {
Graphics.batch.draw(Graphics.tileCracks[Block.MAX_HP - hp], x * Block.SIZE, y * Block.SIZE);
}
}
}
/** Returns true, if we allowed to draw cracks here */
protected boolean renderCracks() {
return true;
}
/**
* Attempts to place the block in the world at the player's cursor.
*/
@Override
public boolean use() {
int x = LastTry.getMouseXInWorld() / Block.SIZE;
int y = LastTry.getMouseYInWorld() / Block.SIZE;
if (this.canBePlaced(x, y) && Globals.world.blocks.getID(x, y) == ItemID.none) {
Rectangle rectangle = Globals.player.physics.getHitbox();
if (rectangle.intersects(new Rectangle(x * SIZE, y * SIZE, this.width * SIZE,
this.height * SIZE))) {
return false;
}
this.place(x, y);
return true;
}
return false;
}
/**
* Returns required power to break this block
* @return required power to break this block
*/
public ToolPower getRequiredPower() {
return this.power;
}
/**
* Returns the solidity of the block.
* @return true if the block is solid.
*/
public boolean isSolid() {
return this.solid;
}
@Override
public int getMaxInStack() {
return 999;
}
} |
package de.alpharogroup.swing.laf;
import java.awt.Component;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
* The enum class {@link LookAndFeels} provides constants with the fully qualified Names of look and
* feel classes.
*
* @deprecated use instead the same name enum class in the new package de.alpharogroup.swing.plaf
* <br>
* Note: will be removed in the next minor release
*/
public enum LookAndFeels
{
/** The METAL. */
METAL(LookAndFeels.LOOK_AND_FEEL_METAL),
/** The MOTIF. */
MOTIF(LookAndFeels.LOOK_AND_FEEL_MOTIF),
/** The SYSTEM. */
SYSTEM(UIManager.getSystemLookAndFeelClassName()),
/** The WINDOWS. */
WINDOWS(LookAndFeels.LOOK_AND_FEEL_WINDOWS);
private static final String LOOK_AND_FEEL_METAL = "javax.swing.plaf.metal.MetalLookAndFeel";
private static final String LOOK_AND_FEEL_MOTIF = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
private static final String LOOK_AND_FEEL_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
public static void setLookAndFeel(final String aLook, final Component component)
throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException
{
UIManager.setLookAndFeel(aLook);
SwingUtilities.updateComponentTreeUI(component);
}
/** The look and feel name. */
private final String lookAndFeelName;
/**
* Instantiates a new look and feels.
*
* @param name
* the name
*/
LookAndFeels(final String name)
{
lookAndFeelName = name;
}
/**
* Gets the look and feel name.
*
* @return the look and feel name
*/
public String getLookAndFeelName()
{
return lookAndFeelName;
}
} |
package aQute.bnd.main;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.jar.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import aQute.bnd.build.*;
import aQute.bnd.differ.*;
import aQute.bnd.differ.Baseline.BundleInfo;
import aQute.bnd.differ.Baseline.Info;
import aQute.bnd.header.*;
import aQute.bnd.osgi.*;
import aQute.bnd.osgi.Descriptors.PackageRef;
import aQute.bnd.service.diff.*;
import aQute.bnd.version.*;
import aQute.lib.collections.*;
import aQute.lib.getopt.*;
import aQute.lib.tag.*;
/**
* Implements commands to maintain the Package versions db.
*/
public class BaselineCommands {
static TransformerFactory transformerFactory = TransformerFactory.newInstance();
final bnd bnd;
final Baseline baseline;
final DiffPluginImpl differ = new DiffPluginImpl();
final Collection<String> SKIP_HEADERS = Arrays.asList(Constants.CREATED_BY, Constants.BND_LASTMODIFIED,
Constants.BUNDLE_MANIFESTVERSION, "Manifest-Version",
Constants.TOOL);
BaselineCommands(bnd bnd) throws IOException {
this.bnd = bnd;
this.baseline = new Baseline(bnd, differ);
}
@Description("Compare a newer bundle to a baselined bundle and provide versioning advice")
@Arguments(arg = {
"[newer jar]", "[older jar]"
})
interface baseLineOptions extends Options {
@Description("Output file with fixup info")
String fixup();
@Description("Show any differences")
boolean diff();
@Description("Be quiet, only report errors")
boolean quiet();
@Description("Show all, also unchanged")
boolean all();
}
/**
* Compare
*/
@Description("Compare a newer bundle to a baselined bundle and provide versioning advice. If no parameters are given, and there "
+ "is a local project, then we use the projects current build and the baseline jar in the release repo.")
public void _baseline(baseLineOptions opts) throws Exception {
List<String> args = opts._();
if (args.size() == 0) {
Project project = bnd.getProject();
if (project != null) {
for (Builder b : project.getSubBuilders()) {
ProjectBuilder pb = (ProjectBuilder) b;
Jar older = pb.getBaselineJar();
if ( older == null) {
bnd.error("No baseline JAR available. Did you set " + Constants.BASELINE);
return;
}
try {
pb.setProperty(Constants.BASELINE, ""); // do not do baselining in build
// make sure disabling is after getting the baseline jar
Jar newer = pb.build();
try {
differ.setIgnore(pb.getProperty(Constants.DIFFIGNORE));
baseline(opts, newer, older);
bnd.getInfo(b);
}
finally {
newer.close();
}
}
finally {
older.close();
}
}
bnd.getInfo(project);
return;
}
}
if (args.size() != 2) {
throw new IllegalArgumentException("Accepts only two argument (<jar>)");
}
File newer = bnd.getFile(args.remove(0));
if (!newer.isFile())
throw new IllegalArgumentException("Not a valid newer input file: " + newer);
File older = bnd.getFile(args.remove(0));
if (!older.isFile())
throw new IllegalArgumentException("Not a valid older input file: " + older);
Jar nj = new Jar(newer);
Jar oj = new Jar(older);
baseline(opts, nj, oj);
}
private void baseline(baseLineOptions opts, Jar newer, Jar older) throws FileNotFoundException,
UnsupportedEncodingException, IOException, Exception {
PrintStream out = null;
if (opts.fixup() != null) {
out = new PrintStream(bnd.getFile(opts.fixup()), "UTF-8");
}
Set<Info> infos = baseline.baseline(newer, older, null);
BundleInfo bundleInfo = baseline.getBundleInfo();
Info[] sorted = infos.toArray(new Info[infos.size()]);
Arrays.sort(sorted, new Comparator<Info>() {
public int compare(Info o1, Info o2) {
return o1.packageName.compareTo(o2.packageName);
}
});
if (!opts.quiet()) {
bnd.out.printf("===============================================================%n%s %s %s-%s", bundleInfo.mismatch ? '*' : ' ', bundleInfo.bsn, newer.getVersion(), older.getVersion());
if (bundleInfo.mismatch && bundleInfo.suggestedVersion != null)
bnd.out.printf(" suggests %s", bundleInfo.suggestedVersion);
bnd.out.printf("%n===============================================================%n");
boolean hadHeader = false;
for (Info info : sorted) {
if (info.packageDiff.getDelta() != Delta.UNCHANGED || opts.all()) {
if (!hadHeader) {
bnd.out.printf(" %-50s %-10s %-10s %-10s %-10s %-10s%n", "Package", "Delta", "New", "Old",
"Suggest", "If Prov.");
hadHeader = true;
}
bnd.out.printf("%s %-50s %-10s %-10s %-10s %-10s %-10s%n", info.mismatch ? '*' : ' ',
info.packageName,
info.packageDiff.getDelta(),
info.newerVersion,
info.olderVersion != null && info.olderVersion.equals(Version.LOWEST) ? "-": info.olderVersion,
info.suggestedVersion != null && info.suggestedVersion.compareTo(info.newerVersion) <= 0 ? "ok" : info.suggestedVersion,
info.suggestedIfProviders == null ? "-" : info.suggestedIfProviders);
}
}
}
if (out != null) {
// Create a fixup file
Manifest manifest = newer.getManifest();
if (manifest == null)
manifest = new Manifest();
for (Map.Entry<Object,Object> e : manifest.getMainAttributes().entrySet()) {
String key = e.getKey().toString();
if (!SKIP_HEADERS.contains(key)) {
if (!Constants.EXPORT_PACKAGE.equals(key)) {
out.printf("%-40s = ", key);
String value = (String) e.getValue();
out.append(value);
}
out.println();
}
}
doExportPackage(sorted, out);
out.close();
}
}
/**
* Print out the packages from spec jars and check in which ees they appear.
* Example
*
* <pre>
* package overview -ee j2se-1.6.0 -ee j2se-1.5.0 -ee j2ee-1.4.0 javax.activation-1.1.jar
* </pre>
*/
@Description("Print out the packages from spec jars and check in which ees they appear. Very specific. For example, schema ee.j2se-1.6.0 ee.j2se-1.5.0 ee.j2ee-1.4.0")
interface schemaOptions extends Options {
@Description("Output file")
String output(String deflt);
@Description("Specify an XSL file for pretty printing")
String xsl();
}
class PSpec implements Comparable<PSpec> {
String packageName;
Version version;
int id;
public Attrs attrs;
public Tree tree;
public Attrs uses = new Attrs();
public int compareTo(PSpec o) {
return version.compareTo(o.version);
}
}
/**
* Create a schema of a set of jars outling the packages and their versions.
* This will create a list of packages with multiple versions, link to their
* specifications, and the deltas between versions.
*
* <pre>
* bnd package schema <file.jar>*
* </pre>
*
* @param opts
* @throws Exception
*/
public void _schema(schemaOptions opts) throws Exception {
MultiMap<String,PSpec> map = new MultiMap<String,PSpec>();
Tag top = new Tag("jschema");
int n = 1000;
for (String spec : opts._()) {
File f = bnd.getFile(spec);
if (!f.isFile()) {
bnd.messages.NoSuchFile_(f);
} else {
// For each specification jar we found
bnd.trace("spec %s", f);
Jar jar = new Jar(f); // spec
Manifest m = jar.getManifest();
Attributes main = m.getMainAttributes();
Tag specTag = new Tag(top, "specification");
specTag.addAttribute("jar", spec);
specTag.addAttribute("name", main.getValue("Specification-Name"));
specTag.addAttribute("title", main.getValue("Specification-Title"));
specTag.addAttribute("jsr", main.getValue("Specification-JSR"));
specTag.addAttribute("url", main.getValue("Specification-URL"));
specTag.addAttribute("version", main.getValue("Specification-Version"));
specTag.addAttribute("vendor", main.getValue("Specification-Vendor"));
specTag.addAttribute("id", n);
specTag.addContent(main.getValue(Constants.BUNDLE_DESCRIPTION));
Parameters exports = OSGiHeader.parseHeader(m.getMainAttributes().getValue(Constants.EXPORT_PACKAGE));
// Create a map with versions. Ensure import ranges overwrite
// the
// exported versions
Parameters versions = new Parameters();
versions.putAll(exports);
versions.putAll(OSGiHeader.parseHeader(m.getMainAttributes().getValue(Constants.IMPORT_PACKAGE)));
Analyzer analyzer = new Analyzer();
analyzer.setJar(jar);
analyzer.analyze();
Tree tree = differ.tree(analyzer);
for (Entry<String,Attrs> entry : exports.entrySet()) {
// For each exported package in the specification JAR
Attrs attrs = entry.getValue();
String packageName = entry.getKey();
PackageRef packageRef = analyzer.getPackageRef(packageName);
String version = attrs.get(Constants.VERSION_ATTRIBUTE);
PSpec pspec = new PSpec();
pspec.packageName = packageName;
pspec.version = new Version(version);
pspec.id = n;
pspec.attrs = attrs;
pspec.tree = tree;
Collection<PackageRef> uses = analyzer.getUses().get(packageRef);
if (uses != null) {
for (PackageRef x : uses) {
if (x.isJava())
continue;
String imp = x.getFQN();
if (imp.equals(packageName))
continue;
String v = null;
if (versions.containsKey(imp))
v = versions.get(imp).get(Constants.VERSION_ATTRIBUTE);
pspec.uses.put(imp, v);
}
}
map.add(packageName, pspec);
}
jar.close();
n++;
}
}
// We now gather all the information about all packages in the map.
// Next phase is generating the XML. Sorting the packages is
// important because XSLT is brain dead.
SortedList<String> names = new SortedList<String>(map.keySet());
Tag packagesTag = new Tag(top, "packages");
Tag baselineTag = new Tag(top, "baseline");
for (String pname : names) {
// For each distinct package name
SortedList<PSpec> specs = new SortedList<PSpec>(map.get(pname));
PSpec older = null;
Parameters olderExport = null;
for (PSpec newer : specs) {
// For each package in the total set
Tag pack = new Tag(packagesTag, "package");
pack.addAttribute("name", newer.packageName);
pack.addAttribute("version", newer.version);
pack.addAttribute("spec", newer.id);
Parameters newerExport = new Parameters();
newerExport.put(pname, newer.attrs);
if (older != null) {
String compareId = newer.packageName + "-" + newer.id + "-" + older.id;
pack.addAttribute("delta", compareId);
bnd.trace(" newer=%s older=%s", newerExport, olderExport);
Set<Info> infos = baseline.baseline(newer.tree, newerExport, older.tree, olderExport,
new Instructions(pname));
for (Info info : infos) {
Tag tag = getTag(info);
tag.addAttribute("id", compareId);
tag.addAttribute("newerSpec", newer.id);
tag.addAttribute("olderSpec", older.id);
baselineTag.addContent(tag);
}
older.tree = null;
older.attrs = null;
older = newer;
}
// XRef, show the used packages for this package
for (Entry<String,String> uses : newer.uses.entrySet()) {
Tag reference = new Tag(pack, "import");
reference.addAttribute("name", uses.getKey());
reference.addAttribute("version", uses.getValue());
}
older = newer;
olderExport = newerExport;
}
}
String o = opts.output("schema.xml");
File of = bnd.getFile(o);
File pof = of.getParentFile();
if (!pof.exists() && !pof.mkdirs()) {
throw new IOException("Could not create directory " + pof);
}
OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(of), "UTF-8");
try {
PrintWriter pw = new PrintWriter(fw);
try {
pw.println("<?xml version='1.0'?>");
top.print(0, pw);
}
finally {
pw.close();
}
}
finally {
fw.close();
}
if (opts.xsl() != null) {
URL home = bnd.getBase().toURI().toURL();
URL xslt = new URL(home, opts.xsl());
String path = of.getAbsolutePath();
if (path.endsWith(".xml"))
path = path.substring(0, path.length() - 4);
path = path + ".html";
File html = new File(path);
bnd.trace("xslt %s %s %s %s", xslt, of, html, html.exists());
FileOutputStream out = new FileOutputStream(html);
try {
Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt.openStream()));
transformer.transform(new StreamSource(of), new StreamResult(out));
}
finally {
out.close();
}
}
}
private Tag getTag(Info info) {
Tag tag = new Tag("info");
tag.addAttribute("name", info.packageName);
tag.addAttribute("newerVersion", info.newerVersion);
tag.addAttribute("olderVersion", info.olderVersion);
tag.addAttribute("suggestedVersion", info.suggestedVersion);
tag.addAttribute("suggestedIfProviders", info.suggestedIfProviders);
tag.addAttribute("mismatch", info.mismatch);
tag.addAttribute("warning", info.warning);
StringBuilder sb = new StringBuilder();
if (info.packageDiff.getDelta() == Delta.UNCHANGED)
tag.addAttribute("equals", "true");
else {
traverseTag(sb, info.packageDiff, "");
String s = sb.toString().trim();
if (s.length() != 0) {
Tag d = new Tag(tag, "diff", s);
d.setCDATA();
}
}
if (info.providers != null)
for (String provider : info.providers) {
Tag p = new Tag(tag, "provider");
p.addAttribute("provider", provider);
}
return tag;
}
private void traverseTag(StringBuilder sb, Diff diff, String indent) {
sb.append(indent);
sb.append(diff.toString().trim().replace('\n', ' '));
sb.append("\n");
if (diff.getDelta() == Delta.ADDED || diff.getDelta() == Delta.REMOVED)
return;
for (Diff child : diff.getChildren()) {
if (child.getDelta() != Delta.UNCHANGED && child.getDelta() != Delta.IGNORED)
traverseTag(sb, child, indent + " ");
}
}
/**
* @param exports
* @param out
* @throws IOException
*/
public void doExportPackage(Info[] infos, PrintStream out) throws IOException {
out.printf("# Suggested versions\n%-40s = ", Constants.EXPORT_PACKAGE);
String del = "";
for (Info info : infos) {
out.append(del);
out.printf("\\\n ");
out.append(info.packageName);
info.attributes.put(Constants.VERSION_ATTRIBUTE, info.suggestedVersion.toString());
for (Map.Entry<String,String> clause : info.attributes.entrySet()) {
if (clause.getKey().equals(Constants.USES_DIRECTIVE))
continue;
out.append(";\\\n ");
out.append(clause.getKey());
out.append("=");
Processor.quote(out, clause.getValue());
}
if (info.providers != null && !info.providers.isEmpty()) {
out.append(";\\\n " + Constants.PROVIDER_TYPE_DIRECTIVE + "=\"");
String del2 = "";
for (String part : info.providers) {
out.append(del2);
out.append("\\\n ");
out.append(part);
del2 = ",";
}
out.append("\"");
}
del = ",";
}
}
} |
package de.bmoth.parser.ast;
import de.bmoth.antlr.BMoThParser;
import de.bmoth.antlr.BMoThParser.*;
import de.bmoth.antlr.BMoThParserBaseVisitor;
import de.bmoth.parser.ast.nodes.*;
import de.bmoth.parser.ast.nodes.ExpressionOperatorNode.ExpressionOperator;
import de.bmoth.parser.ast.nodes.QuantifiedExpressionNode.QuatifiedExpressionOperator;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.RuleNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import static de.bmoth.parser.ast.nodes.FormulaNode.FormulaType.EXPRESSION_FORMULA;
import static de.bmoth.parser.ast.nodes.FormulaNode.FormulaType.PREDICATE_FORMULA;
public class SemanticAstCreator {
private final LinkedHashMap<Token, Token> declarationReferences;
private final HashMap<Token, DeclarationNode> declarationMap = new HashMap<>();
private final Node semanticNode;
public Node getAstNode() {
return this.semanticNode;
}
public SemanticAstCreator(FormulaAnalyser formulaAnalyser) {
this.declarationReferences = formulaAnalyser.declarationReferences;
FormulaContext formulaContext = formulaAnalyser.formula;
FormulaNode.FormulaType type = formulaContext.expression() != null ? EXPRESSION_FORMULA : PREDICATE_FORMULA;
FormulaNode formulaNode = new FormulaNode(type);
formulaNode.setImplicitDeclarations(createDeclarationList(formulaAnalyser.implicitDeclarations));
FormulaVisitor formulaVisitor = new FormulaVisitor();
Node node;
if (type == EXPRESSION_FORMULA) {
node = formulaContext.expression().accept(formulaVisitor);
} else {
node = formulaContext.predicate().accept(formulaVisitor);
}
formulaNode.setFormula(node);
this.semanticNode = formulaNode;
}
public SemanticAstCreator(MachineAnalyser machineAnalyser) {
this.declarationReferences = machineAnalyser.declarationReferences;
MachineNode machineNode = new MachineNode(null, null);
machineNode.setConstants(createDeclarationList(machineAnalyser.constantsDeclarations));
machineNode.setVariables(createDeclarationList(machineAnalyser.variablesDeclarations));
FormulaVisitor formulaVisitor = new FormulaVisitor();
if (machineAnalyser.properties != null) {
PredicateNode pred = (PredicateNode) machineAnalyser.properties.predicate().accept(formulaVisitor);
machineNode.setProperties(pred);
}
if (machineAnalyser.invariant != null) {
PredicateNode pred = (PredicateNode) machineAnalyser.invariant.predicate().accept(formulaVisitor);
machineNode.setInvariant(pred);
}
if (machineAnalyser.initialisation != null) {
SubstitutionNode substitution = (SubstitutionNode) machineAnalyser.initialisation.substitution()
.accept(formulaVisitor);
machineNode.setInitialisation(substitution);
}
{
List<OperationNode> operationsList = new ArrayList<>();
for (Entry<String, OperationContext> entry : machineAnalyser.operationsDeclarations.entrySet()) {
OperationContext operationContext = entry.getValue();
SubstitutionNode substitution = (SubstitutionNode) operationContext.substitution()
.accept(formulaVisitor);
OperationNode operationNode = new OperationNode(entry.getValue(), entry.getKey(), substitution);
operationsList.add(operationNode);
}
machineNode.setOperations(operationsList);
}
this.semanticNode = machineNode;
}
private List<DeclarationNode> createDeclarationList(LinkedHashMap<String, Token> constantsDeclarations) {
List<DeclarationNode> declarationList = new ArrayList<>();
for (Entry<String, Token> entry : constantsDeclarations.entrySet()) {
Token token = entry.getValue();
DeclarationNode declNode = new DeclarationNode(token, entry.getKey());
declarationList.add(declNode);
declarationMap.put(token, declNode);
}
return declarationList;
}
class FormulaVisitor extends BMoThParserBaseVisitor<Node> {
@Override
public Node visitChildren(RuleNode node) {
throw new AssertionError(node.getClass() + " is not implemented yet in semantic Ast creator.");
}
@Override
public Node visitQuantifiedPredicate(BMoThParser.QuantifiedPredicateContext ctx) {
List<Token> identifiers = ctx.quantified_variables_list().identifier_list().identifiers;
List<DeclarationNode> declarationList = new ArrayList<>();
for (Token token : identifiers) {
DeclarationNode declNode = new DeclarationNode(token, token.getText());
declarationList.add(declNode);
declarationMap.put(token, declNode);
}
PredicateNode predNode = (PredicateNode) ctx.predicate().accept(this);
return new QuantifiedPredicateNode(ctx, declarationList, predNode);
}
@Override
public Node visitSequenceEnumerationExpression(BMoThParser.SequenceEnumerationExpressionContext ctx) {
if (ctx.expression_list() == null) {
return new ExpressionOperatorNode(ctx, new ArrayList<>(), ExpressionOperator.EMPTY_SEQUENCE);
} else {
return new ExpressionOperatorNode(ctx, createExprNodeList(ctx.expression_list().expression()),
ExpressionOperator.SEQ_ENUMERATION);
}
}
@Override
public Node visitFunctionCallExpression(BMoThParser.FunctionCallExpressionContext ctx) {
return new ExpressionOperatorNode(ctx, createExprNodeList(ctx.expression()),
ExpressionOperator.FUNCTION_CALL);
}
@Override
public Node visitParenthesesPredicate(BMoThParser.ParenthesesPredicateContext ctx) {
return ctx.predicate().accept(this);
}
@Override
public Node visitParenthesesExpression(BMoThParser.ParenthesesExpressionContext ctx) {
return ctx.expression().accept(this);
}
@Override
public Node visitCastPredicateExpression(BMoThParser.CastPredicateExpressionContext ctx) {
// internally, we do not distinguish bools and predicates
PredicateNode predicate = (PredicateNode) ctx.predicate().accept(this);
return new CastPredicateExpressionNode(predicate);
}
@Override
public Node visitQuantifiedExpression(BMoThParser.QuantifiedExpressionContext ctx) {
List<Token> identifiers = ctx.quantified_variables_list().identifier_list().identifiers;
List<DeclarationNode> declarationList = new ArrayList<>();
for (Token token : identifiers) {
DeclarationNode declNode = new DeclarationNode(token, token.getText());
declarationList.add(declNode);
declarationMap.put(token, declNode);
}
PredicateNode predNode = (PredicateNode) ctx.predicate().accept(this);
ExprNode exprNode = (ExprNode) ctx.expression().accept(this);
return new QuantifiedExpressionNode(ctx, declarationList, predNode, exprNode, ctx.operator);
}
@Override
public Node visitSetComprehensionExpression(BMoThParser.SetComprehensionExpressionContext ctx) {
List<Token> identifiers = ctx.identifier_list().identifiers;
List<DeclarationNode> declarationList = new ArrayList<>();
for (Token token : identifiers) {
DeclarationNode declNode = new DeclarationNode(token, token.getText());
declarationList.add(declNode);
declarationMap.put(token, declNode);
}
PredicateNode predNode = (PredicateNode) ctx.predicate().accept(this);
return new QuantifiedExpressionNode(ctx, declarationList, predNode, null,
QuatifiedExpressionOperator.SET_COMPREHENSION);
}
@Override
public Node visitNestedCoupleAsTupleExpression(BMoThParser.NestedCoupleAsTupleExpressionContext ctx) {
List<ExpressionContext> exprs = ctx.exprs;
ExprNode left = (ExprNode) exprs.get(0).accept(this);
for (int i = 1; i < exprs.size(); i++) {
List<ExprNode> list = new ArrayList<>();
list.add(left);
list.add((ExprNode) exprs.get(i).accept(this));
left = new ExpressionOperatorNode(ctx, list, ExpressionOperator.COUPLE);
}
return left;
}
@Override
public ExpressionOperatorNode visitExpressionOperator(BMoThParser.ExpressionOperatorContext ctx) {
String operator = ctx.operator.getText();
return new ExpressionOperatorNode(ctx, createExprNodeList(ctx.expression()), operator);
}
@Override
public ExprNode visitSetEnumerationExpression(BMoThParser.SetEnumerationExpressionContext ctx) {
return new ExpressionOperatorNode(ctx, createExprNodeList(ctx.expression_list().expression()),
ExpressionOperator.SET_ENUMERATION);
}
@Override
public ExprNode visitEmptySetExpression(BMoThParser.EmptySetExpressionContext ctx) {
return new ExpressionOperatorNode(ctx, new ArrayList<>(), ExpressionOperator.EMPTY_SET);
}
@Override
public ExprNode visitNumberExpression(BMoThParser.NumberExpressionContext ctx) {
int value = Integer.parseInt(ctx.Number().getText());
return new NumberNode(ctx, value);
}
@Override
public IdentifierExprNode visitIdentifierExpression(BMoThParser.IdentifierExpressionContext ctx) {
return createIdentifierExprNode(ctx.IDENTIFIER().getSymbol());
}
@Override
public IdentifierPredicateNode visitPredicateIdentifier(BMoThParser.PredicateIdentifierContext ctx) {
return createIdentifierPredicateNode(ctx.IDENTIFIER().getSymbol());
}
// Predicates
@Override
public PredicateNode visitPredicateOperator(BMoThParser.PredicateOperatorContext ctx) {
List<PredicateNode> list = new ArrayList<>();
List<PredicateContext> predicate = ctx.predicate();
for (PredicateContext predicateContext : predicate) {
PredicateNode predNode = (PredicateNode) predicateContext.accept(this);
list.add(predNode);
}
return new PredicateOperatorNode(ctx, list);
}
@Override
public PredicateNode visitPredicateOperatorWithExprArgs(BMoThParser.PredicateOperatorWithExprArgsContext ctx) {
return new PredicateOperatorWithExprArgsNode(ctx, createExprNodeList(ctx.expression()));
}
private List<ExprNode> createExprNodeList(List<ExpressionContext> list) {
ArrayList<ExprNode> exprNodes = new ArrayList<>();
for (ExpressionContext expressionContext : list) {
ExprNode exprNode = (ExprNode) expressionContext.accept(this);
exprNodes.add(exprNode);
}
return exprNodes;
}
// Substitutions
@Override
public Node visitBlockSubstitution(BMoThParser.BlockSubstitutionContext ctx) {
return ctx.substitution().accept(this);
}
@Override
public SubstitutionNode visitAssignSubstitution(BMoThParser.AssignSubstitutionContext ctx) {
List<IdentifierExprNode> idents = new ArrayList<>();
List<Token> identifierTokens = ctx.identifier_list().identifiers;
for (Token token : identifierTokens) {
IdentifierExprNode identExprNode = createIdentifierExprNode(token);
idents.add(identExprNode);
}
List<ExprNode> expressions = new ArrayList<>();
List<ExpressionContext> exprsContexts = ctx.expression_list().exprs;
for (ExpressionContext expressionContext : exprsContexts) {
ExprNode exprNode = (ExprNode) expressionContext.accept(this);
expressions.add(exprNode);
}
List<SubstitutionNode> sublist = new ArrayList<>();
for (int i = 0; i < idents.size(); i++) {
SingleAssignSubstitutionNode singleAssignSubstitution = new SingleAssignSubstitutionNode(idents.get(i),
expressions.get(i));
sublist.add(singleAssignSubstitution);
}
if (sublist.size() == 1) {
return sublist.get(0);
} else {
return new ParallelSubstitutionNode(sublist);
}
}
@Override
public SubstitutionNode visitAnySubstitution(BMoThParser.AnySubstitutionContext ctx) {
List<Token> identifiers = ctx.identifier_list().identifiers;
List<DeclarationNode> declarationList = new ArrayList<>();
for (Token token : identifiers) {
DeclarationNode declNode = new DeclarationNode(token, token.getText());
declarationList.add(declNode);
declarationMap.put(token, declNode);
}
PredicateNode predNode = (PredicateNode) ctx.predicate().accept(this);
SubstitutionNode sub = (SubstitutionNode) ctx.substitution().accept(this);
return new AnySubstitutionNode(declarationList, predNode, sub);
}
@Override
public SelectSubstitutionNode visitSelectSubstitution(BMoThParser.SelectSubstitutionContext ctx) {
PredicateNode predicate = (PredicateNode) ctx.predicate().accept(this);
SubstitutionNode sub = (SubstitutionNode) ctx.substitution().accept(this);
return new SelectSubstitutionNode(predicate, sub);
}
@Override
public SelectSubstitutionNode visitPreSubstitution(BMoThParser.PreSubstitutionContext ctx) {
PredicateNode predicate = (PredicateNode) ctx.predicate().accept(this);
SubstitutionNode sub = (SubstitutionNode) ctx.substitution().accept(this);
return new SelectSubstitutionNode(predicate, sub);
}
private IdentifierExprNode createIdentifierExprNode(Token token) {
Token declToken = SemanticAstCreator.this.declarationReferences.get(token);
DeclarationNode declarationNode = declarationMap.get(declToken);
if (declarationNode == null) {
throw new AssertionError(token.getText() + " Line " + token.getLine());
}
return new IdentifierExprNode(token, declarationNode);
}
private IdentifierPredicateNode createIdentifierPredicateNode(Token token) {
Token declToken = SemanticAstCreator.this.declarationReferences.get(token);
DeclarationNode declarationNode = declarationMap.get(declToken);
if (declarationNode == null) {
throw new AssertionError(token.getText() + " Line " + token.getLine());
}
return new IdentifierPredicateNode(token, declarationNode);
}
@Override
public SubstitutionNode visitParallelSubstitution(BMoThParser.ParallelSubstitutionContext ctx) {
List<SubstitutionNode> result = new ArrayList<>();
List<SubstitutionContext> substitution = ctx.substitution();
for (SubstitutionContext substitutionContext : substitution) {
SubstitutionNode sub = (SubstitutionNode) substitutionContext.accept(this);
result.add(sub);
}
return new ParallelSubstitutionNode(result);
}
}
} |
package de.braintags.vertx.util;
public class DebugDetection {
private static final boolean develop = detectDevelopMode();
private static final boolean profiling = detectProfilingMode();
private static final boolean test = detectTestMode();
private static final boolean fileCachingDisabled = detectFileCachingDisabled();
public static boolean isLaunchedByEclipse() {
return develop;
}
public static boolean isTest() {
return test;
}
public static boolean isProfiling() {
return profiling;
}
public static boolean isFileCachingDisabled() {
return fileCachingDisabled;
}
private static boolean detectTestMode() {
String test = System.getProperty("test");
if (test != null)
return "true".equals(test);
else
return detectDevelopMode();
}
private static boolean detectFileCachingDisabled() {
return "true".equals(System.getProperties().getProperty("vertx.disableFileCaching"));
}
private static boolean detectProfilingMode() {
return "true".equals(System.getProperties().getProperty("profiling"));
}
private static boolean detectDevelopMode() {
String develop = System.getProperty("develop");
if (develop != null)
return "true".equals(develop);
else
return java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString()
.indexOf("-agentlib:jdwp") >= 0;
}
} |
package org.dalesbred;
import org.dalesbred.annotation.Reflective;
import org.dalesbred.dialect.HsqldbDialect;
import org.dalesbred.result.EmptyResultException;
import org.dalesbred.result.NonUniqueResultException;
import org.dalesbred.result.ResultSetProcessor;
import org.dalesbred.result.RowMapper;
import org.junit.Rule;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.*;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.*;
public class DatabaseTest {
private final Database db = TestDatabaseProvider.createInMemoryHSQLDatabase();
@Rule
public final TransactionalTestsRule rule = new TransactionalTestsRule(db);
@Test
public void meaningfulToString() {
db.setAllowImplicitTransactions(true);
assertEquals("Database [dialect=" + new HsqldbDialect().toString() + ", allowImplicitTransactions=true]", db.toString());
}
@Test
public void primitivesQueries() {
assertThat(db.findUniqueInt("values (42)"), is(42));
assertThat(db.findUnique(Integer.class, "values (42)"), is(42));
assertThat(db.findUnique(Long.class, "values (cast(42 as bigint))"), is(42L));
assertThat(db.findUnique(Float.class, "values (42.0)"), is(42.0f));
assertThat(db.findUnique(Double.class, "values (42.0)"), is(42.0));
assertThat(db.findUnique(String.class, "values ('foo')"), is("foo"));
assertThat(db.findUnique(Boolean.class, "values (true)"), is(true));
assertThat(db.findUnique(Boolean.class, "values (cast(null as boolean))"), is(nullValue()));
}
@Test
public void bigNumbers() {
assertThat(db.findUnique(BigDecimal.class, "values (4242242848428484848484848)"), is(new BigDecimal("4242242848428484848484848")));
}
@Test
public void autoDetectingTypes() {
assertThat(db.findUnique(Object.class, "values (42)"), is(42));
assertThat(db.findUnique(Object.class, "values ('foo')"), is("foo"));
assertThat(db.findUnique(Object.class, "values (true)"), is(true));
}
@Test
public void constructorRowMapping() {
List<Department> departments = db.findAll(Department.class, "select * from (values (1, 'foo'), (2, 'bar')) d");
assertThat(departments.size(), is(2));
assertThat(departments.get(0).id, is(1));
assertThat(departments.get(0).name, is("foo"));
assertThat(departments.get(1).id, is(2));
assertThat(departments.get(1).name, is("bar"));
}
@Test
public void map() {
Map<Integer, String> map = db.findMap(Integer.class, String.class, "select * from (values (1, 'foo'), (2, 'bar')) d");
assertThat(map.size(), is(2));
assertThat(map.get(1), is("foo"));
assertThat(map.get(2), is("bar"));
}
@Test
public void mapWithNullConversion() {
Map<String, String> map = db.findMap(String.class, String.class, "values ('foo', cast (null as clob)), (cast (null as clob), 'bar')");
assertThat(map.size(), is(2));
assertThat(map.get("foo"), is(nullValue()));
assertThat(map.get(null), is("bar"));
}
@Test
public void mapWithMultipleArguments() {
Map<Integer, Department> map = db.findMap(Integer.class, Department.class,
"select * from (values (1, 10, 'foo'), (2, 20, 'bar')) d");
assertThat(map.size(), is(2));
assertThat(map.get(1).id, is(10));
assertThat(map.get(1).name, is("foo"));
assertThat(map.get(2).id, is(20));
assertThat(map.get(2).name, is("bar"));
}
@Test
public void findUnique_singleResult() {
assertThat(db.findUnique(Integer.class, "values (42)"), is(42));
}
@Test(expected = NonUniqueResultException.class)
public void findUnique_nonUniqueResult() {
db.findUnique(Integer.class, "VALUES (1), (2)");
fail("Expected NonUniqueResultException");
}
@Test(expected = EmptyResultException.class)
public void findUnique_emptyResult() {
db.findUnique(Integer.class, "select * from (values (1)) n where false");
}
@Test
public void findUniqueOrNull_singleResult() {
assertThat(db.findUniqueOrNull(Integer.class, "values (42)"), is(42));
}
@Test(expected = NonUniqueResultException.class)
public void findUniqueOrNull_nonUniqueResult() {
db.findUniqueOrNull(Integer.class, "values (1), (2)");
}
@Test
public void findUniqueOrNull_emptyResult() {
assertThat(db.findUniqueOrNull(Integer.class, "select * from (values (1)) n where false"), is(nullValue()));
}
@Test
public void findUniqueOrNull_nullResult() {
assertThat(db.findUniqueOrNull(Integer.class, "values (cast (null as int))"), is(nullValue()));
}
@Test
public void findOptional_emptyResult() {
assertThat(db.findOptional(Integer.class, "select * from (values (1)) n where false"), is(Optional.empty()));
}
@Test
public void findOptionalInt_singleResult() {
assertThat(db.findOptionalInt("values (42)"), is(OptionalInt.of(42)));
}
@Test
public void findOptionalInt_emptyResult() {
assertThat(db.findOptionalInt("values (cast (null as int))"), is(OptionalInt.empty()));
}
@Test
public void findOptionalLong_singleResult() {
assertThat(db.findOptionalLong("values (42)"), is(OptionalLong.of(42)));
}
@Test
public void findOptionalLong_emptyResult() {
assertThat(db.findOptionalLong("values (cast (null as int))"), is(OptionalLong.empty()));
}
@Test
public void findOptionalDouble_singleResult() {
assertThat(db.findOptionalDouble("values (42.3)"), is(OptionalDouble.of(42.3)));
}
@Test
public void findOptionalDouble_emptyResult() {
assertThat(db.findOptionalDouble("values (cast (null as float))"), is(OptionalDouble.empty()));
}
@Test(expected = NonUniqueResultException.class)
public void findOptional_nonUniqueResult() {
db.findOptional(Integer.class, "values (1), (2)");
}
@Test
public void findOptional_nullResult() {
assertThat(db.findOptional(Integer.class, "values (cast (null as int))"), is(Optional.empty()));
}
@Test
public void rowMapper() {
RowMapper<Integer> squaringRowMapper = resultSet -> {
int value = resultSet.getInt(1);
return value*value;
};
assertThat(db.findAll(squaringRowMapper, "values (1), (2), (3)"), is(asList(1, 4, 9)));
assertThat(db.findUnique(squaringRowMapper, "values (7)"), is(49));
assertThat(db.findUniqueOrNull(squaringRowMapper, "select * from (values (1)) n where false"), is(nullValue()));
assertThat(db.findOptional(squaringRowMapper, "values (7)"), is(Optional.of(49)));
assertThat(db.findOptional(squaringRowMapper, "select * from (values (1)) n where false"), is(Optional.empty()));
}
@Test
public void customResultProcessor() {
ResultSetProcessor<Integer> rowCounter = resultSet -> {
int rows = 0;
while (resultSet.next()) rows++;
return rows;
};
assertThat(db.executeQuery(rowCounter, "values (1), (2), (3)"), is(3));
}
@Test(expected = DatabaseException.class)
public void creatingDatabaseWithJndiDataSourceThrowsExceptionWhenContextIsNotConfigured() {
Database.forJndiDataSource("foo");
}
@Test
public void implicitTransactions() {
db.setAllowImplicitTransactions(false);
assertFalse(db.isAllowImplicitTransactions());
db.setAllowImplicitTransactions(true);
assertTrue(db.isAllowImplicitTransactions());
}
public static class Department {
final int id;
final String name;
@Reflective
public Department(int id, String name) {
this.id = id;
this.name = name;
}
}
} |
package de.fraunhofer.iosb.ilt.sta.query;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.fraunhofer.iosb.ilt.sta.ServiceFailureException;
import de.fraunhofer.iosb.ilt.sta.jackson.ObjectMapperFactory;
import de.fraunhofer.iosb.ilt.sta.model.Entity;
import de.fraunhofer.iosb.ilt.sta.model.EntityType;
import de.fraunhofer.iosb.ilt.sta.model.ext.EntityList;
import de.fraunhofer.iosb.ilt.sta.service.SensorThingsService;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A query for reading operations.
*
* @author Nils Sommer, Hylke van der Schaaf
* @param <T> The type of entity this query returns.
*/
public class Query<T extends Entity<T>> implements QueryRequest<T>, QueryParameter<T> {
/**
* The logger for this class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(Query.class);
private final SensorThingsService service;
private final EntityType plural;
private final Class<T> entityClass;
private final Entity<?> parent;
private final List<NameValuePair> params = new ArrayList<>();
public Query(SensorThingsService service, Class<T> entityClass) {
this(service, entityClass, null);
}
public Query(SensorThingsService service, Class<T> entityClass, Entity<?> parent) {
this.service = service;
this.plural = EntityType.listForClass(entityClass);
this.entityClass = entityClass;
this.parent = parent;
}
public EntityType getEntityType() {
return plural;
}
public Class<T> getEntityClass() {
return entityClass;
}
public SensorThingsService getService() {
return service;
}
@Override
public Query<T> filter(String options) {
for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
NameValuePair param = it.next();
if (param.getName().equals("$filter")) {
it.remove();
break;
}
}
if (options.isEmpty()) {
return this;
}
this.params.add(new BasicNameValuePair("$filter", options));
return this;
}
@Override
public Query<T> top(int n) {
this.params.add(new BasicNameValuePair("$top", Integer.toString(n)));
return this;
}
@Override
public Query<T> orderBy(String clause) {
this.params.add(new BasicNameValuePair("$orderby", clause));
return this;
}
@Override
public Query<T> skip(int n) {
this.params.add(new BasicNameValuePair("$skip", Integer.toString(n)));
return this;
}
@Override
public Query<T> count() {
params.add(new BasicNameValuePair("$count", "true"));
return this;
}
public Query<T> expand(Expansion expansion) {
params.add(new BasicNameValuePair("$expand", expansion.toString()));
return this;
}
public Query<T> expand(String expansion) {
params.add(new BasicNameValuePair("$expand", expansion));
return this;
}
public Query<T> select(String... fields) {
StringBuilder selectValue = new StringBuilder();
for (String field : fields) {
selectValue.append(field).append(",");
}
params.add(new BasicNameValuePair("$select", selectValue.substring(0, selectValue.length() - 1)));
return this;
}
@Override
public T first() throws ServiceFailureException {
this.top(1);
List<T> asList = this.list().toList();
if (asList.isEmpty()) {
return null;
}
return asList.get(0);
}
@SuppressWarnings("unchecked")
@Override
public EntityList<T> list() throws ServiceFailureException {
EntityList<T> list = new EntityList<>(plural);
URIBuilder uriBuilder = new URIBuilder(service.getFullPath(parent, plural));
uriBuilder.addParameters(params);
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(uriBuilder.build());
LOGGER.debug("Fetching: {}", httpGet.getURI());
httpGet.addHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());
response = service.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code < 200 || code >= 300) {
throw new IllegalArgumentException(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
}
String json = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
final ObjectMapper mapper = ObjectMapperFactory.get();
list = mapper.readValue(json, plural.getTypeReference());
} catch (URISyntaxException | IOException ex) {
LOGGER.error("Failed to fetch list.", ex);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException ex) {
}
}
list.setService(service, entityClass);
return list;
}
} |
package ee.tuleva.onboarding.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "https://pension.tuleva.ee");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
List<String> allowedHeaders = Arrays.asList(
"x-requested-with",
HttpHeaders.CONTENT_TYPE,
HttpHeaders.AUTHORIZATION,
HttpHeaders.USER_AGENT,
HttpHeaders.ORIGIN,
HttpHeaders.ACCEPT
);
response.setHeader("Access-Control-Allow-Headers", String.join(", ", allowedHeaders));
HttpServletRequest request = ((HttpServletRequest) req);
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
} |
package bt.peer;
import bt.net.Peer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
/**
* @since 1.1
*/
public abstract class ScheduledPeerSource implements PeerSource {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledPeerSource.class);
private final ExecutorService executor;
private final ReentrantLock lock;
private final AtomicReference<Future<?>> futureOptional;
private final Queue<Peer> peers;
public ScheduledPeerSource(ExecutorService executor) {
this.executor = executor;
this.lock = new ReentrantLock();
this.futureOptional = new AtomicReference<>();
this.peers = new LinkedBlockingQueue<>();
}
@Override
public Collection<Peer> getPeers() {
return peers;
}
@Override
public boolean update() {
if (peers.isEmpty()) {
schedulePeerCollection();
}
return !peers.isEmpty();
}
private void schedulePeerCollection() {
if (lock.tryLock()) {
try {
if (futureOptional.get() != null) {
Future<?> future = futureOptional.get();
if (future.isDone()) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.warn("Peer collection finished with exception in peer source: " + toString(), e);
}
futureOptional.set(null);
}
}
if (futureOptional.get() == null) {
futureOptional.set(executor.submit(() -> peers.addAll(collectPeers())));
}
} finally {
lock.unlock();
}
}
}
/**
* @since 1.1
*/
protected abstract Collection<Peer> collectPeers();
} |
package gdsc.analytics;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Populates the client with information from the system
*/
public class ClientParametersManager
{
/**
* Populates the client parameters with information from the system
*
* @param data
* The data
*/
public static final void populate(ClientParameters data)
{
String region = System.getProperty("user.region");
if (region == null)
{
region = System.getProperty("user.country");
}
data.setUserLanguage((System.getProperty("user.language") + "-" + region).toLowerCase());
String hostName = "localhost";
try
{
final InetAddress iAddress = InetAddress.getLocalHost();
// This performs a lookup of the name service as well
// e.g. host.domain.com
hostName = iAddress.getCanonicalHostName();
// This only retrieves the bare hostname
// e.g. host
// hostName = iAddress.getHostName();
// This retrieves the IP address as a string
// e.g. 192.168.0.1
//hostName = iAddress.getHostAddress();
}
catch (UnknownHostException e)
{
//ignore this
}
data.setHostName(hostName);
final String os_name = System.getProperty("os.name");
final Dimension d = getScreenSize(os_name);
data.setScreenResolution(d.width + "x" + d.height);
// The browser and operating system are taken from the User-Agent property.
//data.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // To simulate Chrome
// The Java URLConnection User-Agent property will default to 'Java/1.6.0.19' where the
// last part is the JRE version. Add the operating system to this, e.g. Java/1.6.0.19 (Windows NT 6.1)
StringBuilder sb = new StringBuilder();
sb.append("Java/").append(System.getProperty("java.version"));
sb.append(" (").append(getPlatform(os_name)).append(")");
data.setUserAgent(sb.toString());
// Note: Adding the OS does not currently work within Google Analytics.
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
// "The User Agent of the browser. Note that Google has libraries to identify real user agents.
// Hand crafting your own agent could break at any time."
// A better option is to pass in custom dimension so this data can be used in reports.
}
/**
* Get the platform for the User-Agent string
*
* @return The platform
*/
/**
* @param os_name
* @return
*/
private static String getPlatform(String os_name)
{
// Note that on Windows the os.version property does not directly translate into the user agent platform token:
// https://en.wikipedia.org/wiki/Windows_NT#Releases
final String lc_os_name = os_name.toLowerCase();
if (lc_os_name.contains("windows"))
{
//@formatter:off
if (lc_os_name.contains("10")) return "Windows NT 10.0";
if (lc_os_name.contains("server 2016")) return "Windows NT 10.0";
if (lc_os_name.contains("8.1")) return "Windows NT 6.3";
if (lc_os_name.contains("server 2012 r2")) return "Windows NT 6.3";
if (lc_os_name.contains("8")) return "Windows NT 6.2";
if (lc_os_name.contains("server 2012")) return "Windows NT 6.2";
if (lc_os_name.contains("7")) return "Windows NT 6.1";
if (lc_os_name.contains("server 2011")) return "Windows NT 6.1";
if (lc_os_name.contains("server 2008 r2")) return "Windows NT 6.1";
if (lc_os_name.contains("vista")) return "Windows NT 6.0";
if (lc_os_name.contains("server 2008")) return "Windows NT 6.0";
if (lc_os_name.contains("server 2003")) return "Windows NT 5.2";
if (lc_os_name.contains("xp x64")) return "Windows NT 5.2";
if (lc_os_name.contains("xp")) return "Windows NT 5.1";
if (lc_os_name.contains("2000, service")) return "Windows NT 5.01";
if (lc_os_name.contains("2000")) return "Windows NT 5.0";
if (lc_os_name.contains("nt 4")) return "Windows NT 4.0";
if (lc_os_name.contains("mw")) return "Windows 98; Win 9x 4.90";
if (lc_os_name.contains("98")) return "Windows 98";
if (lc_os_name.contains("95")) return "Windows 95";
if (lc_os_name.contains("ce")) return "Windows CE";
return "Windows NT 6.1"; // Default to Windows 7
//@formatter:on
}
// Mac - Note sure what to put here.
// E.g. Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A
if (lc_os_name.startsWith("mac"))
// Just pick a recent valid platform from a valid Mac User-Agent string
return "Macintosh; Intel Mac OS X 10_9_3";
// Linux variants will just return 'Linux'.
// This is apparently detected by Google Analytics so we leave this as is.
// Other - Just leave it
final String os_version = System.getProperty("os.version");
return os_name + " " + os_version;
}
public static Dimension getScreenSize(String os_name)
{
if (isWindows(os_name)) // GraphicsEnvironment.getConfigurations is *very* slow on Windows
return Toolkit.getDefaultToolkit().getScreenSize();
if (GraphicsEnvironment.isHeadless())
return new Dimension(0, 0);
// Can't use Toolkit.getScreenSize() on Linux because it returns
// size of all displays rather than just the primary display.
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
GraphicsConfiguration[] gc = gd[0].getConfigurations();
Rectangle bounds = gc[0].getBounds();
if ((bounds.x == 0 && bounds.y == 0) || (isLinux(os_name) && gc.length > 1))
return new Dimension(bounds.width, bounds.height);
else
return Toolkit.getDefaultToolkit().getScreenSize();
}
private static boolean isWindows(String os_name)
{
return os_name.startsWith("Windows");
}
private static boolean isLinux(String os_name)
{
return os_name.startsWith("Linux");
}
} |
package hudson.plugins.tasks.util;
import hudson.model.Build;
import hudson.model.ModelObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang.StringUtils;
import de.java2html.converter.JavaSource2HTMLConverter;
import de.java2html.javasource.JavaSource;
import de.java2html.javasource.JavaSourceParser;
import de.java2html.options.JavaSourceConversionOptions;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
/**
* Renders a source file containing an annotation for the whole file or a
* specific line number.
*/
public class SourceDetail implements ModelObject, Serializable {
/** Unique identifier of this class. */
private static final long serialVersionUID = -3209724023376797741L;
/** Offset of the source code generator. After this line the actual source file lines start. */
protected static final int SOURCE_GENERATOR_OFFSET = 12;
/** The current build as owner of this object. */
@SuppressWarnings("Se")
private final Build<?, ?> owner;
/** Stripped file name of this annotation without the path prefix. */
private final String fileName;
/** The annotation to be shown. */
private final FileAnnotation annotation;
/** The line containing identified by the annotation or an empty string. */
private String line = StringUtils.EMPTY;
/** The source code after the annotation or an empty string. */
private String suffix = StringUtils.EMPTY;
/** The source code before the warning or the whole source code if there is no specific line given. */
private String prefix = StringUtils.EMPTY;
/**
* Creates a new instance of this source code object.
*
* @param owner
* the current build as owner of this object
* @param annotation
* the warning to display in the source file
*/
public SourceDetail(final Build<?, ?> owner, final FileAnnotation annotation) {
this.owner = owner;
this.annotation = annotation;
fileName = StringUtils.substringAfterLast(annotation.getFileName(), "/");
initializeContent();
}
/**
* Initializes the content of the source file: reads the file, colors it, and
* splits it into three parts.
*/
private void initializeContent() {
InputStream file = null;
try {
String linkName = annotation.getFileName();
if (linkName.startsWith("/") || linkName.contains(":") || owner == null) {
file = new FileInputStream(new File(linkName));
}
else {
file = owner.getProject().getWorkspace().child(linkName).read();
}
splitSourceFile(highlightSource(file));
}
catch (IOException exception) {
line = "Can't read file: " + exception.getLocalizedMessage();
}
finally {
IOUtils.closeQuietly(file);
}
}
/** {@inheritDoc} */
public String getDisplayName() {
return fileName;
}
/**
* Returns the tool tip to be shown if hovering over the highlighted line.
*
* @return the tool tip to be shown
*/
public String getToolTip() {
return annotation.getToolTip();
}
/**
* Returns the tool tip to be shown if hovering over the highlighted line.
*
* @return the tool tip to be shown
*/
public String getMessage() {
return annotation.getMessage();
}
/**
* Highlights the specified source and returns the result as an HTML string.
*
* @param file
* the source file to highlight
* @return the source as an HTML string
* @throws IOException
*/
public final String highlightSource(final InputStream file) throws IOException {
JavaSource source = new JavaSourceParser().parse(file);
JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter();
StringWriter writer = new StringWriter();
JavaSourceConversionOptions options = JavaSourceConversionOptions.getDefault();
options.setShowLineNumbers(true);
options.setAddLineAnchors(true);
converter.convert(source, options, writer);
return writer.toString();
}
/**
* Splits the source code into three blocks: the line to highlight and the
* source code before and after this line.
*
* @param sourceFile
* the source code of the whole file as rendered HTML string
*/
public final void splitSourceFile(final String sourceFile) {
LineIterator lineIterator = IOUtils.lineIterator(new StringReader(sourceFile));
if (annotation.isLineAnnotation()) {
StringBuilder prefixBuilder = new StringBuilder(sourceFile.length());
StringBuilder suffixBuilder = new StringBuilder(sourceFile.length());
suffixBuilder.append("</td></tr>\n");
suffixBuilder.append("<tr><td>\n");
suffixBuilder.append("<code>\n");
int warningLine = annotation.getLineNumber();
int lineNumber = 1;
while (lineIterator.hasNext()) {
String content = lineIterator.nextLine();
if (lineNumber - SOURCE_GENERATOR_OFFSET == warningLine) {
line = content;
}
else if (lineNumber - SOURCE_GENERATOR_OFFSET < warningLine) {
prefixBuilder.append(content + "\n");
}
else {
suffixBuilder.append(content + "\n");
}
lineNumber++;
}
prefixBuilder.append("</code>\n");
prefixBuilder.append("</td></tr>\n");
prefixBuilder.append("<tr><td bgcolor=\"#FFFFC0\">\n");
prefix = prefixBuilder.toString();
suffix = suffixBuilder.toString();
}
else {
prefix = sourceFile;
suffix = StringUtils.EMPTY;
line = StringUtils.EMPTY;
}
}
/**
* Gets the file name of this source file.
*
* @return the file name
*/
public String getFileName() {
return fileName;
}
/**
* Returns the build as owner of this object.
*
* @return the build
*/
public Build<?, ?> getOwner() {
return owner;
}
/**
* Returns the line that should be highlighted.
*
* @return the line to highlight
*/
public String getLine() {
return line;
}
/**
* Returns whether this source code object has an highlighted line.
*
* @return <code>true</code> if this source code object has an highlighted
* line
*/
public boolean hasHighlightedLine() {
return StringUtils.isNotEmpty(line);
}
/**
* Returns the suffix of the source file. The suffix contains the part of
* the source after the line to highlight.
*
* @return the suffix of the source file
*/
public String getSuffix() {
return suffix;
}
/**
* Returns the prefix of the source file. The prefix contains the part of
* the source before the line to highlight.
*
* @return the prefix of the source file
*/
public String getPrefix() {
return prefix;
}
} |
package info.debatty.java.datasets.enron;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.apache.commons.mail.util.MimeMessageParser;
/**
*
* @author Thibault Debatty
*/
public class Email {
private String raw;
private final MimeMessageParser parser;
private final String mailbox;
private final String user;
Email(final String raw, final String mailbox) throws MessagingException {
this.raw = raw;
String[] strings = mailbox.split(File.separator, 2);
this.user = strings[0];
this.mailbox = strings[1];
Session s = Session.getDefaultInstance(new Properties());
InputStream is = new ByteArrayInputStream(raw.getBytes());
MimeMessage message = new MimeMessage(s, is);
parser = new MimeMessageParser(message);
}
public String getUser() {
return user;
}
public String getFrom() throws Exception {
return parser.getFrom();
}
public String getMailbox() {
return mailbox;
}
private static List<String> addressToString(List<Address> addresses) {
ArrayList<String> strings = new ArrayList<String>();
for (Address address : addresses) {
strings.add(address.toString());
}
return strings;
}
public List<String> getTo() throws Exception {
return addressToString(parser.getTo());
}
public List<String> getCc() throws Exception {
return addressToString(parser.getCc());
}
public List<String> getBcc() throws Exception {
return addressToString(parser.getBcc());
}
public String getPlainContent() {
return parser.getPlainContent();
}
public String getSubject() throws Exception {
return parser.getSubject();
}
public String getRaw() {
return raw;
}
} |
package it.unito.geosummly.tools;
import it.unito.geosummly.io.templates.FoursquareObjectTemplate;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.logging.Logger;
/**
*
* Tools for the sampling state
*
*/
public class SamplingTools {
//Variables of the 1st category level
private int total;
private ArrayList<String> ids;
private long timestamp;
private ArrayList<Integer> beenHere;
private HashMap<String, Integer> map;
private ArrayList<ArrayList<BigDecimal>> coordinates;
//Variables of the 2nd category level
private int totalSecond;
private ArrayList<String> idsSecond;
private long timestampSecond;
private ArrayList<Integer> beenHereSecond;
private HashMap<String, Integer> mapSecond;
private ArrayList<ArrayList<Byte>> matrixSecond;
private ArrayList<ArrayList<BigDecimal>> coordinatesSecond;
public static Logger logger = Logger.getLogger(SamplingTools.class.toString());
public SamplingTools() {
this.total = 0;
this.ids = new ArrayList<String>();
this.timestamp = (long) 0;
this.beenHere = new ArrayList<Integer>();
this.map = new HashMap<String, Integer>();
this.coordinates = new ArrayList<ArrayList<BigDecimal>>();
this.totalSecond = 0;
this.idsSecond = new ArrayList<String>();
this.timestampSecond = (long) 0;
this.beenHereSecond = new ArrayList<Integer>();
this.mapSecond = new HashMap<String, Integer>();
this.coordinatesSecond = new ArrayList<ArrayList<BigDecimal>>();
this.matrixSecond = new ArrayList<ArrayList<Byte>>();
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public HashMap<String, Integer> getMap() {
return map;
}
public void setMap(HashMap<String, Integer> map) {
this.map = map;
}
public ArrayList<String> getIds() {
return ids;
}
public void setIds(ArrayList<String> ids) {
this.ids = ids;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public ArrayList<Integer> getBeenHere() {
return beenHere;
}
public void setBeenHere(ArrayList<Integer> beenHere) {
this.beenHere=beenHere;
}
public ArrayList<ArrayList<BigDecimal>> getCooridnates() {
return coordinates;
}
public void setCoordinates(ArrayList<ArrayList<BigDecimal>> coordinates) {
this.coordinates = coordinates;
}
public int getTotalSecond() {
return totalSecond;
}
public void setTotalSecond(int totalSecond) {
this.totalSecond = totalSecond;
}
public ArrayList<String> getIdsSecond() {
return idsSecond;
}
public void setIdsSecond(ArrayList<String> idsSecond) {
this.idsSecond = idsSecond;
}
public long getTimestampSecond() {
return timestampSecond;
}
public void setTimestampsSecond(long timestampSecond) {
this.timestampSecond = timestampSecond;
}
public ArrayList<Integer> getBeenHereSecond() {
return beenHereSecond;
}
public void setBeenHereSecond(ArrayList<Integer> beenHereSecond) {
this.beenHereSecond = beenHereSecond;
}
public HashMap<String, Integer> getMapSecond() {
return mapSecond;
}
public void setMapSecond(HashMap<String, Integer> mapSecond) {
this.mapSecond = mapSecond;
}
public ArrayList<ArrayList<BigDecimal>> getCooridnatesSecond() {
return coordinatesSecond;
}
public void setCoordinatesSecond(ArrayList<ArrayList<BigDecimal>> coordinatesSecond) {
this.coordinatesSecond = coordinatesSecond;
}
public ArrayList<ArrayList<Byte>> getMatrixSecond() {
return matrixSecond;
}
public void setMatrixSecond(ArrayList<ArrayList<Byte>> matrixSecond) {
this.matrixSecond = matrixSecond;
}
/**Get a list with all elements equal to zero*/
/*public ArrayList<BigDecimal> buildListZero(int size) {
ArrayList<BigDecimal> toRet=new ArrayList<BigDecimal>();
int i=0;
while(i<size) {
toRet.add(new BigDecimal(0.0));
i++;
}
return toRet;
}*/
/**Get a list with all elements equal to zero.
* Only categories, no coordinates.
*/
public ArrayList<Byte> buildListZero2(int size) {
ArrayList<Byte> toRet=new ArrayList<Byte>();
int i=0;
while(i<size) {
toRet.add((byte) 0);
i++;
}
return toRet;
}
/**Update the hash map given as parameter
* with new string values from a single venue
*/
/*public HashMap<String, Integer> updateMap(HashMap<String, Integer> map,
ArrayList<String> categories) {
if(!map.containsKey(categories.get(0)))
//first value in the map has to be 2
map.put(categories.get(0), map.size()+2);
return map;
}*/
/**Update the hash map given as parameter
* with new string values from a single venue.
* Only categories, no coordinates.
*/
public HashMap<String, Integer> updateMap2(HashMap<String, Integer> map,
ArrayList<String> categories) {
if(!map.containsKey(categories.get(0)))
map.put(categories.get(0), map.size());
return map;
}
/**Get a row of the matrix with latitude, longitude
* and occurrence value of a single venue
*/
/*public ArrayList<BigDecimal> fillRowWithSingle(HashMap<String, Integer> map,
String category,
BigDecimal lat,
BigDecimal lng) {
int size=map.size()+2;
ArrayList<BigDecimal> row=buildListZero(size);
row.set(0, lat); //lat, lng and area are in position 0 and 1
row.set(1, lng);
int index=map.get(category);
row.set(index, new BigDecimal(1.0));
return row;
}*/
/**Get a row of the matrix with latitude, longitude
* and occurrence value of a single venue.
*/
public ArrayList<Byte> fillRowWithSingle2(HashMap<String, Integer> map,
String category) {
int size = map.size();
ArrayList<Byte> row = buildListZero2(size);
int index = map.get(category);
row.set(index, (byte) 1);
return row;
}
/**Fix the matrix rows giving them the same size*/
/*public ArrayList<ArrayList<BigDecimal>> fixRowsLength(int totElem,
ArrayList<ArrayList<BigDecimal>> matrix) {
int i;
for(ArrayList<BigDecimal> row: matrix) {
i=row.size();
while(i<totElem) {
row.add(new BigDecimal(0.0));
i++;
}
}
return matrix;
}*/
public ArrayList<ArrayList<Byte>> fixRowsLength2(int totElem,
ArrayList<ArrayList<Byte>> matrix) {
int i;
for(ArrayList<Byte> row: matrix) {
i = row.size();
while(i<totElem) {
row.add((byte) 0);
i++;
}
}
return matrix;
}
/**Sort matrix of single venues
* in alphabetical order (column names)
*/
/*public ArrayList<ArrayList<BigDecimal>> sortMatrixSingles(
ArrayList<ArrayList<BigDecimal>> matrix,
HashMap<String,Integer> map) {
ArrayList<ArrayList<BigDecimal>> sortedMatrix =
new ArrayList<ArrayList<BigDecimal>>();
int value;
ArrayList<BigDecimal> sortedRecord;
ArrayList<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys);
//Put the coordinate values into the sorted record
for(ArrayList<BigDecimal> row: matrix) {
sortedRecord=new ArrayList<BigDecimal>();
sortedRecord.add(row.get(0));
sortedRecord.add(row.get(1));
sortedRecord.add(row.get(2));
sortedRecord.add(row.get(3));
for(String k: keys) {
value=map.get(k)+2;
sortedRecord.add(row.get(value));
}
sortedMatrix.add(sortedRecord);
}
return sortedMatrix;
}*/
/**Sort matrix of single venues in alphabetical order (column names)
*/
public ArrayList<ArrayList<Byte>> sortMatrixSingles2(
ArrayList<ArrayList<Byte>> matrix,
HashMap<String,Integer> map) {
ArrayList<ArrayList<Byte>> sortedMatrix =
new ArrayList<ArrayList<Byte>>();
int value;
ArrayList<Byte> sortedRecord;
ArrayList<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys);
//Put the coordinate values into the sorted record
for(ArrayList<Byte> row: matrix) {
sortedRecord = new ArrayList<Byte>();
for(String k: keys) {
value = map.get(k);
sortedRecord.add(row.get(value));
}
sortedMatrix.add(sortedRecord);
}
return sortedMatrix;
}
/**Get the informations of single venues of a cell*/
/**Get the informations of single venues of a cell*/
public ArrayList<ArrayList<Byte>> getInformations2(BigDecimal lat,
BigDecimal lng,
ArrayList<ArrayList<Byte>> matrix,
ArrayList<FoursquareObjectTemplate> cell,
HashMap<String, String> tree) {
ArrayList<Byte> rowOfMatrix =
new ArrayList<Byte>();
ArrayList<Byte> rowOfMatrixSecondLevel =
new ArrayList<Byte>();
for(FoursquareObjectTemplate venue: cell) {
if(venue.getCategories().length > 0) {
String category =
getTopCategory(venue.getCategories()[0].getName(), tree);
String categorySecondLevel =
getSubCategory(venue.getCategories()[0].getName(), tree);
//update the matrix only if the category has a name
if(category != null) {
ArrayList<String> aux = new ArrayList<String>();
aux.add(category);
updateMap2(this.map, aux);//update the hash map
//create a consistent row (related to the categories).
//one row for each venue;
rowOfMatrix = fillRowWithSingle2(this.map, category);
//update the overall number of categories
if(this.total < rowOfMatrix.size())
this.total = rowOfMatrix.size();
//add venue and cell coordinates to the record
ArrayList<BigDecimal> coord = new ArrayList<BigDecimal>();
coord.add(new BigDecimal(venue.getLatitude()));
coord.add(new BigDecimal(venue.getLongitude()));
coord.add(lat);
coord.add(lng);
this.coordinates.add(coord);
this.ids.add(venue.getVenueId()); //memorize venue id
if(this.timestamp == (long) 0)
this.timestamp = venue.getTimestamp(); //memorize timestamp
this.beenHere.add(venue.getCheckinsCount()); //memorize check-ins count
//add the complete record
matrix.add(rowOfMatrix);
}
if(categorySecondLevel != null) {
ArrayList<String> auxSecondLevel = new ArrayList<String>();
auxSecondLevel.add(categorySecondLevel);
updateMap2(this.mapSecond, auxSecondLevel);
rowOfMatrixSecondLevel =
fillRowWithSingle2(this.mapSecond, categorySecondLevel);
if(this.totalSecond < rowOfMatrixSecondLevel.size());
this.totalSecond = rowOfMatrixSecondLevel.size();
//add venue and cell coordinates to the record
ArrayList<BigDecimal> coordSecond = new ArrayList<BigDecimal>();
coordSecond.add(new BigDecimal(venue.getLatitude()));
coordSecond.add(new BigDecimal(venue.getLongitude()));
coordSecond.add(lat);
coordSecond.add(lng);
this.coordinatesSecond.add(coordSecond);
this.idsSecond.add(venue.getVenueId()); //memorize venue id
if(this.timestampSecond == (long) 0)
this.timestampSecond = venue.getTimestamp(); //memorize timestamp
this.beenHereSecond.add(venue.getCheckinsCount()); //memorize check-ins count
this.matrixSecond.add(rowOfMatrixSecondLevel);
}
}
}
return matrix;
}
/**
* Get the corresponding top category of the category "name".
* Totally there are 3 category levels.
*/
public String getTopCategory(String name, HashMap<String, String> map) {
//Get the value corresponding to the key "name"
//2nd or 1st or null category level
String tmp=map.get(name);
if(tmp != null) { //2nd category level
String category = map.get(tmp);
if(category != null) //1st category level
return category;
else //already in the 1st category level
return tmp;
}
else //already in the 1st category level
return name;
}
/**
* Get the corresponding sub category of the category "name".
* Totally there are 3 category levels.
*/
public String getSubCategory(String name, HashMap<String, String> map) {
//Get the value corresponding to the key "name"
//2nd or 1st or null category level
String tmp=map.get(name);
if(tmp !=null) { //2nd category level
String category = map.get(tmp);
if(category != null) //1st category level
return tmp; //return the 2nd category level
else // already in the 2nd category level
return name;
}
else //already in the 1st category level, so return null
return null;
}
/**Sort the features in alphabetical order*/
/*public ArrayList<String> sortFeatures(HashMap<String,Integer> map) {
ArrayList<String> sortedFeatures = new ArrayList<String>();
ArrayList<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys);
sortedFeatures.add("Latitude");
sortedFeatures.add("Longitude");
for(String s: keys)
sortedFeatures.add(s);
return sortedFeatures;
}*/
/**Sort the features in alphabetical order*/
public ArrayList<String> sortFeatures2(HashMap<String,Integer> map) {
ArrayList<String> sortedFeatures = new ArrayList<String>();
ArrayList<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys);
for(String s: keys)
sortedFeatures.add(s);
return sortedFeatures;
}
/**Get the features list for the dataset of single venues*/
/*public ArrayList<String> getFeaturesForSingles(ArrayList<String> features) {
features.add(0, "Timestamp (ms)");
features.add(1, "Been Here");
features.add(2, "Venue Id");
features.add(3, "Venue Latitude");
features.add(4, "Venue Longitude");
features.set(5, "Focal Latitude");
features.set(6, "Focal Longitude");
return features;
}*/
/**Get the features list for the dataset of single venues*/
public ArrayList<String> getFeaturesForSingles2(ArrayList<String> features) {
features.add(0, "Timestamp (ms)");
features.add(1, "Been Here");
features.add(2, "Venue Id");
features.add(3, "Venue Latitude");
features.add(4, "Venue Longitude");
features.add(5, "Focal Latitude");
features.add(6, "Focal Longitude");
return features;
}
} |
package japsa.tools.bio.sim;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Random;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import japsa.bio.sim.IlluminaSequencing;
import japsa.bio.sim.PacBioSequencing;
import japsa.seq.Genome;
import japsa.seq.Sequence;
import japsa.seq.SequenceOutputStream;
import japsa.util.CommandLine;
import japsa.util.Logging;
import japsa.util.Simulation;
import japsa.util.deploy.Deployable;
/**
* @author minhduc
*
*/
@Deployable(
scriptName = "jsa.sim.capsim",
scriptDesc = "Simulate capture sequencing"
)
public class SimulateCaptureCmd extends CommandLine{
//CommandLine cmdLine;
public SimulateCaptureCmd(){
super();
Deployable annotation = getClass().getAnnotation(Deployable.class);
setUsage(annotation.scriptName() + " [options]");
setDesc(annotation.scriptDesc());
//Input/output
addString("reference", null, "Name of genome to be ",true);
addString("probe", null, "File containing probes mapped to the reference in bam format");
addString("logFile", "-", "Log file");
addString("ID", "", "A unique ID for the data set");
//addString("fragment", null, "Output of fragment file");
addString("miseq", null, "Name of read file if miseq is simulated");
addString("pacbio", null, "Name of read file if pacbio is simulated");
//Fragment size distribution
addInt("fmedian", 2000 , "Median of fragment size at shearing");
addDouble("fshape", 6, "Shape parameter of the fragment size distribution");
addInt("smedian", 1300 , "Median of fragment size distribution");
addDouble("sshape", 6, "Shape parameter of the fragment size distribution");
addInt("tmedian", 0 , "Median of target fragment size (the fragment size of the data).\n If specified, will override fmedian and smedian.\n Othersise will be estimated");
addDouble("tshape", 0, "Shape parameter of the effective fragment size distribution");
addInt("num", 1000000, "Number of fragments ");
//addDouble("mismatch",0.01,"probability of mismatches");
//addDouble("deletion",0.01,"probability of deletion");
//addDouble("insertion",0.01,"probability of insertion");
//addDouble("extension",0.01,"probability of indel extention");
//Specific parameter for each sequencing technology
addInt("pblen", 30000, "PacBio: Average (polymerase) read length");
addInt("illen", 300, "Illumina: read length");
addString("ilmode", "pe", "Illumina: Sequencing mode: pe = paired-end, mp=mate-paired and se=singled-end");
addInt("seed", 0, "Random seed, 0 for a random seed");
addStdHelp();
}
public static void main(String [] args) throws IOException{
CommandLine cmdLine = new SimulateCaptureCmd ();
args = cmdLine.stdParseLine(args);
String logFile = cmdLine.getStringVal("logFile");
String probe = cmdLine.getStringVal("probe");
String ID = cmdLine.getStringVal("ID");
String referenceFile = cmdLine.getStringVal("reference");
int fmedian = cmdLine.getIntVal("fmedian");
double fshape = cmdLine.getDoubleVal("fshape");
int smedian = cmdLine.getIntVal("smedian");
double sshape = cmdLine.getDoubleVal("sshape");
int tmedian = cmdLine.getIntVal("smedian");
double tshape = cmdLine.getDoubleVal("sshape");
int seed = cmdLine.getIntVal("seed");
int num = cmdLine.getIntVal("num");
int pblen = cmdLine.getIntVal("pblen");
int pbshape = 6;
String miseq = cmdLine.getStringVal("miseq");
String pacbio = cmdLine.getStringVal("pacbio");
if (miseq == null && pacbio == null){
System.err.println("One of miseq or pacbio must be set\n" + cmdLine.usageString());
System.exit(-1);
}
if (miseq != null && pacbio != null){
System.err.println("One of miseq or pacbio must be set\n" + cmdLine.usageString());
System.exit(-1);
}
int flank = fmedian + (fmedian / 4);
double hybridizationRatio = 0.5;
double [] dist2 = null;
if (tmedian <=0){
Logging.info("Estimating target distribution");
dist2 = new double[fmedian*6];
}else{
dist2 = new double[tmedian*6];
double max = 0;
for (int i = 0; i < dist2.length;i++){
dist2[i] = Simulation.logLogisticPDF(i + 1, smedian, sshape);
if (dist2[i] > max)
max = dist2[i];
}
}
//double [] dist2 = new double[smedian*4];
//double max = 0.0;
//for (int i = 0; i < dist2.length;i++){
// dist2[i] = Simulation.logLogisticPDF(i + 1, smedian, sshape);
// if (dist2[i] > max)
// max = dist2[i];
//Normalise to 1
//for (int i = 0; i < dist2.length;i++){
// //Logging.info("dist2 [" + i + "] = " + dist2[i] + " max = " + max + " after " + dist2[i] / max);
// dist2[i] = dist2[i] / max;
SequenceOutputStream miSeq1Fq = null, miSeq2Fq = null, pacbioFq = null;
if (miseq != null){
miSeq1Fq = SequenceOutputStream.makeOutputStream(miseq + "_1.fastq.gz");
miSeq2Fq = SequenceOutputStream.makeOutputStream(miseq + "_2.fastq.gz");
}
if (pacbio != null){
pacbioFq = SequenceOutputStream.makeOutputStream(pacbio + ".fastq.gz");
}
SequenceOutputStream
logOS = logFile.equals("-")? (new SequenceOutputStream(System.err)):(SequenceOutputStream.makeOutputStream(logFile));
logOS.print("Parameters for simulation \n" + cmdLine.optionValues());
seed = Simulation.seed(seed);
Random rnd = new Random(seed);
logOS.print("#Seed " + seed + "\n");
Genome genome = new Genome();
genome.read(referenceFile);
ArrayList<Sequence> chrList = genome.chrList();
logOS.print("Read " + chrList.size() + " chr " + genome.getLength() + "bp\n" );
BitSet [] bitSets = null;
GenomicRegion genRegion = null;
SamReader samReader = null;
long [] accLen = null;
if (probe != null){
genRegion = new GenomicRegion();
SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
samReader = SamReaderFactory.makeDefault().open(new File(probe));
SAMRecordIterator samIter = samReader.iterator();
Logging.info("Mark capturable regions");
bitSets = new BitSet[chrList.size()];
for (int i = 0; i < bitSets.length;i++)
bitSets[i] = new BitSet();
//Mark regions from which fragments *may* be captured
while (samIter.hasNext()){
SAMRecord sam = samIter.next();
if (sam.getReadUnmappedFlag())
continue;
int start = sam.getAlignmentStart();
int end = sam.getAlignmentEnd();
if ((end - start) < hybridizationRatio * sam.getReadLength())
continue;
int refIndex = sam.getReferenceIndex();
//TODO: this part can be improved
bitSets[refIndex].set(Math.max(start - flank,0), end);
}
samIter.close();
//Logging.info("Mark capturable regions -- done");
for (int x=0; x < genome.chrList().size();x++){
Sequence chrom = genome.chrList().get(x);
BitSet myBitSet = bitSets[x];
int regionStart = -1;
for (int i = 0; i < chrom.length();i++){
if (myBitSet.get(i) && (regionStart < 0)){
//start of a new region
regionStart = i;
}else if (!myBitSet.get(i) && (regionStart >= 0)){
//end of a region
genRegion.addRegion(x, regionStart, i - regionStart);
regionStart = -1;
}
}
if (regionStart >=0){
genRegion.addRegion(x, regionStart, chrom.length() - regionStart);
}
}//for
//Logging.info("Mark capturable regions 2 -- done");
}else{
accLen = new long[chrList.size()];
accLen[0] = chrList.get(0).length();
Logging.info("Acc 0 " + accLen[0]);
for (int i = 1; i < accLen.length;i++){
accLen[i] = accLen[i-1] + chrList.get(i).length();
Logging.info("Acc " +i + " " + accLen[i]);
}
}
//if (fragment != null)
// sos = SequenceOutputStream.makeOutputStream(fragment);
long numFragment = 0;
//actual number of fragments generated, including the non probed
long numGen = 0;
long
fragmentRej1 = 0,
fragmentRej2 = 0,
fragmentRej3 = 0,
fragmentRej4 = 0;
while (numFragment < num){
numGen ++;
if (numGen % 1000000 == 0){
Logging.info("Generated " + numGen + " selected " + numFragment
+ "; reject1 = " + fragmentRej1
+ "; reject2 = " + fragmentRej2
+ "; reject3 = " + fragmentRej3
+ "; reject4 = " + fragmentRej4);
}
//1. Generate the length of the next fragment
int fragLength =
Math.max((int) Simulation.logLogisticSample(fmedian, fshape, rnd), 50);
//Logging.info("Gen0 " + fragLength);
//2. Generate the position of the fragment
//toss the coin
double r = rnd.nextDouble();
int chrIndex = 0, chrPos = 0;
if (genRegion != null){
long p = (long) (r * genRegion.totLength);
int index = 0;
while (p > genRegion.regions.get(index).accuLength){
index ++;
}
if (index > 0){
p = p - genRegion.regions.get(index - 1).accuLength;
}
if (p > genRegion.regions.get(index).length){
Logging.exit("Not expecting2 " + p + " vs " + index, 1);
}
chrPos = ((int) p) + genRegion.regions.get(index).position;
chrIndex = genRegion.regions.get(index).chrIndex;
}else{
long p = (long) (r * genome.getLength());
int index = 0;
while (p > accLen[index])
index ++;
//identify the chroms
if (index > 0){
p = p - accLen[index - 1];
}
chrIndex = index;
chrPos = (int) p;
//Logging.info("Found " + index + " " + myP + " " + p);
}
if (chrPos > chrList.get(chrIndex).length()){
Logging.exit("Not expecting " + chrPos + " vs " + chrIndex, 1);
}
//Take the min of the frag length and the length to the end
fragLength = Math.min(fragLength, chrList.get(chrIndex).length() - chrPos);
if (fragLength < 50){
Logging.warn("Whoops");
continue;
}
if (samReader != null){
//if probe is provided, see if the fragment is rejected
if (!bitSets[chrIndex].get(chrPos)){
//Logging.info("Reject0 " + fragLength);
fragmentRej1 ++;
continue;//while
}
/**
* Implement regions that may be capturable
* @author minhduc
*
*/
static class GenomicRegion{
Genome genome;
long totLength = 0;
static class Region{
int chrIndex;
int position;
int length;
long accuLength;
}
ArrayList<Region> regions = new ArrayList<Region>();
Region addRegion(int cIndex, int pos, int length){
Region region = new Region();
region.chrIndex = cIndex;
region.position = pos;
region.length = length;
totLength += length;
region.accuLength = totLength;
regions.add(region);
return region;
}
}
} |
package md2k.mcerebrum.cstress;
public class StreamConstants {
public static final String ORG_MD2K_CSTRESS_DATA_ACCEL_ACTIVITY = "org.md2k.cstress.data.accel.activity";
public static final String ORG_MD2K_CSTRESS_DATA_ACCEL_MAGNITUDE = "org.md2k.cstress.data.accel.magnitude";
public static final String ORG_MD2K_CSTRESS_DATA_ACCEL_WINDOWED_MAGNITUDE_STDEV = "org.md2k.cstress.data.accel.windowed.magnitude.stdev";
public static final String ORG_MD2K_CSTRESS_DATA_ACCELX = "org.md2k.cstress.data.accelx";
public static final String ORG_MD2K_CSTRESS_DATA_ACCELX_NORMALIZED = "org.md2k.cstress.data.accelx.normalized";
public static final String ORG_MD2K_CSTRESS_DATA_ACCELY = "org.md2k.cstress.data.accely";
public static final String ORG_MD2K_CSTRESS_DATA_ACCELY_NORMALIZED = "org.md2k.cstress.data.accely.normalized";
public static final String ORG_MD2K_CSTRESS_DATA_ACCELZ = "org.md2k.cstress.data.accelz";
public static final String ORG_MD2K_CSTRESS_DATA_ACCELZ_NORMALIZED = "org.md2k.cstress.data.accelz.normalized";
public static final String ORG_MD2K_CSTRESS_DATA_ECG = "org.md2k.cstress.data.ecg";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_OUTLIER = "org.md2k.cstress.data.ecg.outlier";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS = "org.md2k.cstress.data.ecg.peaks";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS_NOISE_LEV = "org.md2k.cstress.data.ecg.peaks.noise_lev";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS_RPEAKS = "org.md2k.cstress.data.ecg.peaks.rpeaks";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS_SIG_LEV = "org.md2k.cstress.data.ecg.peaks.sig_lev";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS_TEMP1 = "org.md2k.cstress.data.ecg.peaks.temp1";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS_TEMP2 = "org.md2k.cstress.data.ecg.peaks.temp2";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS_THR1 = "org.md2k.cstress.data.ecg.peaks.thr1";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_PEAKS_THR2 = "org.md2k.cstress.data.ecg.peaks.thr2";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_QUALITY = "org.md2k.cstress.data.ecg.quality";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR = "org.md2k.cstress.data.ecg.rr";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_AVE = "org.md2k.cstress.data.ecg.rr_ave";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_HEARTRATE = "org.md2k.cstress.data.ecg.rr.heartrate";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_LOMB_HIGH_FREQUENCY_ENERGY = "org.md2k.cstress.data.ecg.rr.LombHighFrequencyEnergy";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_LOMB_LOW_FREQUENCY_ENERGY = "org.md2k.cstress.data.ecg.rr.LombLowFrequencyEnergy";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_LOMB_MEDIUM_FREQUENCY_ENERGY = "org.md2k.cstress.data.ecg.rr.LombMediumFrequencyEnergy";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_LOW_HIGH_FREQUENCY_ENERGY_RATIO = "org.md2k.cstress.data.ecg.rr.LowHighFrequencyEnergyRatio";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_VALUE = "org.md2k.cstress.data.ecg.rr_value";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_VALUE_DIFF = "org.md2k.cstress.data.ecg.rr_value_diff";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_RR_VALUE_FILTERED = "org.md2k.cstress.data.ecg.rr_value.filtered";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_VALIDFILTER_RR_VALUE = "org.md2k.cstress.data.ecg.validfilter_rr_value";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_WINDOW_QUALITY = "org.md2k.cstress.data.ecg.window.quality";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y2 = "org.md2k.cstress.data.ecg.y2";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y2_NORMALIZED = "org.md2k.cstress.data.ecg.y2-normalized";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y3 = "org.md2k.cstress.data.ecg.y3";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y3_NORMALIZED = "org.md2k.cstress.data.ecg.y3-normalized";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y4 = "org.md2k.cstress.data.ecg.y4";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y4_NORMALIZED = "org.md2k.cstress.data.ecg.y4-normalized";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y5 = "org.md2k.cstress.data.ecg.y5";
public static final String ORG_MD2K_CSTRESS_DATA_ECG_Y5_NORMALIZED = "org.md2k.cstress.data.ecg.y5-normalized";
public static final String ORG_MD2K_CSTRESS_DATA_RIP = "org.md2k.cstress.data.rip";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_BREATH_RATE = "org.md2k.cstress.data.rip.BreathRate";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_DOWN_INTERCEPTS = "org.md2k.cstress.data.rip.downIntercepts";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_DOWN_INTERCEPTS_FILTERED = "org.md2k.cstress.data.rip.downIntercepts.filtered";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_DOWN_INTERCEPTS_FILTERED_1SEC = "org.md2k.cstress.data.rip.downIntercepts.filtered.1sec";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_DOWN_INTERCEPTS_FILTERED_1SEC_T20 = "org.md2k.cstress.data.rip.downIntercepts.filtered.1sec.t20";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_EXPRDURATION = "org.md2k.cstress.data.rip.exprduration";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_IERATIO = "org.md2k.cstress.data.rip.IERatio";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_INSPDURATION = "org.md2k.cstress.data.rip.inspduration";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_INSPIRATION_AMPLITUDE = "org.md2k.cstress.data.rip.inspirationAmplitude";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_MAC = "org.md2k.cstress.data.rip.mac";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_MINUTE_VENTILATION = "org.md2k.cstress.data.rip.MinuteVentilation";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_PEAKS = "org.md2k.cstress.data.rip.peaks";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_PEAKS_FILTERED = "org.md2k.cstress.data.rip.peaks.filtered";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_QUALITY = "org.md2k.cstress.data.rip.quality";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_RESPDURATION = "org.md2k.cstress.data.rip.respduration";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_RESPIRATION_DURATION = "org.md2k.cstress.data.rip.respirationDuration";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_RSA = "org.md2k.cstress.data.rip.RSA";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_SMOOTH = "org.md2k.cstress.data.rip.smooth";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_STRETCH = "org.md2k.cstress.data.rip.stretch";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_UP_INTERCEPTS = "org.md2k.cstress.data.rip.upIntercepts";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_UP_INTERCEPTS_FILTERED = "org.md2k.cstress.data.rip.upIntercepts.filtered";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_UP_INTERCEPTS_FILTERED_1SEC = "org.md2k.cstress.data.rip.upIntercepts.filtered.1sec";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_UP_INTERCEPTS_FILTERED_1SEC_T20 = "org.md2k.cstress.data.rip.upIntercepts.filtered.1sec.t20";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_VALLEYS = "org.md2k.cstress.data.rip.valleys";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_VALLEYS_FILTERED = "org.md2k.cstress.data.rip.valleys.filtered";
public static final String ORG_MD2K_CSTRESS_DATA_RIP_WINDOW_QUALITY = "org.md2k.cstress.data.rip.window.quality";
public static final String ORG_MD2K_CSTRESS_FV = "org.md2k.cstress.fv";
public static final String ORG_MD2K_CSTRESS_PROBABILITY = "org.md2k.cstress.probability";
public static final String ORG_MD2K_CSTRESS_PROBABILITY_IMPUTED = "org.md2k.cstress.probability.imputed";
public static final String ORG_MD2K_CSTRESS_PROBABILITY_SMOOTHED = "org.md2k.cstress.probability.smoothed";
public static final String ORG_MD2K_CSTRESS_STRESSLABEL = "org.md2k.cstress.stresslabel";
public static final String ORG_MD2K_CSTRESS_PROBABILITY_AVAILABLE = "org.md2k.cstress.probability.available";
public static final String ORG_MD2K_CSTRESS_STRESS_EPISODE_EMA_FAST = "org.md2k.cstress.stress.episode.ema.fast";
public static final String ORG_MD2K_CSTRESS_STRESS_EPISODE_EMA_SLOW = "org.md2k.cstress.stress.episode.ema.slow";
public static final String ORG_MD2K_CSTRESS_STRESS_EPISODE_EMA_SIGNAL = "org.md2k.cstress.stress.episode.ema.signal";
public static final String ORG_MD2K_CSTRESS_STRESS_EPISODE_CLASSIFICATION = "org.md2k.cstress.stress.episode.classification";
public static final String ORG_MD2K_CSTRESS_FV_RIP = "org.md2k.cstress.fv.rip";
public static final String ORG_MD2K_CSTRESS_RIP_PROBABILITY = "org.md2k.cstress.probability.rip";
public static final String ORG_MD2K_CSTRESS_RIP_STRESSLABEL = "org.md2k.cstress.stresslabel.rip";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_EXPRDURATION_BACK_DIFFERENCE = "org.md2k.puffMarker.data.rip.exprduration.backward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_EXPRDURATION_FORWARD_DIFFERENCE = "org.md2k.puffMarker.data.rip.exprduration.forward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_INSPDURATION_BACK_DIFFERENCE = "org.md2k.puffMarker.data.rip.inspduration.backward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_INSPDURATION_FORWARD_DIFFERENCE = "org.md2k.puffMarker.data.rip.inspduration.forward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_IERATIO_BACK_DIFFERENCE = "org.md2k.puffMarker.data.rip.IERatio.backward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_IERATIO_FORWARD_DIFFERENCE = "org.md2k.puffMarker.data.rip.IERatio.forward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_STRETCH_BACK_DIFFERENCE = "org.md2k.puffMarker.data.rip.stretch.backward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_STRETCH_FORWARD_DIFFERENCE = "org.md2k.puffMarker.data.rip.stretch.forward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_RESPDURATION_BACK_DIFFERENCE = "org.md2k.puffMarker.data.rip.respduration.backward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_RESPDURATION_FORWARD_DIFFERENCE = "org.md2k.puffMarker.data.rip.respduration.forward.diff";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_D5_EXPRDURATION = "org.md2k.puffMarker.data.rip.respduration.d5.exprduration";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_D5_STRETCH = "org.md2k.puffMarker.data.rip.respduration.d5.stretch";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_MAX_AMPLITUDE = "org.md2k.puffMarker.data.rip.respduration.max.amplitude";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_MIN_AMPLITUDE = "org.md2k.puffMarker.data.rip.respduration.min.amplitude";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_MAX_RATE_OF_CHANGE = "org.md2k.puffMarker.data.rip.respduration.max.rateofchange";
public static final String ORG_MD2K_PUFFMARKER_DATA_RIP_MIN_RATE_OF_CHANGE = "org.md2k.puffMarker.data.rip.respduration.min.rateofchange";
} |
package net.finmath.functions;
import java.util.Calendar;
import net.finmath.optimizer.GoldenSectionSearch;
import net.finmath.rootfinder.NewtonsMethod;
import net.finmath.stochastic.RandomVariableInterface;
/**
* This class implements some functions as static class methods.
*
* It provides functions like
* <ul>
* <li>the Black-Scholes formula,
* <li>the inverse of the Back-Scholes formula with respect to (implied) volatility,
* <li>the Bachelier formula,
* <li>the inverse of the Bachelier formula with respect to (implied) volatility,
* <li>the corresponding functions (versions) for caplets and swaptions,
* <li>analytic approximation for European options under the SABR model,
* <li>some convexity adjustments.
* </ul>
*
* @author Christian Fries
* @version 1.9
* @date 27.04.2012
*/
public class AnalyticFormulas {
// Suppress default constructor for non-instantiability
private AnalyticFormulas() {
// This constructor will never be invoked
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a log-normal process with constant log-volatility.
*
* The method also handles cases where the forward and/or option strike is negative
* and some limit cases where the forward and/or the option strike is zero.
*
* @param forward The forward of the underlying.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @return Returns the value of a European call option under the Black-Scholes model.
*/
public static double blackScholesGeneralizedOptionValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double payoffUnit)
{
if(optionMaturity < 0) {
return 0;
}
else if(forward < 0) {
// We use max(X,0) = X + max(-X,0)
return (forward - optionStrike) * payoffUnit + blackScholesGeneralizedOptionValue(-forward, volatility, optionMaturity, -optionStrike, payoffUnit);
}
else if((forward == 0) || (optionStrike <= 0.0) || (volatility <= 0.0) || (optionMaturity <= 0.0))
{
// Limit case (where dPlus = +/- infty)
return Math.max(forward - optionStrike,0) * payoffUnit;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
return valueAnalytic;
}
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a log-normal process with constant log-volatility.
*
* The model specific quantities are considered to be random variable, i.e.,
* the function may calculate an per-path valuation in a single call.
*
* @param forward The forward of the underlying.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @return Returns the value of a European call option under the Black-Scholes model.
*/
public static RandomVariableInterface blackScholesGeneralizedOptionValue(
RandomVariableInterface forward,
RandomVariableInterface volatility,
double optionMaturity,
double optionStrike,
RandomVariableInterface payoffUnit)
{
if(optionMaturity < 0) {
return forward.mult(0.0);
}
else
{
RandomVariableInterface dPlus = forward.div(optionStrike).log().add(volatility.squared().mult(0.5 * optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity));
RandomVariableInterface dMinus = dPlus.sub(volatility.mult(Math.sqrt(optionMaturity)));
RandomVariableInterface valueAnalytic = dPlus.apply(NormalDistribution::cumulativeDistribution).mult(forward).sub(dMinus.apply(NormalDistribution::cumulativeDistribution).mult(optionStrike)).mult(payoffUnit);
return valueAnalytic;
}
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a log-normal process with constant log-volatility.
*
* @param initialStockValue The spot value of the underlying.
* @param riskFreeRate The risk free rate r (df = exp(-r T)).
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @return Returns the value of a European call option under the Black-Scholes model.
*/
public static double blackScholesOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
return blackScholesGeneralizedOptionValue(
initialStockValue * Math.exp(riskFreeRate * optionMaturity), // forward
volatility,
optionMaturity,
optionStrike,
Math.exp(-riskFreeRate * optionMaturity) // payoff unit
);
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), or a put, i.e., the payoff max(K-S(T),0), where S follows a log-normal process with constant log-volatility.
*
* @param initialStockValue The spot value of the underlying.
* @param riskFreeRate The risk free rate r (df = exp(-r T)).
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T for the call and zero for the put.
* @param isCall If true, the value of a call is calculated, if false, the value of a put is calculated.
* @return Returns the value of a European call/put option under the Black-Scholes model.
*/
public static double blackScholesOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike,
boolean isCall) {
double callValue = blackScholesOptionValue(initialStockValue, riskFreeRate, volatility, optionMaturity, optionStrike);
if(isCall) {
return callValue;
}
else {
double putValue = callValue - (initialStockValue-optionStrike * Math.exp(-riskFreeRate * optionMaturity));
return putValue;
}
}
/**
* Calculates the Black-Scholes option value of an atm call option.
*
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param forward The forward, i.e., the expectation of the index under the measure associated with payoff unit.
* @param payoffUnit The payoff unit, i.e., the discount factor or the anuity associated with the payoff.
* @return Returns the value of a European at-the-money call option under the Black-Scholes model
*/
public static double blackScholesATMOptionValue(
double volatility,
double optionMaturity,
double forward,
double payoffUnit)
{
if(optionMaturity < 0) return 0.0;
// Calculate analytic value
double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);
double dMinus = -dPlus;
double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;
return valueAnalytic;
}
/**
* Calculates the delta of a call option under a Black-Scholes model
*
* The method also handles cases where the forward and/or option strike is negative
* and some limit cases where the forward or the option strike is zero.
* In the case forward = option strike = 0 the method returns 1.0.
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the option
*/
public static double blackScholesOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionMaturity < 0) {
return 0;
}
else if(initialStockValue < 0) {
// We use Indicator(S>K) = 1 - Indicator(-S>-K)
return 1 - blackScholesOptionDelta(-initialStockValue, riskFreeRate, volatility, optionMaturity, -optionStrike);
}
else if(initialStockValue == 0)
{
// Limit case (where dPlus = +/- infty)
if(optionStrike < 0) return 1.0; // dPlus = +infinity
else if(optionStrike > 0) return 0.0; // dPlus = -infinity
else return 1.0; // Matter of definition of continuity of the payoff function
}
else if((optionStrike <= 0.0) || (volatility <= 0.0) || (optionMaturity <= 0.0)) // (and initialStockValue > 0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double delta = NormalDistribution.cumulativeDistribution(dPlus);
return delta;
}
}
/**
* Calculates the delta of a call option under a Black-Scholes model
*
* The method also handles cases where the forward and/or option strike is negative
* and some limit cases where the forward or the option strike is zero.
* In the case forward = option strike = 0 the method returns 1.0.
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the option
*/
public static RandomVariableInterface blackScholesOptionDelta(
RandomVariableInterface initialStockValue,
RandomVariableInterface riskFreeRate,
RandomVariableInterface volatility,
double optionMaturity,
double optionStrike)
{
if(optionMaturity < 0) {
return initialStockValue.mult(0.0);
}
else
{
// Calculate delta
RandomVariableInterface dPlus = initialStockValue.div(optionStrike).log().add(volatility.squared().mult(0.5).add(riskFreeRate).mult(optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity));
RandomVariableInterface delta = dPlus.apply(NormalDistribution::cumulativeDistribution);
return delta;
}
}
/**
* Calculates the delta of a call option under a Black-Scholes model
*
* The method also handles cases where the forward and/or option strike is negative
* and some limit cases where the forward or the option strike is zero.
* In the case forward = option strike = 0 the method returns 1.0.
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the option
*/
public static RandomVariableInterface blackScholesOptionDelta(
RandomVariableInterface initialStockValue,
RandomVariableInterface riskFreeRate,
RandomVariableInterface volatility,
double optionMaturity,
RandomVariableInterface optionStrike)
{
if(optionMaturity < 0) {
return initialStockValue.mult(0.0);
}
else
{
// Calculate delta
RandomVariableInterface dPlus = initialStockValue.div(optionStrike).log().add(volatility.squared().mult(0.5).add(riskFreeRate).mult(optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity));
RandomVariableInterface delta = dPlus.apply(NormalDistribution::cumulativeDistribution);
return delta;
}
}
/**
* This static method calculated the gamma of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The gamma of the option
*/
public static double blackScholesOptionGamma(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate gamma
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double gamma = Math.exp(-0.5*dPlus*dPlus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return gamma;
}
}
/**
* This static method calculated the gamma of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The gamma of the option
*/
public static RandomVariableInterface blackScholesOptionGamma(
RandomVariableInterface initialStockValue,
RandomVariableInterface riskFreeRate,
RandomVariableInterface volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return initialStockValue.mult(0.0);
}
else
{
// Calculate gamma
RandomVariableInterface dPlus = initialStockValue.div(optionStrike).log().add(volatility.squared().mult(0.5).add(riskFreeRate).mult(optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity));
RandomVariableInterface gamma = dPlus.squared().mult(-0.5).exp().div(initialStockValue.mult(volatility).mult(Math.sqrt(2.0 * Math.PI * optionMaturity)));
return gamma;
}
}
/**
* This static method calculated the vega of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The vega of the option
*/
public static double blackScholesOptionVega(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate vega
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double vega = Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) * initialStockValue * Math.sqrt(optionMaturity);
return vega;
}
}
/**
* This static method calculated the rho of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The rho of the option
*/
public static double blackScholesOptionRho(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate rho
double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return rho;
}
}
/**
* Calculates the Black-Scholes option implied volatility of a call, i.e., the payoff
* <p><i>max(S(T)-K,0)</i></p>, where <i>S</i> follows a log-normal process with constant log-volatility.
* The admissible values for <code>optionValue</code> are between <code>forward * payoffUnit - optionStrike</code> (the inner value) and <code>forward * payoffUnit</code>.
*
* @param forward The forward of the underlying (which is equal to S(0) / payoffUnit, given the spot value S(0)).
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor), (which is equal to exp(-maturity * r), given the interest rate r).
* @param optionValue The option value. The admissible values for <code>optionValue</code> are between <code>forward * payoffUnit - optionStrike</code> (the inner value) and <code>forward * payoffUnit</code>.
* @return Returns the implied volatility of a European call option under the Black-Scholes model.
*/
public static double blackScholesOptionImpliedVolatility(
double forward,
double optionMaturity,
double optionStrike,
double payoffUnit,
double optionValue)
{
// Limit the maximum number of iterations, to ensure this calculation returns fast, e.g. in cases when there is no such thing as an implied vol
// TODO: An exception should be thrown, when there is no implied volatility for the given value.
int maxIterations = 500;
double maxAccuracy = 1E-15;
if(optionStrike <= 0.0)
{
// Actually it is not an option
return 0.0;
}
else
{
// Calculate an lower and upper bound for the volatility
double p = NormalDistribution.inverseCumulativeDistribution((optionValue/payoffUnit+optionStrike)/(forward+optionStrike)) / Math.sqrt(optionMaturity);
double q = 2.0 * Math.abs(Math.log(forward/optionStrike)) / optionMaturity;
double volatilityLowerBound = p + Math.sqrt(Math.max(p * p - q, 0.0));
double volatilityUpperBound = p + Math.sqrt( p * p + q );
// If strike is close to forward the two bounds are close to the analytic solution
if(Math.abs(volatilityLowerBound - volatilityUpperBound) < maxAccuracy) return (volatilityLowerBound+volatilityUpperBound) / 2.0;
// Solve for implied volatility
NewtonsMethod solver = new NewtonsMethod(0.5*(volatilityLowerBound+volatilityUpperBound) /* guess */);
while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) {
double volatility = solver.getNextPoint();
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
double derivativeAnalytic = forward * Math.sqrt(optionMaturity) * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0*Math.PI) * payoffUnit;
double error = valueAnalytic - optionValue;
solver.setValueAndDerivative(error,derivativeAnalytic);
}
return solver.getBestPoint();
}
}
/**
* Calculates the Black-Scholes option value of a digital call option.
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return Returns the value of a European call option under the Black-Scholes model
*/
public static double blackScholesDigitalOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return valueAnalytic;
}
}
/**
* Calculates the delta of a digital option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the digital option
*/
public static double blackScholesDigitalOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return delta;
}
}
/**
* Calculates the vega of a digital option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The vega of the digital option
*/
public static double blackScholesDigitalOptionVega(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate vega
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;
return vega;
}
}
/**
* Calculates the rho of a digital option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The rho of the digital option
*/
public static double blackScholesDigitalOptionRho(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else if(optionStrike <= 0.0) {
double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity);
return rho;
}
else
{
// Calculate rho
double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus)
+ Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI);
return rho;
}
}
/**
* Calculate the value of a caplet assuming the Black'76 model.
*
* @param forward The forward (spot).
* @param volatility The Black'76 volatility.
* @param optionMaturity The option maturity
* @param optionStrike The option strike.
* @param periodLength The period length of the underlying forward rate.
* @param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
* @return Returns the value of a caplet under the Black'76 model
*/
public static double blackModelCapletValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double periodLength,
double discountFactor)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);
}
/**
* Calculate the value of a digital caplet assuming the Black'76 model.
*
* @param forward The forward (spot).
* @param volatility The Black'76 volatility.
* @param periodLength The period length of the underlying forward rate.
* @param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
* @param optionMaturity The option maturity
* @param optionStrike The option strike.
* @return Returns the price of a digital caplet under the Black'76 model
*/
public static double blackModelDgitialCapletValue(
double forward,
double volatility,
double periodLength,
double discountFactor,
double optionMaturity,
double optionStrike)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;
}
/**
* Calculate the value of a swaption assuming the Black'76 model.
*
* @param forwardSwaprate The forward (spot)
* @param volatility The Black'76 volatility.
* @param optionMaturity The option maturity.
* @param optionStrike The option strike.
* @param swapAnnuity The swap annuity corresponding to the underlying swap.
* @return Returns the value of a Swaption under the Black'76 model
*/
public static double blackModelSwaptionValue(
double forwardSwaprate,
double volatility,
double optionMaturity,
double optionStrike,
double swapAnnuity)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
}
/**
* Calculates the value of an Exchange option under a generalized Black-Scholes model, i.e., the payoff \( max(S_{1}(T)-S_{2}(T),0) \),
* where \( S_{1} \) and \( S_{2} \) follow a log-normal process with constant log-volatility and constant instantaneous correlation.
*
* The method also handles cases where the forward and/or option strike is negative
* and some limit cases where the forward and/or the option strike is zero.
*
* @param spot1 Value of \( S_{1}(0) \)
* @param spot2 Value of \( S_{2}(0) \)
* @param volatility1 Volatility of \( \log(S_{1}(t)) \)
* @param volatility2 Volatility of \( \log(S_{2}(t)) \)
* @param correlation Instantaneous correlation of \( \log(S_{1}(t)) \) and \( \log(S_{2}(t)) \)
* @param optionMaturity The option maturity \( T \).
* @return Returns the value of a European exchange option under the Black-Scholes model.
*/
public static double margrabeExchangeOptionValue(
double spot1,
double spot2,
double volatility1,
double volatility2,
double correlation,
double optionMaturity)
{
double volatility = Math.sqrt(volatility1*volatility1 + volatility2*volatility2 - 2.0 * volatility1*volatility2*correlation);
return blackScholesGeneralizedOptionValue(spot1, volatility, optionMaturity, spot2, 1.0);
}
/**
* Calculates the option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a
* normal process with constant volatility, i.e., a Bachelier model.
*
* @param forward The forward of the underlying.
* @param volatility The Bachelier volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @return Returns the value of a European call option under the Bachelier model.
*/
public static double bachelierOptionValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double payoffUnit)
{
if(optionMaturity < 0) {
return 0;
}
else if(forward == optionStrike) {
return volatility * Math.sqrt(optionMaturity / Math.PI / 2.0) * payoffUnit;
}
else
{
// Calculate analytic value
double dPlus = (forward - optionStrike) / (volatility * Math.sqrt(optionMaturity));
double valueAnalytic = ((forward - optionStrike) * NormalDistribution.cumulativeDistribution(dPlus)
+ (volatility * Math.sqrt(optionMaturity)) * NormalDistribution.density(dPlus)) * payoffUnit;
return valueAnalytic;
}
}
/**
* Calculates the option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a
* normal process with constant volatility, i.e., a Bachelier model.
*
* @param forward The forward of the underlying.
* @param volatility The Bachelier volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @return Returns the value of a European call option under the Bachelier model.
*/
public static RandomVariableInterface bachelierOptionValue(
RandomVariableInterface forward,
RandomVariableInterface volatility,
double optionMaturity,
double optionStrike,
RandomVariableInterface payoffUnit)
{
if(optionMaturity < 0) {
return forward.mult(0.0);
}
else
{
RandomVariableInterface integratedVolatility = volatility.mult(Math.sqrt(optionMaturity));
RandomVariableInterface dPlus = forward.sub(optionStrike).div(integratedVolatility);
RandomVariableInterface valueAnalytic = dPlus.apply(NormalDistribution::cumulativeDistribution).mult(forward.sub(optionStrike))
.add(dPlus.apply(NormalDistribution::density).mult(integratedVolatility)).mult(payoffUnit);
return valueAnalytic;
}
}
/**
* Calculates the Bachelier option implied volatility of a call, i.e., the payoff
* <p><i>max(S(T)-K,0)</i></p>, where <i>S</i> follows a normal process with constant volatility.
*
* @param forward The forward of the underlying.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @param optionValue The option value.
* @return Returns the implied volatility of a European call option under the Bachelier model.
*/
public static double bachelierOptionImpliedVolatility(
double forward,
double optionMaturity,
double optionStrike,
double payoffUnit,
double optionValue)
{
if(forward == optionStrike) {
return optionValue / Math.sqrt(optionMaturity / Math.PI / 2.0) / payoffUnit;
}
// Limit the maximum number of iterations, to ensure this calculation returns fast, e.g. in cases when there is no such thing as an implied vol
// TODO: An exception should be thrown, when there is no implied volatility for the given value.
int maxIterations = 100;
double maxAccuracy = 0.0;
// Calculate an lower and upper bound for the volatility
double volatilityLowerBound = 0.0;
double volatilityUpperBound = (optionValue + Math.abs(forward-optionStrike)) / Math.sqrt(optionMaturity) / payoffUnit;
volatilityUpperBound /= Math.min(1.0, NormalDistribution.density((forward - optionStrike) / (volatilityUpperBound * Math.sqrt(optionMaturity))));
// Solve for implied volatility
GoldenSectionSearch solver = new GoldenSectionSearch(volatilityLowerBound, volatilityUpperBound);
while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) {
double volatility = solver.getNextPoint();
double valueAnalytic = bachelierOptionValue(forward, volatility, optionMaturity, optionStrike, payoffUnit);
double error = valueAnalytic - optionValue;
solver.setValue(error*error);
}
return solver.getBestPoint();
}
/**
* Calculate the value of a CMS option using the Black-Scholes model for the swap rate together with
* the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @param optionStrike The option strike
* @return Value of the CMS option
*/
public static double huntKennedyCMSOptionValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);
return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;
}
/**
* Calculate the value of a CMS strike using the Black-Scholes model for the swap rate together with
* the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @param optionStrike The option strike
* @return Value of the CMS strike
*/
public static double huntKennedyCMSFloorValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);
// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)
return huntKennedyCMSOptionValue + optionStrike * payoffUnit;
}
/**
* Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit
* using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @return Convexity adjusted forward rate
*/
public static double huntKennedyCMSAdjustedRate(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double rateUnadjusted = forwardSwaprate;
double rateAdjusted = forwardSwaprate * convexityAdjustment;
return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;
}
/**
* Calculated the approximation to the lognormal Black volatility using the
* standard SABR model and the standard Hagan approximation.
*
* @param alpha initial value of the stochastic volatility process of the SABR model.
* @param beta CEV parameter of the SABR model.
* @param rho Correlation (leverages) of the stochastic volatility.
* @param nu Volatility of the stochastic volatility (vol-of-vol).
* @param underlying Underlying (spot) value.
* @param strike Strike.
* @param maturity Maturity.
* @return Implied lognormal Black volatility.
*/
public static double sabrHaganLognormalBlackVolatilityApproximation(double alpha, double beta, double rho, double nu, double underlying, double strike, double maturity)
{
return sabrHaganLognormalBlackVolatilityApproximation(alpha, beta, rho, nu, 0.0, underlying, strike, maturity);
}
/**
* Calculated the approximation to the lognormal Black volatility using the
* standard SABR model and the standard Hagan approximation.
*
* @param alpha initial value of the stochastic volatility process of the SABR model.
* @param beta CEV parameter of the SABR model.
* @param rho Correlation (leverages) of the stochastic volatility.
* @param nu Volatility of the stochastic volatility (vol-of-vol).
* @param displacement The displacement parameter d.
* @param underlying Underlying (spot) value.
* @param strike Strike.
* @param maturity Maturity.
* @return Implied lognormal Black volatility.
*/
public static double sabrHaganLognormalBlackVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity)
{
if(alpha <= 0) {
throw new IllegalArgumentException("α must be greater than 0.");
}
if(rho > 1 || rho < -1) {
throw new IllegalArgumentException("ρ must be between -1 and 1.");
}
if(nu <= 0) {
throw new IllegalArgumentException("ν must be greater than 0.");
}
if(underlying <= 0) {
throw new IllegalArgumentException("Approximation not definied for non-positive underlyings.");
}
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
strike += displacement;
if(Math.abs(underlying - strike) < 0.0001 * (1+Math.abs(underlying))) {
/*
* ATM case - we assume underlying = strike
*/
double term1 = alpha / (Math.pow(underlying,1-beta));
double term2 = Math.pow(1-beta,2)/24 * Math.pow(alpha,2)/Math.pow(underlying,2*(1-beta))
+ rho*beta*alpha*nu/(4*Math.pow(underlying,1-beta))
+ (2-3*rho*rho)*nu*nu/24;
return term1 * (1+ term2 * maturity);
}
else{
/*
* General non-ATM case no prob with log(F/K)
*/
double FK = underlying * strike;
double z = nu/alpha * Math.pow(FK, (1-beta)/2) * Math.log(underlying / strike);
double x = Math.log((Math.sqrt(1- 2*rho * z + z*z) + z - rho)/(1 - rho));
double term1 = alpha / Math.pow(FK,(1-beta)/2)
/ (1 + Math.pow(1-beta,2)/24*Math.pow(Math.log(underlying/strike),2)
+ Math.pow(1-beta,4)/1920 * Math.pow(Math.log(underlying/strike),4));
double term2 = (Math.abs(x-z) < 1E-10) ? 1 : z / x;
double term3 = 1 + (Math.pow(1 - beta,2)/24 *Math.pow(alpha, 2)/Math.pow(FK, 1-beta)
+ rho*beta*nu*alpha / 4 / Math.pow(FK, (1-beta)/2)
+ (2-3*rho*rho)/24 * nu*nu) *maturity;
return term1 * term2 * term3;
}
}
/**
* Return the implied normal volatility (Bachelier volatility) under a SABR model using the
* approximation of Berestycki.
*
* @param alpha initial value of the stochastic volatility process of the SABR model.
* @param beta CEV parameter of the SABR model.
* @param rho Correlation (leverages) of the stochastic volatility.
* @param nu Volatility of the stochastic volatility (vol-of-vol).
* @param displacement The displacement parameter d.
* @param underlying Underlying (spot) value.
* @param strike Strike.
* @param maturity Maturity.
* @return The implied normal volatility (Bachelier volatility)
*/
public static double sabrBerestyckiNormalVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity)
{
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
strike += displacement;
double forwardStrikeAverage = (underlying+strike) / 2.0; // Original paper uses a geometric average here
double z;
if(beta < 1.0) z = nu / alpha * (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)) / (1.0-beta);
else z = nu / alpha * Math.log(underlying/strike);
double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho));
double term1;
if(Math.abs(underlying - strike) < 1E-10 * (1+Math.abs(underlying))) {
// ATM case - we assume underlying = strike
term1 = alpha * Math.pow(underlying, beta);
}
else {
term1 = nu * (underlying-strike) / x;
}
double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24));
return Math.max(sigma, 0.0);
}
/**
* Return the implied normal volatility (Bachelier volatility) under a SABR model using the
* approximation of Hagan.
*
* @param alpha initial value of the stochastic volatility process of the SABR model.
* @param beta CEV parameter of the SABR model.
* @param rho Correlation (leverages) of the stochastic volatility.
* @param nu Volatility of the stochastic volatility (vol-of-vol).
* @param displacement The displacement parameter d.
* @param underlying Underlying (spot) value.
* @param strike Strike.
* @param maturity Maturity.
* @return The implied normal volatility (Bachelier volatility)
*/
public static double sabrNormalVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity)
{
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
strike += displacement;
double forwardStrikeAverage = (underlying+strike) / 2.0;
double z = nu / alpha * (underlying-strike) / Math.pow(forwardStrikeAverage, beta);
double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho));
double term1;
if(Math.abs(underlying - strike) < 1E-8 * (1+Math.abs(underlying))) {
// ATM case - we assume underlying = strike
term1 = alpha * Math.pow(underlying, beta);
}
else {
double z2 = (1.0 - beta) / (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta));
term1 = alpha * z2 * z * (underlying-strike) / x;
}
double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24));
return Math.max(sigma, 0.0);
}
/**
* Return the parameter alpha (initial value of the stochastic vol process) of a SABR model using the
* to match the given at-the-money volatility.
*
* @param normalVolatility ATM volatility to match.
* @param beta CEV parameter of the SABR model.
* @param rho Correlation (leverages) of the stochastic volatility.
* @param nu Volatility of the stochastic volatility (vol-of-vol).
* @param displacement The displacement parameter d.
* @param underlying Underlying (spot) value.
* @param maturity Maturity.
* @return The implied normal volatility (Bachelier volatility)
*/
public static double sabrAlphaApproximation(double normalVolatility, double beta, double rho, double nu, double displacement, double underlying, double maturity)
{
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
// ATM case.
double forwardStrikeAverage = underlying;
double guess = normalVolatility/Math.pow(underlying, beta);
NewtonsMethod search = new NewtonsMethod(guess);
while(!search.isDone() && search.getAccuracy() > 1E-16 && search.getNumberOfIterations() < 100) {
double alpha = search.getNextPoint();
double term1 = alpha * Math.pow(underlying, beta);
double term2 = (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24));
double derivativeTerm1 = Math.pow(underlying, beta);
double derivativeTerm2 = maturity * (2*(-beta*(2-beta)*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))));
double sigma = term1 * term2;
double derivative = derivativeTerm1 * term2 + term1 * derivativeTerm2;
search.setValueAndDerivative(sigma-normalVolatility, derivative);
}
return search.getBestPoint();
}
/**
* Return the skew of the implied normal volatility (Bachelier volatility) under a SABR model using the
* approximation of Berestycki. The skew is the first derivative of the implied vol w.r.t. the strike,
* evaluated at the money.
*
* @param alpha initial value of the stochastic volatility process of the SABR model.
* @param beta CEV parameter of the SABR model.
* @param rho Correlation (leverages) of the stochastic volatility.
* @param nu Volatility of the stochastic volatility (vol-of-vol).
* @param displacement The displacement parameter d.
* @param underlying Underlying (spot) value.
* @param maturity Maturity.
* @return The skew of the implied normal volatility (Bachelier volatility)
*/
public static double sabrNormalVolatilitySkewApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double maturity)
{
double sigma = sabrBerestyckiNormalVolatilityApproximation(alpha, beta, rho, nu, displacement, underlying, underlying, maturity);
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
double a = alpha/Math.pow(underlying, 1-beta);
double c = 1.0/24*Math.pow(a, 3)*beta*(1.0-beta);
double skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying) - maturity*c*(3.0*rho*nu/a + beta - 2.0);
// Some alternative representations
// double term1dterm21 = (beta*(2-beta)*alpha*alpha*alpha)/24*Math.pow(underlying,-3.0*(1.0-beta)) * (1.0-beta);
// double term1dterm22 = beta*alpha*alpha*rho*nu / 4 * Math.pow(underlying,-2.0*(1.0-beta)) * -(1.0-beta) * 0.5;
// skew = + 1.0/2.0*sigma/underlying*(rho*nu/alpha * Math.pow(underlying, 1-beta) + beta) + maturity * (term1dterm21+term1dterm22);
// skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*3.0*c) + maturity*2.0*c*(1+beta);
// skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*c) - maturity*c*(2.0*rho*nu/a - 2.0);
// The follwoing may be used as approximations (for beta=0 the approximation is exact).
// double approximation = (rho*nu/a + beta) * (1.0/2.0*sigma/underlying);
// double residual = skew - approximation;
return skew;
}
/**
* Return the curvature of the implied normal volatility (Bachelier volatility) under a SABR model using the
* approximation of Berestycki. The curvatures is the second derivative of the implied vol w.r.t. the strike,
* evaluated at the money.
*
* @param alpha initial value of the stochastic volatility process of the SABR model.
* @param beta CEV parameter of the SABR model.
* @param rho Correlation (leverages) of the stochastic volatility.
* @param nu Volatility of the stochastic volatility (vol-of-vol).
* @param displacement The displacement parameter d.
* @param underlying Underlying (spot) value.
* @param maturity Maturity.
* @return The curvature of the implied normal volatility (Bachelier volatility)
*/
public static double sabrNormalVolatilityCurvatureApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double maturity)
{
double sigma = sabrBerestyckiNormalVolatilityApproximation(alpha, beta, rho, nu, displacement, underlying, underlying, maturity);
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
/*
double d1xdz1 = 1.0;
double d2xdz2 = rho;
double d3xdz3 = 3.0*rho*rho-1.0;
double d1zdK1 = -nu/alpha * Math.pow(underlying, -beta);
double d2zdK2 = + nu/alpha * beta * Math.pow(underlying, -beta-1.0);
double d3zdK3 = - nu/alpha * beta * (1.0+beta) * Math.pow(underlying, -beta-2.0);
double d1xdK1 = d1xdz1*d1zdK1;
double d2xdK2 = d2xdz2*d1zdK1*d1zdK1 + d1xdz1*d2zdK2;
double d3xdK3 = d3xdz3*d1zdK1*d1zdK1*d1zdK1 + 3.0*d2xdz2*d2zdK2*d1zdK1 + d1xdz1*d3zdK3;
double term1 = alpha * Math.pow(underlying, beta) / nu;
*/
double d2Part1dK2 = nu * ((1.0/3.0 - 1.0/2.0 * rho * rho) * nu/alpha * Math.pow(underlying, -beta) + (1.0/6.0 * beta*beta - 2.0/6.0 * beta) * alpha/nu*Math.pow(underlying, beta-2));
double d0BdK0 = (-1.0/24.0 *beta*(2-beta)*alpha*alpha*Math.pow(underlying, 2*beta-2) + 1.0/4.0 * beta*alpha*rho*nu*Math.pow(underlying, beta-1.0) + (2.0 -3.0*rho*rho)*nu*nu/24);
double d1BdK1 = (-1.0/48.0 *beta*(2-beta)*(2*beta-2)*alpha*alpha*Math.pow(underlying, 2*beta-3) + 1.0/8.0 * beta*(beta-1.0)*alpha*rho*nu*Math.pow(underlying, beta-2));
double d2BdK2 = (-1.0/96.0 *beta*(2-beta)*(2*beta-2)*(2*beta-3)*alpha*alpha*Math.pow(underlying, 2*beta-4) + 1.0/16.0 * beta*(beta-1)*(beta-2)*alpha*rho*nu*Math.pow(underlying, beta-3));
double curvatureApproximation = nu/alpha * ((1.0/3.0 - 1.0/2.0 * rho * rho) * sigma*nu/alpha * Math.pow(underlying, -2*beta));
double curvaturePart1 = nu/alpha * ((1.0/3.0 - 1.0/2.0 * rho * rho) * sigma*nu/alpha * Math.pow(underlying, -2*beta) + (1.0/6.0 * beta*beta - 2.0/6.0 * beta) * sigma*alpha/nu*Math.pow(underlying, -2));
double curvatureMaturityPart = (rho*nu + alpha*beta*Math.pow(underlying, beta-1))*d1BdK1 + alpha*Math.pow(underlying, beta)*d2BdK2;
return (curvaturePart1 + maturity * curvatureMaturityPart);
}
public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {
double x = lognormalVolatiltiy * Math.sqrt(maturity / 8);
double y = org.apache.commons.math3.special.Erf.erf(x);
double normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;
return normalVol;
}
/**
* Re-implementation of the Excel PRICE function (a rather primitive bond price formula).
* The re-implementation is not exact, because this function does not consider daycount conventions.
*
* @param settlementDate Valuation date.
* @param maturityDate Maturity date of the bond.
* @param coupon Coupon payment.
* @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
* @param redemption Redemption (notional repayment).
* @param frequency Frequency (1,2,4).
* @return price Clean price.
*/
public static double price(
java.util.Date settlementDate,
java.util.Date maturityDate,
double coupon,
double yield,
double redemption,
int frequency)
{
double price = 0.0;
if(maturityDate.after(settlementDate)) {
price += redemption;
}
Calendar paymentDate = Calendar.getInstance();
paymentDate.setTime(maturityDate);
while(paymentDate.after(settlementDate)) {
price += coupon;
// Discount back
price /= 1.0 + yield / frequency;
paymentDate.add(Calendar.MONTH, -12/frequency);
}
Calendar periodEndDate = (Calendar)paymentDate.clone();
periodEndDate.add(Calendar.MONTH, +12/frequency);
// Accrue running period
double accrualPeriod = (paymentDate.getTimeInMillis() - settlementDate.getTime()) / (periodEndDate.getTimeInMillis() - paymentDate.getTimeInMillis());
price *= Math.pow(1.0 + yield / frequency, accrualPeriod);
price -= coupon * accrualPeriod;
return price;
}
/**
* Re-implementation of the Excel PRICE function (a rather primitive bond price formula).
* The re-implementation is not exact, because this function does not consider daycount conventions.
* We assume we have (int)timeToMaturity/frequency future periods and the running period has
* an accrual period of timeToMaturity - frequency * ((int)timeToMaturity/frequency).
*
* @param timeToMaturity The time to maturity.
* @param coupon Coupon payment.
* @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
* @param redemption Redemption (notional repayment).
* @param frequency Frequency (1,2,4).
* @return price Clean price.
*/
public static double price(
double timeToMaturity,
double coupon,
double yield,
double redemption,
int frequency)
{
double price = 0.0;
if(timeToMaturity > 0) {
price += redemption;
}
double paymentTime = timeToMaturity;
while(paymentTime > 0) {
price += coupon;
// Discount back
price = price / (1.0 + yield / frequency);
paymentTime -= 1.0 / frequency;
}
// Accrue running period
double accrualPeriod = 0.0- paymentTime;
price *= Math.pow(1.0 + yield / frequency, accrualPeriod);
price -= coupon * accrualPeriod;
return price;
}
} |
package net.finmath.functions;
import java.util.Calendar;
import net.finmath.rootfinder.NewtonsMethod;
/**
* This class implements some functions as static class methods.
*
* It provides functions like the Black-Scholes formula,
* the inverse of the Back-Scholes formula with respect to (implied) volatility,
* the corresponding functions for caplets and swaptions.
*
* @author Christian Fries
* @version 1.8
* @date 27.04.2012
*/
public class AnalyticFormulas {
// Suppress default constructor for non-instantiability
private AnalyticFormulas() {
// This constructor will never be invoked
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a log-normal process with constant log-volatility.
*
* The method also handles cases where the forward and/or option strike is negative
* and some limit cases where the forward and/or the option strike is zero.
*
* @param forward The forward of the underlying.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @return Returns the value of a European call option under the Black-Scholes model.
*/
public static double blackScholesGeneralizedOptionValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double payoffUnit)
{
if(forward < 0) {
// We use max(X,0) = X + max(-X,0)
return (forward - optionStrike) * payoffUnit + blackScholesGeneralizedOptionValue(-forward, volatility, optionMaturity, -optionStrike, payoffUnit);
}
else if(forward == 0)
{
// Limit case (where dPlus = +/- infty)
if(optionStrike < 0) return (forward - optionStrike) * payoffUnit; // dPlus = +infinity
else if(optionStrike >= 0) return 0.0; // dPlus = -infinity
}
if((optionStrike <= 0.0) || (optionMaturity <= 0.0))
{
return Math.max(forward - optionStrike,0) * payoffUnit;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
return valueAnalytic;
}
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a log-normal process with constant log-volatility.
*
* @param initialStockValue The spot value of the underlying.
* @param riskFreeRate The risk free rate r (df = exp(-r T)).
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @return Returns the value of a European call option under the Black-Scholes model.
*/
public static double blackScholesOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
return blackScholesGeneralizedOptionValue(
initialStockValue * Math.exp(riskFreeRate * optionMaturity), // forward
volatility,
optionMaturity,
optionStrike,
Math.exp(-riskFreeRate * optionMaturity) // payoff unit
);
}
/**
* Calculates the Black-Scholes option value of an atm call option.
*
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param forward The forward, i.e., the expectation of the index under the measure associated with payoff unit.
* @param payoffUnit The payoff unit, i.e., the discount factor or the anuity associated with the payoff.
* @return Returns the value of a European at-the-money call option under the Black-Scholes model
*/
public static double blackScholesATMOptionValue(
double volatility,
double optionMaturity,
double forward,
double payoffUnit)
{
// Calculate analytic value
double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);
double dMinus = -dPlus;
double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;
return valueAnalytic;
}
/**
* Calculates the delta of a call option under a Black-Scholes model
*
* The method also handles cases where the forward and/or option strike is negative
* and some limit cases where the forward or the option strike is zero.
* In the case forward = option strike = 0 the method returns 1.0.
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the option
*/
public static double blackScholesOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(initialStockValue < 0) {
// We use Indicator(S>K) = 1 - Indicator(-S>-K)
return 1 - blackScholesOptionDelta(-initialStockValue, riskFreeRate, volatility, optionMaturity, -optionStrike);
}
else if(initialStockValue == 0)
{
// Limit case (where dPlus = +/- infty)
if(optionStrike < 0) return 1.0; // dPlus = +infinity
else if(optionStrike > 0) return 0.0; // dPlus = -infinity
else return 1.0; // Matter of definition of continuity of the payoff function
}
else if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double delta = NormalDistribution.cumulativeDistribution(dPlus);
return delta;
}
}
/**
* This static method calculated the gamma of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The gamma of the option
*/
public static double blackScholesOptionGamma(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate gamma
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double gamma = Math.exp(-0.5*dPlus*dPlus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return gamma;
}
}
/**
* This static method calculated the vega of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The vega of the option
*/
public static double blackScholesOptionVega(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate vega
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double vega = Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) * initialStockValue * Math.sqrt(optionMaturity);
return vega;
}
}
/**
* Calculates the Black-Scholes option implied volatility of a call, i.e., the payoff
* <p><i>max(S(T)-K,0)</i></p>, where <i>S</i> follows a log-normal process with constant log-volatility.
*
* @param forward The forward of the underlying.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @param optionValue The option value.
* @return Returns the implied volatility of a European call option under the Black-Scholes model.
*/
public static double blackScholesOptionImpliedVolatility(
double forward,
double optionMaturity,
double optionStrike,
double payoffUnit,
double optionValue)
{
// Limit the maximum number of iterations, to ensure this calculation returns fast, e.g. in cases when there is no such thing as an implied vol
// TODO: An exception should be thrown, when there is no implied volatility for the given value.
int maxIterations = 500;
double maxAccuracy = 1E-15;
if(optionStrike <= 0.0)
{
// Actually it is not an option
return 0.0;
}
else
{
// Calculate an lower and upper bound for the volatility
double p = NormalDistribution.inverseCumulativeDistribution((optionValue/payoffUnit+optionStrike)/(forward+optionStrike)) / Math.sqrt(optionMaturity);
double q = 2.0 * Math.abs(Math.log(forward/optionStrike)) / optionMaturity;
double volatilityLowerBound = p + Math.sqrt(Math.max(p * p - q, 0.0));
double volatilityUpperBound = p + Math.sqrt( p * p + q );
// If strike is close to forward the two bounds are close to the analytic solution
if(Math.abs(volatilityLowerBound - volatilityUpperBound) < maxAccuracy) return (volatilityLowerBound+volatilityUpperBound) / 2.0;
// Solve for implied volatility
NewtonsMethod solver = new NewtonsMethod(0.5*(volatilityLowerBound+volatilityUpperBound) /* guess */);
while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) {
double volatility = solver.getNextPoint();
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
double derivativeAnalytic = forward * Math.sqrt(optionMaturity) * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0*Math.PI) * payoffUnit;
double error = valueAnalytic - optionValue;
solver.setValueAndDerivative(error,derivativeAnalytic);
}
return solver.getBestPoint();
}
}
/**
* Calculates the Black-Scholes option value of a digital call option.
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return Returns the value of a European call option under the Black-Scholes model
*/
public static double blackScholesDigitalOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return valueAnalytic;
}
}
/**
* Calculates the delta of a digital option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the digital option
*/
public static double blackScholesDigitalOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return delta;
}
}
/**
* Calculate the value of a caplet assuming the Black'76 model.
*
* @param forward The forward (spot).
* @param volatility The Black'76 volatility.
* @param optionMaturity The option maturity
* @param optionStrike The option strike.
* @param periodLength The period length of the underlying forward rate.
* @param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
* @return Returns the value of a caplet under the Black'76 model
*/
public static double blackModelCapletValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double periodLength,
double discountFactor)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);
}
/**
* Calculate the value of a digital caplet assuming the Black'76 model.
*
* @param forward The forward (spot).
* @param volatility The Black'76 volatility.
* @param periodLength The period length of the underlying forward rate.
* @param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
* @param optionMaturity The option maturity
* @param optionStrike The option strike.
* @return Returns the price of a digital caplet under the Black'76 model
*/
public static double blackModelDgitialCapletValue(
double forward,
double volatility,
double periodLength,
double discountFactor,
double optionMaturity,
double optionStrike)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;
}
/**
* Calculate the value of a swaption assuming the Black'76 model.
*
* @param forwardSwaprate The forward (spot)
* @param volatility The Black'76 volatility.
* @param optionMaturity The option maturity.
* @param optionStrike The option strike.
* @param swapAnnuity The swap annuity corresponding to the underlying swap.
* @return Returns the value of a Swaption under the Black'76 model
*/
public static double blackModelSwaptionValue(
double forwardSwaprate,
double volatility,
double optionMaturity,
double optionStrike,
double swapAnnuity)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
}
/**
* Calculate the value of a CMS option using the Black-Scholes model for the swap rate together with
* the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @param optionStrike The option strike
* @return Value of the CMS option
*/
public static double huntKennedyCMSOptionValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);
return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;
}
/**
* Calculate the value of a CMS strike using the Black-Scholes model for the swap rate together with
* the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @param optionStrike The option strike
* @return Value of the CMS strike
*/
public static double huntKennedyCMSFloorValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);
// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)
return huntKennedyCMSOptionValue + optionStrike * payoffUnit;
}
/**
* Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit
* using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @return Convexity adjusted forward rate
*/
public static double huntKennedyCMSAdjustedRate(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double rateUnadjusted = forwardSwaprate;
double rateAdjusted = forwardSwaprate * convexityAdjustment;
return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;
}
/**
* Re-implementation of the Excel PRICE function (a rather primitive bond price formula).
* The re-implementation is not exact, because this function does not consider daycount conventions.
*
* @param settlementDate Valuation date.
* @param maturityDate Maturity date of the bond.
* @param coupon Coupon payment.
* @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
* @param redemption Redemption (notional repayment).
* @param frequency Frequency (1,2,4).
* @return price Clean price.
*/
public static double price(
java.util.Date settlementDate,
java.util.Date maturityDate,
double coupon,
double yield,
double redemption,
int frequency)
{
double price = 0.0;
if(maturityDate.after(settlementDate)) {
price += redemption;
}
Calendar paymentDate = Calendar.getInstance();
paymentDate.setTime(maturityDate);
while(paymentDate.after(settlementDate)) {
price += coupon;
// Disocunt back
price /= 1.0 + yield / frequency;
paymentDate.add(Calendar.MONTH, -12/frequency);
}
Calendar periodEndDate = (Calendar)paymentDate.clone();
periodEndDate.add(Calendar.MONTH, +12/frequency);
// Accrue running period
double accrualPeriod = (paymentDate.getTimeInMillis() - settlementDate.getTime()) / (periodEndDate.getTimeInMillis() - paymentDate.getTimeInMillis());
price *= Math.pow(1.0 + yield / frequency, accrualPeriod);
price -= coupon * accrualPeriod;
return price;
}
/**
* Re-implementation of the Excel PRICE function (a rather primitive bond price formula).
* The re-implementation is not exact, because this function does not consider daycount conventions.
* We assume we have (int)timeToMaturity/frequency future periods and the running period has
* an accrual period of timeToMaturity - frequency * ((int)timeToMaturity/frequency).
*
* @param timeToMaturity The time to maturity.
* @param coupon Coupon payment.
* @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
* @param redemption Redemption (notional repayment).
* @param frequency Frequency (1,2,4).
* @return price Clean price.
*/
public static double price(
double timeToMaturity,
double coupon,
double yield,
double redemption,
int frequency)
{
double price = 0.0;
if(timeToMaturity > 0) {
price += redemption;
}
double paymentTime = timeToMaturity;
while(paymentTime > 0) {
price += coupon;
// Discount back
price = price / (1.0 + yield / frequency);
paymentTime -= 1.0 / frequency;
}
// Accrue running period
double accrualPeriod = 0.0- paymentTime;
price *= Math.pow(1.0 + yield / frequency, accrualPeriod);
price -= coupon * accrualPeriod;
return price;
}
} |
package net.glowstone.io.entity;
import net.glowstone.entity.objects.GlowItemFrame;
import net.glowstone.io.nbt.NbtSerialization;
import net.glowstone.util.nbt.CompoundTag;
import org.bukkit.Location;
class ItemFrameStore extends EntityStore<GlowItemFrame> {
public ItemFrameStore() {
super(GlowItemFrame.class, "ItemFrame");
}
public GlowItemFrame createEntity(Location location, CompoundTag compound) {
// item frame will be set by loading code below
return new GlowItemFrame(null, location, null);
}
@Override
public void load(GlowItemFrame entity, CompoundTag tag) {
super.load(entity, tag);
if (tag.isInt("Facing")) {
entity.setFacingDirectionNumber((tag.getInt("Facing")));
}
if (tag.isCompound("Item")) {
entity.setItemInFrame(NbtSerialization.readItem(tag.getCompound("Item")));
}
if (tag.isInt("Rotation")) {
entity.setRotationAngle((tag.getInt("Rotation") * 45));
}
}
@Override
public void save(GlowItemFrame entity, CompoundTag tag) {
super.save(entity, tag);
tag.putInt("Facing", entity.getFacingNumber());
tag.putCompound("Item", NbtSerialization.writeItem(entity.getItem(), -1));
tag.putInt("Rotation", (int) entity.getRotationAngle() / 45);
}
} |
package components;
import java.awt.Insets;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
/**
* TreeComponent
* @author Fernanda Floriano Silva
*/
public class TreeComponent extends JPanel {
// private String selectedDir;
public static final Insets defaultScrollInsets = new Insets(8, 8, 8, 8);
protected Insets scrollInsets = defaultScrollInsets;
/**
* Construct Tree
* @param tree
* @param dir
* @param scrollPane
* @param name
*/
public void constructTree(JTree tree, File dir, JScrollPane scrollPane, String name) throws SecurityException, FileNotFoundException {
setFeatures(scrollPane, name, dir, tree);
addTree(tree, dir.getAbsoluteFile(), scrollPane, name, dir.getName());
selectNode(dir, tree);
}
/**
* Select Node
* @param dir
* @param tree
*/
private void selectNode(File dir, JTree tree) {
tree.setSelectionRow(tree.getRowForPath(tree.getNextMatch(dir.getName().trim(), 0, Position.Bias.Forward)));
tree.scrollRowToVisible(tree.getRowForPath(tree.getNextMatch(dir.getName().trim(), 0, Position.Bias.Forward)));
}
/**
* Set Features
* @param scrollPane
* @param name
* @param dir
* @param tree
*/
private void setFeatures(JScrollPane scrollPane, String name, File dir, JTree tree) {
scrollPane.setBorder(BorderFactory.createTitledBorder(name + "(" + dir.getName() + ")"));
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
}
/**
* Add Tree
* @param tree
* @param dir
* @param scrollPane
* @param name
* @param fileName
*/
public void addTree(JTree tree, File dir, JScrollPane scrollPane, String name, String fileName) throws SecurityException, FileNotFoundException {
FileTreeNode rootNode = new FileTreeNode(null, dir.getParent());
// Populate the root node with its subdirectories
boolean addedNodes = rootNode.populateDirectories(true);
tree.setModel(new DefaultTreeModel(rootNode));
// Listen for Tree Selection Events
tree.addTreeExpansionListener(new TreeExpansionHandler());
}
// Returns the full pathname for a path, or null if not a known path
public String getPathName(TreePath path) {
Object o = path.getLastPathComponent();
if (o instanceof FileTreeNode) {
return ((FileTreeNode) o).fullName;
}
return null;
}
// Adds a new node to the tree after construction.
// Returns the inserted node, or null if the parent
// directory has not been expanded.
public FileTreeNode addNode(FileTreeNode parent, String name, JTree tree) {
int index = parent.addNode(name);
if (index != -1) {
((DefaultTreeModel) tree.getModel()).nodesWereInserted(parent,
new int[]{index});
return (FileTreeNode) parent.getChildAt(index);
}
// No node was created
return null;
}
// Autoscrolling support
public void setScrollInsets(Insets insets) {
this.scrollInsets = insets;
}
public Insets getScrollInsets() {
return scrollInsets;
}
// Inner class that represents a node in this file system tree
public static class FileTreeNode extends DefaultMutableTreeNode {
public FileTreeNode(String parent, String name)
throws SecurityException, FileNotFoundException {
this.name = name;
// See if this node exists and whether it is a directory
fullName = parent == null ? name : parent + File.separator + name;
File f = new File(fullName);
if (f.exists() == false) {
throw new FileNotFoundException("File " + fullName
+ " does not exist");
}
isDir = f.isDirectory();
// Hack for Windows which doesn't consider a drive to be a
// directory!
if (isDir == false && f.isFile() == false) {
isDir = true;
}
}
// Override isLeaf to check whether this is a directory
@Override
public boolean isLeaf() {
return !isDir;
}
// Override getAllowsChildren to check whether this is a directory
@Override
public boolean getAllowsChildren() {
return isDir;
}
// Return whether this is a directory
public boolean isDir() {
return isDir;
}
// Get full path
public String getFullName() {
return fullName;
}
// For display purposes, we return our own name
@Override
public String toString() {
return name;
}
// If we are a directory, scan our contents and populate
// with children. In addition, populate those children
// if the "descend" flag is true. We only descend once,
// to avoid recursing the whole subtree.
// Returns true if some nodes were added
boolean populateDirectories(boolean descend) {
boolean addedNodes = false;
// Do this only once
if (populated == false) {
File f;
try {
f = new File(fullName);
} catch (SecurityException e) {
populated = true;
return false;
}
if (interim == true) {
// We have had a quick look here before:
// remove the dummy node that we added last time
removeAllChildren();
interim = false;
}
String[] names = f.list(); // Get list of contents
// Process the contents
ArrayList list = new ArrayList();
if (names != null) {
for (int i = 0; i < names.length; i++) {
String nameLocal = names[i];
File d = new File(fullName, nameLocal);
try {
FileTreeNode node = new FileTreeNode(fullName, nameLocal);
list.add(node);
if (descend && d.isDirectory()) {
node.populateDirectories(false);
}
addedNodes = true;
if (descend == false) {
// Only add one node if not descending
break;
}
} catch (Throwable t) {
// Ignore phantoms or access problems
}
}
}
if (addedNodes == true) {
// Now sort the list of contained files and directories
Object[] nodes = list.toArray();
Arrays.sort(nodes, new Comparator() {
@Override
public boolean equals(Object o) {
return false;
}
@Override
public int compare(Object o1, Object o2) {
FileTreeNode node1 = (FileTreeNode) o1;
FileTreeNode node2 = (FileTreeNode) o2;
// Directories come first
if (node1.isDir != node2.isDir) {
return node1.isDir ? -1 : +1;
}
// Both directories or both files -
// compare based on pathname
return node1.fullName.compareTo(node2.fullName);
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
});
// Add sorted items as children of this node
for (int j = 0; j < nodes.length; j++) {
this.add((FileTreeNode) nodes[j]);
}
}
// If we were scanning to get all subdirectories,
// or if we found no content, there is no
// reason to look at this directory again, so
// set populated to true. Otherwise, we set interim
// so that we look again in the future if we need to
if (descend == true || addedNodes == false) {
populated = true;
} else {
// Just set interim state
interim = true;
}
}
return addedNodes;
}
// Adding a new file or directory after
// constructing the FileTree. Returns
// the index of the inserted node.
public int addNode(String name) {
// If not populated yet, do nothing
if (populated == true) {
// Do not add a new node if
// the required node is already there
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
FileTreeNode node = (FileTreeNode) getChildAt(i);
if (node.name.equals(name)) {
// Already exists - ensure
// we repopulate
if (node.isDir()) {
node.interim = true;
node.populated = false;
}
return -1;
}
}
// Add a new node
try {
FileTreeNode node = new FileTreeNode(fullName, name);
add(node);
return childCount;
} catch (Exception e) {
}
}
return -1;
}
protected String name; // Name of this component
protected String fullName; // Full pathname
protected boolean populated;// true if we have been populated
protected boolean interim; // true if we are in interim state
protected boolean isDir; // true if this is a directory
}
// Inner class that handles Tree Expansion Events
protected class TreeExpansionHandler implements TreeExpansionListener {
@Override
public void treeExpanded(TreeExpansionEvent evt) {
TreePath path = evt.getPath(); // The expanded path
JTree tree = (JTree) evt.getSource(); // The tree
// Get the last component of the path and
// arrange to have it fully populated.
FileTreeNode node = (FileTreeNode) path.getLastPathComponent();
if (node.populateDirectories(true)) {
((DefaultTreeModel) tree.getModel()).nodeStructureChanged(node);
}
}
@Override
public void treeCollapsed(TreeExpansionEvent evt) {
// Nothing to do
}
}
}
class FileListTransferable implements Transferable {
public FileListTransferable(File[] files) {
fileList = new ArrayList();
fileList.addAll(Arrays.asList(files));
}
// Implementation of the Transferable interface
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.javaFileListFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor fl) {
return fl.equals(DataFlavor.javaFileListFlavor);
}
@Override
public Object getTransferData(DataFlavor fl) {
if (!isDataFlavorSupported(fl)) {
return null;
}
return fileList;
}
List fileList; // The list of files
} |
package net.tridentsdk.server;
import net.tridentsdk.api.Trident;
import net.tridentsdk.api.reflect.FastClass;
import net.tridentsdk.api.scheduling.Scheduler;
import net.tridentsdk.api.scheduling.TridentRunnable;
import net.tridentsdk.plugin.TridentPlugin;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class TridentScheduler implements Scheduler {
private final Map<RunnableWrapper, AtomicLong> asyncTasks = new ConcurrentHashMap<>();
private final Map<RunnableWrapper, AtomicLong> syncTasks = new ConcurrentHashMap<>();
// basically a thread pool that has an entry for a thread, and the number of plugins assigned to it
private final Map<ExecutorService, AtomicInteger> threads = new ConcurrentHashMap<>();
private final Map<TridentPlugin, ExecutorService> threadAssignments = new ConcurrentHashMap<>();
private final Collection<Integer> cancelledId = new CopyOnWriteArraySet<>();
private final Map<Future<?>, RunnableWrapper> asyncReturns = new ConcurrentHashMap<>();
private final Collection<Map.Entry<Future<?>, String>> syncReturns = new HashSet<>();
private int currentId;
public TridentScheduler() {
// use two for now, can be more later
this.threads.put(Executors.newSingleThreadExecutor(), new AtomicInteger(0));
this.threads.put(Executors.newSingleThreadExecutor(), new AtomicInteger(0));
}
private ExecutorService getMostUsed() {
return Collections.max(this.threads.entrySet(),
new Comparator<Map.Entry<ExecutorService, AtomicInteger>>(){
@Override
public int compare(Map.Entry<ExecutorService, AtomicInteger> o1,
Map.Entry<ExecutorService, AtomicInteger> o2){
return o1.getValue().get() - o2.getValue().get();
}
}).getKey();
}
private void addUse(ExecutorService service) {
this.threads.get(service).incrementAndGet();
}
private ExecutorService getCachedAssignment(TridentPlugin plugin) {
if (this.threadAssignments.containsKey(plugin)) {
return this.threadAssignments.get(plugin);
} else {
ExecutorService retVal = this.getMostUsed();
this.addUse(retVal);
this.threadAssignments.put(plugin, retVal);
return retVal;
}
}
@Override
public TridentRunnable runTaskAsynchronously(TridentPlugin plugin, TridentRunnable runnable) {
synchronized (this) {
this.assignId(runnable);
this.executeAsync(new RunnableWrapper(runnable, plugin));
return runnable;
}
}
@Override
public TridentRunnable runTaskSynchronously(TridentPlugin plugin, TridentRunnable runnable) {
synchronized (this) {
this.assignId(runnable);
this.syncTasks.put(new RunnableWrapper(runnable, plugin), new AtomicLong(0L));
return runnable;
}
}
@Override
public TridentRunnable runTaskAsyncLater(TridentPlugin plugin, TridentRunnable runnable, long delay) {
synchronized (this) {
this.assignId(runnable);
this.asyncTasks.put(new RunnableWrapper(runnable, plugin), new AtomicLong(delay));
return runnable;
}
}
@Override
public TridentRunnable runTaskSyncLater(TridentPlugin plugin, TridentRunnable runnable, long delay) {
synchronized (this) {
this.assignId(runnable);
this.syncTasks.put(new RunnableWrapper(runnable, plugin), new AtomicLong(delay));
return runnable;
}
}
@Override
public TridentRunnable runTaskAsyncRepeating(TridentPlugin plugin, TridentRunnable runnable,
long delay, long initialInterval) {
synchronized (this) {
this.assignId(runnable);
this.syncTasks.put(new RunnableWrapper(runnable, plugin, true), new AtomicLong(initialInterval));
return null;
}
}
@Override
public TridentRunnable runTaskSyncRepeating(TridentPlugin plugin, TridentRunnable runnable,
long delay, long initialInterval) {
synchronized (this) {
this.assignId(runnable);
this.asyncTasks.put(new RunnableWrapper(runnable, plugin, true), new AtomicLong(initialInterval));
return null;
}
}
@Override
public void cancel(int id) {
this.cancelledId.add(id);
}
@Override
public void cancel(TridentRunnable runnable) {
this.cancelledId.add(runnable.getId());
}
/**
* Called when the server ticks, the lifeblood of this class, should only be called on the main thread unless you
* want difficulties
*/
public void tick() {
for (Map.Entry<Future<?>, RunnableWrapper> entry : this.asyncReturns.entrySet()) {
if (entry.getKey().isDone()) {
entry.getValue().getRunnable().runAfterSync();
this.asyncReturns.remove(entry.getKey());
}
}
for (Map.Entry<RunnableWrapper, AtomicLong> entry : this.asyncTasks.entrySet()) {
if (this.cancelledId.contains(entry.getKey().getRunnable().getId())) {
this.asyncTasks.remove(entry.getKey());
continue;
}
long time = entry.getValue().decrementAndGet();
if (time <= 0L) {
RunnableWrapper wrapper = entry.getKey();
this.executeAsync(wrapper);
this.asyncTasks.remove(wrapper);
if (wrapper.isRepeating()) {
this.asyncTasks.put(wrapper, new AtomicLong(wrapper.getRunnable().getInterval()));
}
}
}
for (Map.Entry<RunnableWrapper, AtomicLong> entry : this.syncTasks.entrySet()) {
if (this.cancelledId.contains(entry.getKey().getRunnable().getId())) {
this.syncTasks.remove(entry.getKey());
continue;
}
long time = entry.getValue().decrementAndGet();
if (time <= 0L) {
RunnableWrapper wrapper = entry.getKey();
this.executeSync(wrapper, false);
this.syncTasks.remove(wrapper);
if (wrapper.isRepeating()) {
this.syncTasks.put(wrapper, new AtomicLong(wrapper.getRunnable().getInterval()));
}
}
}
}
private void executeAsync(RunnableWrapper wrapper) {
wrapper.getRunnable().prerunSync();
final TridentRunnable runnable = wrapper.getRunnable();
this.asyncReturns.put(this.getCachedAssignment(wrapper.getPlugin()).submit(new Callable() {
@Override
public Object call() throws Exception {
runnable.run();
runnable.runAfterAsync();
return null;
}
}), wrapper);
}
private void executeSync(RunnableWrapper wrapper, boolean addToSync) {
wrapper.getRunnable().prerunSync();
wrapper.getRunnable().run();
wrapper.getRunnable().runAfterSync();
final TridentRunnable runnable = wrapper.getRunnable();
Future<?> future = this.getCachedAssignment(wrapper.getPlugin()).submit(new Callable() {
@Override
public Object call() throws Exception {
runnable.runAfterAsync();
return null;
}
});
if (addToSync) {
this.syncReturns.add(new AbstractMap.SimpleEntry<Future<?>, String>(future,
wrapper.getPlugin().getDescription().name()));
}
}
/**
* Uses fast reflection to assign an ID to each runnable, that way there is no publicly exposed "setId()" that could
* break things
*/
private void assignId(TridentRunnable runnable) {
FastClass.get(TridentRunnable.class).getField(runnable, "id").set(this.currentId);
this.currentId++;
}
public void shutdown() {
if (Trident.getServer().getConfig().getBoolean("in-a-hurry-mode")) {
for (Map.Entry<RunnableWrapper, AtomicLong> entry : this.asyncTasks.entrySet()) {
if (entry.getKey().getRunnable().usesInAHurry()) {
FastClass.get(TridentRunnable.class).getField(entry.getKey().getRunnable(), "inAHurry").set(true);
this.executeAsync(entry.getKey());
}
}
for (Map.Entry<RunnableWrapper, AtomicLong> entry : this.syncTasks.entrySet()) {
if (entry.getKey().getRunnable().usesInAHurry()) {
FastClass.get(TridentRunnable.class).getField(entry.getKey().getRunnable(), "inAHurry").set(true);
this.executeSync(entry.getKey(), true);
}
}
for (Map.Entry<Future<?>, String> future : this.syncReturns) {
try {
future.getKey().get(3L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignored exception
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
Trident.getLogger().warning("Runnable from " + future.getValue()
+ " took more than 3 seconds in a hurry, going ahead with cancellation!");
}
}
for (Map.Entry<Future<?>, RunnableWrapper> entry : this.asyncReturns.entrySet()) {
try {
entry.getKey().get(3L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
// ignored exception
} catch (TimeoutException e) {
Trident.getLogger().warning("Runnable from " + entry.getValue().getPlugin().getDescription().name()
+ " took more than 3 seconds in a hurry, going ahead with cancellation!");
}
}
for (Map.Entry<Future<?>, RunnableWrapper> entry : this.asyncReturns.entrySet()) {
if (entry.getKey().isDone()) {
entry.getValue().getRunnable().runAfterSync();
this.asyncReturns.remove(entry.getKey());
}
}
}
for (Map.Entry<ExecutorService, AtomicInteger> entry : this.threads.entrySet()) {
entry.getKey().shutdownNow();
}
}
private class RunnableWrapper {
private final TridentRunnable runnable;
private final TridentPlugin plugin;
private final boolean repeating;
private RunnableWrapper(TridentRunnable runnable, TridentPlugin plugin) {
this(runnable, plugin, false);
}
private RunnableWrapper(TridentRunnable runnable, TridentPlugin plugin, boolean repeating) {
this.plugin = plugin;
this.runnable = runnable;
this.repeating = repeating;
}
public boolean isRepeating() {
return this.repeating;
}
public TridentRunnable getRunnable() {
return this.runnable;
}
public TridentPlugin getPlugin() {
return this.plugin;
}
}
} |
package org.amc.servlet.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.amc.servlet.model.JobTemplate;
public class JobTemplateDAOImpl extends BasicDAO implements JobTemplateDAO
{
private static String tablename="jobtemplate";
/* (non-Javadoc)
* @see org.amc.servlet.dao.JobTemplateDAO#addJobTemplate(org.amc.servlet.model.JobTemplate)
*/
@Override
public void addJobTemplate(JobTemplate job) throws SQLException
{
//id,name,company,colour,external,part_id,qss_no, revision,version
Connection connection=getConnection();
PreparedStatement statement=connection.prepareStatement("INSERT INTO "+tablename+" VALUES(NULL,?,?,?,?,?,?,?,?)");
statement.setString(1, job.getName());
statement.setString(2, job.getCompany());
statement.setString(3, job.getColour());
statement.setBoolean(4, job.getExternal());
statement.setString(5, job.getPart_id());
statement.setString(6, job.getQss_no());
statement.setString(7, job.getRevision());
statement.setString(8, job.getVersion());
statement.executeUpdate();
closeDBObjects(null, statement, connection);
}
/* (non-Javadoc)
* @see org.amc.servlet.dao.JobTemplateDAO#updateJobTemplate(org.amc.servlet.model.JobTemplate)
*/
@Override
public void updateJobTemplate(JobTemplate job) throws SQLException
{
//id,name,company,colour,external,part_id,qss_no, revision,version
Connection connection=getConnection();
PreparedStatement statement=connection.prepareStatement("UPDATE "+tablename+" set name=?,"
+ "company=?,"
+ "colour=?,"
+ "external=?,"
+ "part_id=?,"
+ "qss_no=?,"
+ "revision=?,"
+ "version=? where id=?");
statement.setString(1, job.getName());
statement.setString(2, job.getCompany());
statement.setString(3, job.getColour());
statement.setBoolean(4, job.getExternal());
statement.setString(5, job.getPart_id());
statement.setString(6, job.getQss_no());
statement.setString(7, job.getRevision());
statement.setString(8, job.getVersion());
statement.setString(9, String.valueOf(job.getId()));
statement.executeUpdate();
closeDBObjects(null, statement, connection);
}
/* (non-Javadoc)
* @see org.amc.servlet.dao.JobTemplateDAO#deleteJobTemplate(org.amc.servlet.model.JobTemplate)
*/
@Override
public void deleteJobTemplate(JobTemplate job)
{
}
/* (non-Javadoc)
* @see org.amc.servlet.dao.JobTemplateDAO#getJobTemplate(int)
*/
@Override
public JobTemplate getJobTemplate(String jobTemplateId) throws SQLException
{
Connection connection=getConnection();
PreparedStatement statement=connection.prepareStatement("select * from "+tablename+" where id=?;");
statement.setString(1, jobTemplateId);
ResultSet rs=statement.executeQuery();
JobTemplate tempJob=null;
if(rs.next())
{
tempJob=getJobTemplate(rs);
}
closeDBObjects(rs, statement, connection);
return tempJob;
}
/* (non-Javadoc)
* @see org.amc.servlet.dao.JobTemplateDAO#findJobTemplates(java.lang.String, java.lang.String)
*/
@Override
public List<JobTemplate> findJobTemplates(String col,String value) throws SQLException
{
Connection connection=getConnection();
PreparedStatement statement=connection.prepareStatement("select * from "+tablename+" where "+col+" REGEXP ?;");
statement.setString(1, value);
ResultSet rs=statement.executeQuery();
List<JobTemplate> list=new ArrayList<JobTemplate>();
while(rs.next())
{
JobTemplate tempJob=getJobTemplate(rs);
list.add(tempJob);
}
closeDBObjects(rs, statement, connection);
return list;
}
@Override
public List<JobTemplate> findJobTemplates() throws SQLException
{
Connection connection=getConnection();
Statement statement=connection.createStatement();
ResultSet rs=statement.executeQuery("select * from "+tablename+";");
List<JobTemplate> list=new ArrayList<JobTemplate>();
while(rs.next())
{
JobTemplate tempJob=getJobTemplate(rs);
list.add(tempJob);
}
closeDBObjects(rs, statement, connection);
return list;
}
//Don't call next or close the ResultSet
private JobTemplate getJobTemplate(ResultSet rs) throws SQLException
{
JobTemplate tempJob=new JobTemplate(
rs.getString("name"),
rs.getString("part_id"),
rs.getString("company"),
rs.getString("version"),
rs.getString("revision"),
rs.getString("colour"),
rs.getBoolean("external"),
rs.getString("qss_no")
);
tempJob.setId(rs.getInt("ID"));
return tempJob;
}
} |
package org.asteriskjava.tools;
import org.asteriskjava.live.DefaultAsteriskServer;
import org.asteriskjava.manager.ManagerEventListener;
import org.asteriskjava.manager.event.*;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A diagnostic tool that creates an HTML file showing the state changing events
* received from Asterisk on the Manager API.<p>
* The following events are shown:
* <ul>
* <li>NewChannel</li>
* <li>NewState</li>
* <li>Rename</li>
* <li>Dial</li>
* <li>Bridge (Link and Unlink)</li>
* <li>Hangup</li>
* </ul>
* Usage: java org.asteriskjava.tools.HtmlEventTracer host username password
*
* @version $Id$
*/
public class HtmlEventTracer implements ManagerEventListener
{
private String filename = "trace.html";
private PrintWriter writer;
private final List<String> uniqueIds;
private final List<ManagerEvent> events;
private final Map<Class<? extends ManagerEvent>, String> colors;
public HtmlEventTracer()
{
uniqueIds = new ArrayList<String>();
events = new ArrayList<ManagerEvent>();
colors = new HashMap<Class<? extends ManagerEvent>, String>();
colors.put(NewChannelEvent.class, "#7cd300"); // green
colors.put(NewStateEvent.class, "#a4b6c8");
colors.put(NewExtenEvent.class, "#efefef"); // grey
colors.put(RenameEvent.class, "#ddeeff"); // light blue
colors.put(DialEvent.class, "#feec30"); // yellow
colors.put(BridgeEvent.class, "#fff8ae"); // light yellow
colors.put(HangupEvent.class, "#ff6c17"); // orange
try
{
writer = new PrintWriter(filename);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
if (args.length != 3)
{
System.err.println("Usage: java org.asteriskjava.tools.HtmlEventTracer host username password");
System.exit(1);
}
final HtmlEventTracer tracer;
final DefaultAsteriskServer server;
tracer = new HtmlEventTracer();
server = new DefaultAsteriskServer(args[0], args[1], args[2]);
server.initialize();
server.getManagerConnection().addEventListener(tracer);
System.err.println("Event tracer successfully started. Press Ctrl-C to write trace file and exit.");
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
tracer.write();
server.shutdown();
}
}
);
while(true)
{
Thread.sleep(1000);
}
}
public void onManagerEvent(ManagerEvent event)
{
events.add(event);
System.out.println("> " + event);
for (String property : new String[]{"uniqueId", "uniqueId1", "uniqueId2", "srcUniqueId", "destUniqueId"})
{
String uniqueId;
uniqueId = getProperty(event, property);
if (uniqueId != null && !uniqueIds.contains(uniqueId))
{
uniqueIds.add(uniqueId);
}
}
}
public void write()
{
writer.append("<table border='1'><tr><td> </td>");
for (String uniqueId : uniqueIds)
{
writer.append("<td><font size='-2'>");
writer.append(uniqueId.substring(0, uniqueId.lastIndexOf('.') + 1));
writer.append("</font>");
writer.append(uniqueId.substring(uniqueId.lastIndexOf('.') + 1, uniqueId.length()));
writer.append("</td>");
}
writer.append("</tr>");
writer.println("");
for (ManagerEvent event : events)
{
boolean print = false;
StringBuilder line = new StringBuilder();
line.append("<tr><td>");
line.append(event.getClass().getSimpleName());
line.append("<br><font size='-2'>");
line.append(event.getDateReceived());
line.append("</font></td>");
for (String uniqueId : uniqueIds)
{
String text;
text = getText(uniqueId, event);
if (text == null)
{
line.append("<td> </td>");
}
else
{
String color = getColor(event.getClass());
line.append("<td bgcolor='").append(color).append("'><tt>").append(text).append("</tt></td>");
print = true;
}
}
line.append("</tr>");
if (print)
{
writer.println(line.toString());
}
}
writer.append("</table>");
writer.close();
System.err.println("Trace file successfully written to " + filename + ".");
}
private String getColor(Class<? extends ManagerEvent> clazz)
{
for (Map.Entry<Class<? extends ManagerEvent>, String> entry : colors.entrySet())
{
if (entry.getKey().isAssignableFrom(clazz))
{
return entry.getValue();
}
}
return "#ffffff";
}
protected String getProperty(Object obj, String property)
{
try
{
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors())
{
if (!propertyDescriptor.getName().equals(property))
{
continue;
}
final Object o = propertyDescriptor.getReadMethod().invoke(obj);
return o != null ? o.toString() : null;
}
}
catch (Exception e)
{
System.err.println("Unable to read property '" + property + "' from object " + obj + ": " + e.getMessage());
return null;
}
return null;
}
protected String getText(String uniqueId, ManagerEvent event)
{
String format = null;
String[] properties = null;
if (uniqueId.equals(getProperty(event, "uniqueId")))
{
if (event instanceof NewChannelEvent)
{
format = "%s<br>%s";
properties = new String[]{"channel", "state"};
}
else if (event instanceof NewStateEvent)
{
format = "%s<br>%s";
properties = new String[]{"channel", "state"};
}
else if (event instanceof NewExtenEvent)
{
format = "%s,%s,%s<br>%s(%s)";
properties = new String[]{"context", "extension", "priority", "application", "appData"};
}
else if (event instanceof RenameEvent)
{
format = "old: %s<br>new: %s";
properties = new String[]{"oldname", "newname"};
}
else if (event instanceof HoldEvent)
{
format = "%s";
properties = new String[]{"status"};
}
else if (event instanceof AbstractParkedCallEvent)
{
format = "exten: %s<br>from: %s";
properties = new String[]{"exten", "from"};
}
else if (event instanceof HangupEvent)
{
format = "%s<br>%s (%s)";
properties = new String[]{"channel", "cause", "causeTxt"};
}
}
if (event instanceof BridgeEvent)
{
if (uniqueId.equals(getProperty(event, "uniqueId1")))
{
format = "%s<br>%s<br>%s";
properties = new String[]{"uniqueId2", "channel2", "bridgeState"};
}
else if (uniqueId.equals(getProperty(event, "uniqueId2")))
{
format = "%s<br>%s<br>%s";
properties = new String[]{"uniqueId1", "channel1", "bridgeState"};
}
}
if (event instanceof DialEvent)
{
if (uniqueId.equals(getProperty(event, "srcUniqueId")))
{
format = "To: %s";
properties = new String[]{"destination"};
}
else if (uniqueId.equals(getProperty(event, "destUniqueId")))
{
format = "From: %s";
properties = new String[]{"src"};
}
}
if (format != null)
{
String[] args = new String[properties.length];
for (int i = 0; i < properties.length; i++)
{
String value;
value = getProperty(event, properties[i]);
if (value == null)
{
args[i] = "";
}
else
{
value = value.replace("<", "<");
value = value.replace(">", ">");
args[i] = value;
}
}
return String.format(format, (Object[]) args);
}
return null;
}
} |
package org.hive.weChat.entity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hive.common.pay.PayConfig;
import org.hive.common.util.HttpKit;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* <p>
*
*
* @author Dax
* @version v1.0.0
* @since 2017/7/17 15:06
*/
public final class WeChatPayConfig implements PayConfig {
private static final Log log = LogFactory.getLog(WeChatPayConfig.class);
private static final String PROPERTY_PLACEHOLDER = "weChatConfig.properties";
private static final ThreadLocal<WeChatPayConfig> WE_CHAT_PAY_CONFIG_THREAD_LOCAL = new ThreadLocal<>();
// APPID
private String appid;
private String secretKey;
private String mch_id;
private String notify_url;
// MD5
private String sign_type;
private WeChatPayConfig() {
log.info(" " + PROPERTY_PLACEHOLDER);
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(PROPERTY_PLACEHOLDER);
try {
Properties properties = new Properties();
properties.load(inputStream);
this.appid = properties.getProperty("appid");
this.mch_id = properties.getProperty("mch_id");
this.secretKey = properties.getProperty("secretKey");
this.notify_url = properties.getProperty("notify_url");
this.sign_type = properties.getProperty("sign_type");
} catch (IOException e) {
log.debug(" " + PROPERTY_PLACEHOLDER + " ", e);
} finally {
HttpKit.close(inputStream);
}
}
public static PayConfig initBaseConfig() {
if (WE_CHAT_PAY_CONFIG_THREAD_LOCAL.get() == null) {
synchronized (WeChatPayConfig.class) {
if (WE_CHAT_PAY_CONFIG_THREAD_LOCAL.get() == null) {
WeChatPayConfig weChatPayConfig = new WeChatPayConfig();
WE_CHAT_PAY_CONFIG_THREAD_LOCAL.set(weChatPayConfig);
return weChatPayConfig;
}
}
}
return WE_CHAT_PAY_CONFIG_THREAD_LOCAL.get();
}
@Override
public String getAppid() {
return appid;
}
@Override
public String getMch_id() {
return mch_id;
}
@Override
public String getSecretKey() {
return secretKey;
}
@Override
public String getNotify_url() {
return notify_url;
}
@Override
public String getSign_type() {
return sign_type;
}
} |
package org.irmacard.cardemu;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.sf.scuba.smartcards.CardServiceException;
import org.irmacard.credentials.Attributes;
import org.irmacard.credentials.CredentialsException;
import org.irmacard.credentials.idemix.IdemixCredential;
import org.irmacard.credentials.idemix.IdemixCredentials;
import org.irmacard.credentials.idemix.proofs.ProofList;
import org.irmacard.credentials.idemix.proofs.ProofListBuilder;
import org.irmacard.credentials.idemix.smartcard.IRMACard;
import org.irmacard.credentials.idemix.smartcard.IRMAIdemixCredential;
import org.irmacard.credentials.idemix.smartcard.SmartCardEmulatorService;
import org.irmacard.credentials.info.CredentialDescription;
import org.irmacard.credentials.info.DescriptionStore;
import org.irmacard.credentials.info.InfoException;
import org.irmacard.credentials.util.log.LogEntry;
import org.irmacard.credentials.util.log.RemoveLogEntry;
import org.irmacard.credentials.util.log.VerifyLogEntry;
import org.irmacard.idemix.IdemixService;
import org.irmacard.verification.common.AttributeDisjunction;
import org.irmacard.verification.common.AttributeIdentifier;
import org.irmacard.verification.common.DisclosureProofRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.*;
/**
* Handles issuing, disclosing, and deletion of credentials; keeps track of log entries; and handles (de)
* serialization of credentials and log entries from/to storage.
*/
@SuppressWarnings("unused")
public class CredentialManager {
private static HashMap<Short, IRMAIdemixCredential> credentials = new HashMap<>();
private static List<LogEntry> logs = new LinkedList<>();
// Type tokens for Gson (de)serialization
private static Type credentialsType = new TypeToken<HashMap<Short, IRMAIdemixCredential>>() {}.getType();
private static Type logsType = new TypeToken<List<LogEntry>>() {}.getType();
private static SharedPreferences settings;
private static final String TAG = "CredentialManager";
private static final String CREDENTIAL_STORAGE = "credentials";
private static final String LOG_STORAGE = "logs";
public static void init(SharedPreferences s) {
settings = s;
}
/**
* Extract credentials and logs from an IRMACard instance retrieved from storage.
*/
@SuppressWarnings("unchecked")
public static void loadFromCard() {
Log.i(TAG, "Loading credentials from card");
IRMACard card = CardManager.loadCard();
try {
Field f = card.getClass().getDeclaredField("credentials");
f.setAccessible(true);
credentials = (HashMap<Short, IRMAIdemixCredential>) f.get(card);
} catch (NoSuchFieldException|IllegalAccessException|ClassCastException e) {
e.printStackTrace();
}
try {
IdemixService is = new IdemixService(new SmartCardEmulatorService(card));
is.open();
is.sendCardPin("000000".getBytes());
logs = new IdemixCredentials(is).getLog();
} catch (CardServiceException|InfoException e) {
e.printStackTrace();
}
}
/**
* Saves the credentials and logs to storage.
*/
public static void save() {
Log.i(TAG, "Saving credentials");
Gson gson = new Gson();
String credentialsJson = gson.toJson(credentials, credentialsType);
String logsJson = gson.toJson(logs, logsType);
settings.edit()
.putString(CREDENTIAL_STORAGE, credentialsJson)
.putString(LOG_STORAGE, logsJson)
.apply();
}
/**
* Loads the credentials and logs from storage.
*/
public static void load() {
Log.i(TAG, "Loading credentials");
Gson gson = new Gson();
String credentialsJson = settings.getString(CREDENTIAL_STORAGE, "");
String logsJson = settings.getString(LOG_STORAGE, "");
if (!credentialsJson.equals("")) {
try {
credentials = gson.fromJson(credentialsJson, credentialsType);
} catch (Exception e) {
credentials = new HashMap<>();
}
}
if (credentials == null) {
credentials = new HashMap<>();
}
if (!logsJson.equals("")) {
try {
logs = gson.fromJson(logsJson, logsType);
} catch (Exception e) {
logs = new LinkedList<>();
}
}
if (logs == null) {
logs = new LinkedList<>();
}
}
/**
* Given an Idemix credential, return its attributes.
*
* @throws InfoException if we received null, or if the credential type was not found in the DescriptionStore
*/
private static Attributes getAttributes(IdemixCredential credential) throws InfoException {
Attributes attributes = new Attributes();
short id = Attributes.extractCredentialId(credential.getAttribute(1));
CredentialDescription cd = DescriptionStore.getInstance().getCredentialDescription(id);
if (cd == null)
throw new InfoException("Credential type not found in DescriptionStore");
attributes.add(Attributes.META_DATA_FIELD, credential.getAttribute(1).toByteArray());
for (int i = 0; i < cd.getAttributeNames().size(); i++) {
String name = cd.getAttributeNames().get(i);
BigInteger value = credential.getAttribute(i + 2); // + 2: skip secret key and metadata
attributes.add(name, value.toByteArray());
}
return attributes;
}
/**
* Given an issuer and credential name, return the corresponding credential if we have it.
* @return The credential, or null if we do not have it
* @throws InfoException if this combination of issuer/credentialname was not found in the DescriptionStore
*/
public static Attributes getAttributes(String issuer, String credentialName) throws InfoException {
if (issuer == null || credentialName == null)
return null;
CredentialDescription cd = DescriptionStore.getInstance().getCredentialDescriptionByName(issuer, credentialName);
if (cd == null)
throw new InfoException("Issuer or credential not found in DescriptionStore");
IRMAIdemixCredential credential = credentials.get(cd.getId());
if (credential == null)
return null;
return getAttributes(credential.getCredential());
}
/**
* Given a credential ID, return the corresponding credential if we have it
* @return The credential, or null if we do not have it
* @throws InfoException if no credential with this id was found in the DescriptionStore
*/
public static Attributes getAttributes(short id) throws InfoException {
CredentialDescription cd = DescriptionStore.getInstance().getCredentialDescription(id);
if (cd == null)
throw new InfoException("Credential type not found in DescriptionStore");
IRMAIdemixCredential credential = credentials.get(cd.getId());
if (credential == null)
return null;
return getAttributes(credential.getCredential());
}
/**
* Get a map containing all credential descriptions and attributes we currently have
*/
public static HashMap<CredentialDescription, Attributes> getAllAttributes() {
HashMap<CredentialDescription, Attributes> map = new HashMap<>();
CredentialDescription cd;
for (short id : credentials.keySet()) {
try {
cd = DescriptionStore.getInstance().getCredentialDescription(id);
map.put(cd, getAttributes(credentials.get(id).getCredential()));
} catch (InfoException e) {
e.printStackTrace();
}
}
return map;
}
private static void delete(CredentialDescription cd, boolean shouldSave) {
if (cd == null)
return;
IRMAIdemixCredential cred = credentials.remove(cd.getId());
if (cred != null) {
logs.add(new RemoveLogEntry(Calendar.getInstance().getTime(), cd));
if (shouldSave)
save();
}
}
/**
* Delete the credential with this description if we have it
*/
public static void delete(CredentialDescription cd) {
delete(cd, true);
}
/**
* Delete the credential with this id if we have it
*/
public static void delete(short id) {
delete(id, true);
}
private static void delete(short id, boolean shouldSave) {
try {
CredentialDescription cd = DescriptionStore.getInstance().getCredentialDescription(id);
delete(cd, shouldSave);
} catch (InfoException e) {
e.printStackTrace();
}
}
/**
* Delete all credentials.
*/
public static void deleteAll() {
for (short id : credentials.keySet())
delete(id, false);
save();
}
public static boolean isEmpty() {
return credentials.isEmpty();
}
public static List<LogEntry> getLog() {
return logs;
}
/**
* Given a disclosure request with selected attributes, build a proof collection. This function assumes that each
* {@link AttributeDisjunction} in the contents of the request has a selected (as in
* {@link AttributeDisjunction#getSelected()}) {@link AttributeIdentifier}, and we assume that we have the
* credential of this identifier.
* @throws CredentialsException if something goes wrong
*/
public static ProofList getProofs(DisclosureProofRequest request) throws CredentialsException {
if (!isApproved(request))
throw new CredentialsException("Select an attribute in each disjunction first");
List<AttributeDisjunction> content = request.getContent();
ProofListBuilder builder = new ProofListBuilder(request.getContext(), request.getNonce());
Map<Short, List<Integer>> toDisclose = new HashMap<>();
// Group the chosen attribute identifiers by their credential ID in the toDisclose map
for (AttributeDisjunction disjunction : content) {
AttributeIdentifier identifier = disjunction.getSelected();
String issuer = identifier.getIssuerName();
String credentialName = identifier.getCredentialName();
CredentialDescription cd = getCredentialDescription(issuer, credentialName);
short id = cd.getId();
List<Integer> attributes;
if (toDisclose.get(id) == null) {
attributes = new ArrayList<>(5);
attributes.add(1); // Always disclose metadata
toDisclose.put(id, attributes);
} else
attributes = toDisclose.get(id);
int j = cd.getAttributeNames().indexOf(identifier.getAttributeName());
if (j == -1) // our CredentialDescription does not contain the asked-for attribute
throw new CredentialsException("Attribute \"" + identifier.getAttributeName() + "\" not found");
attributes.add(j + 2);
}
for (short id : toDisclose.keySet()) {
List<Integer> attributes = toDisclose.get(id);
IdemixCredential credential = credentials.get(id).getCredential();
builder.addProofD(credential, attributes);
}
logs.addAll(0, generateLogEntries(toDisclose));
return builder.build();
}
private static List<LogEntry> generateLogEntries(Map<Short, List<Integer>> toDisclose)
throws CredentialsException {
List<LogEntry> logs = new ArrayList<>(toDisclose.size());
for (short id : toDisclose.keySet()) {
List<Integer> attributes = toDisclose.get(id);
try {
CredentialDescription cd = DescriptionStore.getInstance().getCredentialDescription(id);
HashMap<String, Boolean> booleans = new HashMap<>(cd.getAttributeNames().size());
for (int i = 0; i < cd.getAttributeNames().size(); ++i) {
String attrName = cd.getAttributeNames().get(i);
booleans.put(attrName, attributes.contains(i + 2));
}
// The third argument should be a VerificationDescription, and we don't have one here.
// Fortunately it seems to be optional, at least for the log screen...
logs.add(new VerifyLogEntry(Calendar.getInstance().getTime(), cd, null, booleans));
} catch (InfoException e) {
throw new CredentialsException(e);
}
}
return logs;
}
/**
* Helper function that either returns a non-null CredentialDescription or throws an exception
*/
private static CredentialDescription getCredentialDescription(String issuer, String credentialName)
throws CredentialsException {
// Find the corresponding CredentialDescription
CredentialDescription cd;
try {
cd = DescriptionStore.getInstance().getCredentialDescriptionByName(issuer, credentialName);
} catch (InfoException e) { // Should not happen
e.printStackTrace();
throw new CredentialsException("Could not read DescriptionStore", e);
}
if (cd == null)
throw new CredentialsException("Unknown issuer or credential");
return cd;
}
/**
* Given a disclosure request, see if we have satisfy it - i.e., if we have at least one attribute for each
* disjunction.
*/
public static boolean canSatisfy(DisclosureProofRequest request) {
for (AttributeDisjunction disjunction : request.getContent())
if (getCandidates(disjunction).isEmpty())
return false;
return true;
}
/**
* Returns true if the request has been approved by the user - that is, if each disjunction of the request has a
* selected attribute
*/
public static boolean isApproved(DisclosureProofRequest request) {
for (AttributeDisjunction disjunction : request.getContent())
if (disjunction.getSelected() == null)
return false;
return true;
}
/**
* Given an {@link AttributeDisjunction}, return attributes (and their values) that we have and that are
* contained in the disjunction.
*/
public static LinkedHashMap<AttributeIdentifier, String> getCandidates(AttributeDisjunction disjunction) {
LinkedHashMap<AttributeIdentifier, String> map = new LinkedHashMap<>();
for (AttributeIdentifier attribute : disjunction) {
Attributes foundAttrs = null;
try {
foundAttrs = getAttributes(attribute.getIssuerName(), attribute.getCredentialName());
} catch (InfoException e) {
e.printStackTrace();
}
if (foundAttrs != null && foundAttrs.get(attribute.getAttributeName()) != null) {
String value = new String(foundAttrs.get(attribute.getAttributeName()));
map.put(attribute, value);
}
}
return map;
}
public static boolean contains(AttributeIdentifier identifier) {
try {
Attributes attrs = getAttributes(identifier.getIssuerName(), identifier.getCredentialName());
if (attrs == null)
return false;
return attrs.get(identifier.getAttributeName()) != null;
} catch (InfoException e) {
return false;
}
}
} |
package org.jfrog.hudson.pipeline.common;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.*;
import hudson.plugins.git.util.BuildData;
import hudson.remoting.Channel;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.util.ArgumentListBuilder;
import jenkins.MasterToSlaveFileCallable;
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Ref;
import org.jenkinsci.plugins.workflow.cps.CpsScript;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jfrog.build.api.BuildInfoFields;
import org.jfrog.build.api.Vcs;
import org.jfrog.build.client.ProxyConfiguration;
import org.jfrog.build.extractor.clientConfiguration.IncludeExcludePatterns;
import org.jfrog.hudson.CredentialsConfig;
import org.jfrog.hudson.action.ActionableHelper;
import org.jfrog.hudson.pipeline.common.types.ArtifactoryServer;
import org.jfrog.hudson.pipeline.common.types.DistributionConfig;
import org.jfrog.hudson.pipeline.common.types.PromotionConfig;
import org.jfrog.hudson.pipeline.common.types.buildInfo.BuildInfo;
import org.jfrog.hudson.util.BuildUniqueIdentifierHelper;
import org.jfrog.hudson.util.ExtractorUtils;
import org.jfrog.hudson.util.IncludesExcludes;
import org.jfrog.hudson.util.RepositoriesUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;
public class Utils {
public static final String CONAN_USER_HOME = "CONAN_USER_HOME"; // Conan user home environment variable name
public static final String BUILD_INFO = "buildInfo"; // The build info argument used in pipeline
private static final String UNIX_SPECIAL_CHARS = "`^<>| ,;!?'\"()[]{}$*\\&#"; // Unix special characters to escape in '/bin/sh' execution
/**
* Prepares Artifactory server either from serverID or from ArtifactoryServer.
*
* @param artifactoryServerID
* @param pipelineServer
* @return
*/
public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,
ArtifactoryServer pipelineServer) {
if (artifactoryServerID == null && pipelineServer == null) {
return null;
}
if (artifactoryServerID != null && pipelineServer != null) {
return null;
}
if (pipelineServer != null) {
CredentialsConfig credentials = pipelineServer.createCredentialsConfig();
return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,
credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry());
}
org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());
if (server == null) {
return null;
}
return server;
}
public static BuildInfo prepareBuildinfo(Run build, BuildInfo buildinfo) {
if (buildinfo == null) {
return new BuildInfo(build);
}
return buildinfo;
}
public static ObjectMapper mapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper;
}
public static EnvVars extractBuildParameters(Run build, TaskListener listener) {
EnvVars buildVariables = new EnvVars();
try {
ParametersAction parameters = build.getAction(ParametersAction.class);
if (parameters != null) {
for (ParameterValue p : parameters) {
if (p.isSensitive()) {
continue;
}
String v = p.createVariableResolver(null).resolve(p.getName());
if (v != null) {
buildVariables.put(p.getName(), v);
}
}
}
} catch (Exception e) {
listener.getLogger().println("Can't get build variables");
return null;
}
return buildVariables;
}
public static List<Vcs> extractVcsBuildData(Run build) {
List<Vcs> result = new ArrayList<Vcs>();
List<BuildData> buildData = build.getActions(BuildData.class);
if (buildData != null) {
for (BuildData data : buildData) {
String sha1 = data.getLastBuiltRevision().getSha1String();
Iterator<String> iterator = data.getRemoteUrls().iterator();
if (iterator.hasNext()) {
result.add(new Vcs(iterator.next(), sha1));
}
}
}
return result;
}
public static String extractVcsRevision(FilePath filePath) throws IOException, InterruptedException {
if (filePath == null) {
return "";
}
FilePath dotGitPath = new FilePath(filePath, ".git");
if (dotGitPath.exists()) {
return dotGitPath.act(new MasterToSlaveFileCallable<String>() {
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
FileRepository repository = new FileRepository(f);
Ref head = repository.getRef("HEAD");
return head.getObjectId().getName();
}
});
}
return extractVcsRevision(filePath.getParent());
}
public static Computer getCurrentComputer(Launcher launcher) {
Jenkins j = Jenkins.getInstance();
for (Computer c : j.getComputers()) {
if (c.getChannel() == launcher.getChannel()) {
return c;
}
}
return null;
}
public static IncludesExcludes getArtifactsIncludeExcludeForDeyployment(IncludeExcludePatterns patternFilter) {
if (patternFilter == null) {
return new IncludesExcludes("", "");
}
String[] excludePatterns = patternFilter.getExcludePatterns();
String[] includePatterns = patternFilter.getIncludePatterns();
StringBuilder include = new StringBuilder();
StringBuilder exclude = new StringBuilder();
for (int i = 0; i < includePatterns.length; i++) {
if (include.length() > 0) {
include.append(", ");
}
include.append(includePatterns[i]);
}
for (int i = 0; i < excludePatterns.length; i++) {
if (exclude.length() > 0) {
exclude.append(", ");
}
exclude.append(excludePatterns[i]);
}
IncludesExcludes result = new IncludesExcludes(include.toString(), exclude.toString());
return result;
}
public static org.jfrog.build.api.Build getGeneratedBuildInfo(Run build, TaskListener listener, Launcher launcher, String jsonBuildPath) {
ObjectMapper mapper = new ObjectMapper();
FilePath generatedBuildInfoFilePath = null;
InputStream inputStream = null;
try {
StringWriter writer = new StringWriter();
generatedBuildInfoFilePath = new FilePath(launcher.getChannel(), jsonBuildPath);
inputStream = generatedBuildInfoFilePath.read();
IOUtils.copy(inputStream, writer, "UTF-8");
String buildInfoFileContent = writer.toString();
if (StringUtils.isBlank(buildInfoFileContent)) {
return new org.jfrog.build.api.Build();
}
return mapper.readValue(buildInfoFileContent, org.jfrog.build.api.Build.class);
} catch (Exception e) {
listener.error("Couldn't read generated build info at : " + jsonBuildPath);
build.setResult(Result.FAILURE);
throw new Run.RunnerAbortedException();
} finally {
if (inputStream != null) {
IOUtils.closeQuietly(inputStream);
}
deleteFilePathQuietly(generatedBuildInfoFilePath);
}
}
private static void deleteFilePathQuietly(FilePath filePath) {
try {
if (filePath != null && filePath.exists()) {
filePath.delete();
}
} catch (Exception e) {
// Ignore exceptions
}
}
public static String createTempJsonFile(Launcher launcher, final String name, final String dir) throws Exception {
return launcher.getChannel().call(new MasterToSlaveCallable<String, Exception>() {
public String call() throws IOException {
File tempFile = File.createTempFile(name, ".json", new File(dir));
tempFile.deleteOnExit();
return tempFile.getAbsolutePath();
}
});
}
public static void exeConan(ArgumentListBuilder args, FilePath pwd, Launcher launcher, TaskListener listener, Run build, EnvVars env) {
boolean failed;
try {
if (!pwd.exists()) {
pwd.mkdirs();
}
if (launcher.isUnix()) {
boolean hasMaskedArguments = args.hasMaskedArguments();
StringBuilder sb = new StringBuilder();
for (String arg : args.toList()) {
sb.append(escapeUnixArgument(arg)).append(" ");
}
args.clear();
args.add("sh", "-c");
if (hasMaskedArguments) {
args.addMasked(sb.toString());
} else {
args.add(sb.toString());
}
} else {
args = args.toWindowsCommand();
}
int exitValue = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(pwd).join();
failed = (exitValue != 0);
} catch (Exception e) {
listener.error("Couldn't execute the conan client executable. " + e.getMessage());
build.setResult(Result.FAILURE);
throw new Run.RunnerAbortedException();
}
if (failed) {
build.setResult(Result.FAILURE);
throw new Run.RunnerAbortedException();
}
}
public static String escapeUnixArgument(String arg) {
StringBuilder res = new StringBuilder();
for (char c : arg.toCharArray()) {
if (UNIX_SPECIAL_CHARS.indexOf(c) >= 0) {
res.append("\\");
}
res.append(c);
}
return res.toString();
}
public static PromotionConfig createPromotionConfig(Map<String, Object> promotionParams, boolean isTargetRepositoryMandatory) {
final String targetRepository = "targetRepo";
List<String> mandatoryParams = new ArrayList<String>(Arrays.asList(ArtifactoryServer.BUILD_NAME, ArtifactoryServer.BUILD_NUMBER));
List<String> allowedParams = Arrays.asList(ArtifactoryServer.BUILD_NAME, ArtifactoryServer.BUILD_NUMBER, targetRepository, "sourceRepo", "status", "comment", "includeDependencies", "copy", "failFast");
if (isTargetRepositoryMandatory) {
mandatoryParams.add(targetRepository);
}
if (!promotionParams.keySet().containsAll(mandatoryParams)) {
throw new IllegalArgumentException(mandatoryParams.toString() + " are mandatory arguments");
}
if (!allowedParams.containsAll(promotionParams.keySet())) {
throw new IllegalArgumentException("Only the following arguments are allowed: " + allowedParams.toString());
}
final ObjectMapper mapper = new ObjectMapper();
PromotionConfig config = mapper.convertValue(promotionParams, PromotionConfig.class);
return config;
}
public static org.jfrog.hudson.release.promotion.PromotionConfig convertPromotionConfig(PromotionConfig pipelinePromotionConfig) {
org.jfrog.hudson.release.promotion.PromotionConfig promotionConfig = new org.jfrog.hudson.release.promotion.PromotionConfig();
promotionConfig.setBuildName(pipelinePromotionConfig.getBuildName());
promotionConfig.setBuildNumber(pipelinePromotionConfig.getBuildNumber());
promotionConfig.setTargetRepo(pipelinePromotionConfig.getTargetRepo());
promotionConfig.setSourceRepo(pipelinePromotionConfig.getSourceRepo());
promotionConfig.setStatus(pipelinePromotionConfig.getStatus());
promotionConfig.setComment(pipelinePromotionConfig.getComment());
promotionConfig.setIncludeDependencies(pipelinePromotionConfig.isIncludeDependencies());
promotionConfig.setCopy(pipelinePromotionConfig.isCopy());
promotionConfig.setFailFast(pipelinePromotionConfig.isFailFast());
return promotionConfig;
}
public static DistributionConfig createDistributionConfig(Map<String, Object> promotionParams) {
List<String> mandatoryParams = new ArrayList<String>(Arrays.asList(ArtifactoryServer.BUILD_NAME, ArtifactoryServer.BUILD_NUMBER, "targetRepo"));
List<String> allowedParams = Arrays.asList(ArtifactoryServer.BUILD_NAME, ArtifactoryServer.BUILD_NUMBER, "publish", "overrideExistingFiles", "gpgPassphrase", "async", "targetRepo", "sourceRepos", "dryRun");
if (!promotionParams.keySet().containsAll(mandatoryParams)) {
throw new IllegalArgumentException(mandatoryParams.toString() + " are mandatory arguments");
}
if (!allowedParams.containsAll(promotionParams.keySet())) {
throw new IllegalArgumentException("Only the following arguments are allowed: " + allowedParams.toString());
}
final ObjectMapper mapper = new ObjectMapper();
DistributionConfig config = mapper.convertValue(promotionParams, DistributionConfig.class);
return config;
}
public static String getAgentName(FilePath ws) {
if (ws.getChannel() != null) {
return ws.getChannel() instanceof LocalChannel ? "Master" : ((Channel) ws.getChannel()).getName();
}
return "Unknown";
}
/**
* Add the buildInfo to step variables if missing and set its cps script.
* @param cpsScript the cps script
* @param stepVariables step variables map
* @return the build info
*/
public static BuildInfo appendBuildInfo(CpsScript cpsScript, Map<String, Object> stepVariables) {
BuildInfo buildInfo = (BuildInfo) stepVariables.get(BUILD_INFO);
if (buildInfo == null) {
buildInfo = (BuildInfo) cpsScript.invokeMethod("newBuildInfo", Maps.newLinkedHashMap());
stepVariables.put(BUILD_INFO, buildInfo);
}
buildInfo.setCpsScript(cpsScript);
return buildInfo;
}
public static ProxyConfiguration getProxyConfiguration(org.jfrog.hudson.ArtifactoryServer server) {
if (server.isBypassProxy()) {
return null;
}
return org.jfrog.hudson.ArtifactoryServer.createProxyConfiguration(Jenkins.getInstance().proxy);
}
public static ArrayListMultimap<String, String> getPropertiesMap(BuildInfo buildInfo, Run build, StepContext context) throws IOException, InterruptedException {
ArrayListMultimap<String, String> properties = ArrayListMultimap.create();
if (buildInfo.getName() != null) {
properties.put("build.name", buildInfo.getName());
} else {
properties.put("build.name", BuildUniqueIdentifierHelper.getBuildName(build));
}
if (buildInfo.getNumber() != null) {
properties.put("build.number", buildInfo.getNumber());
} else {
properties.put("build.number", BuildUniqueIdentifierHelper.getBuildNumber(build));
}
properties.put("build.timestamp", build.getTimestamp().getTime().getTime() + "");
Cause.UpstreamCause parent = ActionableHelper.getUpstreamCause(build);
if (parent != null) {
properties.put("build.parentName", ExtractorUtils.sanitizeBuildName(parent.getUpstreamProject()));
properties.put("build.parentNumber", parent.getUpstreamBuild() + "");
}
EnvVars env = context.get(EnvVars.class);
String revision = ExtractorUtils.getVcsRevision(env);
if (StringUtils.isNotBlank(revision)) {
properties.put(BuildInfoFields.VCS_REVISION, revision);
}
return properties;
}
public static String replaceTildeWithUserHome(String path) {
return path.replaceFirst("^~", System.getProperty("user.home"));
}
} |
package org.jtrfp.trcl.snd;
import java.util.Collection;
import java.util.concurrent.Callable;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Camera;
import org.jtrfp.trcl.core.Features;
import org.jtrfp.trcl.core.TRFactory;
import org.jtrfp.trcl.core.TRFactory.TR;
import org.jtrfp.trcl.ext.tr.GPUFactory.GPUFeature;
import org.jtrfp.trcl.ext.tr.SoundSystemFactory.SoundSystemFeature;
import org.jtrfp.trcl.gpu.GLFragmentShader;
import org.jtrfp.trcl.gpu.GLProgram;
import org.jtrfp.trcl.gpu.GLUniform;
import org.jtrfp.trcl.gpu.GLVertexShader;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.math.Misc;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.obj.WorldObject;
public class SamplePlaybackEvent extends AbstractSoundEvent {
private final SoundTexture soundTexture;
private final double[] pan;
private final double playbackRatio;
private Double lengthInSeconds = null;
private SamplePlaybackEvent(SoundTexture tex, double startTimeSeconds,
double[] pan, Factory origin, SoundEvent parent) {
this(tex,startTimeSeconds,pan,origin,parent,1);
}//end constructor
public SamplePlaybackEvent(SoundTexture tex, double startTimeSeconds,
double[] pan, Factory origin,
SoundEvent parent, double playbackRatio) {
this(tex,startTimeSeconds,pan,origin,parent,playbackRatio,tex.getLengthInRealtimeSeconds());
}
public SamplePlaybackEvent(SoundTexture tex, double startTimeSeconds,
double[] pan, Factory factory, SoundEvent parent,
double playbackRatio, double lengthInSeconds) {
super(startTimeSeconds, lengthInSeconds, factory,
parent);
soundTexture = tex;
this.pan = pan;
this.playbackRatio = playbackRatio;
this.lengthInSeconds = lengthInSeconds;
}
/**
* @return the soundTexture
*/
public SoundTexture getSoundTexture() {
return soundTexture;
}
/**
* @return the pan
*/
public double[] getPan() {
return pan;
}
@Override
public void apply(GL3 gl, double bufferStartTimeSeconds) {
SamplePlaybackEvent.Factory origin = (SamplePlaybackEvent.Factory)getOrigin();
origin.getPanU().set((float)getPan()[0], (float)getPan()[1]);//Pan center
final SoundSystem ss = Features.get(getOrigin().getTR(),SoundSystemFeature.class);
final double bufferSizeSeconds = ss.getBufferSizeSeconds(),
startTimeInBuffers=((getStartRealtimeSeconds()-bufferStartTimeSeconds)/(double)bufferSizeSeconds)*2-1,
lengthPerRow = getSoundTexture().getLengthPerRowSeconds();
final int lengthInSegments = (int)(getSoundTexture().getNumRows()) * 2; //Times two because of the turn
origin.getNumRowsU().set((float)getSoundTexture().getNumRows());//Kludge to get around int limitations in ES 2
origin.getStartU().set((float)startTimeInBuffers);
origin.getLengthPerRowU()
.set((float)((2/playbackRatio)*(lengthPerRow/bufferSizeSeconds)));
getSoundTexture().getGLTexture().bindToTextureUnit(0, gl);
gl.glDrawArrays(GL3.GL_LINE_STRIP, 0, lengthInSegments+1);
}//end apply(...)
public static class Factory extends AbstractSoundEvent.Factory{
private GLVertexShader soundVertexShader;
private GLFragmentShader soundFragmentShader;//1 fragment = 1 frame
private GLProgram soundProgram;
private GLUniform panU,numRowsU,startU,lengthPerRowU,soundTextureU;
public Factory(final TR tr) {
super(tr);
final GPU gpu = Features.get(tr, GPUFeature.class);
tr.getThreadManager().submitToGL(new Callable<Void>() {
@Override
public Void call() throws Exception {
soundVertexShader = gpu.newVertexShader();
soundFragmentShader= gpu.newFragmentShader();
soundVertexShader
.setSourceFromResource("/shader/soundVertexShader.glsl");
soundFragmentShader
.setSourceFromResource("/shader/soundFragShader.glsl");
soundProgram = gpu.newProgram().attachShader(soundVertexShader)
.attachShader(soundFragmentShader).link().use();
panU = soundProgram.getUniform("pan");
numRowsU = soundProgram.getUniform("numRows");
startU = soundProgram.getUniform("start");
lengthPerRowU= soundProgram.getUniform("lengthPerRow");
soundTextureU= soundProgram.getUniform("soundTexture");
return null;
}// end call()
}).get();
}//end constructor
@Override
public void apply(GL3 gl, Collection<SoundEvent> events, double bufferStartTimeSeconds) {
gl.glLineWidth(1);
gl.glDisable(GL3.GL_LINE_SMOOTH);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glEnable(GL3.GL_BLEND);
gl.glDepthFunc(GL3.GL_ALWAYS);
gl.glProvokingVertex(GL3.GL_FIRST_VERTEX_CONVENTION);
gl.glDepthMask(false);
gl.glBlendFunc(GL3.GL_ONE, GL3.GL_ONE);
soundProgram.use();
soundTextureU.set((int)0);
for(SoundEvent ev:events)
ev.apply(gl, bufferStartTimeSeconds);
//Cleanup
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);
gl.glDisable(GL3.GL_BLEND);
}//end apply(...)
public SamplePlaybackEvent create(SoundTexture tex, double [] source, Camera dest, double volumeScalar){
return create(tex, source, dest, volumeScalar, 1);
}
public SamplePlaybackEvent create(SoundTexture tex, double [] source, Camera dest, double volumeScalar, double samplePlaybackRatio){
final double UNIT_FACTOR = TRFactory.mapSquareSize*8;
final double dist = TRFactory.rolloverDistance(Vect3D.distance(source, dest.getPosition()));
final double unitDist = dist/UNIT_FACTOR;
final double vol = Misc.clamp(1./Math.pow(unitDist, 2),
0,1)*volumeScalar;
final double [] work = new double[3];
final double [] destPos = dest.getPosition();
TRFactory.twosComplimentSubtract(source, destPos, work);
Rotation rot;
try{rot = new Rotation(dest.getHeading(), dest.getTop(),Vector3D.PLUS_K, Vector3D.PLUS_J);}
catch(MathArithmeticException e){rot = new Rotation(Vector3D.PLUS_K, 0);}//Default if given weird top/heading.
if((work[0]==0)&&(work[1]==0)&&(work[2]==0))
work[0]=1;
final Vector3D localDir = rot.applyTo(new Vector3D(work)).normalize();
final double pFactor = (localDir.getX()+1)/2;
assert !Vect3D.isAnyNaN(source);
final double [] pan = new double[]{vol*pFactor,vol*(1-pFactor)};
final SoundSystem ss = Features.get(getTR(),SoundSystemFeature.class);
// Temporal dither to avoid phasiness
final double delay = dist*.000001+Math.random()*.005;
final double startTime = ss.getCurrentFrameBufferTimeCounter()+delay;
return create(tex,startTime,pan, null, samplePlaybackRatio);
}//end create(...)
public SamplePlaybackEvent create(SoundTexture tex, WorldObject source, Camera dest, double volumeScalar){
return create(tex,source.getPosition(),dest,volumeScalar);
}
public SamplePlaybackEvent create(SoundTexture tex, double [] pan){
final SoundSystem ss = Features.get(getTR(),SoundSystemFeature.class);
return create(tex,(ss.getCurrentFrameBufferTimeCounter()),pan);
}
public SamplePlaybackEvent create(SoundTexture tex, double startTimeSeconds,
double[] pan){
return new SamplePlaybackEvent(tex,startTimeSeconds,pan,this,null);
}//end create(...)
public SamplePlaybackEvent create(SoundTexture tex, double startTimeSeconds,
double[] pan, SoundEvent parent){
return new SamplePlaybackEvent(tex,startTimeSeconds,pan,this,parent);
}//end create(...)
public SamplePlaybackEvent create(SoundTexture tex, double startTimeSeconds,
double[] pan, SoundEvent parent, double playbackRatio){
return new SamplePlaybackEvent(tex,startTimeSeconds,pan,this,parent,playbackRatio);
}//end create(...)
public SamplePlaybackEvent create(SoundTexture tex, double startTimeSeconds,
double[] pan, SoundEvent parent, double playbackRatio, double lengthSeconds){
return new SamplePlaybackEvent(tex,startTimeSeconds,pan,this,parent,playbackRatio,lengthSeconds);
}//end create(...)
/**
* @return the panU
*/
GLUniform getPanU() {
return panU;
}
/**
* @return the startU
*/
GLUniform getStartU() {
return startU;
}
/**
* @return the lengthPerRowU
*/
GLUniform getLengthPerRowU() {
return lengthPerRowU;
}
/**
* @return the numRowsU
*/
GLUniform getNumRowsU() {
return numRowsU;
}
/**
* @return the soundProgram
*/
GLProgram getSoundProgram() {
return soundProgram;
}
}//end Factory
/**
* @return the playbackRatio
*/
public double getPlaybackRatio() {
return playbackRatio;
}
}//end SamplePlaybackEvent |
package org.lightmare.deploy;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.lightmare.cache.MetaContainer;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Manager class for application deployment
*
* @author levan
*
*/
public class LoaderPoolManager {
// Amount of deployment thread pool
private static final int LOADER_POOL_SIZE = 5;
// Name prefix of deployment threads
private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-";
// Lock for pool reopening
private static final Lock LOCK = new ReentrantLock();
/**
* Tries to lock Lock object or waits while locks
*
* @return <code>boolean</code>
*/
private static boolean tryLock() {
boolean locked = LOCK.tryLock();
while (ObjectUtils.notTrue(locked)) {
locked = LOCK.tryLock();
}
return locked;
}
private static void unlock() {
LOCK.unlock();
}
/**
* Gets class loader for existing {@link org.lightmare.deploy.MetaCreator}
* instance
*
* @return {@link ClassLoader}
*/
protected static ClassLoader getCurrent() {
ClassLoader current;
MetaCreator creator = MetaContainer.getCreator();
ClassLoader creatorLoader;
if (ObjectUtils.notNull(creator)) {
// Gets class loader for this deployment
creatorLoader = creator.getCurrent();
if (ObjectUtils.notNull(creatorLoader)) {
current = creatorLoader;
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
return current;
}
/**
* Implementation of {@link ThreadFactory} interface for application loading
*
* @author levan
*
*/
private static final class LoaderThreadFactory implements ThreadFactory {
/**
* Constructs and sets thread name
*
* @param thread
*/
private void nameThread(Thread thread) {
String name = StringUtils
.concat(LOADER_THREAD_NAME, thread.getId());
thread.setName(name);
}
/**
* Sets priority of {@link Thread} instance
*
* @param thread
*/
private void setPriority(Thread thread) {
thread.setPriority(Thread.MAX_PRIORITY);
}
/**
* Sets {@link ClassLoader} to passed {@link Thread} instance
*
* @param thread
*/
private void setContextClassLoader(Thread thread) {
ClassLoader parent = getCurrent();
thread.setContextClassLoader(parent);
}
/**
* Configures (sets name, priority and {@link ClassLoader}) passed
* {@link Thread} instance
*
* @param thread
*/
private void configureThread(Thread thread) {
nameThread(thread);
setPriority(thread);
setContextClassLoader(thread);
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
configureThread(thread);
return thread;
}
}
// Thread pool for deploying and removal of beans and temporal resources
private static ExecutorService LOADER_POOL;
/**
* Checks if loader {@link ExecutorService} is null or is shut down or is
* terminated
*
* @return <code>boolean</code>
*/
private static boolean invalid() {
return LOADER_POOL == null || LOADER_POOL.isShutdown()
|| LOADER_POOL.isTerminated();
}
private static void initLoaderPool() {
if (invalid()) {
LOADER_POOL = Executors.newFixedThreadPool(LOADER_POOL_SIZE,
new LoaderThreadFactory());
}
}
/**
* Checks and if not valid reopens deploy {@link ExecutorService} instance
*
* @return {@link ExecutorService}
*/
protected static ExecutorService getLoaderPool() {
if (invalid()) {
boolean locked = tryLock();
if (locked) {
try {
initLoaderPool();
} finally {
unlock();
}
}
}
return LOADER_POOL;
}
/**
* Submit passed {@link Runnable} implementation in loader pool
*
* @param runnable
*/
public static void submit(Runnable runnable) {
getLoaderPool().submit(runnable);
}
/**
* Submits passed {@link Callable} implementation in loader pool
*
* @param callable
* @return {@link Future}<code><T></code>
*/
public static <T> Future<T> submit(Callable<T> callable) {
ExecutorService pool = getLoaderPool();
Future<T> future = pool.submit(callable);
return future;
}
/**
* Clears existing {@link ExecutorService}s from loader threads
*/
public static void reload() {
boolean locked = tryLock();
if (locked) {
try {
if (ObjectUtils.notNull(LOADER_POOL)) {
LOADER_POOL.shutdown();
LOADER_POOL = null;
}
} finally {
unlock();
}
}
}
} |
package org.lightmare.ejb.handlers;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import org.lightmare.cache.ConnectionData;
import org.lightmare.cache.InjectionData;
import org.lightmare.cache.InterceptorData;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.ejb.EjbConnector;
import org.lightmare.ejb.interceptors.InvocationContextImpl;
import org.lightmare.jpa.jta.BeanTransactions;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Handler class to intercept bean method calls to provide database transactions
*
* @author Levan
*
*/
public class BeanHandler implements InvocationHandler, Cloneable {
private Object bean;
private final Class<?> beanClass;
private final Field transactionField;
private final Collection<ConnectionData> connectionDatas;
private final Collection<InjectionData> injectionDatas;
private final Collection<InterceptorData> interceptorDatas;
private final MetaData metaData;
protected BeanHandler(final MetaData metaData) {
this.beanClass = metaData.getBeanClass();
this.transactionField = metaData.getTransactionField();
this.connectionDatas = metaData.getConnections();
this.injectionDatas = metaData.getInjects();
this.interceptorDatas = metaData.getInterceptors();
this.metaData = metaData;
}
public MetaData getMetaData() {
return metaData;
}
public Object getBean() {
return bean;
}
protected void setBean(final Object bean) {
this.bean = bean;
}
/**
* Sets passed value to beans {@link Field}
*
* @param field
* @param value
* @throws IOException
*/
private void setFieldValue(Field field, Object value) throws IOException {
MetaUtils.setFieldValue(field, bean, value);
}
/**
* Invokes passed bean {@link Method}
*
* @param method
* @param arguments
* @return {@link Object}
* @throws IOException
*/
private Object invokeMethod(Method method, Object... arguments)
throws IOException {
return MetaUtils.invoke(method, bean, arguments);
}
private void setConnection(Field connectionField, EntityManager em)
throws IOException {
setFieldValue(connectionField, em);
}
/**
* Sets each injected EJB bean as value to annotated field respectively for
* passed {@link InjectionData} object
*/
private void configureInjection(InjectionData injectionData)
throws IOException {
MetaData injectMetaData = injectionData.getMetaData();
if (injectMetaData == null) {
String beanName;
String mappedName = injectionData.getMappedName();
if (mappedName == null || mappedName.isEmpty()) {
beanName = injectionData.getName();
} else {
beanName = injectionData.getMappedName();
}
injectMetaData = MetaContainer.getSyncMetaData(beanName);
injectMetaData.setInterfaceClasses(injectionData
.getInterfaceClasses());
injectionData.setMetaData(injectMetaData);
}
EjbConnector ejbConnector = new EjbConnector();
Object injectBean = ejbConnector.connectToBean(injectMetaData);
setFieldValue(injectionData.getField(), injectBean);
}
/**
* Sets injected EJB bean as values to {@link javax.ejb.EJB} annotated
* fields respectively
*
* @throws IOException
*/
private void configureInjects() throws IOException {
if (CollectionUtils.valid(injectionDatas)) {
for (InjectionData inject : injectionDatas) {
configureInjection(inject);
}
}
}
/**
* Method to configure (injections {@link javax.ejb.EJB} or
* {@link PersistenceUnit} annotated fields and etc.) {@link BeanHandler}
* after initialization
*
* @throws IOException
*/
public void configure() throws IOException {
// TODO Add other configurations
configureInjects();
}
/**
* Method to set bean field and to configure (injections
* {@link javax.ejb.EJB} or {@link PersistenceUnit} annotated fields and
* etc.) {@link BeanHandler} after initialization
*
* @param bean
* @throws IOException
*/
public void configure(final Object bean) throws IOException {
setBean(bean);
configure();
}
/**
* Creates and caches {@link UserTransaction} per thread
*
* @param em
* @return {@link UserTransaction}
*/
private UserTransaction getTransaction(Collection<EntityManager> ems) {
UserTransaction transaction = BeanTransactions.getTransaction(ems);
return transaction;
}
private void setTransactionField(Collection<EntityManager> ems)
throws IOException {
if (ObjectUtils.notNull(transactionField)) {
UserTransaction transaction = getTransaction(ems);
setFieldValue(transactionField, transaction);
}
}
private EntityManager createEntityManager(ConnectionData connection)
throws IOException {
EntityManager em;
EntityManagerFactory emf = connection.getEmf();
Field connectionField = connection.getConnectionField();
Field unitField = connection.getUnitField();
if (ObjectUtils.notNull(emf)) {
em = emf.createEntityManager();
if (ObjectUtils.notNull(unitField)) {
setFieldValue(unitField, emf);
}
setConnection(connectionField, em);
} else {
em = null;
}
return em;
}
private Collection<EntityManager> createEntityManagers() throws IOException {
Collection<EntityManager> ems;
if (CollectionUtils.valid(connectionDatas)) {
ems = new ArrayList<EntityManager>();
for (ConnectionData connection : connectionDatas) {
EntityManager em = createEntityManager(connection);
ems.add(em);
}
} else {
ems = null;
}
return ems;
}
/**
* Closes {@link EntityManager} if there is not
* {@link javax.annotation.Resource} annotation in current bean
*
* @param transaction
* @param em
*/
private void close(Method method) throws IOException {
try {
if (ObjectUtils.notNull(method)) {
if (transactionField == null) {
BeanTransactions.commitTransaction(this, method);
} else {
BeanTransactions.closeEntityManagers();
}
}
} finally {
BeanTransactions.remove(this, method);
}
}
/**
* Calls {@link BeanTransactions#rollbackTransaction(BeanHandler, Method))}
* is case of {@link Throwable} is thrown at passed {@link Method} execution
* time
*
* @param method
* @throws IOException
*/
private void rollback(Method method) throws IOException {
try {
if (ObjectUtils.notNull(method)) {
BeanTransactions.rollbackTransaction(this, method);
}
} catch (Throwable th) {
close(method);
throw new IOException(th);
}
}
/**
* Fills {@link Queue} of methods and targets for specified bean
* {@link Method} and {@link InterceptorData} object
*
* @param interceptorData
* @param methods
* @param targets
* @throws IOException
*/
private void fillInterceptor(InterceptorData interceptorData,
Queue<Method> methods, Queue<Object> targets) throws IOException {
Class<?> interceptorClass = interceptorData.getInterceptorClass();
Object interceptor = MetaUtils.instantiate(interceptorClass);
Method method = interceptorData.getInterceptorMethod();
methods.offer(method);
targets.offer(interceptor);
}
/**
* Checks if current {@link javax.interceptor.Interceptors} data is valid
* for specified {@link Method} call
*
* @param interceptor
* @param method
* @return <code>boolean</code>
*/
private boolean checkInterceptor(InterceptorData interceptor, Method method) {
boolean valid;
Method beanMethod = interceptor.getBeanMethod();
if (ObjectUtils.notNull(beanMethod)) {
valid = beanMethod.equals(method);
} else {
valid = Boolean.TRUE;
}
return valid;
}
/**
* Invokes first method from {@link javax.interceptor.Interceptors}
* annotated data
*
* @param method
* @param parameters
* @throws IOException
*/
private Object[] callInterceptors(Method method, Object[] parameters)
throws IOException {
Object[] intercepteds;
if (CollectionUtils.valid(interceptorDatas)) {
Iterator<InterceptorData> interceptors = interceptorDatas
.iterator();
InterceptorData interceptor;
Queue<Method> methods = new LinkedList<Method>();
Queue<Object> targets = new LinkedList<Object>();
boolean valid;
while (interceptors.hasNext()) {
interceptor = interceptors.next();
valid = checkInterceptor(interceptor, method);
if (valid) {
fillInterceptor(interceptor, methods, targets);
}
}
InvocationContext context = new InvocationContextImpl(methods,
targets, parameters);
try {
context.proceed();
intercepteds = context.getParameters();
} catch (Exception ex) {
throw new IOException(ex);
}
} else {
intercepteds = parameters;
}
return intercepteds;
}
private Object invokeBeanMethod(final Collection<EntityManager> ems,
final Method method, Object[] arguments) throws IOException {
if (transactionField == null) {
BeanTransactions.addTransaction(this, method, ems);
} else {
setTransactionField(ems);
}
// Calls interceptors for this method or bean instance
Object[] intercepteds = callInterceptors(method, arguments);
// Calls for bean method with "intercepted" parameters
Object value = invokeMethod(method, intercepteds);
return value;
}
@Override
public Object invoke(Object proxy, Method method, Object[] arguments)
throws Throwable {
Object value;
Collection<EntityManager> ems = createEntityManagers();
Method realMethod = null;
try {
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
// Gets real method of bean class
realMethod = MetaUtils.getDeclaredMethod(beanClass, methodName,
parameterTypes);
value = invokeBeanMethod(ems, realMethod, arguments);
} catch (Throwable th) {
rollback(realMethod);
throw new Throwable(th);
} finally {
close(realMethod);
}
return value;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
} |
package org.lightmare.ejb.handlers;
import java.lang.reflect.Method;
/**
* Handler class to call EJB bean methods for REST services
*
* @author levan
*
*/
public class RestHandler<T> {
// Appropriated bean's handler
private final BeanHandler handler;
// EJB bean instance
private final T bean;
public RestHandler(BeanHandler handler, T bean) {
this.handler = handler;
this.bean = bean;
}
/**
* Invokes passed {@link Method} for bean by {@link BeanHandler} instance
*
* @param method
* @param args
* @return {@link Object}
* @throws Throwable
*/
public Object invoke(Method method, Object[] args) throws Throwable {
return handler.invoke(bean, method, args);
}
} |
package org.lightmare.jpa.jta;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.EJBException;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.hibernate.cfg.NotYetImplementedException;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.ejb.meta.MetaContainer;
import org.lightmare.ejb.meta.MetaData;
import org.lightmare.utils.ObjectUtils;
/**
* Class to manage {@link javax.transaction.UserTransaction} for
* {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls
*
* @author levan
*
*/
public class BeanTransactions {
private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction";
private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction";
private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented";
/**
* Inner class to cache {@link EntityTransaction}s and {@link EntityManager}
* s in one {@link Collection} for {@link UserTransaction} implementation
*
* @author levan
*
*/
private static class TransactionData {
EntityManager em;
EntityTransaction entityTransaction;
}
private static TransactionData createTransactionData(
EntityTransaction entityTransaction, EntityManager em) {
TransactionData transactionData = new TransactionData();
transactionData.em = em;
transactionData.entityTransaction = entityTransaction;
return transactionData;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(
EntityTransaction... entityTransactions) {
UserTransaction transaction = MetaContainer.getTransaction();
if (transaction == null) {
transaction = new UserTransactionImpl(entityTransactions);
MetaContainer.setTransaction(transaction);
}
if (ObjectUtils.avaliable(entityTransactions)) {
((UserTransactionImpl) transaction)
.addTransactions(entityTransactions);
}
return transaction;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(Collection<EntityManager> ems) {
UserTransaction transaction = MetaContainer.getTransaction();
if (transaction == null) {
transaction = new UserTransactionImpl();
MetaContainer.setTransaction(transaction);
}
Collection<TransactionData> entityTransactions = getEntityTransactions(ems);
addEntityTransactions((UserTransactionImpl) transaction,
entityTransactions);
return transaction;
}
/**
* Gets appropriated {@link TransactionAttributeType} for instant
* {@link Method} of {@link javax.ejb.Stateless} bean
*
* @param metaData
* @param method
* @return {@link TransactionAttributeType}
*/
public static TransactionAttributeType getTransactionType(
MetaData metaData, Method method) {
TransactionAttributeType attrType = metaData.getTransactionAttrType();
TransactionManagementType manType = metaData.getTransactionManType();
TransactionAttribute attr = method
.getAnnotation(TransactionAttribute.class);
TransactionAttributeType type;
if (manType.equals(TransactionManagementType.CONTAINER)) {
if (attr == null) {
type = attrType;
} else {
type = attr.value();
}
} else {
type = null;
}
return type;
}
/**
* Gets status of passed transaction by {@link UserTransaction#getStatus()}
* method call
*
* @param transaction
* @return <code>int</code>
* @throws IOException
*/
private static int getStatus(UserTransaction transaction)
throws IOException {
int status;
try {
status = transaction.getStatus();
} catch (SystemException ex) {
throw new IOException(ex);
}
return status;
}
/**
* Checks if transaction is active and if it is not vegins transaction
*
* @param entityTransaction
*/
private static void beginEntityTransaction(
EntityTransaction entityTransaction) {
if (!entityTransaction.isActive()) {
entityTransaction.begin();
}
}
private static EntityTransaction getEntityTransaction(EntityManager em) {
EntityTransaction entityTransaction;
if (em == null) {
entityTransaction = null;
} else {
entityTransaction = em.getTransaction();
beginEntityTransaction(entityTransaction);
}
return entityTransaction;
}
private static Collection<TransactionData> getEntityTransactions(
Collection<EntityManager> ems) {
Collection<TransactionData> entityTransactions = null;
if (ObjectUtils.avaliable(ems)) {
entityTransactions = new ArrayList<TransactionData>();
for (EntityManager em : ems) {
EntityTransaction entityTransaction = getEntityTransaction(em);
TransactionData transactionData = createTransactionData(
entityTransaction, em);
entityTransactions.add(transactionData);
}
}
return entityTransactions;
}
private static void addEntityTransaction(UserTransactionImpl transaction,
EntityTransaction entityTransaction, EntityManager em) {
if (ObjectUtils.notNull(entityTransaction)) {
transaction.addTransaction(entityTransaction);
}
if (ObjectUtils.notNull(em)) {
transaction.addEntityManager(em);
}
}
private static void addEntityTransactions(UserTransactionImpl transaction,
Collection<TransactionData> entityTransactions) {
if (ObjectUtils.avaliable(entityTransactions)) {
for (TransactionData transactionData : entityTransactions) {
addEntityTransaction(transaction,
transactionData.entityTransaction, transactionData.em);
}
}
}
private static void addEntityManager(UserTransactionImpl transaction,
EntityManager em) {
if (ObjectUtils.notNull(em)) {
transaction.addEntityManager(em);
}
}
private static void addEntityManagers(UserTransactionImpl transaction,
Collection<EntityManager> ems) {
if (ObjectUtils.avaliable(ems)) {
for (EntityManager em : ems) {
addEntityManager(transaction, em);
}
}
}
private static void addReqNewTransaction(UserTransactionImpl transaction,
EntityTransaction entityTransaction, EntityManager em) {
if (ObjectUtils.notNull(entityTransaction)) {
transaction.pushReqNew(entityTransaction);
}
if (ObjectUtils.notNull(em)) {
transaction.pushReqNewEm(em);
}
}
private static void addReqNewTransactions(UserTransactionImpl transaction,
Collection<TransactionData> entityTransactions) {
if (ObjectUtils.avaliable(entityTransactions)) {
for (TransactionData transactionData : entityTransactions) {
addReqNewTransaction(transaction,
transactionData.entityTransaction, transactionData.em);
}
}
}
/**
* Decides whether create or join {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param type
* @param transaction
* @param em
* @throws IOException
*/
private static void addTransaction(BeanHandler handler,
TransactionAttributeType type, UserTransactionImpl transaction,
Collection<EntityManager> ems) throws IOException {
Collection<TransactionData> entityTransactions;
if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) {
addEntityManagers(transaction, ems);
} else if (type.equals(TransactionAttributeType.REQUIRED)) {
Object caller = transaction.getCaller();
if (caller == null) {
transaction.setCaller(handler);
}
entityTransactions = getEntityTransactions(ems);
addEntityTransactions(transaction, entityTransactions);
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
entityTransactions = getEntityTransactions(ems);
addReqNewTransactions(transaction, entityTransactions);
} else if (type.equals(TransactionAttributeType.MANDATORY)) {
int status = getStatus(transaction);
if (status == 0) {
throw new EJBException(MANDATORY_ERROR);
} else {
entityTransactions = getEntityTransactions(ems);
addEntityTransactions(transaction, entityTransactions);
}
} else if (type.equals(TransactionAttributeType.NEVER)) {
int status = getStatus(transaction);
if (status > 0) {
throw new EJBException(NEVER_ERROR);
} else {
addEntityManagers(transaction, ems);
}
} else if (type.equals(TransactionAttributeType.SUPPORTS)) {
throw new NotYetImplementedException(SUPPORTS_ERROR);
}
}
/**
* Defines which {@link TransactionAttribute} is used on bean {@link Class}
* and decides whether create or join {@link UserTransaction} by this
* annotation
*
* @param handler
* @param method
* @param entityTransaction
* @throws IOException
*/
public static TransactionAttributeType addTransaction(BeanHandler handler,
Method method, Collection<EntityManager> ems) throws IOException {
MetaData metaData = handler.getMetaData();
TransactionAttributeType type = getTransactionType(metaData, method);
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
if (ObjectUtils.notNull(type)) {
addTransaction(handler, type, transaction, ems);
}
return type;
}
/**
* Commits passed {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void commit(UserTransaction transaction) throws IOException {
try {
transaction.commit();
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (RollbackException ex) {
throw new IOException(ex);
} catch (HeuristicMixedException ex) {
throw new IOException(ex);
} catch (HeuristicRollbackException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Calls {@link UserTransaction#rollback()} method of passed
* {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void rollback(UserTransaction transaction)
throws IOException {
try {
transaction.rollback();
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Decides whether rollback or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param type
* @param handler
* @throws IOException
*/
private static void rollbackTransaction(TransactionAttributeType type,
BeanHandler handler) throws IOException {
if (type.equals(TransactionAttributeType.REQUIRED)
|| type.equals(TransactionAttributeType.MANDATORY)) {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
rollback(transaction);
}
}
/**
* Decides whether rollback or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void rollbackTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
rollbackTransaction(type, handler);
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param type
* @param handler
* @throws IOException
*/
public static void commitTransaction(TransactionAttributeType type,
BeanHandler handler) throws IOException {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
if (type.equals(TransactionAttributeType.REQUIRED)) {
boolean check = transaction.checkCaller(handler);
if (check) {
commit(transaction);
}
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
transaction.commitReqNew();
} else {
transaction.closeEntityManagers();
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void commitTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
commitTransaction(type, handler);
}
}
/**
* Closes cached {@link EntityManager}s after method calll
*/
public static void closeEntityManagers() {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
transaction.closeEntityManagers();
}
} |
package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class Calculate implements Serializable {
public void hello()
{
System.out.println("JPET Store Application");
System.out.println("Class name: Calculate.java");
System.out.println("Hello World");
System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016");
System.out.println("Fri Dec 2 12:52:58 UTC 2016");
}
}
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck |
package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class Calculate implements Serializable {
public void hello()
{
System.out.println("JPET Store Application");
System.out.println("Class name: Calculate.java");
System.out.println("Hello World");
System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017");
System.out.println("Thu Mar 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017");
System.out.println("Tue Mar 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017");
System.out.println("Sun Mar 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017");
System.out.println("Fri Mar 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017");
System.out.println("Wed Mar 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017");
System.out.println("Mon Mar 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017");
System.out.println("Sat Mar 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017");
System.out.println("Thu Mar 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017");
System.out.println("Tue Mar 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017");
System.out.println("Sun Mar 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017");
System.out.println("Fri Mar 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017");
System.out.println("Wed Mar 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017");
System.out.println("Mon Mar 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017");
System.out.println("Sat Mar 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016");
System.out.println("Fri Dec 2 12:52:58 UTC 2016");
}
}
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck |
package org.nsponline.calendar.misc;
import org.nsponline.calendar.store.*;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Steve Gledhill
*/
@SuppressWarnings({"SqlNoDataSourceInspection", "AccessStaticViaInstance"})
public class PatrolData {
final static boolean DEBUG = true;
// final static String JDBC_DRIVER = "org.gjt.mm.mysql.Driver"; //todo change July 32 2015
public final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
public final static String newShiftStyle = "--New Shift Style
// create a Mountain Standard Time time zone
// final static String[] ids = TimeZone.getAvailableIDs(-7 * 60 * 60 * 1000);
// final static SimpleTimeZone MDT = new SimpleTimeZone(-7 * 60 * 60 * 1000, ids[0]);
public final static String NEW_SHIFT_STYLE = "--New Shift Style
// set up rules for daylight savings time
// static {
// MDT.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
// MDT.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
static public HashMap<String, ResortData> resortMap = new HashMap<String, ResortData>();
static private final int IMG_HEIGHT = 80;
static {
resortMap.put("Afton", new ResortData("Afton", "Afton Alps", null, "http:
resortMap.put("AlpineMt", new ResortData("AlpineMt", "Alpine Mt", null, "http:
resortMap.put("Andes", new ResortData("Andes", "Andes Tower Hills", null, "http:
resortMap.put("Brighton", new ResortData("Brighton", "Brighton", "steve@gledhills.com", "http:
resortMap.put("BuenaVista", new ResortData("BuenaVista", "Buena Vista", null, "http:
resortMap.put("CoffeeMill", new ResortData("CoffeeMill", "CoffeeMill", null, "http:
resortMap.put("DetroitMountain",new ResortData("DetroitMountain", "Detroit Mountain", null, "http://detroitmountain.com/", "/images/DetroitMountain.png", 73, 121));
resortMap.put("ElmCreek", new ResortData("ElmCreek", "Elm Creek Park", null, "https:
resortMap.put("GrandTarghee", new ResortData("GrandTarghee", "Grand Targhee", null, "http:
resortMap.put("HermonMountain", new ResortData("HermonMountain", "Hermon Mountain", null, "http:
resortMap.put("Hesperus", new ResortData("Hesperus", "Hesperus", null, "http:
resortMap.put("HylandHills", new ResortData("HylandHills", "Hyland Hills Park", null, " https://threeriversparks.org/parks/hyland-lake-park/hyland-hills-ski-area.aspx", "/images/ThreeRivers.jpg", IMG_HEIGHT, 80));
resortMap.put("IFNordic", new ResortData("IFNordic", "IF Nordic", null, "", "/images/IFNordic.gif", IMG_HEIGHT, 80));
resortMap.put("JacksonHole", new ResortData("JacksonHole", "Jackson Hole Fire/EMS", null, "http://tetonwyo.org/AgencyHome.asp?dept_id=fire", "/images/JacksonHole.jpg", IMG_HEIGHT, 80));
resortMap.put("JacksonSpecialEvents", new ResortData("JacksonSpecialEvents", "Jackson Hole Fire/EMS Special Events", null, "http://tetonwyo.org/AgencyHome.asp?dept_id=fire", "/images/JacksonHole.jpg", IMG_HEIGHT, 80));
resortMap.put("KellyCanyon", new ResortData("KellyCanyon", "Kelly Canyon", null, "http:
resortMap.put("LonesomePine", new ResortData("LonesomePine", "Lonesome Pine Trails", null, "http:
resortMap.put("MagicMountain", new ResortData("MagicMountain", "Magic Mountain", null, "http:
resortMap.put("MountKato", new ResortData("MountKato", "Mount Kato", null, "http:
resortMap.put("NorwayMountain", new ResortData("NorwayMountain", "Norway Mountain", null, "http:
resortMap.put("PaidSnowCreek", new ResortData("PaidSnowCreek", "Paid SnowCreek", null, "http:
resortMap.put("ParkCity", new ResortData("ParkCity", "PCM-Canyons", "dukespeer@gmail.com", "http:
resortMap.put("PebbleCreek", new ResortData("PebbleCreek", "Pebble Creek", null, "http:
resortMap.put("PineCreek", new ResortData("PineCreek", "Pine Creek", null, "http:
resortMap.put("PineMountain", new ResortData("PineMountain", "Pine Mountain", null, "http:
resortMap.put("Plattekill", new ResortData("Plattekill", "Plattekill Mountain", null, "http://plattekill.com/", "/images/PlattekillLogo.png", IMG_HEIGHT, 147));
resortMap.put("Pomerelle", new ResortData("Pomerelle", "Pomerelle", null, "http:
resortMap.put("PowderRidge", new ResortData("PowderRidge", "Powder Ridge", null, "http:
resortMap.put("RMSP", new ResortData("RMSP", "Ragged Mountain", null, "http:
resortMap.put("Sample", new ResortData("Sample", "Sample Resort", null, "http:
resortMap.put("SnowCreek", new ResortData("SnowCreek", "SnowCreek", null, "http:
resortMap.put("SnowKing", new ResortData("SnowKing", "SnowKing", null, "http:
resortMap.put("SoldierHollow", new ResortData("SoldierHollow", "Soldier Hollow", null, "http:
resortMap.put("SoldierMountain", new ResortData("SoldierMountain", "Soldier Mountain", null, "http:
resortMap.put("ThreeRivers", new ResortData("ThreeRivers", "Three Rivers Park", null, "http:
resortMap.put("WelchVillage", new ResortData("WelchVillage", "Welch Village", null, "http:
resortMap.put("WhitePine", new ResortData("WhitePine", "White Pine", null, "http:
resortMap.put("WildMountain", new ResortData("WildMountain", "Wild Mountain", null, "http:
resortMap.put("Willamette", new ResortData("Willamette", "Willamette Backcountry", null, "http:
}
/* - - - - - uncomment the following to run from the Internet - - - - - - */
final static String AMAZON_PRIVATE_IP = "172.31.0.109";//private ip PRODUCTION. must match /etc/my.cnf
// final static String AMAZON_PRIVATE_IP = "172.31.59.53"; //private ip TESTING. must match /etc/my.cnf
// final static String AMAZON_PRIVATE_IP = "127.0.0.1"; //must match /etc/my.cnf
final static String MYSQL_ADDRESS = AMAZON_PRIVATE_IP; //todo get this from an environment or configuration
/*- - - - - end local declarations - - - - - -*/
final static String backDoorFakeFirstName = "System";
final static String backDoorFakeLastName = "Administrator";
final static String backDoorEmail = "Steve@Gledhills.com";
public final static int MAX_PATROLLERS = 400; //todo hack fix me
public final static String SERVLET_URL = "/calendar-1/";
public final static boolean FETCH_MIN_DATA = false;
public final static boolean FETCH_ALL_DATA = true;
//all the folowing instance variables must be initialized in the constructor
// private Connection connection;
Connection connection;
private ResultSet rosterResults;
private ResultSet assignmentResults;
private PreparedStatement shiftStatement;
private ResultSet shiftResults;
private boolean fetchFullData;
private String localResort;
private SessionData sessionData;
public PatrolData(boolean readAllData, String myResort, SessionData sessionData) {
this.sessionData = sessionData;
rosterResults = null;
assignmentResults = null;
shiftStatement = null;
shiftResults = null;
localResort = myResort;
fetchFullData = readAllData;
try {
Class.forName(JDBC_DRIVER).newInstance();
}
catch (Exception e) {
errorOut(sessionData, "Cannot load the driver, reason:" + e.toString());
errorOut(sessionData, "Most likely the Java class path is incorrect.");
//todo do something here. besides throw a NPE later
return;
}
connection = getConnection(localResort, sessionData);
if (connection != null) //error was already displayed, if null
{
resetRoster();
}
else {
errorOut(sessionData,"getConnection(" + localResort + ", sessionData) failed.");
//todo do something here. besides throw a NPE later
}
} //end PatrolData constructor
public Connection getConnection() {
return connection;
}
public static Connection getConnection(String resort, SessionData sessionData) { //todo get rid of static !!!!!!!!!!
Connection conn = null;
try {
debugOut(sessionData, "
conn = java.sql.DriverManager.getConnection(getJDBC_URL(resort), sessionData.getDbUser(), sessionData.getDbPassword());
debugOut(sessionData, "PatrolData.connection " + ((conn == null) ? "FAILED" : "SUCCEEDED") + " for " + getJDBC_URL(resort));
}
catch (Exception e) {
errorOut(sessionData,"Error: " + e.getMessage() + " connecting to table:" + resort);
java.lang.Thread.currentThread().dumpStack();
}
return conn;
}
public void resetAssignments() {
//todo srg, get rid of this method and make assignmentResults method local
try {
String selectAllAssignmentsByDateSQLString = Assignments.getSelectAllAssignmentsByDateSQLString();
logger("resetAssignments: " + selectAllAssignmentsByDateSQLString);
PreparedStatement assignmentsStatement = connection.prepareStatement(selectAllAssignmentsByDateSQLString);
assignmentResults = assignmentsStatement.executeQuery(); //todo uses global :-(
}
catch (Exception e) {
errorOut(sessionData,"(" + localResort + ") Error resetting Assignments table query:" + e.getMessage());
} //end try
}
public Assignments readNextAssignment() {
//todo srg fix all callers to this. it is returning things out of order. use readSortedAssignments
// Map<Thread, StackTraceElement[]> threadMap = Thread.getAllStackTraces();
// Thread currentThread = Thread.currentThread();
// if (threadMap.get(currentThread) != null) {
// logger("[1]" + threadMap.get(currentThread)[1].toString());
// logger("[2]" + threadMap.get(currentThread)[2].toString());
// logger("[3]" + threadMap.get(currentThread)[3].toString());
// logger("[4]" + threadMap.get(currentThread)[4].toString());
// logger("[5]" + threadMap.get(currentThread)[5].toString());
// logger("[6]" + threadMap.get(currentThread)[6].toString());
Assignments ns = null;
try {
if (assignmentResults.next()) { //todo uses global :-(
ns = new Assignments();
ns.read(sessionData, assignmentResults);
}
}
catch (SQLException e) {
logger("(" + localResort + ") Cannot read Assignment, reason:" + e.toString());
return null;
}
return ns;
}
public void resetRoster() {
try {
PreparedStatement rosterStatement = connection.prepareStatement("SELECT * FROM roster ORDER BY LastName, FirstName");
rosterResults = rosterStatement.executeQuery();
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error reseting roster table query:" + e.getMessage());
} //end try
}
public void resetRoster(String sort) {
try {
PreparedStatement rosterStatement = connection.prepareStatement("SELECT * FROM roster ORDER BY " + sort);
rosterResults = rosterStatement.executeQuery();
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error reseting roster table query:" + e.getMessage());
} //end try
}
public void resetShiftDefinitions() {
try {
shiftStatement = connection.prepareStatement("SELECT * FROM shiftdefinitions ORDER BY \"" + ShiftDefinitions.tags[0] + "\""); //sort by default key
shiftResults = shiftStatement.executeQuery();
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error reseting Shifts table query:" + e.getMessage());
} //end try
}
public boolean writeDirectorSettings(DirectorSettings ds) {
return ds.write(connection);
}
public DirectorSettings readDirectorSettings() {
ResultSet directorResults = DirectorSettings.reset(connection);
DirectorSettings ds = null;
//System.out.println("HACK: directorResults starting try");
try {
//System.out.println("ERROR: directorResults inside try");
//noinspection ConstantConditions
if (directorResults.next()) {
ds = new DirectorSettings(localResort);
ds.read(directorResults);
}
else {
System.out.println("ERROR: directorResults.next() failed for resort: ");
}
}
catch (Exception e) {
if (ds == null) {
System.out.println("Cannot read DirectorSettings for resort (ds=null), reason:" + e.toString());
}
else {
System.out.println("Cannot read DirectorSettings for resort " + ds.getResort() + ", reason:" + e.toString());
}
return null;
}
return ds;
}
public ArrayList<ShiftDefinitions> readShiftDefinitions() {
ArrayList<ShiftDefinitions> shiftDefinitions = new ArrayList<ShiftDefinitions>();
try {
String qryString = "SELECT * FROM `shiftdefinitions` ORDER BY `shiftdefinitions`.`EventName` ASC";
// logger("readShiftDefinitions: " + qryString);
PreparedStatement assignmentsStatement = connection.prepareStatement(qryString);
ResultSet assignmentResults = assignmentsStatement.executeQuery();
while (assignmentResults.next()) {
ShiftDefinitions ns = new ShiftDefinitions();
ns.read(assignmentResults);
// logger(".. NextShifts-" + ns.toString());
shiftDefinitions.add(ns);
}
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error resetting Assignments table query:" + e.getMessage());
} //end try
return shiftDefinitions;
}
public void decrementShift(ShiftDefinitions ns) {
if (DEBUG) {
System.out.println("decrement shift:" + ns);
}
int i = ns.getEventIndex();
if (DEBUG) {
System.out.println("event index =" + i);
}
if (i == 0) {
return;
}
deleteShift(ns);
ns.setEventName(Assignments.createAssignmentName(ns.parsedEventName(), i - 1));
writeShift(ns);
}
public void deleteShift(ShiftDefinitions ns) {
String qryString = ns.getDeleteSQLString();
logger("deleteShift: " + qryString);
try {
PreparedStatement sAssign = connection.prepareStatement(qryString);
sAssign.executeUpdate();
ns.setExists(false);
}
catch (Exception e) {
System.out.println("(" + localResort + ") Cannot delete Shift, reason:" + e.toString());
}
}
public boolean writeShift(ShiftDefinitions ns) {
String qryString;
if (ns.exists()) {
qryString = ns.getUpdateShiftDefinitionsQueryString();
}
else {
qryString = ns.getInsertShiftDefinitionsQueryString();
}
logger("writeShift: " + qryString);
try {
PreparedStatement sAssign = connection.prepareStatement(qryString);
sAssign.executeUpdate();
ns.setExists(true);
}
catch (SQLException e) {
errorOut(sessionData, "(" + localResort + ") failed writeShift, reason:" + e.getMessage());
return true;
}
return false;
}
public void close() {
try {
if (DEBUG) {
System.out.println("-- close connection (" + localResort + "): " + Utils.getCurrentDateTimeString());
}
if (connection != null) {
connection.close(); //let it close in finalizer ??
}
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error closing connection:" + e.getMessage());
Thread.currentThread().dumpStack();
} //end try
} // end close
public Roster nextMember(String defaultString) {
Roster member = null;
try {
if (rosterResults.next()) {
member = new Roster(); //" " is the default
member.readFullFromRoster(rosterResults, defaultString);
} //end if
}
catch (SQLException e) {
member = null;
System.out.println("(" + localResort + ") Failed nextMember, reason:" + e.getMessage());
Thread.currentThread().dumpStack();
} //end try
return member;
} //end nextMember
public Roster getMemberByID(String szMemberID) {
Roster member;
String str = "SELECT * FROM roster WHERE IDNumber =" + szMemberID;
if (szMemberID == null || szMemberID.length() <= 3) {
return null;
}
else if (szMemberID.equals(sessionData.getBackDoorUser())) {
member = new Roster(); //" " is the default
member.setLast(backDoorFakeLastName);
member.setFirst(backDoorFakeFirstName);
member.setEmail(backDoorEmail);
member.setID("000000");
member.setDirector("yes");
return member;
}
try {
PreparedStatement rosterStatement = connection.prepareStatement(str);
rosterResults = rosterStatement.executeQuery();
while (rosterResults.next()) {
int id = rosterResults.getInt("IDNumber");
String str1 = id + "";
if (str1.equals(szMemberID)) {
member = new Roster(); //" " is the default
if (fetchFullData) {
member.readFullFromRoster(rosterResults, "");
}
else {
member.readPartialFromRoster(rosterResults, "");
}
return member;
}
} //end while
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error in getMemberByID(" + szMemberID + "): " + e.getMessage());
System.out.println("(" + localResort + ") ERROR in PatrolData:getMemberByID(" + szMemberID + ") maybe a close was already done?");
//noinspection AccessStaticViaInstance
Thread.currentThread().dumpStack();
} //end try
return null; //failed
} //end getMemberByID
public Roster getMemberByEmail(String szEmail) {
Roster member;
String str = "SELECT * FROM roster WHERE email =\"" + szEmail + "\"";
//System.out.println(str);
try {
PreparedStatement rosterStatement = connection.prepareStatement(str);
rosterResults = rosterStatement.executeQuery();
if (rosterResults.next()) {
member = new Roster(); //" " is the default
if (fetchFullData) {
member.readFullFromRoster(rosterResults, "");
}
else {
member.readPartialFromRoster(rosterResults, "");
}
return member;
} //end while
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error in getMemberByEmail(" + szEmail + "): " + e.getMessage());
} //end try
return null; //failure
} //end getMemberByID
public Roster getMemberByName2(String szFullName) {
return getMemberByLastNameFirstName(szFullName);
} //end getMemberByName
public Roster getMemberByLastNameFirstName(String szFullName) {
Roster member;
String str = "SELECT * FROM roster";
try {
PreparedStatement rosterStatement = connection.prepareStatement(str);
rosterResults = rosterStatement.executeQuery();
while (rosterResults.next()) {
// int id = rosterResults.getInt("IDNumber");
String str1 = rosterResults.getString("LastName").trim() + ", " +
rosterResults.getString("FirstName").trim();
//System.out.println("getMemberByLastNameFirstName: (" + szFullName + ") (" + str1 + ") cmp=" + str1.equals(szFullName));
if (str1.equals(szFullName)) {
member = new Roster(); //" " is the default
if (fetchFullData) {
member.readFullFromRoster(rosterResults, "");
}
else {
member.readPartialFromRoster(rosterResults, "");
}
return member;
}
} //end while
}
catch (SQLException e) {
errorOut(sessionData, "(" + localResort + ") failed getMemberByLastNameFirstName(" + szFullName + "):" + e.getMessage());
Thread.currentThread().dumpStack();
}
return null; //not found (or error)
}
public static int StringToIndex(String temp) {
int i;
try {
i = Integer.parseInt(temp);
}
catch (Exception e) {
char ch = temp.charAt(0);
i = ch - 'A' + 10;
}
return i;
}
public static String IndexToString(int i) {
String val;
if (i < 10) {
val = i + ""; //force automatic conversion of integer to string
}
else {
val = String.valueOf((char) ('A' + i - 10));
}
return val;
}
public Assignments readAssignment(String myDate) { //formmat yyyy-mm-dd_p
Assignments ns;
try {
String queryString = "SELECT * FROM assignments WHERE Date=\'" + myDate + "\'";
PreparedStatement assignmentsStatementLocal = connection.prepareStatement(queryString);
ResultSet assignmentResultsLocal = assignmentsStatementLocal.executeQuery();
if (assignmentResultsLocal.next()) {
ns = new Assignments();
ns.read(sessionData, assignmentResultsLocal);
logger("readAssignment(" + queryString + ")= " + ns.toString());
return ns;
}
}
catch (SQLException e) {
errorOut(sessionData, "failed readAssignment, reason:" + e.getMessage());
return null;
}
return null;
}
public boolean writeAssignment(Assignments ns) {
String qryString;
if (ns.exists()) {
qryString = ns.getUpdateQueryString(sessionData);
}
else {
qryString = ns.getInsertQueryString(sessionData);
}
logger("writeAssignment: " + qryString);
try {
PreparedStatement sAssign = connection.prepareStatement(qryString);
sAssign.executeUpdate();
}
catch (SQLException e) {
errorOut(sessionData, "(" + localResort + ") failed writeAssignment, reason:" + e.getMessage());
return true;
}
return false;
}
// decrementAssignment - change 2015-10-06_2 to 2015-10-06_1 (delete _2 and write _1)
// 2015-10-06_0 is ignored
public void decrementAssignment(Assignments ns) {
logger("decrement Assignment:" + ns);
int i = ns.getDatePos(); //1 based
if (i < 1) //#'s are 0 based, can't decrement pos 0
{
return;
}
deleteAssignment(ns);
String qry2String = ShiftDefinitions.createShiftName(ns.getDateOnly(), i - 1);
ns.setDate(qry2String);
writeAssignment(ns);
}
// deleteShift - DELETE Shift assignment for a specified date and index
public void deleteAssignment(Assignments ns) {
String qryString = ns.getDeleteSQLString(sessionData);
logger("deleteAssignment" + qryString);
try {
PreparedStatement sAssign = connection.prepareStatement(qryString);
sAssign.executeUpdate();
ns.setExisted(false);
}
catch (SQLException e) {
errorOut(sessionData, "(" + localResort + ") failed deleteAssignment, reason:" + e.getMessage());
}
}
// AddShiftsToDropDown
static public void AddShiftsToDropDown(PrintWriter out, ArrayList shifts, String selectedShift) {
String lastName = "";
String parsedName;
String selected = "";
if (selectedShift == null) {
selected = " selected";
}
out.println(" <option" + selected + ">" + NEW_SHIFT_STYLE + "</option>");
for (Object shift : shifts) {
ShiftDefinitions data = (ShiftDefinitions) shift;
parsedName = data.parsedEventName();
if (parsedName.equals(selectedShift)) {
selected = " selected";
}
else {
selected = "";
}
if (!parsedName.equals(lastName)) {
out.println("<option" + selected + ">" + parsedName + "</option>");
lastName = parsedName;
}
}
}
// countDropDown
static private void countDropDown(PrintWriter out, String szName, int value) {
out.println("<select size=\"1\" name=\"" + szName + "\">");
for (int i = Math.min(1, value); i <= Assignments.MAX_ASSIGNMENT_SIZE; ++i) {
if (i == value) {
out.println("<option selected>" + i + "</option>");
}
else {
out.println("<option>" + i + "</option>");
}
}
out.println(" </select>");
}
// AddShiftsToTable
static public void AddShiftsToTable(PrintWriter out, ArrayList shifts, String selectedShift) {
int validShifts = 0;
for (Object shift : shifts) {
ShiftDefinitions data = (ShiftDefinitions) shift;
String parsedName = data.parsedEventName();
if (parsedName.equals(selectedShift)) {
//name is if the format of startTime_0, endTime_0, count_0, startTime_1, endTime_1, count_1, etc
// delete_0, delete_1
//shiftCount
out.println("<tr>");
//delete button
// out.println("<td width=\"103\"><input onClick=\"DeleteBtn()\" type=\"button\" value=\"Delete\" name=\"delete_"+validShifts+"\"></td>");
out.println("<td><input type='submit' value='Delete' name='delete_" + validShifts + "'></td>");
out.println("<td>Start: <input type='text' onKeyDown='javascript:return captureEnter(event.keyCode)' name='startTime_" + validShifts + "' size='7' value='" + data.getStartString() + "'></td>");
out.println("<td>End: <input type='text' onKeyDown='javascript:return captureEnter(event.keyCode)' name='endTime_" + validShifts + "' size='7' value='" + data.getEndString() + "'></td>");
out.println("<td>Patroller Count: ");
// out.println("<input type=\"text\" name=\"count_"+validShifts+"\" size=\"4\" value=\""+data.getCount()+"\">");
countDropDown(out, "count_" + validShifts, data.getCount());
out.println("</td>");
//add Day/Seing/Night shift
out.println("<td> ");
out.println("<select size=1 name='shift_" + validShifts + "'>");
//System.out.println("in AddShiftsToTable, data.getType()="+data.getType());
for (int shiftType = 0; shiftType < Assignments.MAX_SHIFT_TYPES; ++shiftType) {
String sel = (data.getType() == shiftType) ? "selected" : "";
out.println("<option " + sel + ">" + Assignments.getShiftName(shiftType) + "</option>");
}
out.println("</select>");
out.println("</td>");
out.println("</tr>");
++validShifts;
}
}
out.println("<INPUT TYPE=\"HIDDEN\" NAME=\"shiftCount\" VALUE=\"" + validShifts + "\">");
}
// AddAssignmentsToTable
static public void AddAssignmentsToTable(PrintWriter out, ArrayList parameterAssignments) {
int validShifts = 0;
for (Object parameterAssignment : parameterAssignments) {
Assignments data = (Assignments) parameterAssignment;
// String parsedName = data.getEventName();
int useCount = data.getUseCount(); //get # of patrollers actually assigned to this shift (warn if deleteing!)
// if(parsedName.equals(selectedShift)) {
//name is if the format of startTime_0, endTime_0, count_0, startTime_1, endTime_1, count_1, etc
// delete_0, delete_1
//shiftCount
out.println("<tr>");
//delete button
// out.println("<td width=\"103\"><input onClick=\"DeleteBtn()\" type=\"button\" value=\"Delete\" name=\"delete_"+validShifts+"\"></td>");
out.println("<td><input type=\"submit\" value=\"Delete\" onclick=\"return confirmShiftDelete(" + useCount + ")\" name=\"delete_" + validShifts + "\"></td>");
out.println("<td>Start: <input type=\"text\" name=\"startTime_" + validShifts + "\" onKeyDown=\"javascript:return captureEnter(event.keyCode)\" size=\"7\" value=\"" + data.getStartingTimeString() + "\"></td>");
out.println("<td>End: <input type=\"text\" name=\"endTime_" + validShifts + "\" onKeyDown=\"javascript:return captureEnter(event.keyCode)\" size=\"7\" value=\"" + data.getEndingTimeString() + "\"></td>");
out.println("<td>Patroller Count: ");
// out.println("<input type=\"text\" name=\"count_"+validShifts+"\" size=\"4\" value=\""+data.getCount()+"\">");
countDropDown(out, "count_" + validShifts, data.getCount());
out.println("</td>");
//add Day/Seing/Night shift
out.println("<td> ");
out.println("<select size=1 name='shift_" + validShifts + "'>");
//System.out.println("in AddAssignmentsToTable, data.getType()="+data.getType());
for (int shiftType = 0; shiftType < Assignments.MAX_SHIFT_TYPES; ++shiftType) {
String sel = (data.getType() == shiftType) ? "selected" : "";
out.println("<option " + sel + ">" + Assignments.getShiftName(shiftType) + "</option>");
}
out.println("</select>");
out.println("</td>");
out.println("</tr>");
++validShifts;
}
out.println("<INPUT TYPE='HIDDEN\' NAME='shiftCount' VALUE='" + validShifts + "'>");
}
static public boolean isValidResort(String resort) {
return resortMap.containsKey(resort);
}
static public ResortData getResortInfo(String theResort) {
return resortMap.get(theResort);
}
public ResortData getResortInfo() {
return resortMap.get(localResort);
}
public static String getResortFullName(String resort) {
if (resortMap.containsKey(resort)) { //resort string is same as db name, value is full resort string
return resortMap.get(resort).getResortFullName();
}
System.out.println("**** Error, unknown resort (" + resort + ")");
Thread.currentThread().dumpStack();
return "Error, invalid resort (" + resort + ")";
}
static public String getJDBC_URL(String resort) {
String jdbcLoc = "jdbc:mysql://" + MYSQL_ADDRESS + "/";
if (isValidResort(resort)) {
return jdbcLoc + resort;
}
logger(resort, "****** Error, unknown resort (" + resort + ")");
Thread.currentThread().dumpStack();
return "invalidResort";
}
public boolean insertNewIndividualAssignment( NewIndividualAssignment newIndividualAssignment) {
String qryString = newIndividualAssignment.getInsertSQLString(sessionData);
logger("insertNewIndividualAssignment" + qryString);
try {
PreparedStatement sAssign = connection.prepareStatement(qryString);
sAssign.executeUpdate();
}
catch (SQLException e) {
System.out.println("Cannot insert newIndividualAssignment, reason:" + e.getMessage());
return false;
}
return true;
}
public boolean updateNewIndividualAssignment(NewIndividualAssignment newIndividualAssignment) {
String qryString = newIndividualAssignment.getUpdateSQLString(sessionData);
logger("updateNewIndividualAssignment: " + qryString);
try {
PreparedStatement sAssign = connection.prepareStatement(qryString);
sAssign.executeUpdate();
}
catch (SQLException e) {
errorOut(sessionData, "(" + localResort + ") Cannot update newIndividualAssignment, reason:" + e.getMessage());
return false;
}
return true;
}
public HashMap<String, NewIndividualAssignment> readNewIndividualAssignments(int year, int month, int day) { //formmat yyyy-mm-dd_i_n
HashMap<String, NewIndividualAssignment> results = new HashMap<String, NewIndividualAssignment>();
String key = NewIndividualAssignment.buildKey(year, month, day, -1, -1);
key += "%";
//SELECT * FROM `newindividualassignment` WHERE `date_shift_pos` LIKE "2009-02-07%"
try {
String queryString = "SELECT * FROM `newindividualassignment` WHERE `date_shift_pos` LIKE \'" + key + "\'";
debugOut(null, "readNewIndividualAssignments: " + queryString);
PreparedStatement assignmentsStatement = connection.prepareStatement(queryString);
ResultSet assignmentResults = assignmentsStatement.executeQuery();
while (assignmentResults.next()) {
NewIndividualAssignment newIndividualAssignment = new NewIndividualAssignment();
newIndividualAssignment.read(sessionData, assignmentResults);
debugOut(null, newIndividualAssignment.toString());
results.put(newIndividualAssignment.getDateShiftPos(), newIndividualAssignment);
}
}
catch (SQLException e) {
errorOut(sessionData, "(" + localResort + ") readNewIndividualAssignments" + e.getMessage());
return null;
}
return results;
}
private void logger(String message) {
if (sessionData != null && sessionData.getRequest() != null) {
Utils.printToLogFile(sessionData.getRequest(), message);
}
else {
logger(localResort, message);
}
}
public static void logger(String myResort, String message) {
Utils.printToLogFile(null, "(" + myResort + ") " + message);
}
public void deleteNewIndividualAssignment(NewIndividualAssignment newIndividualAssignment) {
System.out.println("(" + localResort + ") delete Assignment:" + newIndividualAssignment);
String qryString = newIndividualAssignment.getDeleteSQLString(sessionData);
try {
PreparedStatement sAssign = connection.prepareStatement(qryString);
sAssign.executeUpdate(); //can throw exception
newIndividualAssignment.setExisted(false);
}
catch (Exception e) {
System.out.println("(" + localResort + ") Cannot delete Shift, reason:" + e.toString());
}
}
public ArrayList<Assignments> readAllSortedAssignments(String patrollerId) {
String dateMask = "20%"; //WHERE `date_shift_pos` LIKE '2015-10-%'
// logger("readSortedAssignments(" + dateMask + ")");
ArrayList<Assignments> monthAssignments = new ArrayList<Assignments>();
try {
String qryString = "SELECT * FROM `assignments` WHERE Date like '" + dateMask + "' ORDER BY Date";
logger("readAllSortedAssignments(" + patrollerId + "): " + qryString);
PreparedStatement assignmentsStatement = connection.prepareStatement(qryString);
ResultSet assignmentResults = assignmentsStatement.executeQuery();
// int cnt = 1;
while (assignmentResults.next()) {
Assignments ns = new Assignments();
ns.read(sessionData, assignmentResults);
if (ns.includesPatroller(patrollerId)) {
// logger("(" + (cnt++) + ") NextAssignment-" + ns.toString());
monthAssignments.add(ns);
}
}
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error resetting Assignments table query:" + e.getMessage());
} //end try
return monthAssignments;
}
public ArrayList<Assignments> readSortedAssignments(int year, int month) {
String dateMask = String.format("%4d-%02d-", year, month) + "%";
// logger(" readSortedAssignments(" + dateMask + ")");
ArrayList<Assignments> monthAssignments = new ArrayList<Assignments>();
try {
String qryString = "SELECT * FROM `assignments` WHERE Date like '" + dateMask + "' ORDER BY Date";
debugOut(null, "readSortedAssignments: " + qryString);
PreparedStatement assignmentsStatement = connection.prepareStatement(qryString);
ResultSet assignmentResults = assignmentsStatement.executeQuery();
while (assignmentResults.next()) {
Assignments ns = new Assignments();
ns.read(sessionData, assignmentResults);
// logger(".. NextAssignment-" + ns.toString());
monthAssignments.add(ns);
}
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error resetting Assignments table query:" + e.getMessage());
} //end try
return monthAssignments;
}
public ArrayList<Assignments> readSortedAssignments(int year, int month, int day) {
String dateMask = String.format("%4d-%02d-%02d_", year, month, day) + "%";
// logger(" readSortedAssignments(" + dateMask + ")");
ArrayList<Assignments> monthAssignments = new ArrayList<Assignments>();
try {
String qryString = "SELECT * FROM `assignments` WHERE Date like '" + dateMask + "' ORDER BY Date";
logger("readSortedAssignments:" + qryString);
PreparedStatement assignmentsStatement = connection.prepareStatement(qryString);
ResultSet assignmentResults = assignmentsStatement.executeQuery();
while (assignmentResults.next()) {
Assignments ns = new Assignments();
ns.read(sessionData, assignmentResults);
// logger(".. NextAssignment-" + ns.toString());
monthAssignments.add(ns);
}
}
catch (Exception e) {
System.out.println("(" + localResort + ") Error resetting Assignments table query:" + e.getMessage());
} //end try
return monthAssignments;
}
private static void debugOut(SessionData sessionData, String msg) {
if (DEBUG) {
String localResort = sessionData == null ? "noLoggedInResort" : sessionData.getLoggedInResort();
HttpServletRequest request = sessionData == null ? null : sessionData.getRequest();
Utils.printToLogFile(request ,"DEBUG-PatrolData(" + localResort + "): " + msg);
}
}
private static void errorOut(SessionData sessionData, String msg) {
String localResort = sessionData == null ? "noLoggedInResort" : sessionData.getLoggedInResort();
HttpServletRequest request = sessionData == null ? null : sessionData.getRequest();
Utils.printToLogFile(request ,"ERROR-PatrolData(" + localResort + "): " + msg);
}
public static boolean isValidLogin(PrintWriter out, String resort, String ID, String pass, SessionData sessionData) {
boolean validLogin = false;
ResultSet rs;
//System.out.println("LoginHelp: isValidLogin("+resort + ", "+ID+", "+pass+")");
if (ID == null || pass == null) {
Utils.printToLogFile(sessionData.getRequest(), "Login Failed: either ID (" + ID + ") or Password not supplied");
return false;
}
try {
//noinspection unused
Driver drv = (Driver) Class.forName(PatrolData.JDBC_DRIVER).newInstance();
}
catch (Exception e) {
Utils.printToLogFile(sessionData.getRequest(), "LoginHelp: Cannot find mysql driver, reason:" + e.toString());
out.println("LoginHelp: Cannot find mysql driver, reason:" + e.toString());
return false;
}
if (ID.equalsIgnoreCase(sessionData.getBackDoorUser()) && pass.equalsIgnoreCase(sessionData.getBackDoorPassword())) {
return true;
} // Try to connect to the database
try {
// Change MyDSN, myUsername and myPassword to your specific DSN
Connection c = PatrolData.getConnection(resort, sessionData);
@SuppressWarnings("SqlNoDataSourceInspection")
String szQuery = "SELECT * FROM roster WHERE IDNumber = \"" + ID + "\"";
PreparedStatement sRost = c.prepareStatement(szQuery);
if (sRost == null) {
return false;
}
rs = sRost.executeQuery();
if (rs != null && rs.next()) { //will only loop 1 time
String originalPassword = rs.getString("password");
String lastName = rs.getString("LastName");
String firstName = rs.getString("FirstName");
String emailAddress = rs.getString("email");
originalPassword = originalPassword.trim();
lastName = lastName.trim();
pass = pass.trim();
boolean hasPassword = (originalPassword.length() > 0);
if (hasPassword) {
if (originalPassword.equalsIgnoreCase(pass)) {
validLogin = true;
}
}
else {
if (lastName.equalsIgnoreCase(pass)) {
validLogin = true;
}
}
if (validLogin) {
Utils.printToLogFile(sessionData.getRequest(), "Login Sucessful: " + firstName + " " + lastName + ", " + ID + " (" + resort + ") " + emailAddress);
}
else {
Utils.printToLogFile(sessionData.getRequest(), "Login Failed: ID=[" + ID + "] LastName=[" + lastName + "] suppliedPass=[" + pass + "] dbPass[" + originalPassword + "]");
}
}
else {
Utils.printToLogFile(sessionData.getRequest(), "Login Failed: memberId not found [" + ID + "]");
}
c.close();
}
catch (Exception e) {
out.println("Error connecting or reading table:" + e.getMessage()); //message on browser
Utils.printToLogFile(sessionData.getRequest(), "LoginHelp. Error connecting or reading table:" + e.getMessage());
} //end try
return validLogin;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.