answer
stringlengths 17
10.2M
|
|---|
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class game {
public static void main(String[] ar){
game_Frame fms = new game_Frame();
}
}
class game_Frame extends JFrame implements KeyListener, Runnable{
private static boolean all_stop = false;
private static boolean stage_clear = false;
private static int Q_available = 0;
int f_width, f_height; //frame size
int x, y; //position of plane
int bx = 0; //background move
//variable for keyboard input
boolean KeyUp = false;
boolean KeyDown = false;
boolean KeyLeft = false;
boolean KeyRight = false;
boolean KeySpace = false; //missile
boolean KeyQ = false; //ultimate skill
boolean KeyT = false; //test key. score add
int cnt; //enemy made loop
//speed setting
int player_Speed;
int missile_Speed;
int enemy_missile_Speed;
int fire_Speed;
int enemy_Speed;
int game_Score;
int player_Hitpoint;
int player_Status = 0; //0 : normal, 1 : missile shoot, 2 : crashed
int boss_Hitpoint;
int boss_Status = 0; //0: not appeared, 1: appeared, 2: destroyed
Thread th;
Toolkit tk = Toolkit.getDefaultToolkit();
//for animation
Image plane_img;
Image background_img;
Image explo_img;
Image missile_img;
Image enemy_img1;
Image enemy_img2;
Image enemy_img3;
Image enemy_missile_img;
Image gameover_img;
Image boss1;
Image stage_clear_img;
//to save shot missile
ArrayList Missile_List = new ArrayList();
ArrayList Enemy_List = new ArrayList();
ArrayList Explosion_List = new ArrayList();
//for double buffering
Image buffImage;
Graphics buffg;
Missile ms;
Enemy en;
Explosion ex;
game_Frame(){ //conductor
init();
start();
setTitle("Shooting Game");
setSize(f_width, f_height);
Dimension screen = tk.getScreenSize();
int f_xpos = (int)(screen.getWidth() / 2 - f_width / 2);
int f_ypos = (int)(screen.getHeight() / 2 - f_height / 2);
setLocation(f_xpos, f_ypos);
setResizable(false);
setVisible(true);
}
public void init(){ //initial position
x = 100;
y = 100;
f_width = 1200;
f_height = 600;
//load images
plane_img = new ImageIcon("images/plane_img.png").getImage();
missile_img = new ImageIcon("images/missile_img.png").getImage();
enemy_img1 = new ImageIcon("images/enemy1.png").getImage();
enemy_img2 = new ImageIcon("images/enemy2.png").getImage();
enemy_img3 = new ImageIcon("images/enemy3.png").getImage();
background_img = new ImageIcon("images/background1.jpg").getImage();
explo_img = new ImageIcon("images/enemy_explosion.png").getImage();
enemy_missile_img = new ImageIcon("images/enemy_shot.png").getImage();
gameover_img = new ImageIcon("images/game over.png").getImage();
boss1 = new ImageIcon("images/boss2.png").getImage();
stage_clear_img = new ImageIcon("images/stage_clear.png").getImage();
//setting
game_Score = 0; //initialize game score
player_Hitpoint = 3;
boss_Hitpoint = 10;
player_Speed = 5;
missile_Speed = 7;
enemy_missile_Speed = 7;
fire_Speed = 10;
enemy_Speed = 3;
Sound("sound/BGM01.wav",false);
}
public void start(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this); //keyboard event
th = new Thread(this); // make thread
th.start(); // thread start
}
public void run(){
try{
while(!all_stop){
KeyProcess(); //get the keyboard value to update position
EnemyProcess();
MissileProcess();
ExplosionProcess();
repaint(); //repaint plane using new position
StageClearProcess();
Thread.sleep(20); //delay time
cnt++;
}
}catch (Exception e){}
}
////////// Process ///////////
public void MissileProcess(){
if ( KeySpace == true ){ //shooting
player_Status = 1;
if( ( cnt % fire_Speed ) == 0){
ms = new Missile(x + 155, y + 32,missile_Speed,0); //set missile position
Missile_List.add(ms); //add missile to list
}
}
for ( int i = 0 ; i < Missile_List.size() ; ++i){
ms = (Missile) Missile_List.get(i);
ms.move();
//end of main frame
if ( ms.x > f_width - 20||ms.x<0||ms.y<0||ms.y>f_height){
Missile_List.remove(i);
}
//enemy missile shot
if (Crash(x, y, ms.x, ms.y, plane_img, missile_img) && ms.who == 1 ) {
player_Hitpoint
GameOver(player_Hitpoint);
ex = new Explosion(x + plane_img.getWidth(null) / 2, y + plane_img.getHeight(null) / 2, 1);
Explosion_List.add(ex);
Missile_List.remove(i);
Sound("sound/explosion_sound.wav",false);
}
for (int j = 0 ; j < Enemy_List.size(); ++ j){
en = (Enemy) Enemy_List.get(j);
Image tmp = enemy_img1;
if(en.type == 2) tmp = enemy_img2;
else if(en.type == 3) tmp = enemy_img3;
else if(en.type == 4) tmp = boss1;
if (Crash(ms.x, ms.y, en.x, en.y, missile_img, tmp) && ms.who==0){
Missile_List.remove(i);
if(en.type == 4)
boss_Hitpoint -= 1;
if(en.type != 4 || boss_Hitpoint < 1){
Enemy_List.remove(j);
if(en.type == 4 && boss_Status == 1) boss_Status = 2;
}
game_Score += 10; //get score
if(game_Score % 150 == 0) Q_available += 1;
//explision effect
ex = new Explosion(en.x + tmp.getWidth(null) / 2, en.y + tmp.getHeight(null) / 2 , 0);
Explosion_List.add(ex);
Sound("sound/explosion_sound.wav",false);
}
}
}
}
public void EnemyProcess(){
for (int i = 0 ; i < Enemy_List.size() ; ++i ){
en = (Enemy)(Enemy_List.get(i));
en.move(); //move enemy
if(en.x < -200){
Enemy_List.remove(i);
}
//enemy shoot
if ( cnt % 100 == 0){
ms = new Missile (en.x, en.y + 10, enemy_missile_Speed, 1);
Missile_List.add(ms);
}
Image tmp = enemy_img1;
if(en.type == 2) tmp = enemy_img2;
else if(en.type == 3) tmp = enemy_img3;
else if(en.type == 4) tmp = boss1;
//crashed with enemy
if(Crash(x, y, en.x, en.y, plane_img, tmp)){
player_Hitpoint
GameOver(player_Hitpoint);
Enemy_List.remove(i);
ex = new Explosion(en.x + tmp.getWidth(null) / 2, en.y + tmp.getHeight(null) / 2, 0 );
Explosion_List.add(ex);
ex = new Explosion(x+plane_img.getWidth(null) / 2, y+plane_img.getHeight(null)/ 2, 1 );
Explosion_List.add(ex);
Sound("sound/explosion_sound.wav",false);
}
}
Random random = new Random();
//stage 1 boss appeared
if(game_Score > 200 && boss_Status == 0){
en = new Enemy(f_width , f_height/3 , enemy_Speed, 4);
Enemy_List.add(en);
boss_Status = 1;
}
if ( cnt % 100 == 0 ){ //make enemy
en = new Enemy(f_width + random.nextInt(20)*10 + 20, random.nextInt(550) + 25, enemy_Speed,random.nextInt(3) + 1);
Enemy_List.add(en);
}
if ( cnt % 170 == 0 ){ //make enemy
en = new Enemy(f_width + random.nextInt(7)*10 + 20, random.nextInt(550) + 25, enemy_Speed,random.nextInt(3) + 1);
Enemy_List.add(en);
}
}
public void ExplosionProcess(){
for (int i = 0 ; i < Explosion_List.size(); ++i){
ex = (Explosion) Explosion_List.get(i);
ex.effect();
}
}
public void StageClearProcess(){
if(boss_Status == 2){
stage_clear = true;
Enemy_List.clear();
Missile_List.clear();
//Draw_StageClear();
//buffg = buffImg(stage_clear)
}
}
public void GotoNextStage()//if boss clear, few second wait and goto next stage. next stage's difficulty will increase.
{
if(stage_clear == true)
{
try
{
stage_clear = false;
Thread.sleep(5000);//10 second wait to prepare
/////////difficulty up setting////////////////
enemy_Speed += 2;
enemy_missile_Speed += 4;
boss_Status = 0;
//buffg = buffImage.getGraphics();
}
catch (Exception e){}
}
}
//////////// functions ////////////
public boolean Crash(int x1, int y1, int x2, int y2, Image img1, Image img2){
boolean check = false;
if ( Math.abs( ( x1 + img1.getWidth(null) / 2 ) - ( x2 + img2.getWidth(null) / 2 )) < ( img2.getWidth(null) / 2 + img1.getWidth(null) / 2 )
&& Math.abs( ( y1 + img1.getHeight(null) / 2 ) - ( y2 + img2.getHeight(null) / 2 )) < ( img2.getHeight(null)/2 + img1.getHeight(null)/2 ) ){
check = true;
}
else{
check = false;
}
return check;
}
//////////// draw //////////////
public void paint(Graphics g){
buffImage = createImage(f_width, f_height); //set double buffer size
buffg = buffImage.getGraphics();
if(all_stop == true)
Draw_GameOver(g);
else
update(g);
}
public void update(Graphics g){
Draw_Background();
Draw_Player();
Draw_Enemy();
Draw_Missile();
Draw_Explosion();
Draw_StatusText();
if(stage_clear == true)
Draw_StageClear();
g.drawImage(buffImage, 0, 0, this); //draw image from buffer
}
public void Draw_GameOver(Graphics g){
buffg.clearRect(0, 0, f_width, f_height);
buffg.drawImage(gameover_img, 0, 0, this);
g.drawImage(buffImage, 0, 0, this); //draw image from buffer
}
public void Draw_StageClear()
{
buffg.drawImage(stage_clear_img, f_width/2 - 295, f_height/2, this);
}
public void Draw_Background(){
buffg.clearRect(0, 0, f_width, f_height);
if ( bx > - 600){
bx -= 1;
}else {
bx = 0;
}
buffg.drawImage(background_img, bx, 0, this);
}
public void Draw_Player(){
buffg.drawImage(plane_img, x, y, this);
}
public void Draw_Missile(){
for (int i = 0 ; i < Missile_List.size(); ++i){
//get missile position
ms = (Missile) (Missile_List.get(i));
//draw missile image to the current position
if(ms.who == 0) //plane
buffg.drawImage(missile_img, ms.x, ms.y, this);
if(ms.who == 1) //enemy
buffg.drawImage(enemy_missile_img, ms.x, ms.y, this);
}
}
public void Draw_Enemy(){
for (int i = 0 ; i < Enemy_List.size() ; ++i ){
en = (Enemy)(Enemy_List.get(i));
Image tmp = enemy_img1;
if(en.type == 2) tmp = enemy_img2;
else if(en.type == 3) tmp = enemy_img3;
else if(en.type == 4) tmp = boss1;
buffg.drawImage(tmp, en.x, en.y, this);
}
}
public void Draw_Explosion(){
for (int i = 0 ; i < Explosion_List.size() ; ++i ){
ex = (Explosion)Explosion_List.get(i);
if ( ex.ex_cnt < 20 ){
buffg.drawImage( explo_img, ex.x - explo_img.getWidth(null) / 2, ex.y - explo_img.getHeight(null) / 2, this);
}
else{
Explosion_List.remove(i);
ex.ex_cnt = 0;
}
}
}
public void Draw_StatusText(){
Color white = new Color(255, 255, 255);
buffg.setColor(white);
buffg.setFont(new Font("Defualt", Font.BOLD, 20));
buffg.drawString("SCORE : " + game_Score, 1000, 70);
buffg.drawString("HitPoint : " + player_Hitpoint, 1000, 90);
buffg.drawString("Ultimate Skill : " + Q_available, 1000, 110);
if(boss_Status == 1)
buffg.drawString("Boss HP : " + boss_Hitpoint , 1000, 130);
//buffg.drawString("Missile Count : " + Missile_List.size(), 1000, 110);
//buffg.drawString("Enemy Count : " + Enemy_List.size(), 1000, 130);
}
//////////////// key event ///////////////
public void keyPressed(KeyEvent e){ //keyboard push event
switch(e.getKeyCode()){
case KeyEvent.VK_UP :
KeyUp = true;
break;
case KeyEvent.VK_DOWN :
KeyDown = true;
break;
case KeyEvent.VK_LEFT :
KeyLeft = true;
break;
case KeyEvent.VK_RIGHT :
KeyRight = true;
break;
case KeyEvent.VK_SPACE : //missile
KeySpace = true;
break;
case KeyEvent.VK_Q : //ultimate skill
KeyQ = true;
break;
case KeyEvent.VK_T : //Test key, add 100 score
KeyQ = true;
break;
}
}
public void keyReleased(KeyEvent e){ //keyboard released event
switch(e.getKeyCode()){
case KeyEvent.VK_UP :
KeyUp = false;
break;
case KeyEvent.VK_DOWN :
KeyDown = false;
break;
case KeyEvent.VK_LEFT :
KeyLeft = false;
break;
case KeyEvent.VK_RIGHT :
KeyRight = false;
break;
case KeyEvent.VK_SPACE : //missile
KeySpace = false;
break;
case KeyEvent.VK_Q : //ultimate
KeyQ = false;
break;
case KeyEvent.VK_T : //test key
KeyT = false;
break;
}
}
public void keyTyped(KeyEvent e){} //dealing key event
public void KeyProcess(){ //plane's move scale
if(KeyUp == true) {
if( y > 20 ) y -= 5;
player_Status = 0;
}
if(KeyDown == true) {
if( y+ plane_img.getHeight(null) < f_height ) y += 5;
player_Status = 0;
}
if(KeyLeft == true) {
if ( x > 0 ) x -= 5;
player_Status = 0;
}
if(KeyRight == true) {
if ( x + plane_img.getWidth(null) < f_width ) x += 5;
player_Status = 0;
}
if(KeyQ == true && Q_available > 0){
Sound("sound/ultimate_skill.wav",false);
for(int i = 0; i < Enemy_List.size(); i++){
Enemy en = ((Enemy) Enemy_List.get(i));
if(en.type != 4)
Enemy_List.remove(i);
}
Missile_List.clear();
Q_available -= 1;
KeyQ = false;
}
if(KeyT == true) {
Score
}
}
public void Sound(String file, boolean Loop){
Clip clip;
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file)));
clip = AudioSystem.getClip();
clip.open(ais);
clip.start();
if (Loop) clip.loop(-1); //loop : true - endless
} catch (Exception e) {
e.printStackTrace();
}
}
public void GameOver(int fd){
if(fd <= 0){
all_stop = true;
Sound("sound/Game_Over_sound_effect.wav",false);
}
}
}
class Missile{
//missile position variable
int x,y,speed;
int who; // 0: plane, 1: enemy
Missile(int x, int y, int speed,int who){ //get missile position
this.x = x;
this.y = y;
this.speed = speed;
this.who = who;
}
public void move(){ //move missile
if(this.who == 0)
x += speed;
else
x -= speed;
}
}
class Enemy{
int x,y,speed;
int type;
Enemy(int x, int y, int speed,int type){
this.x = x;
this.y = y;
this.speed = speed;
this.type = type;
}
public void move(){
if(this.type != 4)
x -= speed;
else
if(x>900) x -= speed;
}
}
class Explosion{
int x,y;
int ex_cnt;
int damage;
Explosion(int x, int y, int damage){
this.x = x;
this.y = y;
this.damage = damage;
}
public void effect(){
ex_cnt ++;
}
}
|
package ru.thewizardplusplus.wizardbudget;
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
import org.json.*;
import android.annotation.SuppressLint;
import android.app.*;
import android.os.*;
import android.webkit.*;
import android.content.*;
import android.net.*;
import android.util.*;
import com.dropbox.client2.*;
import com.dropbox.client2.android.*;
import com.dropbox.client2.session.*;
import com.dropbox.client2.exception.*;
public class MainActivity extends Activity {
@Override
public void onBackPressed() {
callGuiFunction("back");
}
@JavascriptInterface
public void updateWidget() {
Utils.updateWidget(this);
}
@JavascriptInterface
public void selectBackupForRestore() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/xml");
startActivityForResult(intent, FILE_SELECT_CODE);
}
@JavascriptInterface
public void saveToDropbox(String filename) {
backup_filename = filename;
Log.d("drop", "start");
String dropbox_token = Settings.getCurrent(this).getDropboxToken();
if (!dropbox_token.isEmpty()) {
Log.d("drop", "not empty");
Log.d("drop", "\"" + dropbox_token + "\"");
AppKeyPair app_keys = getDropboxAppKeys();
AndroidAuthSession session = new AndroidAuthSession(
app_keys,
dropbox_token
);
dropbox_api = new DropboxAPI<AndroidAuthSession>(session);
saveBackupToDropbox();
} else {
Log.d("drop", "empty");
startDropboxAuthentication();
}
}
@JavascriptInterface
public void openSettings() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
@JavascriptInterface
public String getSetting(String name) {
Settings settings = Settings.getCurrent(this);
if (name.equals("credit_card_tag")) {
return settings.getCreditCardTag();
} else if (name.equals("save_backup_to_dropbox")) {
return settings.isSaveBackupToDropbox() ? "true" : "false";
} else if (name.equals(Settings.SETTING_NAME_CURRENT_PAGE)) {
return settings.getCurrentPage();
} else if (name.equals(Settings.SETTING_NAME_CURRENT_SEGMENT)) {
return settings.getCurrentSegment();
} else if (name.equals(Settings.SETTING_NAME_ACTIVE_SPENDING)) {
return settings.getActiveSpending();
} else if (name.equals(Settings.SETTING_NAME_ACTIVE_BUY)) {
return settings.getActiveBuy();
} else if (name.equals(Settings.SETTING_NAME_STATS_RANGE)) {
return String.valueOf(settings.getStatsRange());
} else if (name.equals(Settings.SETTING_NAME_STATS_TAGS)) {
return settings.getStatsTags();
} else if (name.equals("analysis_harvest")) {
return settings.isAnalysisHarvest() ? "true" : "false";
} else if (name.equals("harvest_username")) {
return settings.getHarvestUsername();
} else if (name.equals("harvest_password")) {
return settings.getHarvestPassword();
} else if (name.equals("harvest_subdomain")) {
return settings.getHarvestSubdomain();
} else if (name.equals(Settings.SETTING_NAME_WORKED_HOURS)) {
return settings.getWorkedHours();
} else if (name.equals(Settings.SETTING_NAME_WORK_CALENDAR)) {
return settings.getWorkCalendar();
} else if (name.equals(Settings.SETTING_NAME_HOURS_DATA)) {
return settings.getHoursData();
} else if (name.equals(Settings.SETTING_NAME_NEED_UPDATE_HOURS)) {
return settings.isNeedUpdateHours() ? "true" : "false";
} else {
return "";
}
}
@JavascriptInterface
public void setSetting(String name, String value) {
Settings settings = Settings.getCurrent(this);
if (name.equals(Settings.SETTING_NAME_CURRENT_PAGE)) {
settings.setCurrentPage(value);
} else if (name.equals(Settings.SETTING_NAME_CURRENT_SEGMENT)) {
settings.setCurrentSegment(value);
} else if (name.equals(Settings.SETTING_NAME_ACTIVE_SPENDING)) {
settings.setActiveSpending(value);
} else if (name.equals(Settings.SETTING_NAME_ACTIVE_BUY)) {
settings.setActiveBuy(value);
} else if (name.equals(Settings.SETTING_NAME_STATS_RANGE)) {
settings.setStatsRange(Long.valueOf(value));
} else if (name.equals(Settings.SETTING_NAME_STATS_TAGS)) {
settings.setStatsTags(value);
} else if (name.equals(Settings.SETTING_NAME_WORKED_HOURS)) {
settings.setWorkedHours(value);
} else if (name.equals(Settings.SETTING_NAME_WORK_CALENDAR)) {
settings.setWorkCalendar(value);
} else if (name.equals(Settings.SETTING_NAME_HOURS_DATA)) {
settings.setHoursData(value);
} else if (name.equals(Settings.SETTING_NAME_NEED_UPDATE_HOURS)) {
settings.setNeedUpdateHours(value.equals("true"));
}
settings.save();
}
@JavascriptInterface
public void httpRequest(String name, String url, String headers) {
try {
callGuiFunction(
"addLoadingLogMessage",
new String[]{
JSONObject.quote(
"Start the " + JSONObject.quote(name) + " HTTP request."
)
}
);
Map<String, String> header_map = new HashMap<String, String>();
try {
JSONObject headers_json = new JSONObject(headers);
@SuppressWarnings("unchecked")
Iterator<String> i = headers_json.keys();
while (i.hasNext()) {
String header_name = i.next();
String header_value = headers_json.optString(header_name);
header_map.put(header_name, header_value.toString());
}
} catch(JSONException exception) {}
final MainActivity self = this;
final String name_copy = name;
HttpRequestTask task = new HttpRequestTask(
header_map,
new HttpRequestTask.OnSuccessListener() {
@Override
public void onSuccess(String data) {
self.callGuiFunction(
"setHttpResult",
new String[]{
JSONObject.quote(name_copy),
JSONObject.quote(data)
}
);
}
}
);
task.execute(new URL(url));
} catch(MalformedURLException exception) {}
}
@JavascriptInterface
public void log(String message) {
Log.d("web", message);
}
@JavascriptInterface
public void quit() {
finish();
}
@Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle saved_instance_state) {
super.onCreate(saved_instance_state);
setContentView(R.layout.main);
String current_page =
getIntent()
.getStringExtra(Settings.SETTING_NAME_CURRENT_PAGE);
if (current_page != null) {
Settings settings = Settings.getCurrent(this);
settings.setCurrentPage(current_page);
settings.save();
}
String current_segment =
getIntent()
.getStringExtra(Settings.SETTING_NAME_CURRENT_SEGMENT);
if (current_segment != null) {
Settings settings = Settings.getCurrent(this);
settings.setCurrentSegment(current_segment);
settings.save();
}
boolean need_update_hours =
getIntent()
.getBooleanExtra(Settings.SETTING_NAME_NEED_UPDATE_HOURS, false);
if (need_update_hours) {
Settings settings = Settings.getCurrent(this);
settings.setNeedUpdateHours(true);
settings.save();
}
WebView web_view = (WebView)findViewById(R.id.web_view);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.setWebViewClient(
new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(
WebView view,
String url
) {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(url)
);
startActivity(intent);
} catch(ActivityNotFoundException exception) {}
return true;
}
}
);
web_view.addJavascriptInterface(this, "activity");
SpendingManager spending_manager = new SpendingManager(this);
web_view.addJavascriptInterface(spending_manager, "spending_manager");
BuyManager buy_manager = new BuyManager(this);
web_view.addJavascriptInterface(buy_manager, "buy_manager");
BackupManager backup_manager = new BackupManager(this);
web_view.addJavascriptInterface(backup_manager, "backup_manager");
web_view.loadUrl("file:///android_asset/web/index.html");
}
@Override
protected void onResume() {
super.onResume();
callGuiFunction("refresh");
if (
dropbox_api != null
&& dropbox_api.getSession().authenticationSuccessful()
) {
try {
dropbox_api.getSession().finishAuthentication();
String token = dropbox_api.getSession().getOAuth2AccessToken();
Settings settings = Settings.getCurrent(this);
settings.setDropboxToken(token);
settings.save();
saveBackupToDropbox();
} catch (IllegalStateException exception) {}
}
}
@Override
protected void onActivityResult(
int request_code,
int result_code,
Intent data
) {
if (
result_code == Activity.RESULT_OK
&& request_code == FILE_SELECT_CODE
) {
Uri uri = data.getData();
if (uri != null) {
String path = uri.getPath();
if (path != null) {
String[] path_parts = path.split(":");
restoreBackup(
Environment.getExternalStorageDirectory()
+ "/"
+ path_parts[path_parts.length > 1 ? 1 : 0]
);
callGuiFunction("refresh");
}
}
}
}
private static final int FILE_SELECT_CODE = 1;
private DropboxAPI<AndroidAuthSession> dropbox_api;
private String backup_filename = "";
private void callGuiFunction(String name, String[] arguments) {
String arguments_string = "";
for (int i = 0; i < arguments.length; i++) {
if (i > 0) {
arguments_string += ",";
}
arguments_string += arguments[i];
}
WebView web_view = (WebView)findViewById(R.id.web_view);
web_view.loadUrl(
"javascript:GUI."
+ name
+ "("
+ arguments_string
+ ")"
);
}
private void callGuiFunction(String name) {
callGuiFunction(name, new String[]{});
}
private void restoreBackup(String filename) {
File backup_file = new File(filename);
InputStream in = null;
try {
try {
in = new BufferedInputStream(new FileInputStream(backup_file));
BackupManager backup_manager = new BackupManager(this);
backup_manager.restore(in);
} finally {
if (in != null) {
in.close();
}
}
} catch (IOException exception) {}
}
private void saveBackupToDropbox() {
final Context context_copy = this;
new Thread(
new Runnable() {
@Override
public void run() {
try {
File backup = new File(backup_filename);
FileInputStream in = new FileInputStream(backup);
dropbox_api.putFile(
"/" + backup.getName(),
in,
backup.length(),
null,
null
);
if (
Settings
.getCurrent(context_copy)
.isDropboxNotification()
) {
Date current_date = new Date();
DateFormat notification_timestamp_format =
DateFormat
.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
Locale.US
);
String notification_timestamp =
notification_timestamp_format
.format(current_date);
Utils.showNotification(
context_copy,
context_copy.getString(R.string.app_name),
"Backup saved to Dropbox at "
+ notification_timestamp + ".",
null
);
}
} catch (FileNotFoundException exception) {
} catch (DropboxException exception) {}
}
}
).start();
}
private void startDropboxAuthentication() {
Log.d("drop", "auth");
AppKeyPair app_keys = getDropboxAppKeys();
Log.d("drop", "1");
AndroidAuthSession session = new AndroidAuthSession(app_keys);
Log.d("drop", "2");
dropbox_api = new DropboxAPI<AndroidAuthSession>(session);
Log.d("drop", "3");
try{
dropbox_api.getSession().startOAuth2Authentication(this);
}catch(Exception e) {
Log.d("drop", "error \"" +e.getMessage()+"\"");
}
Log.d("drop", "4");
}
private AppKeyPair getDropboxAppKeys() {
Settings settings = Settings.getCurrent(this);
String app_key = settings.getDropboxAppKey();
Log.d("drop", "key \"" + app_key + "\"");
String app_secret = settings.getDropboxAppSecret();
Log.d("drop", "secret \"" + app_secret + "\"");
return new AppKeyPair(app_key, app_secret);
}
}
|
package axo.core.operators;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
import java.util.Stack;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import axo.core.Action0;
import axo.core.Action1;
import axo.core.Operator;
import axo.core.StreamContext;
import axo.core.concurrent.SchedulerContext;
public abstract class FsmOperator<T, R> extends Operator<T, R> {
private final SchedulerContext scheduler;
private Subscription subscription = null;
private boolean completed = false;
private boolean terminated = false;
private Stack<State<T>> states = new Stack<> ();
private Queue<R> producedElements = new LinkedList<> ();
private long requestedCount = 0;
private boolean elementRequested = false;
public FsmOperator (final StreamContext context, final Subscriber<? super R> subscriber) {
super(context, subscriber);
this.scheduler = context.getScheduler().createSynchronizedContext ();
states.push (state (this::handleInput, this::handleComplete));
}
@Override
public final void onSubscribe (final Subscription subscription) {
this.subscription = subscription;
getSubscriber ().onSubscribe (new Subscription () {
@Override
public void request (final long n) {
if (n <= 0) {
getSubscriber ().onError (new IllegalArgumentException ("n should be > 0 3.9"));
terminated = true;
return;
}
scheduler.schedule (() -> requestElements (n));
}
@Override
public void cancel() {
scheduler.schedule (() -> cancelSubscription ());
}
});
subscription.request (1);
elementRequested = true;
}
@Override
public final void onComplete () {
scheduler.schedule (this::handleOnComplete);
}
@Override
public final void onError (final Throwable t) {
scheduler.schedule (() -> handleOnError (t));
}
@Override
public final void onNext (final T t) {
scheduler.schedule (() -> handleOnNext (t));
}
private void handleOnComplete () {
if (terminated) {
return;
}
}
private void handleOnError (final Throwable t) {
getSubscriber ().onError (t);
terminated = true;
}
private void handleOnNext (final T t) {
elementRequested = false;
if (terminated) {
return;
}
wrapExceptions (() -> {
states.peek ().getInputHandler().apply (t);
});
if (!terminated && !completed && requestedCount > 0) {
subscription.request (1);
elementRequested = true;
}
}
private void requestElements (final long n) {
if (terminated) {
return;
}
if (requestedCount + n <= requestedCount) {
requestedCount = Long.MAX_VALUE;
} else {
requestedCount += n;
}
if (!elementRequested) {
elementRequested = true;
subscription.request (1);
}
scheduler.schedule (this::submitProducedElements);
}
private void cancelSubscription () {
if (terminated) {
return;
}
subscription.cancel ();
terminated = true;
}
private void wrapExceptions (final Action0 action) {
try {
action.apply ();
} catch (Throwable t) {
getSubscriber().onError (t);
terminated = true;
if (subscription != null) {
subscription.cancel ();
}
}
}
private void submitProducedElements () {
wrapExceptions (() -> {
while (requestedCount > 0 && !producedElements.isEmpty ()) {
getSubscriber ().onNext (producedElements.remove ());
-- requestedCount;
}
if (completed && producedElements.isEmpty ()) {
getSubscriber ().onComplete ();
}
});
}
protected final void produce (final R element) {
if (completed) {
throw new IllegalStateException ("Cannot produce elements when the in the completed state");
}
producedElements.add (Objects.requireNonNull (element, "element cannot be null"));
scheduler.schedule (this::submitProducedElements);
}
protected final void complete () {
completed = true;
scheduler.schedule (this::submitProducedElements);
}
@SafeVarargs
protected final void gotoState (final State<T> state, final T ... ts) {
Objects.requireNonNull (state, "state cannot be null");
states.pop ();
states.push (state);
wrapExceptions (() -> {
for (final T t: ts) {
state.getInputHandler ().apply (t);
}
});
}
@SafeVarargs
protected final void pushState (final State<T> state, final T ... ts) {
Objects.requireNonNull (state, "state cannot be null");
states.push (state);
wrapExceptions (() -> {
for (final T t: ts) {
state.getInputHandler ().apply (t);
}
});
}
protected final void popState () {
if (states.size () <= 1) {
throw new IllegalStateException ("cannot pop the last state");
}
states.pop ();
}
protected final void resetState () {
states.clear ();
states.push (new State<T> (this::handleInput, this::handleComplete));
}
public abstract void handleInput (final T input);
public abstract void handleComplete ();
public static <T> State<T> state (final Action1<T> handleInput, final Action0 handleComplete) {
return new State<> (handleInput, handleComplete);
}
public final static class State<T> {
private final Action1<T> handleInput;
private final Action0 handleComplete;
public State (final Action1<T> handleInput, final Action0 handleComplete) {
this.handleInput = Objects.requireNonNull (handleInput, "handleInput cannot be null");
this.handleComplete = Objects.requireNonNull (handleComplete, "handleComplete cannot be null");
}
public Action1<T> getInputHandler () {
return handleInput;
}
public Action0 getCompletionHandler () {
return handleComplete;
}
}
}
|
package org.perl6.nqp.sixmodel.reprs;
import java.util.concurrent.locks.ReentrantLock;
import org.perl6.nqp.runtime.ExceptionHandling;
import org.perl6.nqp.runtime.ThreadContext;
import org.perl6.nqp.sixmodel.REPR;
import org.perl6.nqp.sixmodel.STable;
import org.perl6.nqp.sixmodel.SerializationReader;
import org.perl6.nqp.sixmodel.SerializationWriter;
import org.perl6.nqp.sixmodel.SixModelObject;
import org.perl6.nqp.sixmodel.TypeObject;
public class ReentrantMutex extends REPR {
public SixModelObject type_object_for(ThreadContext tc, SixModelObject HOW) {
STable st = new STable(this, HOW);
SixModelObject obj = new TypeObject();
obj.st = st;
st.WHAT = obj;
return st.WHAT;
}
public SixModelObject allocate(ThreadContext tc, STable st) {
ReentrantMutexInstance obj = new ReentrantMutexInstance();
obj.st = st;
obj.lock = new ReentrantLock();
return obj;
}
public SixModelObject deserialize_stub(ThreadContext tc, STable st) {
return allocate(tc, st);
}
public void deserialize_finish(ThreadContext tc, STable st,
SerializationReader reader, SixModelObject obj) {
/* Already did it all in deserialize_stub. */
}
public void serialize(ThreadContext tc, SerializationWriter writer, SixModelObject obj) {
/* Nothing to do, we just re-create the lock on deserialization. */
}
}
|
package algorithms.tsp;
import algorithms.SubsetChooser;
import junit.framework.TestCase;
public class TSPDynamicOutlineTest extends TestCase {
public TSPDynamicOutlineTest() {
}
public void test0() {
//nP = C(n-1,k) for 1 fixed node
int n = 10;
int k = 3;
SubsetChooser chooser = new SubsetChooser(n-1, k);
int c = 0;
long s, sInv;
StringBuilder sb;
long all1s = 1 << (n-1);
all1s = all1s|all1s-1;
int nSetBits;
long tZeros;
while (true) {
s = chooser.getNextSubset64Bitstring();
if (s == -1) {
break;
}
s <<= 1;
sb = new StringBuilder(Long.toBinaryString(s));
while (sb.length() < n) {
sb = sb.insert(0, "0");
}
sInv = s^all1s;
sInv &= ~1; // clear bit 0
nSetBits = Long.bitCount(sInv);
tZeros = Long.numberOfTrailingZeros(sInv);
System.out.printf("%d (%7s) (%7s) nSetBits=%d tz=%d\n",
s, sb, Long.toBinaryString(sInv), nSetBits, tZeros);
// this permutation of nSetBits can be used for all 84 of the first
// 3-node paths.
// each use of the permutation can be left shifted by tZeros
// then assigned positions relative to the set bits in sInv
// to get the remaining permutations for this specific si
SubsetChooser chooseri = new SubsetChooser(nSetBits, k);
long si;
while (true) {
si = chooseri.getNextSubset64Bitstring();
if (si == -1) {
break;
}
long s2 = si << tZeros;
// the nSetBits in si are to be shifted by tZeros
// then converted to the si set bit positions
}
c++;
}
System.out.printf("n=%d count=%d\n", n, c);
}
}
|
package br.com.daniel.jdbc.teste.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.Test;
import br.com.daniel.jdbc.conexao.Conexao;
import br.com.daniel.jdbc.dao.Dao;
public class DaoTest {
@Test
public void deveraRealizarUmSelect() throws SQLException{
Dao dao = new Dao();
ResultSet result = dao.sid()
.dql(new Conexao().conectarMysql())
.select("SELECT id, nome FROM teste.teste")
.execute();
String nome = null;
Integer idade = null;
while (result.next()) {
nome = result.getString("nome");
idade = result.getInt("idade");
break;
}
Assert.assertEquals("Daniel", nome);
Assert.assertEquals(Integer.valueOf(27), idade);
}
@Test
public void deveraRealizarUmSelectComParametros() throws SQLException{
Dao dao = new Dao();
ResultSet result = dao.sid()
.dql(new Conexao().conectarMysql())
.select("SELECT id, nome FROM teste.teste WHERE id = ? AND nome = ?", 27, "Daniel")
.execute();
String nome = null;
Integer id = null;
while (result.next()) {
nome = result.getString("nome");
id = result.getInt("id");
break;
}
Assert.assertEquals("Daniel", nome);
Assert.assertEquals(Integer.valueOf(1), id);
}
@Test
public void deveraAtualizarUmRegistroNaBaseDeDados() throws SQLException{
Dao dao = new Dao();
Integer id = null;
String nomeSemUpdate = null;
Integer idadeSemUpdate = null;
String nomeAtualizado = null;
Integer idadeAtualizada = null;
ResultSet result1 = dao.sid().dql(new Conexao().conectarMysql())
.select("SELECT * FROM teste.teste WHERE nome = ? AND idade = ?", "Teste", 10)
.execute();
while (result1.next()) {
nomeSemUpdate = result1.getString("nome");
idadeSemUpdate = result1.getInt("idade");
id = result1.getInt("id");
}
Assert.assertEquals("Teste", nomeSemUpdate);
Assert.assertEquals(Integer.valueOf(10), idadeSemUpdate);
result1.close();
// Atualiza dados
Boolean response = dao.sid().dml(new Conexao().conectarMysql())
.update("UPDATE `teste`.`teste` SET `nome`= ?, `idade`= ? WHERE `id`= ? ","Teste2", 22, id)
.execute();
Assert.assertEquals(true, response);
result1 = dao.sid().dql(new Conexao().conectarMysql())
.select("SELECT * FROM teste.teste WHERE nome = ? AND idade = ?", "Teste2", 22)
.execute();
while (result1.next()) {
nomeAtualizado = result1.getString("nome");
idadeAtualizada = result1.getInt("idade");
}
Assert.assertNotEquals(nomeSemUpdate, nomeAtualizado);
Assert.assertNotEquals(idadeSemUpdate, idadeAtualizada);
Assert.assertEquals("Teste2", nomeAtualizado);
Assert.assertEquals(Integer.valueOf(22), idadeAtualizada);
}
@Test
public void deveraExcluirUmRegistro() throws SQLException {
Dao dao = new Dao();
int quantidadeDeRegistros = 0;
ResultSet result = dao.sid().dql(new Conexao().conectarMysql())
.select("SELECT count(id) AS quant FROM teste.teste WHERE nome = ? AND idade = ?", "Teste2", 22)
.execute();
while (result.next()) {
quantidadeDeRegistros = result.getInt("quant");
}
result.close();
Assert.assertEquals(1, quantidadeDeRegistros);
// Exclui o registro
Boolean response = dao.sid().dml(new Conexao().conectarMysql())
.delete("DELETE FROM `teste`.`teste` WHERE nome = ? AND idade = ?", "Teste2", 22)
.execute();
Assert.assertEquals(true, response);
result = dao.sid().dql(new Conexao().conectarMysql())
.select("SELECT count(id) AS quant FROM teste.teste WHERE nome = ? AND idade = ?", "Teste2", 22)
.execute();
while (result.next()) {
quantidadeDeRegistros = result.getInt("quant");
}
result.close();
Assert.assertEquals(0, quantidadeDeRegistros);
}
}
|
package com.alibaba.rocketmq.storm;
import com.alibaba.rocketmq.storm.hbase.HBaseClient;
import com.alibaba.rocketmq.storm.hbase.exception.HBasePersistenceException;
import com.alibaba.rocketmq.storm.model.HBaseData;
import org.junit.Test;
import java.util.Calendar;
import java.util.List;
public class HBaseTest {
@Test
public void scan(){
HBaseClient hBaseClient = new HBaseClient();
hBaseClient.start();
Calendar old = Calendar.getInstance();
old.add(Calendar.DAY_OF_MONTH, -3);
try {
List<HBaseData> list = hBaseClient.scan("3", "9", old, Calendar.getInstance(), "eagle_log", "t");
for (HBaseData hBaseData:list){
System.out.println(hBaseData.toString());
}
} catch (HBasePersistenceException e) {
e.printStackTrace();
}
}
}
|
package com.auth0.client.mgmt;
import com.auth0.json.mgmt.jobs.Job;
import com.auth0.net.Request;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Test;
import java.util.Map;
import static com.auth0.client.MockServer.*;
import static com.auth0.client.RecordedRequestMatcher.hasHeader;
import static com.auth0.client.RecordedRequestMatcher.hasMethodAndPath;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
public class JobsEntityTest extends BaseMgmtEntityTest {
@Test
public void shouldSendAUserAVerificationEmail() throws Exception {
Request<Job> request = api.jobs().sendVerificationEmail("google-oauth2|1234", null);
assertThat(request, is(notNullValue()));
server.jsonResponse(MGMT_JOB_POST_VERIFICATION_EMAIL, 200);
Job response = request.execute();
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest, hasMethodAndPath("POST", "/api/v2/jobs/verification-email"));
assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
Map<String, Object> body = bodyFromRequest(recordedRequest);
assertThat(body.size(), is(1));
assertThat(body, hasEntry("user_id", "google-oauth2|1234"));
assertThat(response, is(notNullValue()));
}
@Test
public void shouldThrowOnNullEmailRecipient() throws Exception {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("'recipient' cannot be null!");
api.jobs().sendVerificationEmail(null, null);
}
}
|
package sh.echo.decisionmaker.fragments;
import sh.echo.decisionmaker.ProgramManager;
import sh.echo.decisionmaker.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
public class DeleteConfirmDialogFragment extends DialogFragment {
// for displaying which option is being deleted
private String itemName;
/**
* Creates an instance of DeleteConfirmDialogFragment for use.
* @return
*/
public static DeleteConfirmDialogFragment newInstance(String itemName) {
DeleteConfirmDialogFragment fragment = new DeleteConfirmDialogFragment();
fragment.itemName = itemName;
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// get saved arguments
if (itemName == null) {
Log.w("DeleteConfirmDialogFragment", "no program name supplied");
itemName = "";
}
// build message string
String message = String.format(getResources().getString(R.string.delete_confirm_dialog_message), itemName);
// create dialog
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.delete_confirm_dialog_title)
.setMessage(message)
.setPositiveButton(R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// confirmed by user, so remove
ProgramManager.removeProgram(itemName);
}
})
.setNegativeButton(R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}
}
|
package com.datdo.mobilib.base;
import android.support.v4.app.Fragment;
import com.datdo.mobilib.event.MblEventCenter;
import com.datdo.mobilib.event.MblEventListener;
import com.datdo.mobilib.util.MblUtils;
public class MblBaseFragment extends Fragment {
@Override
public void onDestroyView() {
if (this instanceof MblEventListener) {
MblEventCenter.removeListenerFromAllEvents((MblEventListener) this);
}
MblUtils.cleanupView(getView());
super.onDestroyView();
}
}
|
package com.hearthsim.test.heroes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.hearthsim.card.Card;
import com.hearthsim.card.Deck;
import com.hearthsim.card.minion.Hero;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.concrete.ChillwindYeti;
import com.hearthsim.card.minion.heroes.Priest;
import com.hearthsim.card.minion.heroes.TestHero;
import com.hearthsim.card.spellcard.concrete.TheCoin;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.player.playercontroller.BruteForceSearchAI;
import com.hearthsim.util.factory.BoardStateFactoryBase;
import com.hearthsim.util.tree.HearthTreeNode;
public class TestPriest {
private HearthTreeNode board;
private Deck deck;
@Before
public void setup() {
board = new HearthTreeNode(new BoardModel(new Priest(), new TestHero()));
Minion minion0_0 = new ChillwindYeti();
Minion minion0_1 = new ChillwindYeti();
Minion minion1_0 = new ChillwindYeti();
Minion minion1_1 = new ChillwindYeti();
board.data_.placeCardHandCurrentPlayer(minion0_1);
board.data_.placeCardHandCurrentPlayer(minion0_0);
board.data_.placeCardHandWaitingPlayer(minion1_1);
board.data_.placeCardHandWaitingPlayer(minion1_0);
Card cards[] = new Card[10];
for (int index = 0; index < 10; ++index) {
cards[index] = new TheCoin();
}
deck = new Deck(cards);
board.data_.getCurrentPlayer().setMana((byte)9);
board.data_.getWaitingPlayer().setMana((byte)9);
board.data_.getCurrentPlayer().setMaxMana((byte)8);
board.data_.getWaitingPlayer().setMaxMana((byte)8);
HearthTreeNode tmpBoard = new HearthTreeNode(board.data_.flipPlayers());
try {
tmpBoard.data_.getCurrentPlayerCardHand(0)
.useOn(PlayerSide.CURRENT_PLAYER,
tmpBoard.data_.getCurrentPlayerHero(), tmpBoard,
deck, null);
tmpBoard.data_.getCurrentPlayerCardHand(0)
.useOn(PlayerSide.CURRENT_PLAYER,
tmpBoard.data_.getCurrentPlayerHero(), tmpBoard,
deck, null);
} catch (HSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board = new HearthTreeNode(tmpBoard.data_.flipPlayers());
try {
board.data_.getCurrentPlayerCardHand(0).useOn(
PlayerSide.CURRENT_PLAYER,
board.data_.getCurrentPlayerHero(), board, deck, null);
board.data_.getCurrentPlayerCardHand(0).useOn(
PlayerSide.CURRENT_PLAYER,
board.data_.getCurrentPlayerHero(), board, deck, null);
} catch (HSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.data_.resetMana();
board.data_.resetMinions();
}
@Test
public void testAiHealAfterTrading() throws HSException {
BoardStateFactoryBase factory = new BoardStateFactoryBase(null, null,
2000000000);
HearthTreeNode tree = new HearthTreeNode(board.data_);
BruteForceSearchAI ai0 = BruteForceSearchAI.buildStandardAI1();
try {
tree = factory.doMoves(tree, ai0);
} catch (HSException e) {
e.printStackTrace();
assertTrue(false);
}
// best move is to kill one enemy yeti with 2 of your own yeti and heal
// one of your own yeti
HearthTreeNode bestPlay = tree.findMaxOfFunc(ai0);
assertFalse(tree == null);
assertEquals(bestPlay.data_.getNumCards_hand(), 0);
assertEquals(bestPlay.data_.getCurrentPlayer().getNumMinions(), 2);
assertEquals(bestPlay.data_.getWaitingPlayer().getNumMinions(), 1);
assertEquals(bestPlay.data_.getCurrentPlayer().getMana(), 6);
assertEquals(bestPlay.data_.getWaitingPlayer().getMana(), 8);
assertEquals(bestPlay.data_.getCurrentPlayerHero().getHealth(), 30);
assertEquals(bestPlay.data_.getWaitingPlayerHero().getHealth(), 30);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(0)
.getHealth(), 3);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(1)
.getHealth(), 1);
assertEquals(bestPlay.data_.getWaitingPlayer().getMinions().get(0)
.getHealth(), 5);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(0)
.getTotalAttack(), 4);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(1)
.getTotalAttack(), 4);
assertEquals(bestPlay.data_.getWaitingPlayer().getMinions().get(0)
.getTotalAttack(), 4);
}
@Test
public void testAiHealBeforeTrading() throws HSException {
// one of your yeti is damaged
PlayerSide.CURRENT_PLAYER.getPlayer(board).getMinions().get(0)
.setHealth((byte) 3);
BoardStateFactoryBase factory = new BoardStateFactoryBase(null, null,
2000000000);
HearthTreeNode tree = new HearthTreeNode(board.data_);
BruteForceSearchAI ai0 = BruteForceSearchAI.buildStandardAI1();
try {
tree = factory.doMoves(tree, ai0);
} catch (HSException e) {
e.printStackTrace();
assertTrue(false);
}
// best move is to heal the damaged yeti and attack with both to kill
// one of the enemy's yeti
HearthTreeNode bestPlay = tree.findMaxOfFunc(ai0);
assertFalse(tree == null);
assertEquals(bestPlay.data_.getNumCards_hand(), 0);
assertEquals(bestPlay.data_.getCurrentPlayer().getNumMinions(), 2);
assertEquals(bestPlay.data_.getWaitingPlayer().getNumMinions(), 1);
assertEquals(bestPlay.data_.getCurrentPlayer().getMana(), 6);
assertEquals(bestPlay.data_.getWaitingPlayer().getMana(), 8);
assertEquals(bestPlay.data_.getCurrentPlayerHero().getHealth(), 30);
assertEquals(bestPlay.data_.getWaitingPlayerHero().getHealth(), 30);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(0)
.getHealth(), 1);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(1)
.getHealth(), 1);
assertEquals(bestPlay.data_.getWaitingPlayer().getMinions().get(0)
.getHealth(), 5);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(0)
.getTotalAttack(), 4);
assertEquals(bestPlay.data_.getCurrentPlayer().getMinions().get(1)
.getTotalAttack(), 4);
assertEquals(bestPlay.data_.getWaitingPlayer().getMinions().get(0)
.getTotalAttack(), 4);
}
@Test
public void testHeropowerAgainstOpponent() throws HSException {
Minion target = board.data_.getCharacter(PlayerSide.WAITING_PLAYER, 0); // Opponent
// hero
target.setHealth((byte) 20);
Hero priest = board.data_.getCurrentPlayerHero();
HearthTreeNode ret = priest.useHeroAbility(PlayerSide.WAITING_PLAYER,
target, board, deck, null);
assertNotNull(ret);
assertEquals(board.data_.getCurrentPlayer().getMana(), 6);
assertEquals(board.data_.getWaitingPlayerHero().getHealth(), 22);
}
@Test
public void testHeropowerAgainstMinion() throws HSException {
Minion target = board.data_.getCharacter(PlayerSide.WAITING_PLAYER, 1);
target.setHealth((byte) 1);
Hero priest = board.data_.getCurrentPlayerHero();
HearthTreeNode ret = priest.useHeroAbility(PlayerSide.WAITING_PLAYER,
target, board, deck, null);
assertNotNull(ret);
assertEquals(board.data_.getCurrentPlayer().getMana(), 6);
assertEquals(PlayerSide.WAITING_PLAYER.getPlayer(board).getMinions()
.get(0).getHealth(), 3);
}
@Test
public void testHeropowerAgainstSelf() throws HSException {
Minion target = board.data_.getCharacter(PlayerSide.CURRENT_PLAYER, 0); // Self
target.setHealth((byte) 20);
Hero priest = board.data_.getCurrentPlayerHero();
HearthTreeNode ret = priest.useHeroAbility(PlayerSide.WAITING_PLAYER,
target, board, deck, null);
assertNotNull(ret);
assertEquals(board.data_.getCurrentPlayer().getMana(), 6);
assertEquals(board.data_.getCurrentPlayerHero().getHealth(), 22);
}
@Test
public void testHeropowerAgainstOwnMinion() throws HSException {
Minion target = board.data_.getCharacter(PlayerSide.CURRENT_PLAYER, 1);
target.setHealth((byte) 1);
Hero priest = board.data_.getCurrentPlayerHero();
HearthTreeNode ret = priest.useHeroAbility(PlayerSide.CURRENT_PLAYER,
target, board, deck, null);
assertNotNull(ret);
assertEquals(board.data_.getCurrentPlayer().getMana(), 6);
assertEquals(PlayerSide.CURRENT_PLAYER.getPlayer(board).getMinions()
.get(0).getHealth(), 3);
}
}
|
package com.ltsllc.miranda.miranda;
import com.ltsllc.miranda.Message;
import com.ltsllc.miranda.Panic;
import com.ltsllc.miranda.StartupPanic;
import com.ltsllc.miranda.test.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import java.util.concurrent.BlockingQueue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
public class TestMirandaPanicPolicy extends TestCase {
private MirandaPanicPolicy mirandaPanicPolicy;
public MirandaPanicPolicy getMirandaPanicPolicy() {
return mirandaPanicPolicy;
}
public void reset () {
super.reset();
mirandaPanicPolicy = null;
}
@Before
public void setup () {
reset();
super.setup();
setuplog4j();
setupMockMiranda();
setupMockTimer();
mirandaPanicPolicy = new MirandaPanicPolicy(10, 10000, getMockMiranda(), getMockTimer());
mirandaPanicPolicy.setTestMode(true);
}
@Test
public void testPanicStartupPanic () {
StartupPanic startupPanic = new StartupPanic("a test", null, StartupPanic.StartupReasons.Test);
boolean result = getMirandaPanicPolicy().panic(startupPanic);
assert (result);
}
@Test
public void testPanicDoesNotUnderstand () {
assert (getMirandaPanicPolicy().getPanicCount() == 0);
Panic panic = new Panic ("a test", null, Panic.Reasons.DoesNotUnderstand);
boolean result = getMirandaPanicPolicy().panic(panic);
assert (!result);
assert (getMirandaPanicPolicy().getPanicCount() == 1);
}
@Test
public void testPanicDoesNotUnderstandNetworkMessage () {
Panic panic = new Panic("a test", null, Panic.Reasons.DoesNotUnderstandNetworkMessage);
int before = getMirandaPanicPolicy().getPanicCount();
boolean result = getMirandaPanicPolicy().panic(panic);
assert (!result);
assert (before == getMirandaPanicPolicy().getPanicCount());
}
}
|
package com.programmaticallyspeaking.tinyws;
import com.programmaticallyspeaking.tinyws.Server.WebSocketHandler;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
public class WebSocketTest extends ClientTestBase {
private boolean useEchoHandler;
private URI createURI() throws URISyntaxException {
return new URI("ws://" + host + ":" + port);
}
@BeforeMethod
public void init() {
useEchoHandler = false;
}
@Override
protected WebSocketHandler createHandler() {
return useEchoHandler ? new EchoHandler() : super.createHandler();
}
private void sendIncorrectFrame() throws Exception {
SimpleClient cl = new SimpleClient(createURI());
cl.sendRawData(new byte [] { (byte)112, 0 });
cl.waitUntilClosed();
}
private SimpleClient sendText(String text) throws Exception {
SimpleClient cl = new SimpleClient(createURI());
cl.send(text);
cl.sendClose(1001);
cl.waitUntilClosed();
return cl;
}
private void sendClose() throws Exception {
SimpleClient cl = new SimpleClient(createURI());
cl.getConnection().close(1001);
cl.waitUntilClosed();
}
@Test
public void Incorrect_frame_should_invoke_onClosedByServer() throws Exception {
sendIncorrectFrame();
WebSocketHandler handler = createdHandlers.remove();
verify(handler, times(1)).onClosedByServer(1002, "Protocol error");
}
@Test
public void Incorrect_frame_should_not_invoke_onClosedByClient() throws Exception {
sendIncorrectFrame();
WebSocketHandler handler = createdHandlers.remove();
verify(handler, never()).onClosedByClient(anyInt(), anyString());
}
@Test
public void Proper_close_should_invoke_onClosedByClient() throws Exception {
sendClose();
WebSocketHandler handler = createdHandlers.remove();
verify(handler, times(1)).onClosedByClient(1001, null);
}
@Test
public void Proper_close_should_not_invoke_onClosedByServer() throws Exception {
sendClose();
WebSocketHandler handler = createdHandlers.remove();
verify(handler, never()).onClosedByServer(anyInt(), anyString());
}
@Test
public void Correct_frame_should_result_in_echo_response() throws Exception {
useEchoHandler = true;
SimpleClient cl = sendText("hello world");
assertThat(cl.messages).containsExactly("hello world");
}
static class SimpleClient extends org.java_websocket.client.WebSocketClient {
private CountDownLatch closeLatch = new CountDownLatch(1);
List<String> messages = new ArrayList<>();
void sendRawData(byte[] data) {
((DraftThatAllowsUsToSendBogusData) getConnection().getDraft()).setDataToSend(data);
getConnection().sendFrame(null);
}
void waitUntilClosed() throws InterruptedException {
closeLatch.await();
}
public SimpleClient(URI serverURI) throws InterruptedException {
super(serverURI, new DraftThatAllowsUsToSendBogusData());
if (!this.connectBlocking()) throw new IllegalStateException("Not connected");
}
public void onOpen(ServerHandshake handshakedata) {
}
public void onMessage(String message) {
messages.add(message);
}
public void onClose(int code, String reason, boolean remote) {
closeLatch.countDown();
}
public void onError(Exception ex) {
}
void sendClose(int code) {
// We just want to send the close frame and let the remote close the connection, otherwise we might
// not receive an echo response in time.
sendRawData(new byte [] { (byte)136, 2, (byte) ((code & 0xff00) >>> 8), (byte) (code & 0xff) });
}
}
static class DraftThatAllowsUsToSendBogusData extends Draft_17 {
private byte[] dataToSend;
void setDataToSend(byte[] data) {
dataToSend = data;
}
@Override
public ByteBuffer createBinaryFrame(Framedata framedata) {
if (dataToSend != null) {
ByteBuffer buf = ByteBuffer.wrap(dataToSend);
dataToSend = null;
return buf;
}
return super.createBinaryFrame(framedata);
}
@Override
public Draft copyInstance() {
return new DraftThatAllowsUsToSendBogusData();
}
}
}
|
package com.tastymonster.automation.codegen;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import com.tastymonster.automation.element.base.ButtonWebElement;
import com.tastymonster.automation.element.base.DivWebElement;
import com.tastymonster.automation.element.base.LinkWebElement;
import com.tastymonster.automation.element.base.PlaceholderWebElement;
import com.tastymonster.automation.element.base.TableWebElement;
import com.tastymonster.automation.element.base.TextBoxWebElement;
import com.tastymonster.automation.util.AutomationUtils;
public class ParseVelocity implements IPresentationParser {
private static Pattern velocityMacroPattern = Pattern.compile( "\\s*#(\\w+)\\s*\\(\\s*(.*)\\s*\\)" );
protected File file;
protected Set<FieldDetails> fields;
/**
* The contents of the page in one big String
*/
private String pageContents;
/**
* The name of the page for code generation purposes (i.e. without file extension, etc)
*/
private String pageName;
/**
* How the browser reaches the page
*/
private String pageURI;
public ParseVelocity( File file ) {
this.file = file;
}
public Set<FieldDetails> getFields() {
return fields;
}
public String getPageContents() {
return pageContents;
}
@Override
public String getPageName() {
return pageName;
}
public void setPageName( String pageName ) {
this.pageName = pageName;
}
private void setPageURI( String pageURI ) {
this.pageURI = pageURI;
}
@Override
public String getPageURI() {
return pageURI;
}
/**
* Sets the member variable pageContents by reading the file contents
* @param path
*/
public void setPageContents( String pageContents ) {
this.pageContents = pageContents;
}
//Maps velocity field types (macros) to WebElement types
private static Map<String, WebElementDetails> macroNameToWebElement = new HashMap<String, WebElementDetails>();
static {
//Forms
macroNameToWebElement.put( "formInput", new WebElementDetails( TextBoxWebElement.class ) );
macroNameToWebElement.put( "formPassword", new WebElementDetails( TextBoxWebElement.class ) );
macroNameToWebElement.put( "formInputWithType", new WebElementDetails( TextBoxWebElement.class ) );
macroNameToWebElement.put( "formButton", new WebElementDetails( ButtonWebElement.class ) );
//Tables
macroNameToWebElement.put( "table", new WebElementDetails( TableWebElement.class ) );
macroNameToWebElement.put( "table2D", new WebElementDetails( TableWebElement.class ) );
//Positional elements
macroNameToWebElement.put( "divStart", new WebElementDetails( DivWebElement.class ) );
macroNameToWebElement.put( "divStartBox", new WebElementDetails( DivWebElement.class ) );
macroNameToWebElement.put( "divStartWithClass", new WebElementDetails( DivWebElement.class ) );
//Clickables
macroNameToWebElement.put( "link", new WebElementDetails( LinkWebElement.class ) );
macroNameToWebElement.put( "button", new WebElementDetails( ButtonWebElement.class ) );
}
//Maps velocity field types (macros) to WebElement types
private static List<String> macrosToIgnore = new ArrayList<String>();
static {
macrosToIgnore.add( "if" );
macrosToIgnore.add( "parse" );
macrosToIgnore.add( "clearfix" );
macrosToIgnore.add( "divEnd" );
macrosToIgnore.add( "horizontalTabBar" );
macrosToIgnore.add( "formEnd" );
macrosToIgnore.add( "tablerows" );
macrosToIgnore.add( "set" );
}
@Override
public Set<FieldDetails> buildFieldDetails() {
Set<FieldDetails> fields = new HashSet<FieldDetails>();
//Here is where the rubber meets the road
// Compare the page contents with a facility for mapping the Velocity macros to a set of regex Patterns
// What gets returned is a fully realized WebElementDetails object, strongly typed to the corresponding
// WebElement type, and containing its page name, its Tab ID, and other details
for ( String line: StringUtils.split( pageContents, System.getProperty("line.separator") ) ) {
Matcher m = parseOneLine( StringUtils.trim( line ) );
if ( m.matches() ) {
String macroName = m.group( 1 );
String macroParams = m.group( 2 );
WebElementDetails elementDetails = getElementDetails( macroName );
//If elementDetails can't resolve to a well-formed set of FieldDetails, just move to the next
if ( elementDetails == null ) {
continue;
}
Map<String, String> fieldAttributes = getFieldAttributesFromParameters( macroParams );
fields.add( new FieldDetails( fieldAttributes, elementDetails.getType(), macroName ) );
}
}
return fields;
}
/**
* Split up the velocity macro parameters and put them into a map. The map should contain an "id" at the very least
* @param m
* @return
*/
private Map<String, String> getFieldAttributesFromParameters( String macroParams ) {
Map<String, String> fieldAttributes = new HashMap<String, String>();
List<String> paramList = Arrays.asList( macroParams.split( "\\s+" ) );
List<String> scrubbedParams = scrubParams( paramList );
//The first parameter will be the id
if ( scrubbedParams.size() >=1 ) {
fieldAttributes.put( "id", scrubbedParams.get( 0 ) );
}
//If the macro contains a third parameter, it's the field label
if ( scrubbedParams.size() >= 4 ) {
String normalizedFieldName = AutomationUtils.normalizeFieldName( scrubbedParams.get( 3 ) );
fieldAttributes.put( "fieldName", normalizedFieldName );
} else {
fieldAttributes.put( "fieldName", scrubbedParams.get( 0 ) );
}
return fieldAttributes;
}
private List<String> scrubParams( List<String> paramList ) {
List<String> scrubbedList = new ArrayList<String>();
for ( String string: paramList ) {
scrubbedList.add( AutomationUtils.normalizeFieldName( string ) );
}
return scrubbedList;
}
/**
* Returns a WebElementDetails object mapped to the correct type for this element. If the element is one to be ignored,
* this will return null, so you must check for that
* @param macroName
* @return
*/
protected WebElementDetails getElementDetails( String macroName ) {
if ( macrosToIgnore.contains( macroName ) ) {
//Check this null!
return null;
}
if ( macroNameToWebElement.containsKey( macroName ) ) {
return macroNameToWebElement.get( macroName );
}
return new WebElementDetails( PlaceholderWebElement.class );
}
/**
* This parses a line and returns the appropriate matcher, but it does NOT initialize the match itself!
* You must call matches() on the return value in order to parse the line
* @param line
* @return
*/
protected Matcher parseOneLine( String line ) {
Matcher matcher = velocityMacroPattern.matcher( line );
return matcher;
}
/**
* Read and return the contents of the file. This should only be called from the ParserFactory
* @param path
*/
public void initPageContents() {
try {
//Use the setter for pageContents
this.setPageContents( readFile( file.getPath() ) );
//Strip off the src path, and get the full path/filename for this, relative to the site root
//TODO - this should come from IPresentationParser.getTemplatePath()
String filePath = file.getPath().replace( "src/main/webapp/templates/", "" );
this.setPageURI( filePath );
this.setPageName( file.getName().replace( ".vm", "" ) );
} catch ( IOException e ) {
e.printStackTrace();
}
}
/**
* This should be in a Utils class
* @param path
* @return
* @throws IOException
*/
protected String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
// Instead of using default, pass in a decoder
return Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
}
}
|
package io.github.classgraph.issues.issue260;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
public class Issue260Test {
@Test
public void issue260Test() {
try (ScanResult scanResult = new ClassGraph().whitelistPackages(Issue260Test.class.getPackage().getName())
.enableAllInfo().verbose().scan()) {
// Should be no exception here
assertThat(true).isTrue();
}
}
}
|
package javax.time.calendar.format;
import static org.testng.Assert.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Collections;
import javax.time.calendar.CalendricalProvider;
import javax.time.calendar.ISOChronology;
import javax.time.calendar.LocalDateTime;
import javax.time.calendar.TimeZone;
import javax.time.calendar.YearMonth;
import javax.time.calendar.ZonedDateTime;
import javax.time.calendar.field.Year;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Test DateTimeFormatters.
*
* @author Stephen Colebourne
*/
@Test
public class TestDateTimeFormatters {
@BeforeMethod
public void setUp() {
}
@SuppressWarnings("unchecked")
public void test_constructor() throws Exception {
for (Constructor constructor : DateTimeFormatters.class.getDeclaredConstructors()) {
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
constructor.newInstance(Collections.nCopies(constructor.getParameterTypes().length, null).toArray());
}
}
@Test(expectedExceptions=NullPointerException.class)
public void test_print_nullCalendrical() {
DateTimeFormatters.isoDate().print((CalendricalProvider) null);
}
public void test_print_isoDate() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC);
assertEquals(DateTimeFormatters.isoDate().print(test), "2008-06-03");
}
public void test_print_isoDate_missingField() {
try {
CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical();
DateTimeFormatters.isoDate().print(test);
fail();
} catch (CalendricalFormatFieldException ex) {
assertEquals(ex.getFieldRule(), ISOChronology.dayOfMonthRule());
assertEquals(ex.getValue(), null);
}
}
public void test_print_isoTime() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC);
assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30");
}
public void test_print_isoTime_nanos1() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30, 1), TimeZone.UTC);
assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30.000000001");
}
public void test_print_isoTime_nanos2() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30, 500000000), TimeZone.UTC);
assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30.5");
}
public void test_print_isoTime_nanos3() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30, 123456000), TimeZone.UTC);
assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30.123456");
}
public void test_print_isoTime_missingField() {
try {
CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical();
DateTimeFormatters.isoTime().print(test);
fail();
} catch (CalendricalFormatFieldException ex) {
assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.hourOfDay());
assertEquals(ex.getValue(), null);
}
}
public void test_print_isoOrdinalDate() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC);
assertEquals(DateTimeFormatters.isoOrdinalDate().print(test), "2008-155");
}
public void test_print_isoOrdinalDate_missingField() {
try {
CalendricalProvider test = Year.isoYear(2008).toCalendrical();
DateTimeFormatters.isoOrdinalDate().print(test);
fail();
} catch (CalendricalFormatFieldException ex) {
assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.dayOfYear());
assertEquals(ex.getValue(), null);
}
}
public void test_print_basicIsoDate() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC);
assertEquals(DateTimeFormatters.basicIsoDate().print(test), "20080603");
}
public void test_print_basicIsoDate_missingField() {
try {
CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical();
DateTimeFormatters.basicIsoDate().print(test);
fail();
} catch (CalendricalFormatFieldException ex) {
assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.dayOfMonth());
assertEquals(ex.getValue(), null);
}
}
public void test_print_rfc1123() {
CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC);
assertEquals(DateTimeFormatters.rfc1123().print(test), "Tue, 03 Jun 2008 11:05:30 Z");
}
public void test_print_rfc1123_missingField() {
try {
CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical();
DateTimeFormatters.rfc1123().print(test);
fail();
} catch (CalendricalFormatFieldException ex) {
assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.dayOfWeek());
assertEquals(ex.getValue(), null);
}
}
}
|
package net.imagej.ops.threshold.apply;
import static org.junit.Assert.assertEquals;
import net.imagej.ops.AbstractOpTest;
import net.imagej.ops.threshold.LocalThresholdMethod;
import net.imagej.ops.threshold.ThresholdNamespace;
import net.imagej.ops.threshold.localBernsen.LocalBernsenThreshold;
import net.imagej.ops.threshold.localContrast.LocalContrastThreshold;
import net.imagej.ops.threshold.localMean.LocalMeanThresholdIntegral;
import net.imagej.ops.threshold.localMean.LocalMeanThreshold;
import net.imagej.ops.threshold.localMedian.LocalMedianThreshold;
import net.imagej.ops.threshold.localMidGrey.LocalMidGreyThreshold;
import net.imagej.ops.threshold.localNiblack.LocalNiblackThreshold;
import net.imagej.ops.threshold.localNiblack.LocalNiblackThresholdIntegral;
import net.imagej.ops.threshold.localPhansalkar.LocalPhansalkarThreshold;
import net.imagej.ops.threshold.localPhansalkar.LocalPhansalkarThresholdIntegral;
import net.imagej.ops.threshold.localSauvola.LocalSauvolaThreshold;
import net.imagej.ops.threshold.localSauvola.LocalSauvolaThresholdIntegral;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.Cursor;
import net.imglib2.algorithm.neighborhood.DiamondShape;
import net.imglib2.algorithm.neighborhood.RectangleShape;
import net.imglib2.exception.IncompatibleTypeException;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImg;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.img.basictypeaccess.array.ByteArray;
import net.imglib2.outofbounds.OutOfBoundsMirrorFactory;
import net.imglib2.outofbounds.OutOfBoundsMirrorFactory.Boundary;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.integer.ByteType;
import org.junit.Before;
import org.junit.Test;
/**
* Test for {@link LocalThreshold} and various {@link LocalThresholdMethod}s.
*
* @author Jonathan Hale
* @author Martin Horn
* @see LocalThreshold
* @see LocalThresholdMethod
*/
public class LocalThresholdTest extends AbstractOpTest {
Img<ByteType> in;
Img<BitType> out;
/**
* Initialize images.
*
* @throws Exception
*/
@Before
public void before() throws Exception {
in = generateByteArrayTestImg(true, new long[] { 10, 10 });
out = in.factory().imgFactory(new BitType()).create(in, new BitType());
}
/**
* Test whether parameters for ops in {@link ThresholdNamespace} opmethods are
* correctly set.
*/
@Test
public void testOpMethods() {
ops.threshold().localMeanThreshold(out, in, new RectangleShape(3, false),
0.0);
ops.threshold().localMeanThreshold(out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 0.0);
ops.threshold().localMeanThreshold(out, in, new DiamondShape(3),
0.0);
ops.threshold().localMeanThreshold(out, in, new DiamondShape(3),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 0.0);
ops.threshold().localBernsenThreshold(out, in, new RectangleShape(3, false),
1.0, Double.MAX_VALUE * 0.5);
ops.threshold().localBernsenThreshold(out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 1.0, Double.MAX_VALUE * 0.5);
ops.threshold().localContrastThreshold(out, in, new RectangleShape(3,
false));
ops.threshold().localContrastThreshold(out, in, new RectangleShape(3,
false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE));
ops.threshold().localMedianThreshold(out, in, new RectangleShape(3, false),
1.0);
ops.threshold().localMedianThreshold(out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 1.0);
ops.threshold().localMidGreyThreshold(out, in, new RectangleShape(3, false),
1.0);
ops.threshold().localMidGreyThreshold(out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 1.0);
ops.threshold().localNiblackThreshold(out, in, new RectangleShape(3, false),
1.0, 2.0);
ops.threshold().localNiblackThreshold(out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 1.0, 2.0);
ops.threshold().localPhansalkarThreshold(out, in, new RectangleShape(3,
false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 0.25, 0.5);
ops.threshold().localPhansalkarThreshold(out, in, new RectangleShape(3,
false));
ops.threshold().localSauvolaThreshold(out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, RandomAccessibleInterval<ByteType>>(
Boundary.SINGLE), 0.5, 0.5);
ops.threshold().localSauvolaThreshold(out, in, new RectangleShape(3,
false));
}
/**
* @see LocalBernsenThreshold
*/
@Test
public void testLocalBernsenThreshold() {
ops.run(LocalBernsenThreshold.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE), 1.0,
Double.MAX_VALUE * 0.5);
assertEquals(out.firstElement().get(), true);
}
/**
* @see LocalContrastThreshold
*/
@Test
public void testLocalContrastThreshold() {
ops.run(LocalContrastThreshold.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE));
assertEquals(out.firstElement().get(), false);
}
/**
* @see LocalMeanThreshold
*/
@Test
public void testLocalThresholdMean() {
ops.run(LocalMeanThreshold.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0);
assertEquals(out.firstElement().get(), true);
}
/**
* @see LocalMeanThresholdIntegral
*/
@Test
public void testLocalMeanThresholdIntegral() {
ops.run(LocalMeanThresholdIntegral.class,
out,
in,
new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0);
assertEquals(out.firstElement().get(), true);
}
/**
* @see LocalMeanThresholdIntegral
* @see LocalMeanThreshold
*/
@SuppressWarnings("null")
@Test
public void testLocalMeanResultsConsistency() {
Img<BitType> out2 = null;
Img<BitType> out3 = null;
try {
out2 = in.factory().imgFactory(new BitType()).create(in, new BitType());
out3 = in.factory().imgFactory(new BitType()).create(in, new BitType());
}
catch (IncompatibleTypeException exc) {
exc.printStackTrace();
}
// Default implementation
ops.run(LocalMeanThreshold.class, out2, in, new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0);
// Integral image-based implementation
ops.run(LocalMeanThresholdIntegral.class,
out3,
in,
new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0);
// Test for pixel-wise equality of the results
Cursor<BitType> cursorOut2 = out2.cursor();
Cursor<BitType> cursorOut3 = out3.cursor();
while (cursorOut2.hasNext() && cursorOut3.hasNext()) {
BitType valueOut2 = cursorOut2.next();
BitType valueOut3 = cursorOut3.next();
assertEquals(valueOut2, valueOut3);
}
}
/**
* @see LocalMedianThreshold
*/
@Test
public void testLocalMedianThreshold() {
ops.run(LocalMedianThreshold.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0);
assertEquals(out.firstElement().get(), true);
}
/**
* @see LocalMidGreyThreshold
*/
@Test
public void testLocalMidGreyThreshold() {
ops.run(LocalMidGreyThreshold.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE), 0.0);
assertEquals(out.firstElement().get(), true);
}
/**
* @see LocalNiblackThreshold
*/
@Test
public void testLocalNiblackThreshold() {
ops.run(LocalNiblackThreshold.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
assertEquals(out.firstElement().get(), true);
}
/**
* @see LocalNiblackThresholdIntegral
*/
@Test
public void testLocalNiblackThresholdIntegral() {
ops.run(LocalNiblackThresholdIntegral.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
assertEquals(out.firstElement().get(), true);
}
/**
* @see LocalNiblackThresholdIntegral
* @see LocalNiblackThreshold
*/
@SuppressWarnings("null")
@Test
public void testLocalNiblackResultsConsistency() {
Img<BitType> out2 = null;
Img<BitType> out3 = null;
try {
out2 = in.factory().imgFactory(new BitType()).create(in, new BitType());
out3 = in.factory().imgFactory(new BitType()).create(in, new BitType());
}
catch (IncompatibleTypeException exc) {
exc.printStackTrace();
}
// Default implementation
ops.run(LocalNiblackThreshold.class, out2, in, new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
// Integral image-based implementation
ops.run(LocalNiblackThresholdIntegral.class,
out3,
in,
new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
// Test for pixel-wise equality of the results
Cursor<BitType> cursorOut2 = out2.cursor();
Cursor<BitType> cursorOut3 = out3.cursor();
while (cursorOut2.hasNext() && cursorOut3.hasNext()) {
BitType valueOut2 = cursorOut2.next();
BitType valueOut3 = cursorOut3.next();
assertEquals(valueOut2, valueOut3);
}
}
/**
* @see LocalPhansalkarThreshold
*/
@Test
public void testLocalPhansalkar() {
ops.run(LocalPhansalkarThreshold.class, out, in, new RectangleShape(3,
false), new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(
Boundary.SINGLE), 0.0, 0.0);
assertEquals(out.firstElement().get(), false);
}
/**
* @see LocalPhansalkarThresholdIntegral
*/
@Test
public void testLocalPhansalkarIntegral() {
ops.run(LocalPhansalkarThresholdIntegral.class, out, in, new RectangleShape(3,
false), new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(
Boundary.SINGLE), 0.0, 0.0);
assertEquals(out.firstElement().get(), false);
}
/**
* @see LocalPhansalkarThresholdIntegral
* @see LocalPhansalkarThreshold
*/
@SuppressWarnings("null")
@Test
public void testLocalPhansalkarResultsConsistency() {
Img<BitType> out2 = null;
Img<BitType> out3 = null;
try {
out2 = in.factory().imgFactory(new BitType()).create(in, new BitType());
out3 = in.factory().imgFactory(new BitType()).create(in, new BitType());
}
catch (IncompatibleTypeException exc) {
exc.printStackTrace();
}
// Default implementation
ops.run(LocalPhansalkarThreshold.class, out2, in, new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
// Integral image-based implementation
ops.run(LocalPhansalkarThresholdIntegral.class,
out3,
in,
new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
// Test for pixel-wise equality of the results
Cursor<BitType> cursorOut2 = out2.cursor();
Cursor<BitType> cursorOut3 = out3.cursor();
while (cursorOut2.hasNext() && cursorOut3.hasNext()) {
BitType valueOut2 = cursorOut2.next();
BitType valueOut3 = cursorOut3.next();
assertEquals(valueOut2, valueOut3);
}
}
/**
* @see LocalSauvolaThreshold
*/
@Test
public void testLocalSauvola() {
ops.run(LocalSauvolaThreshold.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
assertEquals(out.firstElement().get(), false);
}
/**
* @see LocalSauvolaThresholdIntegral
*/
@Test
public void testLocalSauvolaIntegral() {
ops.run(LocalSauvolaThresholdIntegral.class, out, in, new RectangleShape(3, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
assertEquals(out.firstElement().get(), false);
}
/**
* @see LocalSauvolaThresholdIntegral
* @see LocalSauvolaThreshold
*/
@SuppressWarnings("null")
@Test
public void testLocalSauvolaResultsConsistency() {
Img<BitType> out2 = null;
Img<BitType> out3 = null;
try {
out2 = in.factory().imgFactory(new BitType()).create(in, new BitType());
out3 = in.factory().imgFactory(new BitType()).create(in, new BitType());
}
catch (IncompatibleTypeException exc) {
exc.printStackTrace();
}
// Default implementation
ops.run(LocalSauvolaThreshold.class, out2, in, new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
// Integral image-based implementation
ops.run(LocalSauvolaThresholdIntegral.class,
out3,
in,
new RectangleShape(1, false),
new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE),
0.0, 0.0);
// Test for pixel-wise equality of the results
Cursor<BitType> cursorOut2 = out2.cursor();
Cursor<BitType> cursorOut3 = out3.cursor();
while (cursorOut2.hasNext() && cursorOut3.hasNext()) {
BitType valueOut2 = cursorOut2.next();
BitType valueOut3 = cursorOut3.next();
assertEquals(valueOut2, valueOut3);
}
}
public ArrayImg<ByteType, ByteArray> generateKnownByteArrayTestImgSmall() {
final long[] dims = new long[] { 2, 2 };
final byte[] array = new byte[4];
array[0] = (byte) 10;
array[1] = (byte) 20;
array[2] = (byte) 30;
array[3] = (byte) 40;
return ArrayImgs.bytes(array, dims);
}
public ArrayImg<ByteType, ByteArray> generateKnownByteArrayTestImgLarge() {
final long[] dims = new long[] { 3, 3 };
final byte[] array = new byte[9];
array[0] = (byte) 40;
array[1] = (byte) 40;
array[2] = (byte) 20;
array[3] = (byte) 40;
array[4] = (byte) 40;
array[5] = (byte) 20;
array[6] = (byte) 20;
array[7] = (byte) 20;
array[8] = (byte) 100;
return ArrayImgs.bytes(array, dims);
}
}
|
package functionaltests.workflow;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Assert;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.job.Job;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobInfo;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.JobStatus;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.job.factories.JobFactory;
import org.ow2.proactive.scheduler.common.task.Task;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.flow.FlowActionType;
import functionalTests.FunctionalTest;
import functionaltests.SchedulerTHelper;
/**
* Tests the correctness of workflow-controlled jobs
*
* @author The ProActive Team
* @since ProActive Scheduling 2.2
*/
public abstract class TWorkflowJobs extends FunctionalTest {
protected final String jobSuffix = ".xml";
/**
* Each array is a job named $(array index).xml :
* {{ job1 }, { job2 } ... { jobn }}
* Each cell in the matrix is a task and its integer result :
* {{"Task1_name Task1_result", "Task2_name Task2_result", .... "Taskn_name Taskn_result"}}
*
* Each task and result must match exactly once for each job,
* except when using {@link FlowActionType#IF}: there will be no
* result for {@link TaskStatus#SKIPPED} tasks, they must be present in the
* array but with a negative (ie -1) result value
*
* @return the task names / result matrix
*/
public abstract String[][] getJobs();
/**
* @return the search path on the filesystem for job descriptors
*/
public abstract String getJobPrefix();
/**
* For each job described in {@link #jobs}, submit the job,
* wait for finished state, and compare expected result for each task with the actual result
*
* @throws Throwable
*/
protected void internalRun() throws Throwable {
String[][] jobs = getJobs();
for (int i = 0; i < jobs.length; i++) {
Map<String, Long> tasks = new HashMap<String, Long>();
for (int j = 0; j < jobs[i].length; j++) {
String[] val = jobs[i][j].split(" ");
try {
tasks.put(val[0], Long.parseLong(val[1]));
} catch (Throwable t) {
System.out.println(jobs[i][j]);
t.printStackTrace();
}
}
String path = new File(TWorkflowJobs.class.getResource(getJobPrefix() + (i + 1) + jobSuffix)
.toURI()).getAbsolutePath();
SchedulerTHelper.log("Testing job: " + path);
testJob(path, tasks);
}
}
/**
* See @{link {@link SchedulerTHelper#testJobSubmission(Job)}; does about the same,
* but skips the part that expects the initial submitted task set to be identical to
* the finished task set.
*
* @param jobToSubmit
* @param skip tasks that will be skipped due to {@link FlowActionType#IF}, do not wait for their completion
* @return
* @throws Exception
*/
public static JobId testJobSubmission(Job jobToSubmit, List<String> skip) throws Exception {
Scheduler userInt = SchedulerTHelper.getSchedulerInterface();
JobId id = userInt.submit(jobToSubmit);
SchedulerTHelper.log("Job submitted, id " + id.toString());
SchedulerTHelper.log("Waiting for jobSubmitted");
JobState receivedstate = SchedulerTHelper.waitForEventJobSubmitted(id);
Assert.assertEquals(id, receivedstate.getId());
SchedulerTHelper.log("Waiting for job running");
JobInfo jInfo = SchedulerTHelper.waitForEventJobRunning(id);
Assert.assertEquals(jInfo.getJobId(), id);
Assert.assertEquals(JobStatus.RUNNING, jInfo.getStatus());
if (jobToSubmit instanceof TaskFlowJob) {
for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
if (skip != null && skip.contains(t.getName())) {
continue;
}
TaskInfo ti = SchedulerTHelper.waitForEventTaskRunning(id, t.getName());
Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
Assert.assertEquals(TaskStatus.RUNNING, ti.getStatus());
}
for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
if (skip != null && skip.contains(t.getName())) {
continue;
}
TaskInfo ti = SchedulerTHelper.waitForEventTaskFinished(id, t.getName());
Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
Assert.assertTrue(TaskStatus.FINISHED.equals(ti.getStatus()));
}
}
SchedulerTHelper.log("Waiting for job finished");
jInfo = SchedulerTHelper.waitForEventJobFinished(id);
Assert.assertEquals(JobStatus.FINISHED, jInfo.getStatus());
SchedulerTHelper.log("Job finished");
return id;
}
/**
* Submits the job located at <code>jobPath</code>, compares its results with the ones provided
* in <code>expectedResults</code>
*
* Each task for the provided jobs is a org.ow2.proactive.scheduler.examples.IncrementJob
* which adds all the parameters result + 1.
* Testing each task's result enforces that all expected tasks are present, with the right dependency graph,
* thus the correctness of the job.
*
* @param jobPath
* @param expectedResults
* @throws Throwable
*/
public static void testJob(String jobPath, Map<String, Long> expectedResults) throws Throwable {
List<String> skip = new ArrayList<String>();
for (Entry<String, Long> er : expectedResults.entrySet()) {
if (er.getValue() < 0) {
skip.add(er.getKey());
}
}
JobId id = testJobSubmission(jobPath, skip);
JobResult res = SchedulerTHelper.getJobResult(id);
Assert.assertFalse(SchedulerTHelper.getJobResult(id).hadException());
for (Entry<String, TaskResult> result : res.getAllResults().entrySet()) {
Long expected = expectedResults.get(result.getKey());
Assert.assertNotNull(jobPath + ": Not expecting result for task '" + result.getKey() + "'",
expected);
Assert.assertTrue("Task " + result.getKey() + " should be skipped, but returned a result",
expected >= 0);
if (!(result.getValue().value() instanceof Long)) {
System.out.println(result.getValue().value() + " " + result.getValue().value().getClass());
}
Assert.assertTrue(jobPath + ": Result for task '" + result.getKey() + "' is not an Long", result
.getValue().value() instanceof Long);
Assert.assertEquals(jobPath + ": Invalid result for task '" + result.getKey() + "'", expected,
(Long) result.getValue().value());
}
int skipped = 0;
// tasks SKIPPED are short-circuited by an IF flow action
// they are still in the tasks list, but do not return a result
for (Entry<String, Long> expected : expectedResults.entrySet()) {
if (expected.getValue() < 0) {
Assert.assertFalse("Task " + expected.getKey() + " should be skipped, but returned a result",
res.getAllResults().containsKey(expected.getKey()));
skipped++;
}
}
Assert.assertEquals("Expected and actual result sets are not identical in " + jobPath + " (skipped " +
skipped + "): ", expectedResults.size(), res.getAllResults().size() + skipped);
SchedulerTHelper.removeJob(id);
SchedulerTHelper.waitForEventJobRemoved(id);
}
public static JobId testJobSubmission(String jobDescPath, List<String> skip) throws Exception {
Job jobToTest = JobFactory.getFactory().createJob(jobDescPath);
return testJobSubmission(jobToTest, skip);
}
}
|
package soot.jimple.infoflow.problems;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.flowfunc.Identity;
import heros.flowfunc.KillAll;
import heros.solver.PathEdge;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import soot.ArrayType;
import soot.Local;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.IdentityStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.UnopExpr;
import soot.jimple.infoflow.InfoflowManager;
import soot.jimple.infoflow.aliasing.Aliasing;
import soot.jimple.infoflow.collect.MutableTwoElementSet;
import soot.jimple.infoflow.data.Abstraction;
import soot.jimple.infoflow.data.AccessPath;
import soot.jimple.infoflow.solver.IInfoflowSolver;
import soot.jimple.infoflow.solver.functions.SolverCallFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverCallToReturnFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverNormalFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverReturnFlowFunction;
import soot.jimple.infoflow.taintWrappers.ITaintPropagationWrapper;
import soot.jimple.infoflow.util.BaseSelector;
import soot.jimple.infoflow.util.TypeUtils;
/**
* class which contains the flow functions for the backwards solver. This is
* required for on-demand alias analysis.
*/
public class BackwardsInfoflowProblem extends AbstractInfoflowProblem {
private IInfoflowSolver fSolver;
public void setTaintWrapper(ITaintPropagationWrapper wrapper) {
taintWrapper = wrapper;
}
public BackwardsInfoflowProblem(InfoflowManager manager) {
super(manager);
}
public void setForwardSolver(IInfoflowSolver forwardSolver) {
fSolver = forwardSolver;
}
@Override
public FlowFunctions<Unit, Abstraction, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Abstraction, SootMethod>() {
private Abstraction checkAbstraction(Abstraction abs) {
// Primitive types and strings cannot have aliases and thus
// never need to be propagated back
if (!abs.getAccessPath().isStaticFieldRef()) {
if (abs.getAccessPath().getBaseType() instanceof PrimType)
return null;
if (TypeUtils.isStringType(abs.getAccessPath().getBaseType()))
return null;
}
else {
if (abs.getAccessPath().getFirstFieldType() instanceof PrimType)
return null;
if (TypeUtils.isStringType(abs.getAccessPath().getFirstFieldType()))
return null;
}
return abs;
}
/**
* Computes the aliases for the given statement
* @param def The definition statement from which to extract
* the alias information
* @param leftValue The left side of def. Passed in to allow for
* caching, no need to recompute this for every abstraction being
* processed.
* @param d1 The abstraction at the method's start node
* @param source The source abstraction of the alias search
* from before the current statement
* @return The set of abstractions after the current statement
*/
private Set<Abstraction> computeAliases
(final DefinitionStmt defStmt,
Value leftValue,
Abstraction d1,
Abstraction source) {
assert !source.getAccessPath().isEmpty();
// A backward analysis looks for aliases of existing taints and thus
// cannot create new taints out of thin air
if (source == getZeroValue())
return Collections.emptySet();
final Set<Abstraction> res = new MutableTwoElementSet<Abstraction>();
// Check whether the left side of the assignment matches our
// current taint abstraction
final boolean leftSideMatches = Aliasing.baseMatches(leftValue, source);
if (!leftSideMatches)
res.add(source);
else {
// The left side is overwritten completely
// If we have an assignment to the base local of the current taint,
// all taint propagations must be below that point, so this is the
// right point to turn around.
for (Unit u : interproceduralCFG().getPredsOf(defStmt))
fSolver.processEdge(new PathEdge<Unit, Abstraction>(d1, u, source));
}
// We only handle assignments and identity statements
if (defStmt instanceof IdentityStmt) {
res.add(source);
return res;
}
if (!(defStmt instanceof AssignStmt))
return res;
// Get the right side of the assignment
final Value rightValue = BaseSelector.selectBase(defStmt.getRightOp(), false);
// Is the left side overwritten completely?
if (leftSideMatches) {
// Termination shortcut: If the right side is a value we do not track,
// we can stop here.
if (!(rightValue instanceof Local || rightValue instanceof FieldRef))
return Collections.emptySet();
}
// If we assign a constant, there is no need to track the right side
// any further or do any forward propagation since constants cannot
// carry taint.
if (rightValue instanceof Constant)
return res;
// If this statement creates a new array, we cannot track upwards the size
if (defStmt.getRightOp() instanceof NewArrayExpr)
return res;
// We only process heap objects. Binary operations can only
// be performed on primitive objects.
if (defStmt.getRightOp() instanceof BinopExpr)
return res;
if (defStmt.getRightOp() instanceof UnopExpr)
return res;
// If we have a = x with the taint "x" being inactive,
// we must not taint the left side. We can only taint
// the left side if the tainted value is some "x.y".
boolean aliasOverwritten = Aliasing.baseMatchesStrict(rightValue, source)
&& rightValue.getType() instanceof RefType
&& !source.dependsOnCutAP();
if (!aliasOverwritten && !(rightValue.getType() instanceof PrimType)) {
// If the tainted value 'b' is assigned to variable 'a' and 'b'
// is a heap object, we must also look for aliases of 'a' upwards
// from the current statement.
Abstraction newLeftAbs = null;
if (rightValue instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) rightValue;
if (source.getAccessPath().isInstanceFieldRef()
&& ref.getBase() == source.getAccessPath().getPlainValue()
&& source.getAccessPath().firstFieldMatches(ref.getField())) {
newLeftAbs = checkAbstraction(source.deriveNewAbstraction(leftValue, true,
defStmt, source.getAccessPath().getFirstFieldType()));
}
}
else if (manager.getConfig().getEnableStaticFieldTracking()
&& rightValue instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) rightValue;
if (source.getAccessPath().isStaticFieldRef()
&& source.getAccessPath().firstFieldMatches(ref.getField())) {
newLeftAbs = checkAbstraction(source.deriveNewAbstraction(leftValue, true,
defStmt, source.getAccessPath().getBaseType()));
}
}
else if (rightValue == source.getAccessPath().getPlainValue()) {
Type newType = source.getAccessPath().getBaseType();
if (leftValue instanceof ArrayRef)
newType = buildArrayOrAddDimension(newType);
else if (defStmt.getRightOp() instanceof ArrayRef)
newType = ((ArrayType) newType).getElementType();
// Type check
if (!manager.getTypeUtils().checkCast(source.getAccessPath(),
defStmt.getRightOp().getType()))
return Collections.emptySet();
// If the cast was realizable, we can assume that we had the
// type to which we cast. Do not loosen types, though.
if (defStmt.getRightOp() instanceof CastExpr) {
CastExpr ce = (CastExpr) defStmt.getRightOp();
if (!Scene.v().getFastHierarchy().canStoreType(newType, ce.getCastType()))
newType = ce.getCastType();
}
// Special type handling for certain operations
else if (defStmt.getRightOp() instanceof LengthExpr) {
// ignore. The length of an array is a primitive and thus
// cannot have aliases
return res;
}
else if (defStmt.getRightOp() instanceof InstanceOfExpr) {
// ignore. The type check of an array returns a
// boolean which is a primitive and thus cannot
// have aliases
return res;
}
if (newLeftAbs == null)
newLeftAbs = checkAbstraction(source.deriveNewAbstraction(
source.getAccessPath().copyWithNewValue(leftValue, newType, false), defStmt));
}
if (newLeftAbs != null) {
// If we ran into a new abstraction that points to a
// primitive value, we can remove it
if (newLeftAbs.getAccessPath().getLastFieldType() instanceof PrimType)
return res;
if (!newLeftAbs.getAccessPath().equals(source.getAccessPath())) {
// Propagate the new alias upwards
res.add(newLeftAbs);
// Inject the new alias into the forward solver
for (Unit u : interproceduralCFG().getPredsOf(defStmt))
fSolver.processEdge(new PathEdge<Unit, Abstraction>(d1, u, newLeftAbs));
}
}
}
// If we have the tainted value on the left side of the assignment,
// we also have to look or aliases of the value on the right side of
// the assignment.
if ((rightValue instanceof Local || rightValue instanceof FieldRef)
&& !(leftValue.getType() instanceof PrimType)) {
boolean addRightValue = false;
boolean cutFirstField = false;
Type targetType = null;
// if both are fields, we have to compare their fieldName via equals and their bases via PTS
if (leftValue instanceof InstanceFieldRef) {
if (source.getAccessPath().isInstanceFieldRef()) {
InstanceFieldRef leftRef = (InstanceFieldRef) leftValue;
if (leftRef.getBase() == source.getAccessPath().getPlainValue()) {
if (source.getAccessPath().firstFieldMatches(leftRef.getField())) {
targetType = source.getAccessPath().getFirstFieldType();
addRightValue = true;
cutFirstField = true;
}
}
}
// indirect taint propagation:
// if leftValue is local and source is instancefield of this local:
} else if (leftValue instanceof Local && source.getAccessPath().isInstanceFieldRef()) {
Local base = source.getAccessPath().getPlainValue();
if (leftValue == base) {
targetType = source.getAccessPath().getBaseType();
addRightValue = true;
}
} else if (leftValue instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) leftValue;
Local leftBase = (Local) ar.getBase();
if (leftBase == source.getAccessPath().getPlainValue()) {
addRightValue = true;
targetType = source.getAccessPath().getBaseType();
}
// generic case, is true for Locals, ArrayRefs that are equal etc..
} else if (leftValue == source.getAccessPath().getPlainValue()) {
// If this is an unrealizable cast, we can stop propagating
if (!manager.getTypeUtils().checkCast(source.getAccessPath(), leftValue.getType()))
return Collections.emptySet();
addRightValue = true;
targetType = source.getAccessPath().getBaseType();
}
// if one of them is true -> add rightValue
if (addRightValue) {
if (targetType != null) {
// Special handling for some operations
if (defStmt.getRightOp() instanceof ArrayRef)
targetType = buildArrayOrAddDimension(targetType);
else if (leftValue instanceof ArrayRef) {
assert source.getAccessPath().getBaseType() instanceof ArrayType;
targetType = ((ArrayType) targetType).getElementType();
// If we have a type of java.lang.Object, we try to tighten it
if (TypeUtils.isObjectLikeType(targetType))
targetType = rightValue.getType();
// If the types do not match, the right side cannot be an alias
if (!manager.getTypeUtils().checkCast(rightValue.getType(), targetType))
addRightValue = false;
}
}
// Special type handling for certain operations
if (defStmt.getRightOp() instanceof LengthExpr)
targetType = null;
// We do not need to handle casts. Casts only make
// types more imprecise when going backwards.
// If the source has fields, we may not have a primitive type
if (targetType instanceof PrimType || (targetType instanceof ArrayType
&& ((ArrayType) targetType).getElementType() instanceof PrimType))
if (!source.getAccessPath().isStaticFieldRef() && !source.getAccessPath().isLocal())
return Collections.emptySet();
// If the right side's type is not compatible with our current type,
// this cannot be an alias
if (addRightValue) {
if (!manager.getTypeUtils().checkCast(rightValue.getType(), targetType))
addRightValue = false;
}
// Make sure to only track static fields if it has been enabled
if (addRightValue)
if (!manager.getConfig().getEnableStaticFieldTracking()
&& rightValue instanceof StaticFieldRef)
addRightValue = false;
if (addRightValue) {
Abstraction newAbs = checkAbstraction(source.deriveNewAbstraction(
rightValue, cutFirstField, defStmt, targetType));
if (newAbs != null && !newAbs.getAccessPath().equals(source.getAccessPath())) {
res.add(newAbs);
// Inject the new alias into the forward solver
for (Unit u : interproceduralCFG().getPredsOf(defStmt))
fSolver.processEdge(new PathEdge<Unit, Abstraction>(d1, u, newAbs));
}
}
}
}
return res;
}
@Override
public FlowFunction<Abstraction> getNormalFlowFunction(final Unit src, final Unit dest) {
if (src instanceof DefinitionStmt) {
final DefinitionStmt defStmt = (DefinitionStmt) src;
final Value leftValue = BaseSelector.selectBase(defStmt.getLeftOp(), true);
final DefinitionStmt destDefStmt = dest instanceof DefinitionStmt
? (DefinitionStmt) dest : null;
final Value destLeftValue = destDefStmt == null ? null : BaseSelector.selectBase
(destDefStmt.getLeftOp(), true);
return new SolverNormalFlowFunction() {
@Override
public Set<Abstraction> computeTargets(Abstraction d1, Abstraction source) {
if (source == getZeroValue())
return Collections.emptySet();
assert source.isAbstractionActive() || manager.getConfig().getFlowSensitiveAliasing();
Set<Abstraction> res = computeAliases(defStmt, leftValue, d1, source);
if (destDefStmt != null && interproceduralCFG().isExitStmt(destDefStmt))
for (Abstraction abs : res)
computeAliases(destDefStmt, destLeftValue, d1, abs);
return res;
}
};
}
return Identity.v();
}
@Override
public FlowFunction<Abstraction> getCallFlowFunction(final Unit src, final SootMethod dest) {
if (!dest.isConcrete())
return KillAll.v();
final Stmt stmt = (Stmt) src;
final InvokeExpr ie = (stmt != null && stmt.containsInvokeExpr())
? stmt.getInvokeExpr() : null;
final Value[] paramLocals = new Value[dest.getParameterCount()];
for (int i = 0; i < dest.getParameterCount(); i++)
paramLocals[i] = dest.getActiveBody().getParameterLocal(i);
final boolean isSource = manager.getSourceSinkManager() != null
? manager.getSourceSinkManager().getSourceInfo((Stmt) src, interproceduralCFG()) != null : false;
final boolean isSink = manager.getSourceSinkManager() != null
? manager.getSourceSinkManager().isSink(stmt, interproceduralCFG(), null) : false;
// This is not cached by Soot, so accesses are more expensive
// than one might think
final Local thisLocal = dest.isStatic() ? null : dest.getActiveBody().getThisLocal();
// Android executor methods are handled specially. getSubSignature()
// is slow, so we try to avoid it whenever we can
final boolean isExecutorExecute = isExecutorExecute(ie, dest);
return new SolverCallFlowFunction() {
@Override
public Set<Abstraction> computeTargets(Abstraction d1, Abstraction source) {
if (source == getZeroValue())
return Collections.emptySet();
assert source.isAbstractionActive() || manager.getConfig().getFlowSensitiveAliasing();
//if we do not have to look into sources or sinks:
if (!manager.getConfig().getInspectSources() && isSource)
return Collections.emptySet();
if (!manager.getConfig().getInspectSinks() && isSink)
return Collections.emptySet();
// Do not propagate in inactive taints that will be
// activated there since they already came out of the
// callee
if (isCallSiteActivatingTaint(stmt, source.getActivationUnit()))
return Collections.emptySet();
// taint is propagated in CallToReturnFunction, so we do not
// need any taint here if the taint wrapper is exclusive:
if(taintWrapper != null && taintWrapper.isExclusive(stmt, source))
return Collections.emptySet();
// Only propagate the taint if the target field is actually read
if (manager.getConfig().getEnableStaticFieldTracking()
&& source.getAccessPath().isStaticFieldRef())
if (!interproceduralCFG().isStaticFieldRead(dest,
source.getAccessPath().getFirstField()))
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
// if the returned value is tainted - taint values from return statements
if (src instanceof DefinitionStmt) {
DefinitionStmt defnStmt = (DefinitionStmt) src;
Value leftOp = defnStmt.getLeftOp();
if (leftOp == source.getAccessPath().getPlainValue()) {
// look for returnStmts:
for (Unit u : dest.getActiveBody().getUnits()) {
if (u instanceof ReturnStmt) {
ReturnStmt rStmt = (ReturnStmt) u;
if (rStmt.getOp() instanceof Local
|| rStmt.getOp() instanceof FieldRef)
if (manager.getTypeUtils().checkCast(source.getAccessPath(), rStmt.getOp().getType())) {
Abstraction abs = checkAbstraction(source.deriveNewAbstraction
(source.getAccessPath().copyWithNewValue
(rStmt.getOp(), null, false), (Stmt) src));
if (abs != null)
res.add(abs);
}
}
}
}
}
// easy: static
if (manager.getConfig().getEnableStaticFieldTracking()
&& source.getAccessPath().isStaticFieldRef()) {
Abstraction abs = checkAbstraction(source.deriveNewAbstraction(
source.getAccessPath(), stmt));
if (abs != null)
res.add(abs);
}
// checks: this/fields
Value sourceBase = source.getAccessPath().getPlainValue();
if (!isExecutorExecute
&& !source.getAccessPath().isStaticFieldRef()
&& !dest.isStatic()) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) stmt.getInvokeExpr();
if (iIExpr.getBase() == sourceBase && manager.getTypeUtils().hasCompatibleTypesForCall(
source.getAccessPath(), dest.getDeclaringClass())) {
boolean param = false;
// check if it is not one of the params (then we have already fixed it)
for (int i = 0; i < dest.getParameterCount(); i++) {
if (stmt.getInvokeExpr().getArg(i) == sourceBase) {
param = true;
break;
}
}
if (!param) {
Abstraction abs = checkAbstraction(source.deriveNewAbstraction
(source.getAccessPath().copyWithNewValue(thisLocal), (Stmt) src));
if (abs != null)
res.add(abs);
}
}
}
// Map the parameter values into the callee
if (isExecutorExecute) {
if (ie.getArg(0) == source.getAccessPath().getPlainValue()) {
Abstraction abs = checkAbstraction(source.deriveNewAbstraction
(source.getAccessPath().copyWithNewValue(thisLocal), stmt));
if (abs != null)
res.add(abs);
}
}
else if (ie != null && dest.getParameterCount() > 0) {
assert dest.getParameterCount() == ie.getArgCount();
// check if param is tainted:
for (int i = 0; i < ie.getArgCount(); i++) {
if (ie.getArg(i) == source.getAccessPath().getPlainValue()) {
Abstraction abs = checkAbstraction(source.deriveNewAbstraction(
source.getAccessPath().copyWithNewValue(paramLocals[i]), stmt));
if (abs != null)
res.add(abs);
}
}
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getReturnFlowFunction(final Unit callSite, final SootMethod callee,
final Unit exitStmt, final Unit retSite) {
final Value[] paramLocals = new Value[callee.getParameterCount()];
for (int i = 0; i < callee.getParameterCount(); i++)
paramLocals[i] = callee.getActiveBody().getParameterLocal(i);
final Stmt stmt = (Stmt) callSite;
final InvokeExpr ie = (stmt != null && stmt.containsInvokeExpr())
? stmt.getInvokeExpr() : null;
// This is not cached by Soot, so accesses are more expensive
// than one might think
final Local thisLocal = callee.isStatic() ? null : callee.getActiveBody().getThisLocal();
// Android executor methods are handled specially. getSubSignature()
// is slow, so we try to avoid it whenever we can
final boolean isExecutorExecute = isExecutorExecute(ie, callee);
return new SolverReturnFlowFunction() {
@Override
public Set<Abstraction> computeTargets(Abstraction source,
Abstraction d1,
Collection<Abstraction> callerD1s) {
if (source == getZeroValue())
return Collections.emptySet();
assert source.isAbstractionActive() || manager.getConfig().getFlowSensitiveAliasing();
// If we have no caller, we have nowhere to propagate. This
// can happen when leaving the main method.
if (callSite == null)
return Collections.emptySet();
// easy: static
if (manager.getConfig().getEnableStaticFieldTracking()
&& source.getAccessPath().isStaticFieldRef()) {
registerActivationCallSite(callSite, callee, source);
return Collections.singleton(source);
}
final Value sourceBase = source.getAccessPath().getPlainValue();
Set<Abstraction> res = new HashSet<Abstraction>();
// Since we return from the top of the callee into the
// caller, return values cannot be propagated here. They
// don't yet exist at the beginning of the callee.
if (isExecutorExecute) {
// Map the "this" object to the first argument of the call site
if (source.getAccessPath().getPlainValue() == thisLocal) {
Abstraction abs = checkAbstraction(source.deriveNewAbstraction
(source.getAccessPath().copyWithNewValue(ie.getArg(0)), (Stmt) exitStmt));
if (abs != null) {
res.add(abs);
registerActivationCallSite(callSite, callee, abs);
}
}
}
else {
boolean parameterAliases = false;
// check one of the call params are tainted (not if simple type)
Value originalCallArg = null;
for (int i = 0; i < paramLocals.length; i++) {
if (paramLocals[i] == sourceBase) {
parameterAliases = true;
if (callSite instanceof Stmt) {
originalCallArg = ie.getArg(i);
// If this is a constant parameter, we can safely ignore it
if (!AccessPath.canContainValue(originalCallArg))
continue;
if (!manager.getTypeUtils().checkCast(source.getAccessPath(),
originalCallArg.getType()))
continue;
// Primitive types and strings cannot have aliases and thus
// never need to be propagated back
if (source.getAccessPath().getBaseType() instanceof PrimType)
continue;
if (TypeUtils.isStringType(source.getAccessPath().getBaseType()))
continue;
Abstraction abs = checkAbstraction(source.deriveNewAbstraction
(source.getAccessPath().copyWithNewValue(originalCallArg), (Stmt) exitStmt));
if (abs != null) {
res.add(abs);
registerActivationCallSite(callSite, callee, abs);
}
}
}
}
// Map the "this" local
if (!callee.isStatic()) {
if (thisLocal == sourceBase && manager.getTypeUtils().hasCompatibleTypesForCall(
source.getAccessPath(), callee.getDeclaringClass())) {
// check if it is not one of the params (then we have already fixed it)
if (!parameterAliases) {
if (callSite instanceof Stmt) {
Stmt stmt = (Stmt) callSite;
if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) stmt.getInvokeExpr();
Abstraction abs = checkAbstraction(source.deriveNewAbstraction
(source.getAccessPath().copyWithNewValue(iIExpr.getBase()), (Stmt) exitStmt));
if (abs != null) {
res.add(abs);
registerActivationCallSite(callSite, callee, abs);
}
}
}
}
}
}
}
for (Abstraction abs : res)
if (abs != source)
abs.setCorrespondingCallSite((Stmt) callSite);
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getCallToReturnFlowFunction(final Unit call, final Unit returnSite) {
final Stmt iStmt = (Stmt) call;
final InvokeExpr invExpr = iStmt.getInvokeExpr();
final Value[] callArgs = new Value[iStmt.getInvokeExpr().getArgCount()];
for (int i = 0; i < iStmt.getInvokeExpr().getArgCount(); i++)
callArgs[i] = iStmt.getInvokeExpr().getArg(i);
final SootMethod callee = invExpr.getMethod();
final DefinitionStmt defStmt = iStmt instanceof DefinitionStmt
? (DefinitionStmt) iStmt : null;
return new SolverCallToReturnFlowFunction() {
@Override
public Set<Abstraction> computeTargets(Abstraction d1, Abstraction source) {
if (source == getZeroValue())
return Collections.emptySet();
assert source.isAbstractionActive() || manager.getConfig().getFlowSensitiveAliasing();
// Compute wrapper aliases
if (taintWrapper != null) {
Set<Abstraction> wrapperAliases = taintWrapper.getAliasesForMethod(
iStmt, d1, source);
if (wrapperAliases != null && !wrapperAliases.isEmpty()) {
Set<Abstraction> passOnSet = new HashSet<>(wrapperAliases.size());
for (Abstraction abs : wrapperAliases)
if (defStmt != null && defStmt.getLeftOp()
== abs.getAccessPath().getPlainValue()) {
// Do not pass on this taint, but trigger the forward analysis
for (Unit u : interproceduralCFG().getPredsOf(defStmt))
fSolver.processEdge(new PathEdge<Unit, Abstraction>(d1, u, abs));
}
else
passOnSet.add(abs);
return passOnSet;
}
}
// If the callee does not read the given value, we also need to pass it on
// since we do not propagate it into the callee.
if (manager.getConfig().getEnableStaticFieldTracking()
&& source.getAccessPath().isStaticFieldRef()) {
if (interproceduralCFG().isStaticFieldUsed(callee,
source.getAccessPath().getFirstField()))
return Collections.emptySet();
}
// We may not pass on a taint if it is overwritten by this call
if (iStmt instanceof DefinitionStmt && ((DefinitionStmt) iStmt).getLeftOp()
== source.getAccessPath().getPlainValue())
return Collections.emptySet();
// If the base local of the invocation is tainted, we do not
// pass on the taint
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iinv = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if (iinv.getBase() == source.getAccessPath().getPlainValue()
&& !interproceduralCFG().getCalleesOfCallAt(call).isEmpty())
return Collections.emptySet();
}
// We do not pass taints on parameters over the call-to-return edge
for (int i = 0; i < callArgs.length; i++)
if (callArgs[i] == source.getAccessPath().getPlainValue())
return Collections.emptySet();
return Collections.singleton(source);
}
};
}
};
}
}
|
package com.akiban.ais.util;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.CharsetAndCollation;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.IndexName;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.UserTable;
import com.akiban.ais.model.aisb2.AISBBasedBuilder;
import com.akiban.ais.model.aisb2.NewAISBuilder;
import com.akiban.ais.model.aisb2.NewUserTableBuilder;
import org.junit.After;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static com.akiban.ais.util.ChangedTableDescription.ParentChange;
import static com.akiban.ais.util.TableChangeValidator.ChangeLevel;
import static com.akiban.ais.util.TableChangeValidatorException.*;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class TableChangeValidatorTest {
private static final String SCHEMA = "test";
private static final String TABLE = "t";
private static final TableName TABLE_NAME = new TableName(SCHEMA, TABLE);
private static final String NO_INDEX_CHANGE = "{}";
private List<TableChange> NO_CHANGES = new ArrayList<TableChange>();
@After
public void clearChanges() {
NO_CHANGES.clear();
}
private static NewUserTableBuilder builder(TableName name) {
return AISBBasedBuilder.create(SCHEMA).userTable(name);
}
private UserTable table(NewAISBuilder builder) {
AkibanInformationSchema ais = builder.ais();
assertEquals("User table count", 1, ais.getUserTables().size());
return ais.getUserTables().values().iterator().next();
}
private UserTable table(NewAISBuilder builder, TableName tableName) {
UserTable table = builder.ais().getUserTable(tableName);
assertNotNull("Found table: " + tableName, table);
return table;
}
private static TableChangeValidator validate(UserTable t1, UserTable t2,
List<TableChange> columnChanges, List<TableChange> indexChanges,
ChangeLevel expectedChangeLevel) {
return validate(t1, t2, columnChanges, indexChanges, expectedChangeLevel,
asList(changeDesc(TABLE_NAME, TABLE_NAME, false, ParentChange.NONE, "PRIMARY", "PRIMARY")),
false, false, NO_INDEX_CHANGE, false);
}
private static TableChangeValidator validate(UserTable t1, UserTable t2,
List<TableChange> columnChanges, List<TableChange> indexChanges,
ChangeLevel expectedChangeLevel,
List<String> expectedChangedTables) {
return validate(t1, t2, columnChanges, indexChanges, expectedChangeLevel,
expectedChangedTables,
false, false, NO_INDEX_CHANGE, false);
}
private static TableChangeValidator validate(UserTable t1, UserTable t2,
List<TableChange> columnChanges, List<TableChange> indexChanges,
ChangeLevel expectedChangeLevel,
List<String> expectedChangedTables,
boolean expectedParentChange,
boolean expectedPrimaryKeyChange,
String expectedAutoGroupIndexChange,
boolean autoIndexChanges) {
TableChangeValidator validator = new TableChangeValidator(t1, t2, columnChanges, indexChanges, autoIndexChanges);
validator.compareAndThrowIfNecessary();
assertEquals("Final change level", expectedChangeLevel, validator.getFinalChangeLevel());
assertEquals("Parent changed", expectedParentChange, validator.isParentChanged());
assertEquals("Primary key changed", expectedPrimaryKeyChange, validator.isPrimaryKeyChanged());
assertEquals("Changed tables", expectedChangedTables.toString(), validator.getAllChangedTables().toString());
assertEquals("Affected group index", expectedAutoGroupIndexChange, validator.getAffectedGroupIndexes().toString());
assertEquals("Unmodified changes", "[]", validator.getUnmodifiedChanges().toString());
return validator;
}
private static Map<String,String> map(String... pairs) {
assertTrue("Even number of pairs", (pairs.length % 2) == 0);
Map<String,String> map = new TreeMap<String, String>();
for(int i = 0; i < pairs.length; i += 2) {
map.put(pairs[i], pairs[i+1]);
}
return map;
}
private static String changeDesc(TableName oldName, TableName newName, boolean newGroup, ParentChange parentChange, String... indexPairs) {
return ChangedTableDescription.toString(oldName, newName, newGroup, parentChange, map(indexPairs));
}
// Table
@Test
public void sameTable() {
UserTable t = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t, t, NO_CHANGES, NO_CHANGES, ChangeLevel.NONE);
}
@Test
public void unchangedTable() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, ChangeLevel.NONE);
}
@Test
public void changeOnlyTableName() {
TableName name2 = new TableName("x", "y");
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(name2).colBigInt("id").pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, ChangeLevel.METADATA,
asList(changeDesc(TABLE_NAME, name2, false, ParentChange.NONE, "PRIMARY", "PRIMARY")));
}
@Test
public void changeDefaultCharset() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
t1.setCharsetAndCollation(CharsetAndCollation.intern("utf8", "binary"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
t1.setCharsetAndCollation(CharsetAndCollation.intern("utf16", "binary"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, ChangeLevel.METADATA);
}
@Test
public void changeDefaultCollation() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
t1.setCharsetAndCollation(CharsetAndCollation.intern("utf8", "binary"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
t1.setCharsetAndCollation(CharsetAndCollation.intern("utf8", "utf8_general_ci"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, ChangeLevel.METADATA);
}
// Column
@Test
public void addColumn() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
validate(t1, t2, asList(TableChange.createAdd("x")), NO_CHANGES, ChangeLevel.TABLE);
}
@Test
public void dropColumn() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t1, t2, asList(TableChange.createDrop("x")), NO_CHANGES, ChangeLevel.TABLE);
}
@Test
public void modifyColumnDataType() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("y").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colString("y", 32).pk("id"));
validate(t1, t2, asList(TableChange.createModify("y", "y")), NO_CHANGES, ChangeLevel.TABLE);
}
@Test
public void modifyColumnName() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("y").pk("id"));
validate(t1, t2, asList(TableChange.createModify("x", "y")), NO_CHANGES, ChangeLevel.METADATA);
}
@Test
public void modifyColumnNotNullToNull() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", false).pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", true).pk("id"));
validate(t1, t2, asList(TableChange.createModify("x", "x")), NO_CHANGES, ChangeLevel.METADATA);
}
@Test
public void modifyColumnNullToNotNull() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", true).pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", false).pk("id"));
validate(t1, t2, asList(TableChange.createModify("x", "x")), NO_CHANGES, ChangeLevel.METADATA_NOT_NULL);
}
@Test
public void modifyAddGeneratedBy() {
final TableName SEQ_NAME = new TableName(SCHEMA, "seq-1");
UserTable t1 = table(builder(TABLE_NAME).colLong("id", false).pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colLong("id", false).pk("id").sequence(SEQ_NAME.getTableName()));
t2.getColumn("id").setIdentityGenerator(t2.getAIS().getSequence(SEQ_NAME));
t2.getColumn("id").setDefaultIdentity(true);
validate(t1, t2, asList(TableChange.createModify("id", "id")), NO_CHANGES, ChangeLevel.METADATA);
}
@Test
public void modifyDropGeneratedBy() {
final TableName SEQ_NAME = new TableName(SCHEMA, "seq-1");
UserTable t1 = table(builder(TABLE_NAME).colLong("id", false).pk("id").sequence(SEQ_NAME.getTableName()));
t1.getColumn("id").setIdentityGenerator(t1.getAIS().getSequence(SEQ_NAME));
t1.getColumn("id").setDefaultIdentity(true);
UserTable t2 = table(builder(TABLE_NAME).colLong("id", false).pk("id"));
validate(t1, t2, asList(TableChange.createModify("id", "id")), NO_CHANGES, ChangeLevel.METADATA);
}
@Test
public void modifyColumnAddDefault() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", false).colLong("c1", true).pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", false).colLong("c1", true).pk("id"));
t2.getColumn("c1").setDefaultValue("42");
validate(t1, t2, asList(TableChange.createModify("c1", "c1")), NO_CHANGES, ChangeLevel.METADATA);
}
@Test
public void modifyColumnDropDefault() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", false).colLong("c1", true).pk("id"));
t1.getColumn("c1").setDefaultValue("42");
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x", false).colLong("c1", true).pk("id"));
validate(t1, t2, asList(TableChange.createModify("c1", "c1")), NO_CHANGES, ChangeLevel.METADATA);
}
// Column (negative)
@Test(expected=UndeclaredColumnChangeException.class)
public void addColumnUnspecified() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, null);
}
@Test(expected=UnchangedColumnNotPresentException.class)
public void dropColumnUnspecified() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, null);
}
@Test(expected=DropColumnNotPresentException.class)
public void dropColumnUnknown() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t1, t2, asList(TableChange.createDrop("x")), NO_CHANGES, null);
}
@Test
public void modifyColumnNotChanged() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
TableChangeValidator tcv = new TableChangeValidator(t1, t2, asList(TableChange.createModify("x", "x")), NO_CHANGES, false);
tcv.compareAndThrowIfNecessary();
assertEquals("Final change level", ChangeLevel.NONE, tcv.getFinalChangeLevel());
assertEquals("Unmodified change count", 1, tcv.getUnmodifiedChanges().size());
}
@Test(expected=ModifyColumnNotPresentException.class)
public void modifyColumnUnknown() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t1, t2, asList(TableChange.createModify("y", "y")), NO_CHANGES, null);
}
@Test(expected=UndeclaredColumnChangeException.class)
public void modifyColumnUnspecified() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colString("x", 32).pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, null);
}
// Index
@Test
public void addIndex() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
validate(t1, t2, NO_CHANGES, asList(TableChange.createAdd("x")), ChangeLevel.INDEX);
}
@Test
public void dropIndex() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
validate(t1, t2, NO_CHANGES, asList(TableChange.createDrop("x")), ChangeLevel.INDEX);
}
@Test
public void modifyIndexedColumn() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").colBigInt("y").key("k", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").colBigInt("y").key("k", "y").pk("id"));
validate(t1, t2, NO_CHANGES, asList(TableChange.createModify("k", "k")), ChangeLevel.INDEX);
}
@Test
public void modifyIndexedType() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colString("x", 32).key("x", "x").pk("id"));
validate(t1, t2, asList(TableChange.createModify("x", "x")), asList(TableChange.createModify("x", "x")),
ChangeLevel.TABLE);
}
@Test
public void modifyIndexName() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("a", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("b", "x").pk("id"));
validate(t1, t2, NO_CHANGES, asList(TableChange.createModify("a", "b")), ChangeLevel.METADATA);
}
// Index (negative)
@Test(expected=UndeclaredIndexChangeException.class)
public void addIndexUnspecified() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, null);
}
@Test(expected=UnchangedIndexNotPresentException.class)
public void dropIndexUnspecified() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, null);
}
@Test(expected=DropIndexNotPresentException.class)
public void dropIndexUnknown() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t1, t2, NO_CHANGES, asList(TableChange.createDrop("x")), null);
}
@Test
public void modifyIndexNotChanged() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
TableChangeValidator tcv = new TableChangeValidator(t1, t2, NO_CHANGES, asList(
TableChange.createModify("x", "x")), false);
tcv.compareAndThrowIfNecessary();
assertEquals("Final change level", ChangeLevel.NONE, tcv.getFinalChangeLevel());
assertEquals("Unmodified change count", 1, tcv.getUnmodifiedChanges().size());
}
@Test(expected=ModifyIndexNotPresentException.class)
public void modifyIndexUnknown() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
validate(t1, t2, NO_CHANGES, asList(TableChange.createModify("y", "y")), null);
}
@Test(expected=UndeclaredIndexChangeException.class)
public void modifyIndexUnspecified() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").colBigInt("y").key("k", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").colBigInt("y").key("k", "y").pk("id"));
validate(t1, t2, NO_CHANGES, NO_CHANGES, null);
}
@Test(expected=UndeclaredIndexChangeException.class)
public void modifyIndexedColumnIndexUnspecified() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").key("x", "x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colString("x", 32).key("x", "x").pk("id"));
validate(t1, t2, asList(TableChange.createModify("x", "x")), NO_CHANGES, null);
}
// Group
@Test
public void modifyPKColumnTypeSingleTableGroup() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colString("id", 32).pk("id"));
validate(t1, t2,
asList(TableChange.createModify("id", "id")),
asList(TableChange.createModify(Index.PRIMARY_KEY_CONSTRAINT, Index.PRIMARY_KEY_CONSTRAINT)),
ChangeLevel.GROUP,
asList(changeDesc(TABLE_NAME, TABLE_NAME, false, ParentChange.NONE)),
false, true, NO_INDEX_CHANGE, false);
}
@Test
public void dropPrimaryKeySingleTableGroup() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id"));
validate(t1, t2,
NO_CHANGES,
asList(TableChange.createDrop(Index.PRIMARY_KEY_CONSTRAINT)),
ChangeLevel.GROUP,
asList(changeDesc(TABLE_NAME, TABLE_NAME, false, ParentChange.NONE)),
false, true, NO_INDEX_CHANGE, false);
}
@Test
public void dropParentJoinTwoTableGroup() {
TableName parentName = new TableName(SCHEMA, "parent");
UserTable t1 = table(
builder(parentName).colLong("id").pk("id").
userTable(TABLE_NAME).colBigInt("id").colLong("pid").pk("id").joinTo(SCHEMA, "parent", "fk").on("pid", "id"),
TABLE_NAME
);
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colLong("pid").pk("id"));
validate(t1, t2,
NO_CHANGES,
asList(TableChange.createDrop("__akiban_fk")),
ChangeLevel.GROUP,
asList(changeDesc(TABLE_NAME, TABLE_NAME, true, ParentChange.DROP)),
true, false, NO_INDEX_CHANGE, false);
}
@Test
public void dropPrimaryKeyMiddleOfGroup() {
TableName cName = new TableName(SCHEMA, "c");
TableName oName = new TableName(SCHEMA, "o");
TableName iName = new TableName(SCHEMA, "i");
NewAISBuilder builder1 = AISBBasedBuilder.create();
builder1.userTable(cName).colBigInt("id", false).pk("id")
.userTable(oName).colBigInt("id", false).colBigInt("cid", true).pk("id").joinTo(SCHEMA, "c", "fk1").on("cid", "id")
.userTable(iName).colBigInt("id", false).colBigInt("oid", true).pk("id").joinTo(SCHEMA, "o", "fk2").on("oid", "id");
NewAISBuilder builder2 = AISBBasedBuilder.create();
builder2.userTable(cName).colBigInt("id", false).pk("id")
.userTable(oName).colBigInt("id", false).colBigInt("cid", true).joinTo(SCHEMA, "c", "fk1").on("cid", "id")
.userTable(iName).colBigInt("id", false).colBigInt("oid", true).pk("id").joinTo(SCHEMA, "o", "fk2").on("oid", "id");
UserTable t1 = builder1.unvalidatedAIS().getUserTable(oName);
UserTable t2 = builder2.unvalidatedAIS().getUserTable(oName);
validate(
t1, t2,
NO_CHANGES,
asList(TableChange.createDrop(Index.PRIMARY_KEY_CONSTRAINT)),
ChangeLevel.GROUP,
asList(
changeDesc(oName, oName, false, ParentChange.NONE),
changeDesc(iName, iName, true, ParentChange.DROP)
),
false,
true,
NO_INDEX_CHANGE,
false
);
}
// Multi-part
@Test
public void addAndDropColumn() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("x").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colBigInt("y").pk("id"));
validate(t1, t2, asList(TableChange.createDrop("x"), TableChange.createAdd("y")), NO_CHANGES, ChangeLevel.TABLE);
}
@Test
public void addAndDropMultipleColumnAndIndex() {
UserTable t1 = table(builder(TABLE_NAME).colBigInt("id").colDouble("d").colLong("l").colString("s", 32).
key("d", "d").key("l", "l").uniqueKey("k", "l", "d").pk("id"));
UserTable t2 = table(builder(TABLE_NAME).colBigInt("id").colDouble("d").colVarBinary("v", 32).colString("s", 64).
key("d", "d").key("v", "v").uniqueKey("k", "v", "d").pk("id"));
validate(
t1, t2,
asList(TableChange.createDrop("l"), TableChange.createModify("s", "s"), TableChange.createAdd("v")),
asList(TableChange.createDrop("l"), TableChange.createAdd("v"), TableChange.createModify("k", "k")),
ChangeLevel.TABLE,
asList(changeDesc(TABLE_NAME, TABLE_NAME, false, ParentChange.NONE, "PRIMARY", "PRIMARY", "d", "d"))
);
}
// Auto index changes
@Test
public void addDropAndModifyIndexAutoChanges() {
UserTable t1 = table(builder(TABLE_NAME).colLong("c1").colLong("c2").colLong("c3").key("c1", "c1").key("c3", "c3"));
UserTable t2 = table(builder(TABLE_NAME).colLong("c1").colLong("c2").colString("c3", 32).key("c2", "c2").key("c3", "c3"));
validate(
t1, t2,
asList(TableChange.createModify("c3", "c3")),
NO_CHANGES,
ChangeLevel.TABLE,
asList(changeDesc(TABLE_NAME, TABLE_NAME, false, ParentChange.NONE)),
false,
false,
NO_INDEX_CHANGE,
true
);
}
// Group Index changes
@Test
public void dropColumnInGroupIndex() {
NewAISBuilder builder = AISBBasedBuilder.create(SCHEMA);
builder.userTable("p").colLong("id").colLong("x").pk("id")
.userTable(TABLE).colLong("id").colLong("pid").colLong("y").pk("id").joinTo(SCHEMA, "p", "fk").on("pid", "id")
.groupIndex("x_y", Index.JoinType.LEFT).on(TABLE, "y").and("p", "x");
UserTable t1 = builder.unvalidatedAIS().getUserTable(TABLE_NAME);
builder = AISBBasedBuilder.create(SCHEMA);
builder.userTable("p").colLong("id").colLong("x").pk("id")
.userTable(TABLE).colLong("id").colLong("pid").pk("id").joinTo(SCHEMA, "p", "fk").on("pid", "id");
UserTable t2 = builder.unvalidatedAIS().getUserTable(TABLE_NAME);
final String KEY1 = Index.PRIMARY_KEY_CONSTRAINT;
final String KEY2 = "__akiban_fk";
validate(
t1, t2,
asList(TableChange.createDrop("y")),
NO_CHANGES,
ChangeLevel.TABLE,
asList(changeDesc(TABLE_NAME, TABLE_NAME, false, ParentChange.NONE, KEY1, KEY1, KEY2, KEY2)),
false,
false,
"{test.p.x_y=[]}",
false
);
}
@Test
public void dropGFKFrommMiddleWithGroupIndexes() {
TableName iName = new TableName(SCHEMA, "i");
NewAISBuilder builder = AISBBasedBuilder.create(SCHEMA);
builder.userTable("p").colLong("id").colLong("x").pk("id")
.userTable(TABLE).colLong("id").colLong("pid").colLong("y").pk("id").joinTo(SCHEMA, "p", "fk1").on("pid", "id")
.userTable(iName).colLong("id").colLong("tid").colLong("z").pk("id").joinTo(SCHEMA, TABLE, "fk2").on("tid", "id")
.groupIndex("x_y", Index.JoinType.LEFT).on(TABLE, "y").and("p", "x") // spans 2
.groupIndex("x_y_z", Index.JoinType.LEFT).on("i", "z").and(TABLE, "y").and("p", "x"); // spans 3
UserTable t1 = builder.unvalidatedAIS().getUserTable(TABLE_NAME);
builder = AISBBasedBuilder.create(SCHEMA);
builder.userTable("p").colLong("id").colLong("x").pk("id")
.userTable(TABLE).colLong("id").colLong("pid").colLong("y").pk("id").key("__akiban_fk1", "pid")
.userTable(iName).colLong("id").colLong("tid").colLong("z").pk("id").joinTo(SCHEMA, TABLE, "fk2").on("tid", "id");
UserTable t2 = builder.unvalidatedAIS().getUserTable(TABLE_NAME);
validate(
t1, t2,
NO_CHANGES,
NO_CHANGES,
ChangeLevel.GROUP,
asList(changeDesc(TABLE_NAME, TABLE_NAME, true, ParentChange.DROP), changeDesc(iName, iName, true, ParentChange.UPDATE)),
true,
false,
"{test.p.x_y=[], test.p.x_y_z=[]}",
false
);
}
}
|
package com.blogspot.geekabyte.krawkraw;
import com.blogspot.geekabyte.krawkraw.interfaces.KrawlerAction;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.*;
import org.junit.runner.*;
import org.mockito.runners.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class KrawkrawTest {
private final Logger logger = LoggerFactory.getLogger(Krawkraw.class);
private final String host = "http://localhost:" + TestServer.HTTP_PORT;
Krawkraw krawkrawSUT = new Krawkraw();
TestServer testServer;
@Before
public void before() throws Exception {
testServer = new TestServer();
testServer.start();
}
@After
public void after() throws Exception {
testServer.shutDown();
}
@Test
public void test_extractAbsHref() {
Document doc = createDocument("fivelinks");
// System under test
List<String> hrefs = krawkrawSUT.extractAbsHref(doc);
assertEquals(hrefs.size(), 5);
}
@Test
public void test_extractHref() {
Document doc = createDocument("fivelinks");
// System under test
List<String> hrefs = krawkrawSUT.extractHref(doc);
assertEquals(hrefs.size(), 5);
}
@Test
public void test_extractAllFromUrl() throws IOException, InterruptedException {
KrawlerAction mockAction = mock(KrawlerAction.class);
krawkrawSUT.setAction(mockAction);
krawkrawSUT.setBaseUrl("localhost");
krawkrawSUT.setDelay(0);
// System under test
Set<String> hrefs = krawkrawSUT.extractAllFromUrl(host + "/mocksite/index.html");
assertEquals(hrefs.size(), 6);
verify(mockAction, times(6)).execute(any(FetchedPage.class));
}
private Document createDocument(String type) {
switch (type) {
case ("fivelinks"): {
URL path = this.getClass().getResource("/fivelinks.html");
File file = new File(path.getFile());
Document doc = null;
try {
doc = Jsoup.parse(file, "UTF-8");
} catch (IOException e) {
logger.error("Error with file {}", file);
}
return doc;
}
default: {
return null;
}
}
}
private class TestServer {
private final Logger logger = LoggerFactory.getLogger(TestServer.class);
public static final int HTTP_PORT = 50036;
private Server server;
public void start() throws Exception {
server = new Server(HTTP_PORT);
server.setHandler(getMockHandler());
server.start();
}
public void shutDown() throws Exception {
server.stop();
}
public Handler getMockHandler() {
Handler handler = new AbstractHandler() {
public void handle(String target, org.eclipse.jetty.server.Request baseRequest,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println(getContent(target));
}
private String getContent(String filename) {
byte[] contentAsBytes = null;
try {
URL pathAsUrl = this.getClass().getResource(filename);
String pathAsString = pathAsUrl.getPath();
contentAsBytes = Files.readAllBytes(Paths.get(pathAsString));
} catch (IOException e) {
logger.error("Exception while reading {}", filename);
}
if (contentAsBytes != null) {
return new String(contentAsBytes, StandardCharsets.UTF_8);
}
return "";
}
};
return handler;
}
}
}
|
package com.boundary.sdk.event;
import com.boundary.sdk.RawEvent;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RawEventScriptingTest {
private static Logger LOG = LoggerFactory.getLogger(RawEventScriptingTest.class);
ScriptEngineManager manager;
ScriptEngine engine;
RawEvent event;
String scriptDirectory="js/rawevent";
String scriptEngineName = "JavaScript";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
manager = new ScriptEngineManager();
engine = manager.getEngineByName(scriptEngineName);
event = new RawEvent();
engine.put("event", event);
}
@After
public void tearDown() throws Exception {
manager = null;
engine = null;
event = null;
}
/**
* Finds a script to be tested from
* @param scriptName
* @return {@link File}
*/
private FileReader getScript(String scriptName) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource(scriptDirectory + "/" + scriptName);
assertNotNull(url);
File f = new File(url.getFile());
FileReader reader = null;
try {
reader = new FileReader(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
LOG.error(e.getMessage());
}
return reader;
}
private Object runScript(String scriptName) throws ScriptException {
Object o = null;
// evaluate a script string. The script accesses "file"
// variable and calls method on it
try {
o = engine.eval(getScript(scriptName));
} catch (ScriptException e) {
e.printStackTrace();
LOG.error("file: " + e.getFileName());
LOG.error("line: " + e.getLineNumber());
LOG.error("column: " + e.getColumnNumber());
LOG.error("message" + e.getMessage());
throw e;
}
return o;
}
@Test
public void testScriptEngine() throws ScriptException{
event.setTitle("foobar");
runScript("smoke.js");
}
@Test(expected=ScriptException.class)
public void testException() throws ScriptException {
runScript("exception.js");
}
@Test
public void testSetTitle() throws ScriptException {
runScript("set_title.js");
assertEquals("Test setTitle()", event.getTitle(),"foobar");
}
@Test
public void testChangeTitle() throws ScriptException {
String title = "2112";
event.setTitle(title);
runScript("set_title.js");
assertFalse(title == event.getTitle());
}
@Test
public void testReturnsTrue() throws ScriptException {
Boolean o = (Boolean)runScript("return_true.js");
assertTrue(o.booleanValue());
}
@Test
public void testSetSourceRef() throws ScriptException {
runScript("set_source.js");
assertEquals("Check setRef()","Geddy Lee",event.getSource().getRef());
assertEquals("Check setType()","Musician",event.getSource().getType());
}
}
|
package com.conveyal.gtfs.loader;
import com.conveyal.gtfs.TestUtils;
import com.conveyal.gtfs.util.CalendarDTO;
import com.conveyal.gtfs.util.FareDTO;
import com.conveyal.gtfs.util.FareRuleDTO;
import com.conveyal.gtfs.util.FeedInfoDTO;
import com.conveyal.gtfs.util.FrequencyDTO;
import com.conveyal.gtfs.util.InvalidNamespaceException;
import com.conveyal.gtfs.util.PatternDTO;
import com.conveyal.gtfs.util.PatternStopDTO;
import com.conveyal.gtfs.util.RouteDTO;
import com.conveyal.gtfs.util.ShapePointDTO;
import com.conveyal.gtfs.util.StopDTO;
import com.conveyal.gtfs.util.StopTimeDTO;
import com.conveyal.gtfs.util.TripDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import static com.conveyal.gtfs.GTFS.createDataSource;
import static com.conveyal.gtfs.GTFS.makeSnapshot;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* This class contains CRUD tests for {@link JdbcTableWriter} (i.e., editing GTFS entities in the RDBMS). Set up
* consists of creating a scratch database and an empty feed snapshot, which is the necessary starting condition
* for building a GTFS feed from scratch. It then runs the various CRUD tests and finishes by dropping the database
* (even if tests fail).
*/
public class JDBCTableWriterTest {
private static final Logger LOG = LoggerFactory.getLogger(JDBCTableWriterTest.class);
private static String testDBName;
private static DataSource testDataSource;
private static String testNamespace;
private static String simpleServiceId = "1";
private static String firstStopId = "1";
private static String lastStopId = "2";
private static final ObjectMapper mapper = new ObjectMapper();
private static JdbcTableWriter createTestTableWriter (Table table) throws InvalidNamespaceException {
return new JdbcTableWriter(table, testDataSource, testNamespace);
}
@BeforeClass
public static void setUpClass() throws SQLException, IOException, InvalidNamespaceException {
// Create a new database
testDBName = TestUtils.generateNewDB();
String dbConnectionUrl = String.format("jdbc:postgresql://localhost/%s", testDBName);
testDataSource = createDataSource (dbConnectionUrl, null, null);
LOG.info("creating feeds table because it isn't automatically generated unless you import a feed");
Connection connection = testDataSource.getConnection();
connection.createStatement()
.execute("create table if not exists feeds (namespace varchar primary key, md5 varchar, " +
"sha1 varchar, feed_id varchar, feed_version varchar, filename varchar, loaded_date timestamp, " +
"snapshot_of varchar)");
connection.commit();
LOG.info("feeds table created");
// Create an empty snapshot to create a new namespace and all the tables
FeedLoadResult result = makeSnapshot(null, testDataSource);
testNamespace = result.uniqueIdentifier;
// Create a service calendar and two stops, both of which are necessary to perform pattern and trip tests.
createWeekdayCalendar(simpleServiceId, "20180103", "20180104");
createSimpleStop(firstStopId, "First Stop", 34.2222, -87.333);
createSimpleStop(lastStopId, "Last Stop", 34.2233, -87.334);
}
@Test
public void canCreateUpdateAndDeleteFeedInfoEntities() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table feedInfoTable = Table.FEED_INFO;
final Class<FeedInfoDTO> feedInfoDTOClass = FeedInfoDTO.class;
// create new object to be saved
FeedInfoDTO feedInfoInput = new FeedInfoDTO();
String publisherName = "test-publisher";
feedInfoInput.feed_publisher_name = publisherName;
feedInfoInput.feed_publisher_url = "example.com";
feedInfoInput.feed_lang = "en";
feedInfoInput.default_route_color = "1c8edb";
feedInfoInput.default_route_type = "3";
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(feedInfoTable);
String createOutput = createTableWriter.create(mapper.writeValueAsString(feedInfoInput), true);
LOG.info("create {} output:", feedInfoTable.name);
LOG.info(createOutput);
// parse output
FeedInfoDTO createdFeedInfo = mapper.readValue(createOutput, feedInfoDTOClass);
// make sure saved data matches expected data
assertThat(createdFeedInfo.feed_publisher_name, equalTo(publisherName));
// try to update record
String updatedPublisherName = "test-publisher-updated";
createdFeedInfo.feed_publisher_name = updatedPublisherName;
// covert object to json and save it
JdbcTableWriter updateTableWriter = createTestTableWriter(feedInfoTable);
String updateOutput = updateTableWriter.update(
createdFeedInfo.id,
mapper.writeValueAsString(createdFeedInfo),
true
);
LOG.info("update {} output:", feedInfoTable.name);
LOG.info(updateOutput);
FeedInfoDTO updatedFeedInfoDTO = mapper.readValue(updateOutput, feedInfoDTOClass);
// make sure saved data matches expected data
assertThat(updatedFeedInfoDTO.feed_publisher_name, equalTo(updatedPublisherName));
// try to delete record
JdbcTableWriter deleteTableWriter = createTestTableWriter(feedInfoTable);
int deleteOutput = deleteTableWriter.delete(
createdFeedInfo.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, feedInfoTable.name);
// make sure record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
feedInfoTable.name,
createdFeedInfo.id
));
}
/**
* Ensure that potentially malicious SQL injection is sanitized properly during create operations.
* TODO: We might should perform this check on multiple entities and for update and/or delete operations.
*/
@Test
public void canPreventSQLInjection() throws IOException, SQLException, InvalidNamespaceException {
// create new object to be saved
FeedInfoDTO feedInfoInput = new FeedInfoDTO();
String publisherName = "' OR 1 = 1; SELECT '1";
feedInfoInput.feed_publisher_name = publisherName;
feedInfoInput.feed_publisher_url = "example.com";
feedInfoInput.feed_lang = "en";
feedInfoInput.default_route_color = "1c8edb";
feedInfoInput.default_route_type = "3";
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(Table.FEED_INFO);
String createOutput = createTableWriter.create(mapper.writeValueAsString(feedInfoInput), true);
LOG.info("create output:");
LOG.info(createOutput);
// parse output
FeedInfoDTO createdFeedInfo = mapper.readValue(createOutput, FeedInfoDTO.class);
// make sure saved data matches expected data
assertThat(createdFeedInfo.feed_publisher_name, equalTo(publisherName));
}
@Test
public void canCreateUpdateAndDeleteFares() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table fareTable = Table.FARE_ATTRIBUTES;
final Class<FareDTO> fareDTOClass = FareDTO.class;
// create new object to be saved
FareDTO fareInput = new FareDTO();
String fareId = "2A";
fareInput.fare_id = fareId;
fareInput.currency_type = "USD";
fareInput.price = 2.50;
fareInput.agency_id = "RTA";
fareInput.payment_method = 0;
// Empty value should be permitted for transfers and transfer_duration
fareInput.transfers = null;
fareInput.transfer_duration = null;
FareRuleDTO fareRuleInput = new FareRuleDTO();
// Fare ID should be assigned to "child entity" by editor automatically.
fareRuleInput.fare_id = null;
fareRuleInput.route_id = null;
// FIXME There is currently no check for valid zone_id values in contains_id, origin_id, and destination_id.
fareRuleInput.contains_id = "any";
fareRuleInput.origin_id = "value";
fareRuleInput.destination_id = "permitted";
fareInput.fare_rules = new FareRuleDTO[]{fareRuleInput};
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(fareTable);
String createOutput = createTableWriter.create(mapper.writeValueAsString(fareInput), true);
LOG.info("create {} output:", fareTable.name);
LOG.info(createOutput);
// parse output
FareDTO createdFare = mapper.readValue(createOutput, fareDTOClass);
// make sure saved data matches expected data
assertThat(createdFare.fare_id, equalTo(fareId));
assertThat(createdFare.fare_rules[0].fare_id, equalTo(fareId));
// try to update record
String updatedFareId = "3B";
createdFare.fare_id = updatedFareId;
// covert object to json and save it
JdbcTableWriter updateTableWriter = createTestTableWriter(fareTable);
String updateOutput = updateTableWriter.update(
createdFare.id,
mapper.writeValueAsString(createdFare),
true
);
LOG.info("update {} output:", fareTable.name);
LOG.info(updateOutput);
FareDTO updatedFareDTO = mapper.readValue(updateOutput, fareDTOClass);
// make sure saved data matches expected data
assertThat(updatedFareDTO.fare_id, equalTo(updatedFareId));
assertThat(updatedFareDTO.fare_rules[0].fare_id, equalTo(updatedFareId));
// try to delete record
JdbcTableWriter deleteTableWriter = createTestTableWriter(fareTable);
int deleteOutput = deleteTableWriter.delete(
createdFare.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, fareTable.name);
// make sure fare_attributes record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
fareTable.name,
createdFare.id
));
// make sure fare_rules record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
Table.FARE_RULES.name,
createdFare.fare_rules[0].id
));
}
private void assertThatSqlQueryYieldsZeroRows(String sql) throws SQLException {
assertThatSqlQueryYieldsRowCount(sql, 0);
}
private void assertThatSqlQueryYieldsRowCount(String sql, int expectedRowCount) throws SQLException {
LOG.info(sql);
ResultSet resultSet = testDataSource.getConnection().prepareStatement(sql).executeQuery();
assertThat(resultSet.getFetchSize(), equalTo(expectedRowCount));
}
@Test
public void canCreateUpdateAndDeleteRoutes() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table routeTable = Table.ROUTES;
final Class<RouteDTO> routeDTOClass = RouteDTO.class;
// create new object to be saved
String routeId = "500";
RouteDTO createdRoute = createSimpleTestRoute(routeId, "RTA", "500", "Hollingsworth", 3);
// make sure saved data matches expected data
assertThat(createdRoute.route_id, equalTo(routeId));
// TODO: Verify with a SQL query that the database now contains the created data (we may need to use the same
// db connection to do this successfully?)
// try to update record
String updatedRouteId = "600";
createdRoute.route_id = updatedRouteId;
// covert object to json and save it
JdbcTableWriter updateTableWriter = createTestTableWriter(routeTable);
String updateOutput = updateTableWriter.update(
createdRoute.id,
mapper.writeValueAsString(createdRoute),
true
);
LOG.info("update {} output:", routeTable.name);
LOG.info(updateOutput);
RouteDTO updatedRouteDTO = mapper.readValue(updateOutput, routeDTOClass);
// make sure saved data matches expected data
assertThat(updatedRouteDTO.route_id, equalTo(updatedRouteId));
// TODO: Verify with a SQL query that the database now contains the updated data (we may need to use the same
// db connection to do this successfully?)
// try to delete record
JdbcTableWriter deleteTableWriter = createTestTableWriter(routeTable);
int deleteOutput = deleteTableWriter.delete(
createdRoute.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, routeTable.name);
// make sure route record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
routeTable.name,
createdRoute.id
));
}
/**
* Create and store a simple route for testing.
*/
private static RouteDTO createSimpleTestRoute(String routeId, String agencyId, String shortName, String longName, int routeType) throws InvalidNamespaceException, IOException, SQLException {
RouteDTO input = new RouteDTO();
input.route_id = routeId;
input.agency_id = agencyId;
// Empty value should be permitted for transfers and transfer_duration
input.route_short_name = shortName;
input.route_long_name = longName;
input.route_type = routeType;
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(Table.ROUTES);
String output = createTableWriter.create(mapper.writeValueAsString(input), true);
LOG.info("create {} output:", Table.ROUTES.name);
LOG.info(output);
// parse output
return mapper.readValue(output, RouteDTO.class);
}
/**
* Creates a pattern by first creating a route and then a pattern for that route.
*/
private static PatternDTO createSimpleRouteAndPattern(String routeId, String patternId, String name) throws InvalidNamespaceException, SQLException, IOException {
// Create new route
createSimpleTestRoute(routeId, "RTA", "500", "Hollingsworth", 3);
// Create new pattern for route
PatternDTO input = new PatternDTO();
input.pattern_id = patternId;
input.route_id = routeId;
input.name = name;
input.use_frequency = 0;
input.shapes = new ShapePointDTO[]{};
input.pattern_stops = new PatternStopDTO[]{};
// Write the pattern to the database
JdbcTableWriter createPatternWriter = createTestTableWriter(Table.PATTERNS);
String output = createPatternWriter.create(mapper.writeValueAsString(input), true);
LOG.info("create {} output:", Table.PATTERNS.name);
LOG.info(output);
// Parse output
return mapper.readValue(output, PatternDTO.class);
}
/**
* Test that a frequency trip entry CANNOT be added for a timetable-based pattern. Expects an exception to be thrown.
*/
@Test(expected = IllegalStateException.class)
public void cannotCreateFrequencyForTimetablePattern() throws InvalidNamespaceException, IOException, SQLException {
PatternDTO simplePattern = createSimpleRouteAndPattern("900", "8", "The Loop");
TripDTO tripInput = constructFrequencyTrip(simplePattern.pattern_id, simplePattern.route_id, 6 * 60 * 60);
JdbcTableWriter createTripWriter = createTestTableWriter(Table.TRIPS);
createTripWriter.create(mapper.writeValueAsString(tripInput), true);
}
/**
* Checks that creating a frequency trip functions properly. This also updates the pattern to include pattern stops,
* which is a prerequisite for creating a frequency trip with stop times.
*/
@Test
public void canCreateFrequencyForFrequencyPattern() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table tripsTable = Table.TRIPS;
int startTime = 6 * 60 * 60;
PatternDTO simplePattern = createSimpleRouteAndPattern("1000", "9", "The Line");
TripDTO tripInput = constructFrequencyTrip(simplePattern.pattern_id, simplePattern.route_id, startTime);
JdbcTableWriter createTripWriter = createTestTableWriter(tripsTable);
// Update pattern with pattern stops, set to use frequencies, and TODO shape points
JdbcTableWriter patternUpdater = createTestTableWriter(Table.PATTERNS);
simplePattern.use_frequency = 1;
simplePattern.pattern_stops = new PatternStopDTO[]{
new PatternStopDTO(simplePattern.pattern_id, firstStopId, 0),
new PatternStopDTO(simplePattern.pattern_id, lastStopId, 1)
};
String updatedPatternOutput = patternUpdater.update(simplePattern.id, mapper.writeValueAsString(simplePattern), true);
LOG.info("Updated pattern output: {}", updatedPatternOutput);
// Create new trip for the pattern
String createTripOutput = createTripWriter.create(mapper.writeValueAsString(tripInput), true);
TripDTO createdTrip = mapper.readValue(createTripOutput, TripDTO.class);
// Update trip
// TODO: Add update and delete tests for updating pattern stops, stop_times, and frequencies.
String updatedTripId = "100A";
createdTrip.trip_id = updatedTripId;
JdbcTableWriter updateTripWriter = createTestTableWriter(tripsTable);
String updateTripOutput = updateTripWriter.update(tripInput.id, mapper.writeValueAsString(createdTrip), true);
TripDTO updatedTrip = mapper.readValue(updateTripOutput, TripDTO.class);
// Check that saved data matches expected data
assertThat(updatedTrip.frequencies[0].start_time, equalTo(startTime));
assertThat(updatedTrip.trip_id, equalTo(updatedTripId));
// Delete trip record
JdbcTableWriter deleteTripWriter = createTestTableWriter(tripsTable);
int deleteOutput = deleteTripWriter.delete(
createdTrip.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, tripsTable.name);
// Check that route record does not exist in DB
assertThatSqlQueryYieldsZeroRows(
String.format(
"select * from %s.%s where id=%d",
testNamespace,
tripsTable.name,
createdTrip.id
));
}
/**
* Construct (without writing to the database) a trip with a frequency entry.
*/
private TripDTO constructFrequencyTrip(String patternId, String routeId, int startTime) {
TripDTO tripInput = new TripDTO();
tripInput.pattern_id = patternId;
tripInput.route_id = routeId;
tripInput.service_id = simpleServiceId;
tripInput.stop_times = new StopTimeDTO[]{
new StopTimeDTO(firstStopId, 0, 0, 0),
new StopTimeDTO(lastStopId, 60, 60, 1)
};
FrequencyDTO frequency = new FrequencyDTO();
frequency.start_time = startTime;
frequency.end_time = 9 * 60 * 60;
frequency.headway_secs = 15 * 60;
tripInput.frequencies = new FrequencyDTO[]{frequency};
return tripInput;
}
/**
* Create and store a simple stop entity.
*/
private static StopDTO createSimpleStop(String stopId, String stopName, double latitude, double longitude) throws InvalidNamespaceException, IOException, SQLException {
JdbcTableWriter createStopWriter = new JdbcTableWriter(Table.STOPS, testDataSource, testNamespace);
StopDTO input = new StopDTO();
input.stop_id = stopId;
input.stop_name = stopName;
input.stop_lat = latitude;
input.stop_lon = longitude;
String output = createStopWriter.create(mapper.writeValueAsString(input), true);
LOG.info("create {} output:", Table.STOPS.name);
LOG.info(output);
return mapper.readValue(output, StopDTO.class);
}
/**
* Create and store a simple calendar that runs on each weekday.
*/
private static CalendarDTO createWeekdayCalendar(String serviceId, String startDate, String endDate) throws IOException, SQLException, InvalidNamespaceException {
JdbcTableWriter createCalendarWriter = new JdbcTableWriter(Table.CALENDAR, testDataSource, testNamespace);
CalendarDTO calendarInput = new CalendarDTO();
calendarInput.service_id = serviceId;
calendarInput.monday = 1;
calendarInput.tuesday = 1;
calendarInput.wednesday = 1;
calendarInput.thursday = 1;
calendarInput.friday = 1;
calendarInput.saturday = 0;
calendarInput.sunday = 0;
calendarInput.start_date = startDate;
calendarInput.end_date = endDate;
String output = createCalendarWriter.create(mapper.writeValueAsString(calendarInput), true);
LOG.info("create {} output:", Table.CALENDAR.name);
LOG.info(output);
return mapper.readValue(output, CalendarDTO.class);
}
@AfterClass
public static void tearDownClass() {
TestUtils.dropDB(testDBName);
}
}
|
package baseCode.bio.geneset;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
public class TestGeneAnnotations extends TestCase {
InputStream is;
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
is = TestGeneAnnotations.class.getResourceAsStream( "/data/HG-U133_Plus_2_annot_sample.csv" );
if ( is == null ) throw new IllegalStateException();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
public final void testReadAffyCsv() throws Exception {
GeneAnnotations ga = new GeneAnnotations();
ga.readAffyCsv( is, null );
ga.setUp( null );
List geneSets = new ArrayList( ga.getGeneSetToGeneMap().keySet() );
Collections.sort( geneSets );
assertTrue( geneSets.size() > 0 );
}
}
|
package com.datalogics.pdf.hsm.samples;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.adobe.pdfjt.core.credentials.PrivateKeyHolder;
import com.adobe.pdfjt.core.credentials.PrivateKeyHolderFactory;
import com.adobe.pdfjt.core.credentials.impl.ByteArrayKeyHolder;
import com.adobe.pdfjt.core.credentials.impl.utils.CertUtils;
import com.datalogics.pdf.hsm.samples.mock.MockProvider;
import com.datalogics.pdf.hsm.samples.util.LogRecordListCollector;
import com.datalogics.pdf.security.HsmManager;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Unit tests simulating a connected HSM device.
*/
public class MockedHsmTest extends SampleTest {
private static final Logger LOGGER = Logger.getLogger(MockedHsmTest.class.getName());
static final String FILE_NAME = "SignedField.pdf";
static final String MESSAGE = "Fully Qualified Name: Approver";
private static URL inputUrl;
private static URL outputUrl;
private static File outputFile;
private static HsmManager connectedHsmManager;
/**
* Set up to try and sign a document with an unconnected HSM device.
*
* @throws Exception a general exception was thrown
*/
@BeforeClass
public static void setUpForMock() throws Exception {
inputUrl = HsmSignDocument.class.getResource(HsmSignDocument.INPUT_UNSIGNED_PDF_PATH);
outputFile = SampleTest.newOutputFileWithDelete(FILE_NAME);
// The complete file name will be set in the HsmSignDocument class.
outputUrl = outputFile.toURI().toURL();
// Create a connected HsmManager
connectedHsmManager = new ConnectedHsmManager();
}
@Test
public void logMessageIsGenerated() throws Exception {
final ArrayList<LogRecord> logRecords = new ArrayList<LogRecord>();
final Logger logger = Logger.getLogger(HsmSignDocument.class.getName());
try (LogRecordListCollector collector = new LogRecordListCollector(logger, logRecords)) {
HsmSignDocument.signExistingSignatureFields(connectedHsmManager, inputUrl, outputUrl);
} catch (final IllegalStateException e) {
// Expected exception
}
// Verify that we got the expected log message
assertEquals("Must have one log record", 1, logRecords.size());
final LogRecord logRecord = logRecords.get(0);
assertEquals(MESSAGE, logRecord.getMessage());
assertEquals(Level.INFO, logRecord.getLevel());
}
@Test
public void outputFileIsGenerated() throws Exception {
try {
HsmSignDocument.signExistingSignatureFields(connectedHsmManager, inputUrl, outputUrl);
} catch (final IllegalStateException e) {
// Expected exception
}
// Verify the Output file exists.
assertTrue(outputFile.getPath() + " must exist after run", outputFile.exists());
}
/*
* An HsmManager which is always unconnected.
*/
private static class ConnectedHsmManager extends AbstractHsmManager {
private static final String DER_KEY_PATH = "pdfjt-key.der";
private static final String DER_CERT_PATH = "pdfjt-cert.der";
final InputStream certStream = MockedHsmTest.class.getResourceAsStream(DER_CERT_PATH);
final InputStream keyStream = MockedHsmTest.class.getResourceAsStream(DER_KEY_PATH);
private Key key;
private Certificate[] certificateChain;
public ConnectedHsmManager() throws Exception {
initializeProvider();
loadKey();
loadCertificateChain();
}
@Override
public ConnectionState getConnectionState() {
return ConnectionState.CONNECTED;
}
@Override
public Key getKey(final String password, final String keyLabel) {
return key;
}
@Override
public Certificate[] getCertificateChain(final String certLabel) {
return certificateChain;
}
@Override
public String getProviderName() {
return MockProvider.PROVIDER_NAME;
}
private void initializeProvider() {
if (Security.getProvider(MockProvider.PROVIDER_NAME) == null) {
Security.addProvider(new MockProvider());
}
}
private void loadKey() throws Exception {
try {
final byte[] derEncodedPrivateKey = getDerEncodedData(keyStream);
final PrivateKeyHolder privateKeyHolder = PrivateKeyHolderFactory
.newInstance()
.createPrivateKey(derEncodedPrivateKey,
"RSA");
key = CertUtils.createJCEPrivateKey(((ByteArrayKeyHolder) privateKeyHolder).getDerEncodedKey(),
((ByteArrayKeyHolder) privateKeyHolder).getAlgorithm());
} catch (final IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe("Could not create private key: " + e.getMessage());
}
throw new Exception(e);
}
}
private void loadCertificateChain() throws Exception {
try {
final byte[] derEncodedCert = getDerEncodedData(certStream);
final X509Certificate jceCert = (X509Certificate) CertUtils.importCertificate(derEncodedCert);
certificateChain = new X509Certificate[] { jceCert };
} catch (final IOException | CertificateException e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe("Could not create certificate: " + e.getMessage());
}
throw new Exception(e);
}
}
private static byte[] getDerEncodedData(final InputStream inputStream) throws IOException {
final byte[] derData = new byte[inputStream.available()];
final int totalBytes = inputStream.read(derData, 0, derData.length);
if (totalBytes == 0) {
LOGGER.info("getDerEncodedData(): No bytes read from InputStream");
}
inputStream.close();
return derData;
}
}
}
|
package com.github.nkzawa.engineio.client;
import org.junit.After;
import org.junit.Before;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.*;
public abstract class Connection {
final static int TIMEOUT = 10000;
final static int PORT = 3000;
private Process serverProcess;
private ExecutorService serverService;
private Future serverOutout;
private Future serverError;
@Before
public void startServer() throws IOException, InterruptedException {
System.out.println("Starting server ...");
final CountDownLatch latch = new CountDownLatch(1);
serverProcess = Runtime.getRuntime().exec(
"node src/test/resources/server.js", createEnv());
serverService = Executors.newCachedThreadPool();
serverOutout = serverService.submit(new Runnable() {
@Override
public void run() {
BufferedReader reader = new BufferedReader(
new InputStreamReader(serverProcess.getInputStream()));
String line;
try {
line = reader.readLine();
latch.countDown();
do {
System.out.println("SERVER OUT: " + line);
} while ((line = reader.readLine()) != null);
} catch (IOException e) {
e.printStackTrace();
}
}
});
serverError = serverService.submit(new Runnable() {
@Override
public void run() {
BufferedReader reader = new BufferedReader(
new InputStreamReader(serverProcess.getErrorStream()));
String line;
try {
while ((line = reader.readLine()) != null) {
System.err.println("SERVER ERR: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
latch.await(3000, TimeUnit.MILLISECONDS);
}
@After
public void stopServer() throws InterruptedException {
System.out.println("Stopping server ...");
serverProcess.destroy();
serverOutout.cancel(false);
serverError.cancel(false);
serverService.shutdown();
serverService.awaitTermination(3000, TimeUnit.MILLISECONDS);
}
Socket.Options createOptions() {
Socket.Options opts = new Socket.Options();
opts.port = PORT;
return opts;
}
String[] createEnv() {
return new String[] {"DEBUG=engine*", "PORT=" + PORT};
}
}
|
package com.github.sebhoss.units.storage;
import java.math.BigInteger;
import com.github.sebhoss.nullanalysis.Nullsafe;
import com.github.sebhoss.warnings.CompilerWarnings;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for Exabytes.
*/
@SuppressWarnings({ CompilerWarnings.NLS, CompilerWarnings.STATIC_METHOD })
public class ExabyteTest {
/**
* Checks that a new {@link Exabyte} instance must be created with a BigInteger.
*/
@Test
public void shouldConstructWithBigInteger() {
// Given
Exabyte unit;
// When
unit = new Exabyte(Nullsafe.nullsafe(BigInteger.valueOf(1000)));
// Then
Assert.assertNotNull(unit);
}
/**
* Checks that {@link Exabyte#valueOf(long)} does not return <code>null</code>.
*/
@Test
public void shouldCreateExabyte() {
// Given
final StorageUnit<?> unit;
// When
unit = Exabyte.valueOf(1000);
// Then
Assert.assertNotNull("The created unit should never be NULL.", unit);
}
/**
* Checks that {@link Exabyte#toString()} shows the correct symbol.
*/
@Test
public void shouldShowCorrectSymbol() {
// Given
final StorageUnit<?> unit;
// When
unit = StorageUnits.exabyte(1);
// Then
Assert.assertTrue("The symbol for exabyte should be 'EB'.", unit.toString().endsWith("EB"));
}
/**
* Checks that {@link Exabyte#toString()} shows the correct value.
*/
@Test
public void shouldShowCorrectValue() {
// Given
final StorageUnit<?> unit;
// When
unit = StorageUnits.exabyte(1);
// Then
Assert.assertTrue("One exabyte should be interpreted as '1.00' exabytes.", unit.toString().startsWith("1.00"));
}
}
|
package com.github.wz2cool.dynamic;
import com.github.pagehelper.PageRowBounds;
import com.github.wz2cool.dynamic.mybatis.db.mapper.UserDao;
import com.github.wz2cool.dynamic.mybatis.db.model.entity.table.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static com.github.wz2cool.dynamic.builder.DynamicQueryBuilderHelper.isEqual;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = TestApplication.class)
public class DynamicMapperTest {
@Autowired
private UserDao userDao;
@Test
public void testInsert() {
User user = new User();
user.setId(10);
user.setUserName("frank");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
}
@Test
public void testInsertSelective() {
User user = new User();
user.setId(11);
user.setUserName("frank");
int result = userDao.insertSelective(user);
assertEquals(1, result);
}
@Test
public void testDeleteByPrimaryKey() {
User user = new User();
user.setId(12);
user.setUserName("frank");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
result = userDao.deleteByPrimaryKey(12);
assertEquals(1, result);
}
@Test
public void testDeleteByT() {
User user = new User();
user.setId(13);
user.setUserName("frank");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
result = userDao.delete(user);
assertEquals(1, result);
}
@Test
public void testDeleteByDynamicQuery() {
User user = new User();
user.setId(14);
user.setUserName("frank14");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
DynamicQuery<User> dynamicQuery = new DynamicQuery<>(User.class);
FilterDescriptor nameFilter = new FilterDescriptor(
FilterCondition.AND, "userName",
FilterOperator.CONTAINS, "14");
dynamicQuery.addFilters(nameFilter);
result = userDao.deleteByDynamicQuery(dynamicQuery);
assertEquals(1, result);
}
@Test
public void testUpdateByPrimaryKey() {
User user = new User();
user.setId(15);
user.setUserName("frank");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
user.setPassword("test12345");
result = userDao.updateByPrimaryKey(user);
assertEquals(1, result);
}
@Test
public void testUpdateByPrimaryKeySelective() {
User user = new User();
user.setId(16);
user.setUserName("frank");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
User updateUser = new User();
updateUser.setId(16);
updateUser.setPassword("test123");
result = userDao.updateByPrimaryKeySelective(updateUser);
assertEquals(1, result);
}
@Test
public void testUpdateByDynamicQuery() {
User user = new User();
user.setId(17);
user.setUserName("frank17");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
User updateUser = new User();
updateUser.setId(17);
updateUser.setUserName("Marry");
DynamicQuery<User> dynamicQuery = new DynamicQuery<>(User.class);
FilterDescriptor nameFilter = new FilterDescriptor(
FilterCondition.AND, "userName",
FilterOperator.CONTAINS, "17");
dynamicQuery.addFilters(nameFilter);
result = userDao.updateByDynamicQuery(updateUser, dynamicQuery);
assertEquals(1, result);
}
@Test
public void testUpdate() {
User user = new User();
user.setId(18);
user.setUserName("frank18");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
User updateUser = new User();
updateUser.setUserName("Marry");
DynamicQuery<User> dynamicQuery = new DynamicQuery<>(User.class);
FilterDescriptor nameFilter = new FilterDescriptor(
FilterCondition.AND, "userName",
FilterOperator.CONTAINS, "18");
dynamicQuery.addFilters(nameFilter);
result = userDao.updateSelectiveByDynamicQuery(updateUser, dynamicQuery);
assertEquals(1, result);
}
@Test
public void testUpdateByUpdateQuery() {
User user = new User();
user.setId(19);
user.setUserName("frank19");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
UpdateQuery<User> userUpdateQuery = UpdateQuery.createQuery(User.class)
.set(User::getUserName, "Marry")
.set(User::getPassword, null)
.and(User::getUserName, isEqual("frank19"));
result = userDao.updateByUpdateQuery(userUpdateQuery);
assertEquals(1, result);
final User user1 = userDao.selectByPrimaryKey(19);
assertEquals("Marry", user1.getUserName());
assertNull(user1.getPassword());
userDao.deleteByPrimaryKey(19);
}
@Test
public void testSelectAll() {
List<User> users = userDao.selectAll();
assertEquals(true, users.size() > 0);
}
@Test
public void testSelectByT() {
User user = new User();
user.setId(1);
List<User> users = userDao.select(user);
assertEquals(1, users.size());
}
@Test
public void testSelectOne() {
User user = new User();
user.setId(1);
User matchedUser = userDao.selectOne(user);
assertEquals(Integer.valueOf(1), matchedUser.getId());
}
@Test
public void testSelectCount() {
User user = new User();
user.setId(19);
user.setUserName("frank19");
user.setPassword("frank");
int result = userDao.insert(user);
assertEquals(1, result);
User findUser = new User();
user.setId(19);
result = userDao.selectCount(findUser);
assertEquals(true, result > 0);
}
@Test
public void testSelectRowBoundsByDynamicQuery() {
DynamicQuery<User> dynamicQuery = new DynamicQuery<>(User.class);
dynamicQuery.setDistinct(true);
FilterDescriptor idFilter =
new FilterDescriptor("id", FilterOperator.LESS_THAN, 100);
dynamicQuery.addFilters(idFilter);
SortDescriptor idSort =
new SortDescriptor(User::getId, SortDirection.DESC);
dynamicQuery.addSorts(idSort);
PageRowBounds pageRowBounds = new PageRowBounds(1, 2);
List<User> users = userDao.selectRowBoundsByDynamicQuery(dynamicQuery, pageRowBounds);
assertEquals(true, users.size() > 0);
}
}
|
package com.pm.server.controller;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.jayway.jsonpath.JsonPath;
import com.pm.server.ControllerTestTemplate;
import com.pm.server.datatype.Coordinate;
import com.pm.server.datatype.CoordinateImpl;
import com.pm.server.datatype.PlayerState;
import com.pm.server.player.Ghost;
import com.pm.server.repository.GhostRepository;
import com.pm.server.utils.JsonUtils;
public class GhostControllerTest extends ControllerTestTemplate {
@Autowired
private GhostRepository ghostRepository;
private static final List<Coordinate> randomCoordinateList = Arrays.asList(
new CoordinateImpl(12345.54321, 95837.39821),
new CoordinateImpl(49381.30982, 39399.49932)
);
private static final String BASE_MAPPING = "/ghost";
private static final Logger log =
LogManager.getLogger(GhostControllerTest.class.getName());
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.webAppContextSetup(this.webApplicationContext)
.build();
}
@After
public void cleanUp() {
List<Ghost> ghostList = ghostRepository.getAllPlayers();
List<Integer> ghostIdList = new ArrayList<Integer>();
for(Ghost ghost : ghostList) {
ghostIdList.add(ghost.getId());
}
for(Integer id : ghostIdList) {
try {
ghostRepository.deletePlayerById(id);
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
}
assert(ghostRepository.numOfPlayers() == 0);
}
@Test
public void unitTest_createGhost() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
String body = JsonUtils.objectToJson(location);
String path = pathForCreateGhost();
// When
mockMvc
.perform(post(path)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").exists());
}
@Test
public void unitTest_createGhost_sameLocation() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
String body = JsonUtils.objectToJson(location);
String path = pathForCreateGhost();
mockMvc
.perform(post(path)
.content(body)
.header("Content-Type", "application/json")
)
.andExpect(status().isOk());
// When
mockMvc
.perform(post(path)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").exists());
}
@Test
public void unitTest_createGhost_notANumber() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
String body =
"{\"" +
location.getLatitude() + "\":\"" +
"longitude" +
"\"}";
String path = pathForCreateGhost();
// When
mockMvc
.perform(post(path)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isBadRequest());
}
@Test
public void unitTest_createGhost_noLocationGiven() throws Exception {
// Given
String path = pathForCreateGhost();
// When
mockMvc
.perform(post(path)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isBadRequest());
}
@Test
public void unitTest_deleteGhostById() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForDeleteGhostById(id);
// When
mockMvc
.perform(delete(path))
// Then
.andExpect(status().isOk());
}
@Test
public void unitTest_deleteGhostById_noGhost() throws Exception {
// Given
Integer id = 2481;
String path = pathForDeleteGhostById(id);
// When
mockMvc
.perform(delete(path))
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_deleteGhostById_incorrectId() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForDeleteGhostById(id + 1);
// When
mockMvc
.perform(delete(path))
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_getGhostLocationById() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForGetGhostLocationById(id);
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isOk())
.andExpect(jsonPath("$.location.latitude")
.value(location.getLatitude())
)
.andExpect(jsonPath("$.location.longitude")
.value(location.getLongitude())
);
}
@Test
public void unitTest_getGhostLocationById_wrongId() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForGetGhostLocationById(id + 1);
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_getGhostLocationById_noGhost() throws Exception {
// Given
Integer id = 39482;
String path = pathForGetGhostLocationById(id);
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_getAllGhostLocations_singleGhost() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForGetAllGhostLocations();
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id")
.value(id)
)
.andExpect(jsonPath("$[0].location.latitude")
.value(location.getLatitude())
)
.andExpect(jsonPath("$[0].location.longitude")
.value(location.getLongitude())
);
}
@Test
public void unitTest_getAllGhostLocations_multipleGhosts() throws Exception {
// Given
Coordinate location0 = randomCoordinateList.get(0);
Integer id0 = createGhost_failUponException(location0);
Coordinate location1 = randomCoordinateList.get(1);
Integer id1 = createGhost_failUponException(location1);
String path = pathForGetAllGhostLocations();
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id")
.value(id0)
)
.andExpect(jsonPath("$[0].location.latitude")
.value(location0.getLatitude())
)
.andExpect(jsonPath("$[0].location.longitude")
.value(location0.getLongitude())
)
.andExpect(jsonPath("$[1].id")
.value(id1)
)
.andExpect(jsonPath("$[1].location.latitude")
.value(location1.getLatitude())
)
.andExpect(jsonPath("$[1].location.longitude")
.value(location1.getLongitude())
);
}
@Test
public void unitTest_getAllGhostLocations_noGhosts() throws Exception {
// Given
String path = pathForGetAllGhostLocations();
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(0)));
}
@Test
public void unitTest_getGhostStateById() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForGetGhostStateById(id);
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isOk())
.andExpect(jsonPath("$.state").exists());
}
@Test
public void unitTest_getGhostStateById_wrongId() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForGetGhostStateById(id + 1);
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_getGhostStateById_noGhost() throws Exception {
// Given
Integer randomId = 12931;
String path = pathForGetGhostStateById(randomId);
// When
mockMvc
.perform(get(path))
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_setGhostLocationById() throws Exception {
// Given
Coordinate location_original = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location_original);
String path = pathForSetGhostLocationById(id);
Coordinate location_updated = randomCoordinateList.get(0);
String body = JsonUtils.objectToJson(location_updated);
// When
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
.andExpect(status().isOk());
// Then
Coordinate location_result =
getGhostLocationById_failUponException(id);
assertEquals(location_updated.getLatitude(), location_result.getLatitude());
assertEquals(location_updated.getLongitude(), location_result.getLongitude());
}
@Test
public void unitTest_setGhostLocationById_noGhost() throws Exception {
// Given
Integer randomId = 29481;
String pathForSetLocation = pathForSetGhostLocationById(randomId);
Coordinate location = randomCoordinateList.get(0);
String body = JsonUtils.objectToJson(location);
// When
mockMvc
.perform(put(pathForSetLocation)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_setGhostLocationById_noLocationGiven()
throws Exception {
// Given
Integer randomId = 29481;
String pathForSetLocation = pathForSetGhostLocationById(randomId);
// When
mockMvc
.perform(put(pathForSetLocation)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isBadRequest());
}
@Test
public void unitTest_setGhostStateById() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForSetGhostStateById(id);
PlayerState updatedState = PlayerState.READY;
String body = JsonUtils.objectToJson(updatedState);
// When
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
.andExpect(status().isOk());
// Then
PlayerState resultState = getGhostStateById_failUponException(id);
assertEquals(updatedState, resultState);
}
@Test
public void unitTest_setGhostStateById_sameState() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForSetGhostStateById(id);
PlayerState updatedState = PlayerState.READY;
String body = JsonUtils.objectToJson(updatedState);
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
.andExpect(status().isOk());
// When
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
.andExpect(status().isOk());
// Then
PlayerState resultState = getGhostStateById_failUponException(id);
assertEquals(updatedState, resultState);
}
@Test
public void unitTest_setGhostStateById_illegalPowerupState() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForSetGhostStateById(id);
PlayerState updatedState = PlayerState.POWERUP;
String body = JsonUtils.objectToJson(updatedState);
// When
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isBadRequest());
}
@Test
public void unitTest_setGhostStateById_noStateGiven() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForSetGhostStateById(id);
// When
mockMvc
.perform(put(path)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isBadRequest());
}
@Test
public void unitTest_setGhostStateById_invalidStateValue() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForSetGhostStateById(id);
String body = "{\"state\":\"invalidValue\"}";
// When
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isBadRequest());
}
@Test
public void unitTest_setGhostStateById_wrongId() throws Exception {
// Given
Coordinate location = randomCoordinateList.get(0);
Integer id = createGhost_failUponException(location);
String path = pathForSetGhostStateById(id + 1);
PlayerState updatedState = PlayerState.READY;
String body = JsonUtils.objectToJson(updatedState);
// When
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isNotFound());
}
@Test
public void unitTest_setGhostStateById_noGhost() throws Exception {
// Given
Integer randomId = 19349;
String path = pathForSetGhostStateById(randomId);
PlayerState updatedState = PlayerState.READY;
String body = JsonUtils.objectToJson(updatedState);
// When
mockMvc
.perform(put(path)
.content(body)
.header("Content-Type", "application/json")
)
// Then
.andExpect(status().isNotFound());
}
private String pathForCreateGhost() {
return BASE_MAPPING;
}
private String pathForDeleteGhostById(Integer id) {
return BASE_MAPPING + "/" + id;
}
private String pathForGetGhostLocationById(Integer id) {
return BASE_MAPPING + "/" + id + "/" + "location";
}
private String pathForGetAllGhostLocations() {
return BASE_MAPPING + "/" + "locations";
}
private String pathForGetGhostStateById(Integer id) {
return BASE_MAPPING + "/" + id + "/" + "state";
}
private String pathForSetGhostLocationById(Integer id) {
return BASE_MAPPING + "/" + id + "/" + "location";
}
private String pathForSetGhostStateById(Integer id) {
return BASE_MAPPING + "/" + id + "/" + "state";
}
// Returns the ID of the created ghost
private Integer createGhost_failUponException(Coordinate location) {
String path = pathForCreateGhost();
String body = JsonUtils.objectToJson(location);
String jsonContent = null;
try {
MvcResult result = mockMvc
.perform(post(path)
.content(body)
.header("Content-Type", "application/json")
)
.andExpect(status().isOk())
.andReturn();
jsonContent = result.getResponse().getContentAsString();
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
assertNotNull(jsonContent);
return JsonPath.read(jsonContent, "$.id");
}
private Coordinate getGhostLocationById_failUponException(Integer id) {
String path = pathForGetGhostLocationById(id);
String jsonContent = null;
try {
MvcResult result = mockMvc
.perform(get(path))
.andExpect(status().isOk())
.andReturn();
jsonContent = result.getResponse().getContentAsString();
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
assertNotNull(jsonContent);
Double latitude = JsonPath.read(jsonContent, "$.location.latitude");
assertNotNull(latitude);
Double longitude = JsonPath.read(jsonContent, "$.location.longitude");
assertNotNull(longitude);
return new CoordinateImpl(latitude, longitude);
}
private PlayerState getGhostStateById_failUponException(Integer id) {
String path = pathForGetGhostStateById(id);
String jsonContent = null;
try {
MvcResult result = mockMvc
.perform(get(path))
.andExpect(status().isOk())
.andReturn();
jsonContent = result.getResponse().getContentAsString();
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
assertNotNull(jsonContent);
String stateString = JsonPath.read(jsonContent, "$.state");
PlayerState state = null;
try {
state = PlayerState.valueOf(stateString);
}
catch(IllegalArgumentException e) {
log.error(e.getMessage());
fail();
}
assertNotNull(state);
return state;
}
}
|
package org.jasig.portal.channels.portlet;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pluto.PortletContainer;
import org.apache.pluto.PortletContainerImpl;
import org.apache.pluto.PortletContainerServices;
import org.apache.pluto.om.entity.PortletEntity;
import org.apache.pluto.om.portlet.PortletDefinition;
import org.apache.pluto.om.window.PortletWindow;
import org.apache.pluto.services.information.DynamicInformationProvider;
import org.apache.pluto.services.information.InformationProviderAccess;
import org.apache.pluto.services.information.PortletActionProvider;
import org.apache.pluto.services.property.PropertyManager;
import org.apache.pluto.services.property.PropertyManagerService;
import org.jasig.portal.ChannelCacheKey;
import org.jasig.portal.ChannelDefinition;
import org.jasig.portal.ChannelRegistryStoreFactory;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelRuntimeProperties;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.ICacheable;
import org.jasig.portal.ICharacterChannel;
import org.jasig.portal.IDirectResponse;
import org.jasig.portal.IPrivileged;
import org.jasig.portal.PortalControlStructures;
import org.jasig.portal.PortalEvent;
import org.jasig.portal.PortalException;
import org.jasig.portal.container.om.common.ObjectIDImpl;
import org.jasig.portal.container.om.entity.PortletApplicationEntityImpl;
import org.jasig.portal.container.om.entity.PortletEntityImpl;
import org.jasig.portal.container.om.portlet.PortletApplicationDefinitionImpl;
import org.jasig.portal.container.om.portlet.PortletDefinitionImpl;
import org.jasig.portal.container.om.portlet.UserAttributeImpl;
import org.jasig.portal.container.om.portlet.UserAttributeListImpl;
import org.jasig.portal.container.om.window.PortletWindowImpl;
import org.jasig.portal.container.services.FactoryManagerServiceImpl;
import org.jasig.portal.container.services.PortletContainerEnvironmentImpl;
import org.jasig.portal.container.services.information.DynamicInformationProviderImpl;
import org.jasig.portal.container.services.information.InformationProviderServiceImpl;
import org.jasig.portal.container.services.information.PortletStateManager;
import org.jasig.portal.container.services.log.LogServiceImpl;
import org.jasig.portal.container.services.property.PropertyManagerServiceImpl;
import org.jasig.portal.container.servlet.DummyParameterRequestWrapper;
import org.jasig.portal.container.servlet.PortletAttributeRequestWrapper;
import org.jasig.portal.container.servlet.PortletParameterRequestWrapper;
import org.jasig.portal.container.servlet.ServletObjectAccess;
import org.jasig.portal.container.servlet.ServletRequestImpl;
import org.jasig.portal.layout.node.IUserLayoutChannelDescription;
import org.jasig.portal.properties.PropertiesManager;
import org.jasig.portal.security.IOpaqueCredentials;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.ISecurityContext;
import org.jasig.portal.security.provider.NotSoOpaqueCredentials;
import org.jasig.portal.utils.NullOutputStream;
import org.jasig.portal.utils.SAXHelper;
import org.xml.sax.ContentHandler;
/**
* A JSR 168 Portlet adapter that presents a portlet
* through the uPortal channel interface.
* <p>
* There is a related channel type called
* "Portlet Adapter" that is included with uPortal, so to use
* this channel, just select the "Portlet" type when publishing.
* </p>
* <p>
* Note: A portlet can specify the String "password" in the
* user attributes section of the portlet.xml. In this is done,
* this adapter will look for the user's cached password. If
* the user's password is being stored in memory by a caching
* security context, the adapter will consult the cache to fill the
* request for the attribute. If the user's password is not cached,
* <code>null</code> will be set for the attributes value.
* </p>
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
*/
public class CPortletAdapter
implements ICharacterChannel, IPrivileged, ICacheable, IDirectResponse, IPortletAdaptor {
protected final Log log = LogFactory.getLog(getClass());
private static boolean portletContainerInitialized;
private static PortletContainer portletContainer;
private static ServletConfig servletConfig;
private static final ChannelCacheKey systemCacheKey;
private static final ChannelCacheKey instanceCacheKey;
private static final String uniqueContainerName =
PropertiesManager.getProperty("org.jasig.portal.channels.portlet.CPortletAdapter.uniqueContainerName", "Pluto-in-uPortal");
// Publish parameters expected by this channel
private static final String portletDefinitionIdParamName = "portletDefinitionId";
public static final String portletPreferenceNamePrefix = "PORTLET.";
private ChannelStaticData staticData = null;
private ChannelRuntimeData runtimeData = null;
private PortalControlStructures pcs = null;
private boolean portletWindowInitialized = false;
private PortletWindow portletWindow = null;
private Map userInfo = null;
private boolean receivedEvent = false;
private boolean focused = false;
private PortletMode newPortletMode = null;
private long lastRenderTime = Long.MIN_VALUE;
private String expirationCache = null;
private WindowState newWindowState = null;
private Map requestParams = null;
static {
portletContainerInitialized = false;
// Initialize cache keys
ChannelCacheKey key = new ChannelCacheKey();
key.setKeyScope(ChannelCacheKey.SYSTEM_KEY_SCOPE);
key.setKey("SYSTEM_SCOPE_KEY");
systemCacheKey = key;
key = new ChannelCacheKey();
key.setKeyScope(ChannelCacheKey.INSTANCE_KEY_SCOPE);
key.setKey("INSTANCE_SCOPE_KEY");
instanceCacheKey = key;
}
/**
* Receive the servlet config from uPortal's PortalSessionManager servlet.
* Pluto needs access to this object from serveral places.
* @param config the servlet config
*/
public static void setServletConfig(ServletConfig config) {
servletConfig = config;
}
/**
*
* @throws PortalException
*/
private synchronized static void initPortletContainer() throws PortalException {
if (!portletContainerInitialized) {
portletContainerInitialized = true;
try {
PortletContainerEnvironmentImpl environment = new PortletContainerEnvironmentImpl();
LogServiceImpl logService = new LogServiceImpl();
FactoryManagerServiceImpl factorManagerService = new FactoryManagerServiceImpl();
InformationProviderServiceImpl informationProviderService = new InformationProviderServiceImpl();
PropertyManagerService propertyManagerService = new PropertyManagerServiceImpl();
logService.init(servletConfig, null);
factorManagerService.init(servletConfig, null);
informationProviderService.init(servletConfig, null);
environment.addContainerService(logService);
environment.addContainerService(factorManagerService);
environment.addContainerService(informationProviderService);
environment.addContainerService(propertyManagerService);
//Call added in case the context has been re-loaded
PortletContainerServices.destroyReference(uniqueContainerName);
portletContainer = new PortletContainerImpl();
portletContainer.init(uniqueContainerName, servletConfig, environment, new Properties());
} catch (Exception e) {
String message = "Initialization of the portlet container failed.";
//log.error( message, e);
throw new PortalException(message, e);
}
}
}
protected void initPortletWindow() throws PortalException {
try {
initPortletContainer();
PortletContainerServices.prepare(uniqueContainerName);
// Get the portlet definition Id which must be specified as a publish
// parameter. The syntax of the ID is [portlet-context-name].[portlet-name]
String portletDefinitionId = staticData.getParameter(portletDefinitionIdParamName);
if (portletDefinitionId == null) {
throw new PortalException("Missing publish parameter '" + portletDefinitionIdParamName + "'");
}
// Create the PortletDefinition
PortletDefinitionImpl portletDefinition = (PortletDefinitionImpl)InformationProviderAccess.getStaticProvider().getPortletDefinition(ObjectIDImpl.createFromString(portletDefinitionId));
if (portletDefinition == null) {
throw new PortalException("Unable to find portlet definition for ID '" + portletDefinitionId + "'");
}
ChannelDefinition channelDefinition = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl().getChannelDefinition(Integer.parseInt(staticData.getChannelPublishId()));
portletDefinition.setChannelDefinition(channelDefinition);
portletDefinition.loadPreferences();
// Create the PortletApplicationEntity
final PortletApplicationEntityImpl portAppEnt = new PortletApplicationEntityImpl();
portAppEnt.setId(portletDefinition.getId().toString());
portAppEnt.setPortletApplicationDefinition(portletDefinition.getPortletApplicationDefinition());
// Create the PortletEntity
PortletEntityImpl portletEntity = new PortletEntityImpl();
portletEntity.setId(staticData.getChannelPublishId());
portletEntity.setPortletDefinition(portletDefinition);
portletEntity.setPortletApplicationEntity(portAppEnt);
portletEntity.setUserLayout(pcs.getUserPreferencesManager().getUserLayoutManager().getUserLayout());
portletEntity.setChannelDescription((IUserLayoutChannelDescription)pcs.getUserPreferencesManager().getUserLayoutManager().getNode(staticData.getChannelSubscribeId()));
portletEntity.setPerson(staticData.getPerson());
portletEntity.loadPreferences();
// Add the user information into the request See PLT.17.2.
if (userInfo == null) {
UserAttributeListImpl userAttributeList = ((PortletApplicationDefinitionImpl)portletDefinition.getPortletApplicationDefinition()).getUserAttributes();
// here we ask an overridable method to get the user attributes.
// you can extend CPortletAdapter to change the implementation of
// how we get user attributes. This whole initPortletWindow method
// is also overridable.
// Note that we will only call getUserInfo() once.
userInfo = getUserInfo(staticData, userAttributeList);
if (log.isTraceEnabled()) {
//log.trace("For user [" + uid + "] got user info : [" + userInfo + "]");
}
}
// Wrap the request
ServletRequestImpl wrappedRequest = new ServletRequestImpl(pcs.getHttpServletRequest(), staticData.getPerson(), portletDefinition.getInitSecurityRoleRefSet());
// Now create the PortletWindow and hold a reference to it
PortletWindowImpl pw = new PortletWindowImpl();
pw.setId(staticData.getChannelSubscribeId());
pw.setPortletEntity(portletEntity);
pw.setChannelRuntimeData(runtimeData);
pw.setHttpServletRequest(wrappedRequest);
portletWindow = pw;
// Ask the container to load the portlet
synchronized(this) {
portletContainer.portletLoad(portletWindow, wrappedRequest, pcs.getHttpServletResponse());
}
portletWindowInitialized = true;
} catch (Exception e) {
String message = "Initialization of the portlet container failed.";
log.error( message, e);
throw new PortalException(message, e);
} finally {
PortletContainerServices.release();
}
}
/**
* Sets channel runtime properties.
* @return channel runtime properties
*/
public ChannelRuntimeProperties getRuntimeProperties() {
return new ChannelRuntimeProperties();
}
/**
* React to portal events.
* Removes channel state from the channel state map when the session expires.
* @param ev a portal event
*/
public void receiveEvent(PortalEvent ev) {
try {
PortletContainerServices.prepare(uniqueContainerName);
receivedEvent =true;
switch (ev.getEventNumber()) {
// Detect portlet mode changes
// Cannot use the PortletActionProvider to change modes here. It uses
// PortletWindow information to store the changes and the window is
// not current at this point.
case PortalEvent.EDIT_BUTTON_EVENT:
newPortletMode = PortletMode.EDIT;
break;
case PortalEvent.HELP_BUTTON_EVENT:
newPortletMode = PortletMode.HELP;
break;
case PortalEvent.ABOUT_BUTTON_EVENT:
// We might want to consider a custom ABOUT mode here
break;
//Detect portlet window state changes
case PortalEvent.MINIMIZE_EVENT:
newWindowState = WindowState.MINIMIZED;
break;
case PortalEvent.MAXIMIZE_EVENT:
newWindowState = WindowState.NORMAL;
break;
case PortalEvent.DETACH_BUTTON_EVENT:
newWindowState = WindowState.MAXIMIZED;
break;
//Detect end of session or portlet removed from layout
case PortalEvent.UNSUBSCRIBE:
//User is removing this portlet from their layout, remove all
//the preferences they have stored for it.
PortletEntityImpl pe = (PortletEntityImpl)portletWindow.getPortletEntity();
try {
pe.removePreferences();
}
catch (Exception e) {
log.error(e,e);
}
case PortalEvent.SESSION_DONE:
// For both SESSION_DONE and UNSUBSCRIBE, we might want to
// release resources here if we need to
PortletWindowImpl windowImpl = (PortletWindowImpl)portletWindow;
try {
PortletStateManager.clearState(windowImpl);
}
catch (IllegalStateException ise) {
//access the session if it has already been destroyed.
}
break;
default:
break;
}
} finally {
PortletContainerServices.release();
}
}
/**
* Sets the channel static data.
* @param sd the channel static data
* @throws org.jasig.portal.PortalException
*/
public void setStaticData(ChannelStaticData sd) throws PortalException {
staticData = sd;
try {
// Register this portlet's channel subscribe ID in the JNDI context
// this is probably not necessary since afaik nothing other than this
// portlet is reading this List. -andrew petro
List portletIds = (List)sd.getJNDIContext().lookup("/portlet-ids");
portletIds.add(sd.getChannelSubscribeId());
} catch (Exception e) {
throw new PortalException("Error accessing /portlet-ids JNDI context.", e);
}
}
/**
* Sets the channel runtime data.
* @param rd the channel runtime data
* @throws org.jasig.portal.PortalException
*/
public void setRuntimeData(ChannelRuntimeData rd) throws PortalException {
runtimeData =rd;
if (!this.portletWindowInitialized) {
this.initPortletWindow();
}
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletWindowImpl portletWindowimp = (PortletWindowImpl)portletWindow;
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
// Put the current runtime data and wrapped request into the portlet window
portletWindowimp.setChannelRuntimeData(rd);
portletWindowimp.setHttpServletRequest(wrappedRequest);
// Get the portlet url manager which will analyze the request parameters
DynamicInformationProvider dip = InformationProviderAccess.getDynamicProvider(wrappedRequest);
PortletStateManager psm = ((DynamicInformationProviderImpl)dip).getPortletStateManager(portletWindow);
PortletActionProvider pap = dip.getPortletActionProvider(portletWindow);
//If portlet is rendering as root, change mode to maximized, otherwise minimized
if (!psm.isAction() && rd.isRenderingAsRoot()) {
if (WindowState.MINIMIZED.equals(newWindowState)) {
pap.changePortletWindowState(WindowState.MINIMIZED);
}
else {
pap.changePortletWindowState(WindowState.MAXIMIZED);
}
} else if (newWindowState != null) {
pap.changePortletWindowState(newWindowState);
}
else if (!psm.isAction()) {
pap.changePortletWindowState(WindowState.NORMAL);
}
newWindowState =null;
//Check for a portlet mode change
if (newPortletMode != null) {
pap.changePortletMode(newPortletMode);
PortletStateManager.setMode(portletWindow, newPortletMode);
}
newPortletMode = null;
// Process action if this is the targeted channel and the URL is an action URL
if (rd.isTargeted() && psm.isAction()) {
//Create a sink to throw out and output (portlets can't output content during an action)
PrintWriter pw = new PrintWriter(new NullOutputStream());
HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), pw);
try {
//See if a WindowState change was requested for an ActionURL
final String newWindowStateName = wrappedRequest.getParameter(PortletStateManager.UP_WINDOW_STATE);
if (newWindowStateName != null) {
pap.changePortletWindowState(new WindowState(newWindowStateName));
}
HttpServletRequest wrappedPortletRequest = new PortletParameterRequestWrapper(wrappedRequest);
portletContainer.processPortletAction(portletWindow, wrappedPortletRequest, wrappedResponse);
} catch (Exception e) {
throw new PortalException(e);
}
}
} finally {
PortletContainerServices.release();
}
}
/**
* Sets the portal control structures.
* @param pcs the portal control structures
* @throws org.jasig.portal.PortalException
*/
public void setPortalControlStructures(PortalControlStructures pcs1) throws PortalException {
this.pcs = pcs1;
}
/**
* Output channel content to the portal as raw characters
* @param pw a print writer
*/
public void renderCharacters(PrintWriter pw) throws PortalException {
if (!portletWindowInitialized) {
initPortletWindow();
}
try {
String markupString = getMarkup();
pw.print(markupString);
} catch (Exception e) {
throw new PortalException(e);
}
}
/**
* Output channel content to the portal. This version of the
* render method is normally not used since this is a "character channel".
* @param out a sax document handler
*/
public void renderXML(ContentHandler out) throws PortalException {
if (!portletWindowInitialized) {
initPortletWindow();
}
try {
String markupString = getMarkup();
// Output content. This assumes that markupString
// is well-formed. Consider changing to a character
// channel when it becomes available. Until we use the
// character channel, these <div> tags will be necessary.
SAXHelper.outputContent(out, "<div>" + markupString + "</div>");
} catch (Exception e) {
throw new PortalException(e);
}
}
/**
* This is where we do the real work of getting the markup.
* This is called from both renderXML() and renderCharacters().
* @return markup representing channel content
*/
protected synchronized String getMarkup() throws PortalException {
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
final StringWriter sw = new StringWriter();
HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), new PrintWriter(sw));
//Use the parameters from the last request so the portlet maintains it's state
final ChannelRuntimeData rd = runtimeData;
if (!rd.isTargeted() && requestParams != null) {
wrappedRequest = new DummyParameterRequestWrapper(wrappedRequest, requestParams);
}
//Hide the request parameters if this portlet isn't targeted
else {
wrappedRequest = new PortletParameterRequestWrapper(wrappedRequest);
requestParams = wrappedRequest.getParameterMap();
}
portletContainer.renderPortlet(portletWindow, wrappedRequest, wrappedResponse);
//Support for the portlet modifying it's cache timeout
final Map properties = PropertyManager.getRequestProperties(portletWindow, wrappedRequest);
final String[] exprCacheTimeStr = (String[])properties.get(RenderResponse.EXPIRATION_CACHE);
if (exprCacheTimeStr != null && exprCacheTimeStr.length > 0) {
try {
Integer.parseInt(exprCacheTimeStr[0]); //Check for valid number
expirationCache = exprCacheTimeStr[0];
}
catch (NumberFormatException nfe) {
log.error("The specified RenderResponse.EXPIRATION_CACHE value of (" + exprCacheTimeStr + ") is not a number.", nfe);
throw nfe;
}
}
//Keep track of the last time the portlet was successfully rendered
lastRenderTime = System.currentTimeMillis();
//Return the content
return sw.toString();
} catch (Throwable t) {
log.error(t, t);
throw new PortalException(t);
} finally {
PortletContainerServices.release();
}
}
/**
* Generates a channel cache key. The key scope is set to be system-wide
* when the channel is anonymously accessed, otherwise it is set to be
* instance-wide. The caching implementation here is simple and may not
* handle all cases. It may also violate the Portlet Specification so
* this obviously needs further discussion.
* @return the channel cache key
*/
public ChannelCacheKey generateKey() {
ChannelCacheKey cck = null;
// Anonymously accessed pages can be cached system-wide
if(staticData.getPerson().isGuest()) {
cck = systemCacheKey;
} else {
cck = instanceCacheKey;
}
return cck;
}
/**
* Determines whether the cached content for this channel is still valid.
* <p>
* Return <code>true</code> when:<br>
* <ol>
* <li>We have not just received an event</li>
* <li>No runtime parameters are sent to the channel</li>
* <li>The focus hasn't switched.</li>
* </ol>
* Otherwise, return <code>false</code>.
* <p>
* In other words, cache the content in all cases <b>except</b>
* for when a user clicks a channel button, a link or form button within the channel,
* or the <i>focus</i> or <i>unfocus</i> button.
* @param validity the validity object
* @return <code>true</code> if the cache is still valid, otherwise <code>false</code>
*/
public boolean isCacheValid(Object validity) {
PortletEntity pe = portletWindow.getPortletEntity();
PortletDefinition pd = pe.getPortletDefinition();
//Expiration based caching support for the portlet.
String exprCacheTimeStr = pd.getExpirationCache();
try {
if (expirationCache != null)
exprCacheTimeStr = expirationCache;
int exprCacheTime = Integer.parseInt(exprCacheTimeStr);
if (exprCacheTime == 0) {
return false;
}
else if (exprCacheTime > 0) {
if ((lastRenderTime + (exprCacheTime * 1000)) < System.currentTimeMillis())
return false;
}
}
catch (Exception e) {
if (log.isWarnEnabled()) {
String portletId = staticData.getParameter(portletDefinitionIdParamName);
log.warn("Error parsing portlet expiration time (" + exprCacheTimeStr + ") for portlet (" + portletId + ").", e);
}
}
// Determine if the channel focus has changed
boolean previouslyFocused = focused;
focused = runtimeData.isRenderingAsRoot();
boolean focusHasSwitched = focused != previouslyFocused;
// Dirty cache only when we receive an event, one or more request params, or a change in focus
boolean cacheValid = !(receivedEvent || runtimeData.isTargeted() || focusHasSwitched);
receivedEvent = false;
return cacheValid;
}
/**
* Retrieves the users password by iterating over
* the user's security contexts and returning the first
* available cached password.
*
* @param baseContext The security context to start looking for a password from.
* @return the users password
*/
private String getPassword(ISecurityContext baseContext) {
String password = null;
IOpaqueCredentials oc = baseContext.getOpaqueCredentials();
if (oc instanceof NotSoOpaqueCredentials) {
NotSoOpaqueCredentials nsoc = (NotSoOpaqueCredentials)oc;
password = nsoc.getCredentials();
}
// If still no password, loop through subcontexts to find cached credentials
Enumeration en = baseContext.getSubContexts();
while (password == null && en.hasMoreElements()) {
ISecurityContext subContext = (ISecurityContext)en.nextElement();
password = this.getPassword(subContext);
}
return password;
}
/**
* Adds the appropriate information to the request attributes of the portlet.
*
* This is an extension point. You can override this method to set other
* request attributes.
*
* @param request The request to add the attributes to
*/
protected void setupRequestAttributes(final HttpServletRequest request) {
//Add the user information map
request.setAttribute(PortletRequest.USER_INFO, userInfo);
}
/**
* Get the Map of portlet user attribute names to portlet user attribute values.
*
* This is an extension point. You can extend CPortletAdapter and override this
* method to implement the particular user attribute Map creation strategy that
* you need to implement. Such strategies might rename uPortal
* user attributes to names that your particular portlet knows how to consume,
* transform the user attribute values to forms expected by your portlet, add
* additional attributes, convey a CAS proxy ticket or other security token.
* This extension point is the way to accomodate the particular user attributes
* particular portlets require.
*
* The default implementation of this method includes in the userInfo Map
* those uPortal IPerson attributes matching entries in the list of attributes the
* Portlet declared it wanted. Additionally, the default implementation copies
* the cached user password if the Portlet declares it wants the user attribute
* 'password'.
*
* @param staticData data associated with the particular instance of the portlet window for the particular
* user session
* @param userAttributes the user attributes requested by the Portlet
* @return a Map from portlet user attribute names to portlet user attribute values.
*/
protected Map getUserInfo(ChannelStaticData staticData, UserAttributeListImpl userAttributes) {
final String PASSWORD_ATTR = "password";
Map userInfo = new HashMap();
IPerson person = staticData.getPerson();
if (person.getSecurityContext().isAuthenticated()) {
// for each attribute the Portlet requested
for (Iterator iter = userAttributes.iterator(); iter.hasNext(); ) {
UserAttributeImpl userAttribute = (UserAttributeImpl)iter.next();
String attName = userAttribute.getName();
String attValue = (String)person.getAttribute(attName);
if ((attValue == null || attValue.equals("")) && attName.equals(PASSWORD_ATTR)) {
attValue = getPassword(person.getSecurityContext());
}
userInfo.put(attName, attValue);
}
}
return userInfo;
}
}
|
package org.jfree.chart.urls;
import java.io.Serializable;
import org.jfree.data.category.CategoryDataset;
import org.jfree.util.ObjectUtilities;
/**
* A URL generator that can be assigned to a
* {@link org.jfree.chart.renderer.category.CategoryItemRenderer}.
*/
public class StandardCategoryURLGenerator implements CategoryURLGenerator,
Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 2276668053074881909L;
/** Prefix to the URL */
private String prefix = "index.html";
/** Series parameter name to go in each URL */
private String seriesParameterName = "series";
/** Category parameter name to go in each URL */
private String categoryParameterName = "category";
/**
* Creates a new generator with default settings.
*/
public StandardCategoryURLGenerator() {
super();
}
/**
* Constructor that overrides default prefix to the URL.
*
* @param prefix the prefix to the URL (<code>null</code> not permitted).
*/
public StandardCategoryURLGenerator(String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("Null 'prefix' argument.");
}
this.prefix = prefix;
}
/**
* Constructor that overrides all the defaults.
*
* @param prefix the prefix to the URL (<code>null</code> not permitted).
* @param seriesParameterName the name of the series parameter to go in
* each URL (<code>null</code> not permitted).
* @param categoryParameterName the name of the category parameter to go in
* each URL (<code>null</code> not permitted).
*/
public StandardCategoryURLGenerator(String prefix,
String seriesParameterName,
String categoryParameterName) {
if (prefix == null) {
throw new IllegalArgumentException("Null 'prefix' argument.");
}
if (seriesParameterName == null) {
throw new IllegalArgumentException(
"Null 'seriesParameterName' argument.");
}
if (categoryParameterName == null) {
throw new IllegalArgumentException(
"Null 'categoryParameterName' argument.");
}
this.prefix = prefix;
this.seriesParameterName = seriesParameterName;
this.categoryParameterName = categoryParameterName;
}
/**
* Generates a URL for a particular item within a series.
*
* @param dataset the dataset.
* @param series the series index (zero-based).
* @param category the category index (zero-based).
*
* @return The generated URL.
*/
public String generateURL(CategoryDataset dataset, int series,
int category) {
String url = this.prefix;
Comparable seriesKey = dataset.getRowKey(series);
Comparable categoryKey = dataset.getColumnKey(category);
boolean firstParameter = url.indexOf("?") == -1;
url += firstParameter ? "?" : "&";
url += this.seriesParameterName + "=" + URLUtilities.encode(
seriesKey.toString(), "UTF-8");
url += "&" + this.categoryParameterName + "="
+ URLUtilities.encode(categoryKey.toString(), "UTF-8");
return url;
}
/**
* Returns an independent copy of the URL generator.
*
* @return A clone.
*
* @throws CloneNotSupportedException not thrown by this class, but
* subclasses (if any) might.
*/
public Object clone() throws CloneNotSupportedException {
// all attributes are immutable, so we can just return the super.clone()
// FIXME: in fact, the generator itself is immutable, so cloning is
// not necessary
return super.clone();
}
/**
* Tests the generator for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StandardCategoryURLGenerator)) {
return false;
}
StandardCategoryURLGenerator that = (StandardCategoryURLGenerator) obj;
if (!ObjectUtilities.equal(this.prefix, that.prefix)) {
return false;
}
if (!ObjectUtilities.equal(this.seriesParameterName,
that.seriesParameterName)) {
return false;
}
if (!ObjectUtilities.equal(this.categoryParameterName,
that.categoryParameterName)) {
return false;
}
return true;
}
/**
* Returns a hash code.
*
* @return A hash code.
*/
public int hashCode() {
int result;
result = (this.prefix != null ? this.prefix.hashCode() : 0);
result = 29 * result
+ (this.seriesParameterName != null
? this.seriesParameterName.hashCode() : 0);
result = 29 * result
+ (this.categoryParameterName != null
? this.categoryParameterName.hashCode() : 0);
return result;
}
}
|
package com.cibuddy.hid.impl;
import com.codeminders.hidapi.HIDManager;
import java.util.Timer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* "Mirko Jahn" <mirkojahn@gmail.com>
* @version 1.0
*/
public class Activator implements BundleActivator {
private static BundleContext bctx;
private HIDManagerImpl manager;
private Timer usbDeviceUpdateTimer;
private final long EXECUTION_DELAY = 10*1000; // 10 seconds
private final long UPDATE_INTERVAL = 5*1000; // 5 seconds
private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
@Override
public void start(BundleContext bc) throws Exception {
bctx = bc;
try {
LOG.info("Loading native HID libraries. This can't be undone, until the JVM got bounced.");
System.loadLibrary("hidapi-jni");
LOG.debug("Done loading native libraries. Don't even think about calling update on this bundle with ID: "+bc.getBundle().getBundleId());
} catch (Throwable e) {
LOG.warn("Huston we have a problem. Loading of the hid driver failed.",e);
System.out.println("Huston we have a problem. Loading of the hid driver failed: "+e.getMessage());
e.printStackTrace(System.out);
throw new Exception("Start Problem with bundle "+bc.getBundle().getBundleId(),e);
}
manager = new HIDManagerImpl();
// use the method that is not throwing any exceptions here!
manager.run();
usbDeviceUpdateTimer = new Timer();
usbDeviceUpdateTimer.schedule(manager, EXECUTION_DELAY, UPDATE_INTERVAL);
LOG.info("Finished exposing HID devices as services.");
}
@Override
public void stop(BundleContext bc) throws Exception {
LOG.info("Do not try to reinstall this Bundle! You will fail horrobly! BundleId: "+bc.getBundle().getBundleId());
if(usbDeviceUpdateTimer!=null){
usbDeviceUpdateTimer.cancel();
usbDeviceUpdateTimer = null;
}
if(manager != null){
// can't clean-up singleton... setting to null at least.
manager.shutdown();
manager = null;
}
}
protected static BundleContext getContext(){
return bctx;
}
}
|
package com.malhartech.stream;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.io.Output;
import com.malhartech.api.Sink;
import com.malhartech.bufferserver.packet.*;
import com.malhartech.engine.Stream;
import com.malhartech.engine.StreamContext;
import com.malhartech.netlet.DefaultEventLoop;
import com.malhartech.netlet.EventLoop;
import com.malhartech.netlet.Listener;
import com.malhartech.netlet.Listener.ClientListener;
import com.malhartech.tuple.Tuple;
import java.io.IOException;
import static java.lang.Thread.sleep;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public class FastPublisher extends Kryo implements ClientListener, Stream
{
public static final int BUFFER_CAPACITY = 8 * 1024;
private SelectionKey key;
private EventLoop eventloop;
private int count;
private long spinMillis;
protected final int lastIndex;
protected final ByteBuffer[] readBuffers;
protected ByteBuffer readBuffer;
protected volatile int readIndex;
private final ByteBuffer[] writeBuffers;
private ByteBuffer writeBuffer;
private int writeIndex;
private final String id;
private boolean write = true;
public FastPublisher(String id, int streamingWindowThroughput)
{
this.id = id;
int countOf8kBuffers = streamingWindowThroughput / (8 * 1024);
if (streamingWindowThroughput % (8 * 1024) != 0) {
countOf8kBuffers++;
}
if (countOf8kBuffers < 2) {
countOf8kBuffers = 2;
}
writeBuffers = new ByteBuffer[countOf8kBuffers];
readBuffers = new ByteBuffer[countOf8kBuffers];
for (int i = countOf8kBuffers; i
writeBuffers[i] = ByteBuffer.allocateDirect(BUFFER_CAPACITY);
writeBuffers[i].order(ByteOrder.LITTLE_ENDIAN);
readBuffers[i] = writeBuffers[i].asReadOnlyBuffer();
readBuffers[i].limit(0);
}
writeBuffer = writeBuffers[0];
readBuffer = readBuffers[0];
lastIndex = countOf8kBuffers - 1;
}
@Override
public void read() throws IOException
{
SocketChannel channel = (SocketChannel)key.channel();
int read;
if ((read = channel.read(ByteBuffer.allocate(1))) > 0) {
throw new RuntimeException("Publisher " + this + " is not supposed to receive any data");
}
else if (read == -1) {
try {
channel.close();
}
finally {
unregistered(key);
key.attach(Listener.NOOP_CLIENT_LISTENER);
}
}
else {
logger.debug("{} read 0 bytes", this);
}
}
@Override
@SuppressWarnings({"SyncOnNonFinal"})
public void write() throws IOException
{
SocketChannel sc = (SocketChannel)key.channel();
do {
synchronized (readBuffer) {
sc.write(readBuffer);
if (readBuffer.position() < readBuffer.capacity()) {
if (!readBuffer.hasRemaining()) {
synchronized (readBuffers) {
if (write) {
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
write = false;
}
}
}
return;
}
readBuffer.limit(0);
if (readIndex == lastIndex) {
readIndex = 0;
}
else {
readIndex++;
}
}
readBuffer = readBuffers[readIndex];
}
while (true);
}
@Override
public void handleException(Exception cce, DefaultEventLoop el)
{
logger.debug("Generically handling", cce);
}
@Override
public void registered(SelectionKey key)
{
this.key = key;
}
@Override
public void unregistered(SelectionKey key)
{
// do something so that no more data can be written to this channel. But the data already written will be sent.
}
@Override
public boolean isMultiSinkCapable()
{
return false;
}
@Override
public void setSink(String id, Sink<Object> sink)
{
throw new UnsupportedOperationException("setSink(id, sink) not supported on this stream.");
}
@Override
public void setup(StreamContext context)
{
spinMillis = 5; // somehow get it context.attrValue(PortContext.SPIN_MILLIS, 5);
}
@Override
public void teardown()
{
}
@Override
public void activate(StreamContext context)
{
InetSocketAddress address = context.getBufferServerAddress();
eventloop = context.attr(StreamContext.EVENT_LOOP).get();
eventloop.connect(address.isUnresolved() ? new InetSocketAddress(address.getHostName(), address.getPort()) : address, this);
logger.debug("registering publisher: {} {} windowId={} server={}", new Object[] {context.getSourceId(), context.getId(), context.getFinishedWindowId(), context.getBufferServerAddress()});
byte[] serializedRequest = PublishRequestTuple.getSerializedRequest(com.malhartech.bufferserver.packet.Tuple.FAST_VERSION, id, context.getFinishedWindowId());
assert (serializedRequest.length < 128);
writeBuffers[0].put((byte)serializedRequest.length);
writeBuffers[0].put(serializedRequest);
synchronized (readBuffers) {
readBuffers[0].limit(writeBuffers[0].position());
if (!write) {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
write = true;
}
}
}
@Override
public void deactivate()
{
eventloop.disconnect(this);
}
long item;
@Override
@SuppressWarnings("SleepWhileInLoop")
public void put(Object tuple)
{
if (tuple instanceof Tuple) {
final Tuple t = (Tuple)tuple;
byte[] array;
switch (t.getType()) {
case CHECKPOINT:
array = WindowIdTuple.getSerializedTuple((int)t.getWindowId());
array[0] = MessageType.CHECKPOINT_VALUE;
break;
case BEGIN_WINDOW:
array = BeginWindowTuple.getSerializedTuple((int)t.getWindowId());
break;
case END_WINDOW:
array = EndWindowTuple.getSerializedTuple((int)t.getWindowId());
break;
case END_STREAM:
array = EndStreamTuple.getSerializedTuple((int)t.getWindowId());
break;
case RESET_WINDOW:
com.malhartech.tuple.ResetWindowTuple rwt = (com.malhartech.tuple.ResetWindowTuple)t;
array = ResetWindowTuple.getSerializedTuple(rwt.getBaseSeconds(), rwt.getIntervalMillis());
break;
default:
throw new UnsupportedOperationException("this data type is not handled in the stream");
}
int size = array.length;
if (writeBuffer.hasRemaining()) {
logger.debug("putting control tuple {} of size {} at {}", new Object[] {item++, size, writeBuffer.position()});
writeBuffer.put((byte)size);
if (writeBuffer.hasRemaining()) {
writeBuffer.put((byte)(size >> 8));
}
else {
synchronized (readBuffers) {
readBuffers[writeIndex].limit(BUFFER_CAPACITY);
}
advanceWriteBuffer();
writeBuffer.put((byte)(size >> 8));
}
}
else {
synchronized (readBuffers) {
readBuffers[writeIndex].limit(BUFFER_CAPACITY);
}
advanceWriteBuffer();
logger.debug("putting control tuple {} of size {} at {}", new Object[] {item++, size, writeBuffer.position()});
writeBuffer.put((byte)size);
writeBuffer.put((byte)(size >> 8));
}
int remaining = writeBuffer.remaining();
if (remaining < size) {
int offset = 0;
do {
writeBuffer.put(array, offset, remaining);
offset += remaining;
size -= remaining;
synchronized (readBuffers) {
readBuffers[writeIndex].limit(BUFFER_CAPACITY);
}
advanceWriteBuffer();
remaining = writeBuffer.remaining();
if (size <= remaining) {
writeBuffer.put(array, offset, size);
break;
}
}
while (true);
}
else {
writeBuffer.put(array);
}
synchronized (readBuffers) {
readBuffers[writeIndex].limit(writeBuffer.position());
}
}
else {
count++;
int hashcode = tuple.hashCode();
int wi = writeIndex;
int position = writeBuffer.position();
logger.debug("putting tuple {} of at {}/{}", new Object[] {item++, writeIndex, writeBuffer.position()});
int newPosition = position + 2 /* for short size */ + 1 /* for data type */ + 4 /* for partition */;
if (newPosition > BUFFER_CAPACITY) {
writeBuffer.position(BUFFER_CAPACITY);
advanceWriteBuffer();
writeBuffer.position(newPosition - BUFFER_CAPACITY);
}
else {
writeBuffer.position(newPosition);
}
writeClassAndObject(output, tuple);
int size;
if (wi == writeIndex) {
size = writeBuffer.position() - position - 2 /* for short size */;
assert (size <= Short.MAX_VALUE);
writeBuffer.put(position++, (byte)size);
writeBuffer.put(position++, (byte)(size >> 8));
writeBuffer.put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffer.put(position++, (byte)hashcode);
writeBuffer.put(position++, (byte)(hashcode >> 8));
writeBuffer.put(position++, (byte)(hashcode >> 16));
writeBuffer.put(position, (byte)(hashcode >> 24));
synchronized (readBuffers[wi]) {
readBuffers[wi].limit(writeBuffer.position());
}
}
else {
size = BUFFER_CAPACITY - position - 2 + writeBuffer.position();
int index = writeIndex;
synchronized (readBuffers[index]) {
readBuffers[index].position(0);
readBuffers[index].limit(writeBuffer.position());
}
do {
if (index == 0) {
index = lastIndex;
}
else {
index
}
if (index == wi) {
break;
}
synchronized (readBuffers[index]) {
readBuffers[index].position(0);
readBuffers[index].limit(BUFFER_CAPACITY);
}
size += BUFFER_CAPACITY;
}
while (true);
assert (size <= Short.MAX_VALUE);
index = wi;
switch (position) {
case BUFFER_CAPACITY:
position = 0;
if (wi == lastIndex) {
wi = 0;
}
else {
wi++;
}
writeBuffers[wi].put(position++, (byte)size);
writeBuffers[wi].put(position++, (byte)(size >> 8));
writeBuffers[wi].put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffers[wi].put(position++, (byte)hashcode);
writeBuffers[wi].put(position++, (byte)(hashcode >> 8));
writeBuffers[wi].put(position++, (byte)(hashcode >> 16));
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
case BUFFER_CAPACITY - 1:
writeBuffers[wi].put(position, (byte)size);
if (wi == lastIndex) {
wi = 0;
}
else {
wi++;
}
position = 0;
writeBuffers[wi].put(position++, (byte)(size >> 8));
writeBuffers[wi].put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffers[wi].put(position++, (byte)hashcode);
writeBuffers[wi].put(position++, (byte)(hashcode >> 8));
writeBuffers[wi].put(position++, (byte)(hashcode >> 16));
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
case BUFFER_CAPACITY - 2:
writeBuffers[wi].put(position++, (byte)size);
writeBuffers[wi].put(position, (byte)(size >> 8));
if (wi == lastIndex) {
wi = 0;
}
else {
wi++;
}
position = 0;
writeBuffers[wi].put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffers[wi].put(position++, (byte)hashcode);
writeBuffers[wi].put(position++, (byte)(hashcode >> 8));
writeBuffers[wi].put(position++, (byte)(hashcode >> 16));
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
case BUFFER_CAPACITY - 3:
writeBuffers[wi].put(position++, (byte)size);
writeBuffers[wi].put(position++, (byte)(size >> 8));
writeBuffers[wi].put(position, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
if (wi == lastIndex) {
wi = 0;
}
else {
wi++;
}
position = 0;
writeBuffers[wi].put(position++, (byte)hashcode);
writeBuffers[wi].put(position++, (byte)(hashcode >> 8));
writeBuffers[wi].put(position++, (byte)(hashcode >> 16));
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
case BUFFER_CAPACITY - 4:
writeBuffers[wi].put(position++, (byte)size);
writeBuffers[wi].put(position++, (byte)(size >> 8));
writeBuffers[wi].put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffers[wi].put(position, (byte)hashcode);
if (wi == lastIndex) {
wi = 0;
}
else {
wi++;
}
position = 0;
writeBuffers[wi].put(position++, (byte)(hashcode >> 8));
writeBuffers[wi].put(position++, (byte)(hashcode >> 16));
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
case BUFFER_CAPACITY - 5:
writeBuffers[wi].put(position++, (byte)size);
writeBuffers[wi].put(position++, (byte)(size >> 8));
writeBuffers[wi].put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffers[wi].put(position++, (byte)hashcode);
writeBuffers[wi].put(position, (byte)(hashcode >> 8));
if (wi == lastIndex) {
wi = 0;
}
else {
wi++;
}
position = 0;
writeBuffers[wi].put(position++, (byte)(hashcode >> 16));
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
case BUFFER_CAPACITY - 6:
writeBuffers[wi].put(position++, (byte)size);
writeBuffers[wi].put(position++, (byte)(size >> 8));
writeBuffers[wi].put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffers[wi].put(position++, (byte)hashcode);
writeBuffers[wi].put(position++, (byte)(hashcode >> 8));
writeBuffers[wi].put(position, (byte)(hashcode >> 16));
if (wi == lastIndex) {
wi = 0;
}
else {
wi++;
}
position = 0;
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
default:
writeBuffers[wi].put(position++, (byte)size);
writeBuffers[wi].put(position++, (byte)(size >> 8));
writeBuffers[wi].put(position++, com.malhartech.bufferserver.packet.MessageType.PAYLOAD_VALUE);
writeBuffers[wi].put(position++, (byte)hashcode);
writeBuffers[wi].put(position++, (byte)(hashcode >> 8));
writeBuffers[wi].put(position++, (byte)(hashcode >> 16));
writeBuffers[wi].put(position, (byte)(hashcode >> 24));
break;
}
synchronized (readBuffers[index]) {
readBuffers[index].limit(BUFFER_CAPACITY);
}
}
}
if (!write) {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
write = true;
}
}
@SuppressWarnings("SleepWhileInLoop")
public void advanceWriteBuffer()
{
if (writeIndex == lastIndex) {
writeIndex = 0;
}
else {
writeIndex++;
}
try {
while (writeIndex == readIndex) {
sleep(spinMillis);
}
writeBuffer = writeBuffers[writeIndex];
writeBuffer.clear();
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
@Override
public int getCount(boolean reset)
{
if (reset) {
try {
return count;
}
finally {
count = 0;
}
}
return count;
}
private final Output output = new Output()
{
@Override
public void write(int value) throws KryoException
{
if (!writeBuffer.hasRemaining()) {
advanceWriteBuffer();
}
writeBuffer.put((byte)value);
}
@Override
public void write(byte[] bytes) throws KryoException
{
int remaining = writeBuffer.remaining();
if (bytes.length > remaining) {
writeBuffer.put(bytes, 0, remaining);
advanceWriteBuffer();
write(bytes, remaining, bytes.length - remaining);
}
else {
writeBuffer.put(bytes);
}
}
@Override
public void write(byte[] bytes, int offset, int length) throws KryoException
{
int remaining = writeBuffer.remaining();
while (length > remaining) {
writeBuffer.put(bytes, offset, remaining);
offset += remaining;
length -= remaining;
advanceWriteBuffer();
remaining = writeBuffer.remaining();
}
writeBuffer.put(bytes, offset, length);
}
@Override
public void writeByte(byte value) throws KryoException
{
if (!writeBuffer.hasRemaining()) {
advanceWriteBuffer();
}
writeBuffer.put(value);
}
@Override
public void writeByte(int value) throws KryoException
{
if (!writeBuffer.hasRemaining()) {
advanceWriteBuffer();
}
writeBuffer.put((byte)value);
}
@Override
public void writeBytes(byte[] bytes) throws KryoException
{
write(bytes);
}
@Override
public void writeBytes(byte[] bytes, int offset, int count) throws KryoException
{
write(bytes, offset, count);
}
@Override
public void writeInt(int value) throws KryoException
{
switch (writeBuffer.remaining()) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value >> 24));
writeBuffer.put((byte)(value >> 16));
writeBuffer.put((byte)(value >> 8));
writeBuffer.put((byte)value);
break;
case 1:
writeBuffer.put((byte)(value >> 24));
advanceWriteBuffer();
writeBuffer.put((byte)(value >> 16));
writeBuffer.put((byte)(value >> 8));
writeBuffer.put((byte)value);
break;
case 2:
writeBuffer.put((byte)(value >> 24));
writeBuffer.put((byte)(value >> 16));
advanceWriteBuffer();
writeBuffer.put((byte)(value >> 8));
writeBuffer.put((byte)value);
break;
case 3:
writeBuffer.put((byte)(value >> 24));
writeBuffer.put((byte)(value >> 16));
writeBuffer.put((byte)(value >> 8));
advanceWriteBuffer();
writeBuffer.put((byte)value);
break;
default:
writeBuffer.put((byte)(value >> 24));
writeBuffer.put((byte)(value >> 16));
writeBuffer.put((byte)(value >> 8));
writeBuffer.put((byte)value);
break;
}
}
@Override
public int writeInt(int value, boolean optimizePositive) throws KryoException
{
if (!optimizePositive) {
value = (value << 1) ^ (value >> 31);
}
int remaining = writeBuffer.remaining();
if (value >>> 7 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)value);
break;
default:
writeBuffer.put((byte)value);
break;
}
return 1;
}
if (value >>> 14 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7));
writeBuffer.put((byte)((value & 0x7F) | 0x80));
break;
case 1:
writeBuffer.put((byte)(value >>> 7));
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
break;
default:
writeBuffer.put((byte)(value >>> 7));
writeBuffer.put((byte)((value & 0x7F) | 0x80));
break;
}
return 2;
}
if (value >>> 21 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14));
break;
}
return 3;
}
if (value >>> 28 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
}
return 4;
}
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 4:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 28));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
}
return 5;
}
@Override
public void writeString(String value) throws KryoException
{
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
// Detect ASCII.
boolean ascii = false;
if (charCount > 1 && charCount < 64) {
ascii = true;
for (int i = 0; i < charCount; i++) {
int c = value.charAt(i);
if (c > 127) {
ascii = false;
break;
}
}
}
int charIndex = 0;
if (ascii) {
do {
for (int i = writeBuffer.remaining(); i-- > 0 && charIndex < charCount;) {
writeBuffer.put((byte)(value.charAt(charIndex++)));
}
if (charIndex < charCount) {
advanceWriteBuffer();
}
else {
break;
}
}
while (true);
int pos = writeBuffer.position() - 1;
writeBuffer.put(pos, (byte)(writeBuffer.get(pos) | 0x80));
}
else {
writeUtf8Length(charCount + 1);
do {
int c;
for (int i = writeBuffer.remaining(); i-- > 0 && charIndex < charCount; charIndex++) {
c = value.charAt(charIndex);
if (c > 127) {
writeString_slow(value, charCount, charIndex);
return;
}
writeBuffer.put((byte)c);
}
if (charIndex < charCount) {
advanceWriteBuffer();
}
else {
break;
}
}
while (true);
}
}
@Override
public void writeString(CharSequence value) throws KryoException
{
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
writeUtf8Length(charCount + 1);
int charIndex = 0;
do {
int c;
for (int i = writeBuffer.remaining(); i-- > 0; charIndex++) {
c = value.charAt(charIndex);
if (c > 127) {
writeString_slow(value, charCount, charIndex);
return;
}
writeBuffer.put((byte)c);
}
if (charIndex < charCount) {
advanceWriteBuffer();
}
else {
break;
}
}
while (true);
}
@Override
public void writeAscii(String value) throws KryoException
{
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
int charIndex = 0;
do {
for (int i = writeBuffer.remaining(); i-- > 0 && charIndex < charCount;) {
writeBuffer.put((byte)(value.charAt(charIndex++)));
}
if (charIndex < charCount) {
advanceWriteBuffer();
}
else {
break;
}
}
while (true);
int pos = writeBuffer.position() - 1;
writeBuffer.put(pos, (byte)(writeBuffer.get(pos) | 0x80));
}
@Override
public void writeShort(int value) throws KryoException
{
if (writeBuffer.hasRemaining()) {
writeBuffer.put((byte)(value >>> 8));
if (writeBuffer.hasRemaining()) {
writeBuffer.put((byte)value);
}
else {
advanceWriteBuffer();
writeBuffer.put((byte)value);
}
}
else {
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
}
}
@Override
public void writeLong(long value) throws KryoException
{
switch (writeBuffer.remaining()) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 1:
writeBuffer.put((byte)(value >>> 56));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 2:
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 3:
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 4:
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 5:
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 6:
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 7:
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
advanceWriteBuffer();
writeBuffer.put((byte)value);
break;
default:
writeBuffer.put((byte)(value >>> 56));
writeBuffer.put((byte)(value >>> 48));
writeBuffer.put((byte)(value >>> 40));
writeBuffer.put((byte)(value >>> 32));
writeBuffer.put((byte)(value >>> 24));
writeBuffer.put((byte)(value >>> 16));
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
}
}
@Override
public int writeLong(long value, boolean optimizePositive) throws KryoException
{
if (!optimizePositive) {
value = (value << 1) ^ (value >> 63);
}
int remaining = writeBuffer.remaining();
if (value >>> 7 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)value);
break;
default:
writeBuffer.put((byte)value);
break;
}
return 1;
}
if (value >>> 14 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7));
writeBuffer.put((byte)((value & 0x7F) | 0x80));
break;
case 1:
writeBuffer.put((byte)(value >>> 7));
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
break;
default:
writeBuffer.put((byte)(value >>> 7));
writeBuffer.put((byte)((value & 0x7F) | 0x80));
break;
}
return 2;
}
if (value >>> 21 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14));
break;
}
return 3;
}
if (value >>> 28 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21));
break;
}
return 4;
}
if (value >>> 35 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
case 4:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 28));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28));
break;
}
return 5;
}
if (value >>> 42 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35));
break;
case 4:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35));
break;
case 5:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 35));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35));
break;
}
return 6;
}
if (value >>> 49 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42));
break;
case 4:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42));
break;
case 5:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42));
break;
case 6:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 42));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42));
break;
}
return 7;
}
if (value >>> 56 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
case 4:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
case 5:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
case 6:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
case 7:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 49));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49));
break;
}
return 8;
}
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 1:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 2:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 3:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 4:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 5:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 6:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 7:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
case 8:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 56));
break;
default:
writeBuffer.put((byte)((value & 0x7F) | 0x80));
writeBuffer.put((byte)(value >>> 7 | 0x80));
writeBuffer.put((byte)(value >>> 14 | 0x80));
writeBuffer.put((byte)(value >>> 21 | 0x80));
writeBuffer.put((byte)(value >>> 28 | 0x80));
writeBuffer.put((byte)(value >>> 35 | 0x80));
writeBuffer.put((byte)(value >>> 42 | 0x80));
writeBuffer.put((byte)(value >>> 49 | 0x80));
writeBuffer.put((byte)(value >>> 56));
break;
}
return 9;
}
@Override
public void writeBoolean(boolean value) throws KryoException
{
if (writeBuffer.hasRemaining()) {
writeBuffer.put((byte)(value ? 1 : 0));
}
else {
advanceWriteBuffer();
writeBuffer.put((byte)(value ? 1 : 0));
}
}
@Override
public void writeChar(char value) throws KryoException
{
switch (writeBuffer.remaining()) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
case 1:
writeBuffer.put((byte)(value >>> 8));
advanceWriteBuffer();
writeBuffer.put((byte)value);
break;
default:
writeBuffer.put((byte)(value >>> 8));
writeBuffer.put((byte)value);
break;
}
}
private void writeUtf8Length(int value)
{
int remaining = writeBuffer.remaining();
if (value >>> 6 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value | 0x80));
break;
default:
writeBuffer.put((byte)(value | 0x80));
break;
}
}
else if (value >>> 13 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)(value >>> 6));
break;
case 1:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 6));
break;
default:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)(value >>> 6));
break;
}
}
else if (value >>> 20 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 13));
break;
case 1:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
advanceWriteBuffer();
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 13));
break;
case 2:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 13));
break;
default:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 13));
break;
}
}
else if (value >>> 27 == 0) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 20));
break;
case 1:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
advanceWriteBuffer();
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 20));
break;
case 2:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
advanceWriteBuffer();
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 20));
break;
case 3:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 20));
break;
default:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 20));
break;
}
}
else {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 20) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 27));
break;
case 1:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
advanceWriteBuffer();
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 20) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 27));
break;
case 2:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
advanceWriteBuffer();
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 20) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 27));
break;
case 3:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
advanceWriteBuffer();
writeBuffer.put((byte)((value >>> 20) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 27));
break;
case 4:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 20) | 0x80)); // Set bit 8.
advanceWriteBuffer();
writeBuffer.put((byte)(value >>> 27));
break;
default:
writeBuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
writeBuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
writeBuffer.put((byte)((value >>> 20) | 0x80)); // Set bit 8.
writeBuffer.put((byte)(value >>> 27));
break;
}
}
}
private void writeString_slow(CharSequence value, int charCount, int charIndex)
{
int remaining = writeBuffer.remaining();
for (; charIndex < charCount; charIndex++) {
int c = value.charAt(charIndex);
if (c <= 0x007F) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)c);
remaining = writeBuffer.remaining();
break;
default:
writeBuffer.put((byte)c);
remaining
break;
}
}
else if (c > 0x07FF) {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(0xE0 | c >> 12 & 0x0F));
writeBuffer.put((byte)(0x80 | c >> 6 & 0x3F));
writeBuffer.put((byte)(0x80 | c & 0x3F));
remaining = writeBuffer.remaining();
break;
case 1:
writeBuffer.put((byte)(0xE0 | c >> 12 & 0x0F));
advanceWriteBuffer();
writeBuffer.put((byte)(0x80 | c >> 6 & 0x3F));
writeBuffer.put((byte)(0x80 | c & 0x3F));
remaining = writeBuffer.remaining();
break;
case 2:
writeBuffer.put((byte)(0xE0 | c >> 12 & 0x0F));
writeBuffer.put((byte)(0x80 | c >> 6 & 0x3F));
advanceWriteBuffer();
writeBuffer.put((byte)(0x80 | c & 0x3F));
remaining = writeBuffer.remaining();
break;
default:
writeBuffer.put((byte)(0xE0 | c >> 12 & 0x0F));
writeBuffer.put((byte)(0x80 | c >> 6 & 0x3F));
writeBuffer.put((byte)(0x80 | c & 0x3F));
remaining -= 3;
break;
}
}
else {
switch (remaining) {
case 0:
advanceWriteBuffer();
writeBuffer.put((byte)(0xC0 | c >> 6 & 0x1F));
writeBuffer.put((byte)(0x80 | c & 0x3F));
remaining = writeBuffer.remaining();
break;
case 1:
writeBuffer.put((byte)(0xC0 | c >> 6 & 0x1F));
advanceWriteBuffer();
writeBuffer.put((byte)(0x80 | c & 0x3F));
remaining = writeBuffer.remaining();
break;
default:
writeBuffer.put((byte)(0xC0 | c >> 6 & 0x1F));
writeBuffer.put((byte)(0x80 | c & 0x3F));
remaining -= 2;
break;
}
}
}
}
};
private static final Logger logger = LoggerFactory.getLogger(FastPublisher.class);
@Override
public void connected()
{
write = false;
}
@Override
public void disconnected()
{
write = true;
}
}
|
package com.datatorrent.stram;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.apache.hadoop.yarn.api.records.NodeReport;
import org.apache.hadoop.yarn.api.records.NodeState;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.junit.Test;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.Context.PortContext;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.api.Operator.InputPort;
import com.datatorrent.api.PartitionableOperator.Partition;
import com.datatorrent.api.PartitionableOperator.PartitionKeys;
import com.datatorrent.api.annotation.InputPortFieldAnnotation;
import com.datatorrent.api.DAGContext;
import com.datatorrent.api.DefaultInputPort;
import com.datatorrent.api.PartitionableOperator;
import com.datatorrent.api.StreamCodec;
import com.datatorrent.stram.StramChildAgent.ContainerStartRequest;
import com.datatorrent.stram.engine.GenericTestOperator;
import com.datatorrent.stram.plan.PhysicalPlanTest.PartitioningTestOperator;
import com.datatorrent.stram.plan.PhysicalPlanTest.PartitioningTestStreamCodec;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.physical.PTContainer;
import com.datatorrent.stram.plan.physical.PTOperator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class HostLocalTest {
public static class PartitioningTestOperator extends GenericTestOperator implements PartitionableOperator {
final public transient InputPort<Object> inportWithCodec = new DefaultInputPort<Object>() {
@Override
public Class<? extends StreamCodec<Object>> getStreamCodec() {
return PartitioningTestStreamCodec.class;
}
@Override
final public void process(Object payload) {
}
};
@Override
@SuppressWarnings("unchecked")
public Collection<Partition<?>> definePartitions(Collection<? extends Partition<?>> partitions, int incrementalCapacity) {
List<Partition<?>> newPartitions = new ArrayList<Partition<?>>(incrementalCapacity+1);
Partition<PartitioningTestOperator> templatePartition = (Partition<PartitioningTestOperator>)partitions.iterator().next();
for (int i = 0; i < 1; i++) {
Partition<PartitioningTestOperator> p = templatePartition.getInstance(new PartitioningTestOperator());
p.getAttributes().put(OperatorContext.LOCALITY_HOST, "host1");
newPartitions.add(p);
}
for (int i = 1; i < 1 +incrementalCapacity; i++) {
Partition<PartitioningTestOperator> p = templatePartition.getInstance(new PartitioningTestOperator());
p.getAttributes().put(OperatorContext.LOCALITY_HOST, "host2");
newPartitions.add(p);
}
return newPartitions;
}
}
@Test
public void testParitionLocality() {
LogicalPlan dag = new LogicalPlan();
dag.getAttributes().put(DAGContext.APPLICATION_PATH, new File("target", HostLocalTest.class.getName()).getAbsolutePath());
GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class);
GenericTestOperator partitioned = dag.addOperator("partitioned", PartitioningTestOperator.class);
dag.getMeta(partitioned).getAttributes().put(OperatorContext.INITIAL_PARTITION_COUNT, 2);
dag.getMeta(partitioned).getAttributes().put(OperatorContext.LOCALITY_HOST, "host1");
dag.addStream("o1_outport1", o1.outport1, partitioned.inport1);
StreamingContainerManager scm = new StreamingContainerManager(dag);
ResourceRequestHandler rr = new ResourceRequestHandler();
int containerMem = 1000;
Map<String, NodeReport> nodeReports = Maps.newHashMap();
NodeReport nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host1", 0),
NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem*2, 2), 0, null, 0);
nodeReports.put(nr.getNodeId().getHost(), nr);
nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host2", 0),
NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem*2, 2), 0, null, 0);
nodeReports.put(nr.getNodeId().getHost(), nr);
// set resources
rr.updateNodeReports(Lists.newArrayList(nodeReports.values()));
for (ContainerStartRequest csr : scm.containerStartRequests) {
String host = rr.getHost(csr, containerMem);
csr.container.host = host;
//Assert.assertEquals("Hosts set to host1" , "host1",host);
}
}
@Test
public void testNodeLocal() {
LogicalPlan dag = new LogicalPlan();
dag.getAttributes().put(DAGContext.APPLICATION_PATH, new File("target", HostLocalTest.class.getName()).getAbsolutePath());
GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class);
GenericTestOperator partitioned = dag.addOperator("partitioned", GenericTestOperator.class);
dag.getMeta(partitioned).getAttributes().put(OperatorContext.LOCALITY_HOST, "host1");
dag.addStream("o1_outport1", o1.outport1, partitioned.inport1).setLocality(Locality.NODE_LOCAL);
StreamingContainerManager scm = new StreamingContainerManager(dag);
ResourceRequestHandler rr = new ResourceRequestHandler();
int containerMem = 1000;
Map<String, NodeReport> nodeReports = Maps.newHashMap();
NodeReport nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host1", 0),
NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem*2, 2), 0, null, 0);
nodeReports.put(nr.getNodeId().getHost(), nr);
nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host2", 0),
NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem*2, 2), 0, null, 0);
nodeReports.put(nr.getNodeId().getHost(), nr);
// set resources
rr.updateNodeReports(Lists.newArrayList(nodeReports.values()));
for (ContainerStartRequest csr : scm.containerStartRequests) {
String host = rr.getHost(csr, containerMem);
csr.container.host = host;
Assert.assertEquals("Hosts set to host1" , "host1",host);
}
}
@Test
public void testContainerLocal() {
LogicalPlan dag = new LogicalPlan();
dag.getAttributes().put(DAGContext.APPLICATION_PATH, new File("target", HostLocalTest.class.getName()).getAbsolutePath());
GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class);
dag.getMeta(o1).getAttributes().put(OperatorContext.LOCALITY_HOST, "host2");
GenericTestOperator partitioned = dag.addOperator("partitioned", GenericTestOperator.class);
//dag.getMeta(partitioned).getAttributes().put(OperatorContext.LOCALITY_HOST, "host2");
dag.addStream("o1_outport1", o1.outport1, partitioned.inport1).setLocality(Locality.CONTAINER_LOCAL);
StreamingContainerManager scm = new StreamingContainerManager(dag);
ResourceRequestHandler rr = new ResourceRequestHandler();
int containerMem = 1000;
Map<String, NodeReport> nodeReports = Maps.newHashMap();
NodeReport nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host1", 0),
NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem*2, 2), 0, null, 0);
nodeReports.put(nr.getNodeId().getHost(), nr);
nr = BuilderUtils.newNodeReport(BuilderUtils.newNodeId("host2", 0),
NodeState.RUNNING, "httpAddress", "rackName", BuilderUtils.newResource(0, 0), BuilderUtils.newResource(containerMem*2, 2), 0, null, 0);
nodeReports.put(nr.getNodeId().getHost(), nr);
// set resources
rr.updateNodeReports(Lists.newArrayList(nodeReports.values()));
for (ContainerStartRequest csr : scm.containerStartRequests) {
String host = rr.getHost(csr, containerMem);
csr.container.host = host;
Assert.assertEquals("Hosts set to host2" , "host2",host);
}
}
}
|
package VASSAL.counters;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import javax.swing.text.JTextComponent;
import VASSAL.build.GameModule;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.command.ChangePiece;
import VASSAL.command.Command;
import VASSAL.i18n.PieceI18nData;
import VASSAL.i18n.TranslatablePiece;
import VASSAL.tools.ScrollPane;
import VASSAL.tools.SequenceEncoder;
/**
* A Decorator class that endows a GamePiece with a dialog.
*/
public class PropertySheet extends Decorator implements TranslatablePiece {
public static final String ID = "propertysheet;";
protected String oldState;
// properties
protected String menuName;
protected char launchKey;
protected KeyCommand launch;
protected Color backgroundColor;
protected String m_definition;
protected PropertySheetDialog frame;
protected JButton applyButton;
// Commit type definitions
final static String[] COMMIT_VALUES = {"Every Keystroke", "Apply Button or Enter Key", "Close Window or Enter Key"};
static final int COMMIT_IMMEDIATELY = 0;
static final int COMMIT_ON_APPLY = 1;
static final int COMMIT_ON_CLOSE = 2;
static final int COMMIT_DEFAULT = COMMIT_IMMEDIATELY;
// Field type definitions
static final String[] TYPE_VALUES = {"Text", "Multi-line text", "Label Only", "Tick Marks", "Tick Marks with Max Field", "Tick Marks with Value Field", "Tick Marks with Value & Max", "Spinner"};
static final int TEXT_FIELD = 0;
static final int TEXT_AREA = 1;
static final int LABEL_ONLY = 2;
static final int TICKS = 3;
static final int TICKS_MAX = 4;
static final int TICKS_VAL = 5;
static final int TICKS_VALMAX = 6;
static final int SPINNER = 7;
protected int commitStyle = COMMIT_DEFAULT;
protected boolean isUpdating;
protected String state;
protected Map<String,Object> properties = new HashMap<String,Object>();
protected List<JComponent> m_fields;
static final char TYPE_DELIMITOR = ';';
static final char DEF_DELIMITOR = '~';
static final char STATE_DELIMITOR = '~';
static final char LINE_DELIMINATOR = '|';
static final char VALUE_DELIMINATOR = '/';
class PropertySheetDialog extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public PropertySheetDialog(Frame owner) {
super(owner, false);
}
public void actionPerformed(ActionEvent event) {
if (applyButton != null) {
applyButton.setEnabled(false);
}
updateStateFromFields();
}
}
public PropertySheet() {
// format is propertysheet;menu-name;keystroke;commitStyle;backgroundRed;backgroundGreen;backgroundBlue
this(ID + ";Properties;P;;;;", null);
}
public PropertySheet(String type, GamePiece p) {
mySetType(type);
setInner(p);
}
/** Changes the "type" definition this decoration, which discards all value data and structures.
* Format: definition; name; keystroke
*/
public void mySetType(String s) {
s = s.substring(ID.length());
SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(s, TYPE_DELIMITOR);
m_definition = st.nextToken();
menuName = st.nextToken();
launchKey = st.nextChar('\0');
commitStyle = st.nextInt(COMMIT_DEFAULT);
String red = st.hasMoreTokens() ? st.nextToken() : "";
String green = st.hasMoreTokens() ? st.nextToken() : "";
String blue = st.hasMoreTokens() ? st.nextToken() : "";
backgroundColor = red.equals("") ? null : new Color(atoi(red), atoi(green), atoi(blue));
frame = null;
}
public void draw(java.awt.Graphics g, int x, int y, java.awt.Component obs, double zoom) {
piece.draw(g, x, y, obs, zoom);
}
public String getName() {
return piece.getName();
}
public java.awt.Rectangle boundingBox() {
return piece.boundingBox();
}
public Shape getShape() {
return piece.getShape();
}
public String myGetState() {
return state;
}
public void mySetState(String state) {
this.state = state;
updateFieldsFromState();
}
/** returns string defining the field types */
public String myGetType() {
SequenceEncoder se = new SequenceEncoder(TYPE_DELIMITOR);
String red = backgroundColor == null ? "" : Integer.toString(backgroundColor.getRed());
String green = backgroundColor == null ? "" : Integer.toString(backgroundColor.getGreen());
String blue = backgroundColor == null ? "" : Integer.toString(backgroundColor.getBlue());
String commit = Integer.toString(commitStyle);
se.append(m_definition).append(menuName).append(launchKey).append(commit).
append(red).append(green).append(blue);
return ID + se.getValue();
}
protected KeyCommand[] myGetKeyCommands() {
if (launch == null) {
launch = new KeyCommand(menuName, KeyStroke.getKeyStroke(launchKey, java.awt.event.InputEvent.CTRL_MASK), Decorator.getOutermost(this), this);
}
return new KeyCommand[]{launch};
}
/** parses leading integer from string */
int atoi(String s) {
int value = 0;
if (s != null) {
for (int i = 0; i < s.length() && Character.isDigit(s.charAt(i)); ++i) {
value = value * 10 + s.charAt(i) - '0';
}
}
return value;
}
/** parses trailing integer from string */
int atoiRight(String s) {
int value = 0;
if (s != null) {
int base = 1;
for (int i = s.length() - 1; i >= 0 && Character.isDigit(s.charAt(i)); --i, base *= 10) {
value = value + base * (s.charAt(i) - '0');
}
}
return value;
}
// stores field values
private void updateStateFromFields() {
SequenceEncoder encoder = new SequenceEncoder(STATE_DELIMITOR);
for (Object field : m_fields) {
if (field instanceof JTextComponent) {
encoder.append(((JTextComponent) field).getText()
.replace('\n', LINE_DELIMINATOR));
}
else if (field instanceof TickPanel) {
encoder.append(((TickPanel) field).getValue());
}
else {
encoder.append("Unknown");
}
}
if (encoder.getValue() != null && !encoder.getValue().equals(state)) {
mySetState(encoder.getValue());
GamePiece outer = Decorator.getOutermost(PropertySheet.this);
if (outer.getId() != null) {
GameModule.getGameModule().sendAndLog(
new ChangePiece(outer.getId(), oldState, outer.getState()));
}
}
}
private void updateFieldsFromState() {
isUpdating = true;
properties.clear();
SequenceEncoder.Decoder defDecoder =
new SequenceEncoder.Decoder(m_definition, DEF_DELIMITOR);
SequenceEncoder.Decoder stateDecoder =
new SequenceEncoder.Decoder(state, STATE_DELIMITOR);
for (int iField = 0; defDecoder.hasMoreTokens(); ++iField) {
String name = defDecoder.nextToken();
if (name.length() == 0) {
continue;
}
int type = name.charAt(0) - '0';
name = name.substring(1);
String value = stateDecoder.nextToken("");
switch (type) {
case TICKS:
case TICKS_VAL:
case TICKS_MAX:
case TICKS_VALMAX:
int index = value.indexOf('/');
if (index > 0) {
properties.put(name, value.substring(0, index));
}
else {
properties.put(name, value);
}
break;
default:
properties.put(name, value);
}
value = value.replace(LINE_DELIMINATOR, '\n');
if (frame != null) {
Object field = m_fields.get(iField);
if (field instanceof JTextComponent) {
((JTextComponent) field).setText(value);
}
else if (field instanceof TickPanel) {
((TickPanel) field).updateValue(value);
}
}
}
if (applyButton != null) {
applyButton.setEnabled(false);
}
isUpdating = false;
}
public Command myKeyEvent(KeyStroke stroke) {
myGetKeyCommands();
if (launch.matches(stroke)) {
if (frame == null) {
m_fields = new ArrayList<JComponent>();
VASSAL.build.module.Map map = piece.getMap();
Frame parent = null;
if (map != null && map.getView() != null) {
Container topWin = map.getView().getTopLevelAncestor();
if (topWin instanceof JFrame) {
parent = (Frame) topWin;
}
}
else {
parent = GameModule.getGameModule().getFrame();
}
frame = new PropertySheetDialog(parent);
JPanel pane = new JPanel();
JScrollPane scroll =
new JScrollPane(pane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.add(scroll);
// set up Apply button
if (commitStyle == COMMIT_ON_APPLY) {
applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (applyButton != null) {
applyButton.setEnabled(false);
}
updateStateFromFields();
}
});
applyButton.setMnemonic(java.awt.event.KeyEvent.VK_A); // respond to Alt+A
applyButton.setEnabled(false);
}
// ... enable APPLY button when field changes
DocumentListener changeListener = new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
update(e);
}
public void removeUpdate(DocumentEvent e) {
update(e);
}
public void changedUpdate(DocumentEvent e) {
update(e);
}
public void update(DocumentEvent e) {
if (!isUpdating) {
switch (commitStyle) {
case COMMIT_IMMEDIATELY:
// queue commit operation because it could do something unsafe in a an event update
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateStateFromFields();
}
});
break;
case COMMIT_ON_APPLY:
applyButton.setEnabled(true);
break;
case COMMIT_ON_CLOSE:
break;
default:
throw new RuntimeException();
}
}
}
};
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(1, 3, 1, 3);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
SequenceEncoder.Decoder defDecoder =
new SequenceEncoder.Decoder(m_definition, DEF_DELIMITOR);
SequenceEncoder.Decoder stateDecoder =
new SequenceEncoder.Decoder(state, STATE_DELIMITOR);
while (defDecoder.hasMoreTokens()) {
String code = defDecoder.nextToken();
if (code.length() == 0) {
break;
}
int type = code.charAt(0) - '0';
String name = code.substring(1);
JComponent field;
switch (type) {
case TEXT_FIELD:
field = new JTextField(stateDecoder.nextToken(""));
((JTextComponent) field).getDocument()
.addDocumentListener(changeListener);
((JTextField) field).addActionListener(frame);
m_fields.add(field);
break;
case TEXT_AREA:
field = new JTextArea(
stateDecoder.nextToken("").replace(LINE_DELIMINATOR, '\n'));
((JTextComponent) field).getDocument()
.addDocumentListener(changeListener);
m_fields.add(field);
field = new ScrollPane(field);
break;
case TICKS:
case TICKS_VAL:
case TICKS_MAX:
case TICKS_VALMAX:
field = new TickPanel(stateDecoder.nextToken(""), type);
((TickPanel) field).addDocumentListener(changeListener);
((TickPanel) field).addActionListener(frame);
if (backgroundColor != null)
field.setBackground(backgroundColor);
m_fields.add(field);
break;
case SPINNER:
JSpinner spinner = new JSpinner();
JTextField textField =
((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
textField.setText(stateDecoder.nextToken(""));
textField.getDocument().addDocumentListener(changeListener);
m_fields.add(textField);
field = spinner;
break;
case LABEL_ONLY:
default :
stateDecoder.nextToken("");
field = null;
m_fields.add(field);
break;
}
c.gridwidth = type == TEXT_AREA || type == LABEL_ONLY ? 2 : 1;
if (name != null && !name.equals("")) {
c.gridx = 0;
c.weighty = 0.0;
c.weightx = c.gridwidth == 2 ? 1.0 : 0.0;
pane.add(new JLabel(getTranslation(name)), c);
if (c.gridwidth == 2) {
++c.gridy;
}
}
if (field != null) {
c.weightx = 1.0;
c.weighty = type == TEXT_AREA ? 1.0 : 0.0;
c.gridx = type == TEXT_AREA ? 0 : 1;
pane.add(field, c);
++c.gridy;
}
}
if (backgroundColor != null) {
pane.setBackground(backgroundColor);
}
if (commitStyle == COMMIT_ON_APPLY) {
// setup Close button
JButton closeButton = new JButton("Close");
closeButton.setMnemonic(java.awt.event.KeyEvent.VK_C); // respond to Alt+C // key event cannot be resolved
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
updateStateFromFields();
frame.setVisible(false);
}
});
c.gridwidth = 1;
c.weighty = 0.0;
c.anchor = GridBagConstraints.SOUTHEAST;
c.gridwidth = 2; // use the whole row
c.gridx = 0;
c.weightx = 0.0;
JPanel buttonRow = new JPanel();
buttonRow.add(applyButton);
buttonRow.add(closeButton);
if (backgroundColor != null) {
applyButton.setBackground(backgroundColor);
closeButton.setBackground(backgroundColor);
buttonRow.setBackground(backgroundColor);
}
pane.add(buttonRow, c);
}
// move window
Point p = GameModule.getGameModule().getFrame().getLocation();
if (getMap() != null) {
p = getMap().getView().getLocationOnScreen();
Point p2 = getMap().componentCoordinates(getPosition());
p.translate(p2.x, p2.y);
}
frame.setLocation(p.x, p.y);
// watch for window closing - save state
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
updateStateFromFields();
}
});
frame.pack();
}
// Name window and make it visible
frame.setTitle(getLocalizedName());
oldState = Decorator.getOutermost(this).getState();
frame.setVisible(true);
return null;
}
else {
return null;
}
}
public Object getProperty(Object key) {
Object value = properties.get(key);
if (value == null) {
value = super.getProperty(key);
}
return value;
}
public String getDescription() {
return "Property Sheet";
}
public VASSAL.build.module.documentation.HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("PropertySheet.htm");
}
public PieceEditor getEditor() {
return new Ed(this);
}
/** A generic panel for editing unit traits. Not directly related to "PropertySheets" **/
static class PropertyPanel extends JPanel implements FocusListener {
private static final long serialVersionUID = 1L;
GridBagConstraints c = new GridBagConstraints();
public PropertyPanel() {
super(new GridBagLayout());
c.insets = new Insets(0, 4, 0, 4);
//c.ipadx = 5;
c.anchor = GridBagConstraints.WEST;
}
public JTextField addKeystrokeCtrl(char value) {
++c.gridy;
c.gridx = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
add(new JLabel("Keystroke:"), c);
++c.gridx;
JTextField field = new JTextField(Character.toString(value));
Dimension minSize = field.getMinimumSize();
minSize.width = 30;
field.setMinimumSize(minSize);
field.setPreferredSize(minSize);
add(field, c);
field.setSize(minSize);
return field;
}
public JTextField addStringCtrl(String name, String value) {
++c.gridy;
c.gridx = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
add(new JLabel(name), c);
c.weightx = 1.0;
JTextField field = new JTextField(value);
++c.gridx;
add(field, c);
return field;
}
public JButton addColorCtrl(String name, Color value) {
++c.gridy;
c.gridx = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
add(new JLabel(name), c);
c.weightx = 0.0;
JButton button = new JButton("Default");
if (value != null) {
button.setBackground(value);
button.setText("sample");
}
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
Color value = button.getBackground();
Color newColor = JColorChooser.showDialog(PropertyPanel.this, "Choose background color or CANCEL to use default color scheme", value);
if (newColor != null) {
button.setBackground(newColor);
button.setText("sample");
}
else {
button.setBackground(PropertyPanel.this.getBackground());
button.setText("Default");
}
}
});
++c.gridx;
add(button, c);
return button;
}
public JComboBox addComboBox(String name, String[] values, int initialRow) {
JComboBox comboBox = new JComboBox(values);
comboBox.setEditable(false);
comboBox.setSelectedIndex(initialRow);
addCtrl(name, comboBox);
return comboBox;
}
public void addCtrl(String name, JComponent ctrl) {
++c.gridy;
c.gridx = 0;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
add(new JLabel(name), c);
c.weightx = 0.0;
++c.gridx;
add(ctrl, c);
}
DefaultTableModel tableModel;
String[] defaultValues;
public class SmartTable extends JTable {
private static final long serialVersionUID = 1L;
SmartTable(TableModel m) {
super(m);
setSurrendersFocusOnKeystroke(true);
}
//Prepares the editor by querying the data model for the value and selection state of the cell at row, column. }
public Component prepareEditor(TableCellEditor editor, int row, int column) {
if (row == getRowCount() - 1) {
((DefaultTableModel) getModel()).addRow(Ed.DEFAULT_ROW);
}
Component component = super.prepareEditor(editor, row, column);
if (component instanceof JTextComponent) {
((JTextComponent) component).grabFocus();
((JTextComponent) component).selectAll();
}
return component;
}
}
public JTable addTableCtrl(String name, DefaultTableModel theTableModel, String[] theDefaultValues) {
tableModel = theTableModel;
this.defaultValues = theDefaultValues;
++c.gridy;
c.gridx = 0;
c.weighty = 0.0;
c.weightx = 1.0;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
add(new JLabel(name), c);
++c.gridy;
c.weighty = 1.0;
c.fill = GridBagConstraints.BOTH;
final SmartTable table = new SmartTable(tableModel);
add(new ScrollPane(table), c);
c.gridwidth = 1;
++c.gridy;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
c.gridwidth = 2;
c.weighty = 0.0;
c.weightx = 1.0;
JPanel buttonPanel = new JPanel();
// add button
JButton addButton = new JButton("Insert Row");
buttonPanel.add(addButton);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
table.getCellEditor().stopCellEditing();
}
ListSelectionModel selection = table.getSelectionModel();
int iSelection;
if (selection.isSelectionEmpty()) {
tableModel.addRow(defaultValues);
iSelection = tableModel.getRowCount() - 1;
}
else {
iSelection = selection.getMaxSelectionIndex();
tableModel.insertRow(iSelection, defaultValues);
}
tableModel.fireTableDataChanged(); // BING BING BING
selection.setSelectionInterval(iSelection, iSelection);
table.grabFocus();
table.editCellAt(iSelection, 0);
Component comp = table.getCellEditor().getTableCellEditorComponent(table, null, true, iSelection, 0);
if (comp instanceof JComponent) {
((JComponent) comp).grabFocus();
}
}
});
// delete button
final JButton deleteButton = new JButton("Delete Row");
deleteButton.setEnabled(false);
buttonPanel.add(deleteButton);
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
table.getCellEditor().stopCellEditing();
}
ListSelectionModel selection = table.getSelectionModel();
for (int i = selection.getMaxSelectionIndex(); i >= selection.getMinSelectionIndex(); --i) {
if (selection.isSelectedIndex(i)) {
tableModel.removeRow(i);
}
}
tableModel.fireTableDataChanged(); // BING BING BING
}
});
// Ask to be notified of selection changes.
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
//Ignore extra messages.
if (!event.getValueIsAdjusting()) {
ListSelectionModel lsm = (ListSelectionModel) event.getSource();
deleteButton.setEnabled(!lsm.isSelectionEmpty());
}
}
});
add(buttonPanel, c);
c.anchor = GridBagConstraints.WEST;
c.weightx = 0.0;
return table;
}
public void focusGained(FocusEvent event) {
}
// make sure we save user's changes
public void focusLost(FocusEvent event) {
if (event.getComponent() instanceof JTable) {
JTable table = (JTable) event.getComponent();
if (table.isEditing()) {
table.getCellEditor().stopCellEditing();
}
}
}
}
public PieceI18nData getI18nData() {
ArrayList<String> items = new ArrayList<String>();
SequenceEncoder.Decoder defDecoder = new SequenceEncoder.Decoder(m_definition, DEF_DELIMITOR);
while (defDecoder.hasMoreTokens()) {
String item = defDecoder.nextToken();
items.add(item.substring(1));
}
String[] menuNames = new String[items.size()+1];
String[] descriptions = new String[items.size()+1];
menuNames[0] = menuName;
descriptions[0] = "Property Sheet command";
int j = 1;
for (String s : items) {
menuNames[j] = s;
descriptions[j] = "Property Sheet item " + j;
j++;
}
return getI18nData(menuNames, descriptions);
}
private static class Ed implements PieceEditor {
private PropertyPanel m_panel;
private JTextField menuNameCtrl;
private JTextField keystrokeCtrl;
private JButton colorCtrl;
private JTable propertyTable;
private JComboBox commitCtrl;
static final String[] COLUMN_NAMES = {"Name", "Type"};
static final String[] DEFAULT_ROW = {"*new property*", "Text"};
public Ed(PropertySheet propertySheet) {
m_panel = new PropertyPanel();
menuNameCtrl = m_panel.addStringCtrl("Menu Text:", propertySheet.menuName);
keystrokeCtrl = m_panel.addKeystrokeCtrl(propertySheet.launchKey);
commitCtrl = m_panel.addComboBox("Commit changes on:", COMMIT_VALUES, propertySheet.commitStyle);
colorCtrl = m_panel.addColorCtrl("Background Color:", propertySheet.backgroundColor);
DefaultTableModel dataModel = new DefaultTableModel(getTableData(propertySheet.m_definition), COLUMN_NAMES);
AddCreateRow(dataModel);
propertyTable = m_panel.addTableCtrl("Properties:", dataModel, DEFAULT_ROW);
DefaultCellEditor typePicklist = new DefaultCellEditor(new JComboBox(TYPE_VALUES));
propertyTable.getColumnModel().getColumn(1).setCellEditor(typePicklist);
}
protected void AddCreateRow(DefaultTableModel data) {
data.addRow(DEFAULT_ROW);
}
protected String[][] getTableData(String definition) {
SequenceEncoder.Decoder decoder = new SequenceEncoder.Decoder(definition, DEF_DELIMITOR);
int numRows = !definition.equals("") && decoder.hasMoreTokens() ? 1 : 0;
for (int iDef = -1; (iDef = definition.indexOf(DEF_DELIMITOR, iDef + 1)) >= 0;) {
++numRows;
}
String[][] rows = new String[numRows][2];
for (int iRow = 0; decoder.hasMoreTokens() && iRow < numRows; ++iRow) {
String token = decoder.nextToken();
rows[iRow][0] = token.substring(1);
rows[iRow][1] = TYPE_VALUES[token.charAt(0) - '0'];
}
return rows;
}
public java.awt.Component getControls() {
return m_panel;
}
/** returns the type-definition in the format:
definition, name, keystroke, commit, red, green, blue
*/
public String getType() {
if (propertyTable.isEditing()) {
propertyTable.getCellEditor().stopCellEditing();
}
SequenceEncoder defEncoder = new SequenceEncoder(DEF_DELIMITOR);
// StringBuffer definition = new StringBuffer();
// int numRows = propertyTable.getRowCount();
for (int iRow = 0; iRow < propertyTable.getRowCount(); ++iRow) {
String typeString = (String) propertyTable.getValueAt(iRow, 1);
for (int iType = 0; iType < TYPE_VALUES.length; ++iType) {
if (typeString.matches(TYPE_VALUES[iType]) &&
!DEFAULT_ROW[0].equals(propertyTable.getValueAt(iRow, 0))) {
defEncoder.append(iType + (String) propertyTable.getValueAt(iRow, 0));
break;
}
}
}
SequenceEncoder typeEncoder = new SequenceEncoder(TYPE_DELIMITOR);
// calc color strings
String red, green, blue;
if (colorCtrl.getText().equals("Default")) {
red = "";
green = "";
blue = "";
}
else {
red = Integer.toString(colorCtrl.getBackground().getRed());
green = Integer.toString(colorCtrl.getBackground().getGreen());
blue = Integer.toString(colorCtrl.getBackground().getBlue());
}
String definitionString = defEncoder.getValue();
typeEncoder.append(definitionString == null ? "" : definitionString).
append(menuNameCtrl.getText()).
append(keystrokeCtrl.getText()).
append(Integer.toString(commitCtrl.getSelectedIndex())).
append(red).append(green).append(blue);
return ID + typeEncoder.getValue();
}
/** returns a default value-string for the given definition */
public String getState() {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < propertyTable.getRowCount(); ++i) {
buf.append(STATE_DELIMITOR);
}
return buf.toString();
}
}
class TickPanel extends JPanel implements ActionListener, FocusListener, DocumentListener {
private static final long serialVersionUID = 1L;
private int numTicks;
private int maxTicks;
private int panelType;
private JTextField valField;
private JTextField maxField;
private TickLabel ticks;
private List<ActionListener> actionListeners =
new ArrayList<ActionListener>();
private List<DocumentListener> documentListeners =
new ArrayList<DocumentListener>();
public TickPanel(String value, int type) {
super(new GridBagLayout());
set(value);
panelType = type;
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.ipadx = 1;
c.weightx = 0.0;
c.gridx = 0;
c.gridy = 0;
Dimension minSize;
if (panelType == TICKS_VAL || panelType == TICKS_VALMAX) {
valField = new JTextField(Integer.toString(numTicks));
minSize = valField.getMinimumSize();
minSize.width = 24;
valField.setMinimumSize(minSize);
valField.setPreferredSize(minSize);
valField.addActionListener(this);
valField.addFocusListener(this);
add(valField, c);
++c.gridx;
}
if (panelType == TICKS_MAX || panelType == TICKS_VALMAX) {
maxField = new JTextField(Integer.toString(maxTicks));
minSize = maxField.getMinimumSize();
minSize.width = 24;
maxField.setMinimumSize(minSize);
maxField.setPreferredSize(minSize);
maxField.addActionListener(this);
maxField.addFocusListener(this);
if (panelType == TICKS_VALMAX) {
add(new JLabel("/"), c);
++c.gridx;
}
add(maxField, c);
++c.gridx;
}
ticks = new TickLabel(numTicks, maxTicks, panelType);
ticks.addActionListener(this);
c.weightx = 1.0;
add(ticks, c);
doLayout();
}
public void updateValue(String value) {
set(value);
updateFields();
}
private void set(String value) {
set(atoi(value), atoiRight(value));
}
private boolean set(int num, int max) {
boolean changed = false;
if (numTicks == 0 && maxTicks == 0 && num == 0 && max > 0) {
// num = max; // This causes a bug in which ticks set to zero go to max after save/reload of a game
changed = true;
}
if (numTicks == 0 && maxTicks == 0 && max == 0 && num > 0) {
max = num;
changed = true;
}
numTicks = Math.min(max, num);
maxTicks = max;
return changed;
}
public String getValue() {
commitTextFields();
return Integer.toString(numTicks) + VALUE_DELIMINATOR + maxTicks;
}
private void commitTextFields() {
if (valField != null || maxField != null) {
if (set(valField != null ? atoi(valField.getText()) : numTicks,
maxField != null ? atoi(maxField.getText()) : maxTicks)) {
updateFields();
}
}
}
private void updateFields() {
if (valField != null) {
valField.setText(Integer.toString(numTicks));
}
if (maxField != null) {
maxField.setText(Integer.toString(maxTicks));
}
ticks.set(numTicks, maxTicks);
}
private boolean areFieldValuesValid() {
int max = maxField == null ? maxTicks : atoi(maxField.getText());
int val = valField == null ? numTicks : atoi(valField.getText());
return val < max && val >= 0;
}
// field changed
public void actionPerformed(ActionEvent event) {
if (event.getSource() == maxField || event.getSource() == valField) {
commitTextFields();
ticks.set(numTicks, maxTicks);
fireActionEvent();
}
else if (event.getSource() == ticks) {
commitTextFields();
numTicks = ticks.getNumTicks();
if (maxField == null) {
maxTicks = ticks.getMaxTicks();
}
updateFields();
fireDocumentEvent();
}
}
public void addActionListener(ActionListener listener) {
actionListeners.add(listener);
}
public void fireActionEvent() {
for (ActionListener l : actionListeners) {
l.actionPerformed(new ActionEvent(this, 0, null));
}
}
void addDocumentListener(DocumentListener listener) {
if (valField != null)
valField.getDocument().addDocumentListener(this);
if (maxField != null)
maxField.getDocument().addDocumentListener(this);
documentListeners.add(listener);
}
public void fireDocumentEvent() {
for (DocumentListener l : documentListeners) {
l.changedUpdate(null);
}
}
// FocusListener Interface
public void focusLost(FocusEvent event) {
commitTextFields();
ticks.set(numTicks, maxTicks);
}
public void focusGained(FocusEvent event) {
}
public void changedUpdate(DocumentEvent event) {
// do not propagate events unless min/max is valid. We don't want to trigger both
// a state update. A state update might trigger a fix-min/max operation, which would
if (areFieldValuesValid()) {
fireDocumentEvent();
}
}
public void insertUpdate(DocumentEvent event) {
changedUpdate(event);
}
public void removeUpdate(DocumentEvent event) {
changedUpdate(event);
}
}
class TickLabel extends JLabel implements MouseListener {
private static final long serialVersionUID = 1L;
private int numTicks = 0;
private int maxTicks = 0;
protected int panelType;
private List<ActionListener> actionListeners =
new ArrayList<ActionListener>();
public int getNumTicks() {
return numTicks;
}
public int getMaxTicks() {
return maxTicks;
}
public void addActionListener(ActionListener listener) {
actionListeners.add(listener);
}
public TickLabel(int numTicks, int maxTicks, int panelType) {
super(" ");
//Debug.trace("TickLabel( " + maxTicks + ", " + numTicks + " )");
set(numTicks, maxTicks);
this.panelType = panelType;
addMouseListener(this);
}
protected int topMargin = 2;
protected int leftMargin = 2;
protected int numRows;
protected int numCols;
protected int dx = 1;
public void paint(Graphics g) {
//Debug.trace("TickLabcmdel.paint(" + numTicks + "/" + maxTicks + ")");
//Debug.trace(" width=" + getWidth() + " height=" + getHeight());
if (maxTicks > 0) {
// prefered width is 10
// min width before resize is 6
int displayWidth = getWidth() - 2;
dx = Math.min(displayWidth / maxTicks, 10);
// if dx < 2, we have a problem
numRows = dx < 3 ? 3 : dx < 6 ? 2 : 1;
dx = Math.min(displayWidth * numRows / maxTicks, Math.min(getHeight() / numRows, 10));
numCols = (maxTicks + numRows - 1) / numRows;
int dy = dx;
topMargin = (getHeight() - dy * numRows + 2) / 2;
int tick = 0;
int row, col;
if (dx > 4) {
for (; tick < maxTicks; ++tick) {
row = tick / numCols;
col = tick % numCols;
g.setColor(Color.BLACK);
g.drawRect(leftMargin + col * dx, topMargin + row * dy, dx - 3, dy - 3);
g.setColor(tick < numTicks ? Color.BLACK : Color.WHITE);
g.fillRect(leftMargin + 1 + col * dx, topMargin + 1 + row * dy, dx - 4, dy - 4);
}
}
else {
g.setColor(Color.GRAY);
g.fillRect(0, topMargin - 2, numCols * dx + leftMargin * 2, numRows * dy + 4);
for (; tick < maxTicks; ++tick) {
row = tick / numCols;
col = tick % numCols;
g.setColor(tick < numTicks ? Color.BLACK : Color.WHITE);
g.fillRect(leftMargin + col * dx, topMargin + row * dy, dx - 1, dy - 1);
}
}
}
}
public void mouseClicked(MouseEvent event) {
if ((event.isMetaDown() || event.isShiftDown()) && panelType != TICKS_VALMAX) {
new EditTickLabelValueDialog(this);
return;
}
int col = Math.min((event.getX() - leftMargin + 1) / dx, numCols - 1);
int row = Math.min((event.getY() - topMargin + 1) / dx, numRows - 1);
int num = row * numCols + col + 1;
// Checkbox behavior; toggle the box clicked on
// numTicks = num > numTicks ? num : num - 1;
// Slider behavior; set the box clicked on and all to left and clear all boxes to right,
// UNLESS user clicked on last set box (which would do nothing), in this case, toggle the
// box clicked on. This is the only way the user can clear the first box.
numTicks = (num == numTicks) ? num - 1 : num;
fireActionEvent();
repaint();
}
public void fireActionEvent() {
for (ActionListener l : actionListeners) {
l.actionPerformed(new ActionEvent(this, 0, null));
}
}
public void set(int newNumTicks, int newMaxTicks) {
//Debug.trace("TickLabel.set( " + newNumTicks + "," + newMaxTicks + " ) was " + numTicks + "/" + maxTicks);
numTicks = newNumTicks;
maxTicks = newMaxTicks;
String tip = numTicks + "/" + maxTicks;
if (panelType != TICKS_VALMAX) {
tip += " (right-click to edit)";
}
setToolTipText(tip);
repaint();
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public class EditTickLabelValueDialog extends JPanel implements ActionListener, DocumentListener, FocusListener {
private static final long serialVersionUID = 1L;
TickLabel theTickLabel;
JLayeredPane editorParent;
JTextField valueField;
public EditTickLabelValueDialog(TickLabel owner) {
super(new BorderLayout());
theTickLabel = owner;
// Find containing dialog
Container theDialog = theTickLabel.getParent();
while (!(theDialog instanceof JDialog) && theDialog != null) {
theDialog = theDialog.getParent();
}
if (theDialog != null) {
editorParent = ((JDialog) theDialog).getLayeredPane();
Rectangle newBounds = SwingUtilities.convertRectangle(theTickLabel.getParent(), theTickLabel.getBounds(), editorParent);
setBounds(newBounds);
JButton okButton = new JButton("Ok");
switch (panelType) {
case TICKS_VAL:
valueField = new JTextField(Integer.toString(owner.getMaxTicks()));
valueField.setToolTipText("max value");
break;
case TICKS_MAX:
valueField = new JTextField(Integer.toString(owner.getNumTicks()));
valueField.setToolTipText("current value");
break;
case TICKS:
default:
valueField = new JTextField(owner.numTicks + "/" + owner.maxTicks);
valueField.setToolTipText("current value / max value");
break;
}
valueField.addActionListener(this);
valueField.addFocusListener(this);
valueField.getDocument().addDocumentListener(this);
add(valueField, BorderLayout.CENTER);
okButton.addActionListener(this);
add(okButton, BorderLayout.EAST);
editorParent.add(this, JLayeredPane.MODAL_LAYER);
setVisible(true);
valueField.grabFocus();
}
}
public void storeValues() {
String value = valueField.getText();
switch (panelType) {
case TICKS_VAL:
theTickLabel.set(theTickLabel.getNumTicks(), atoi(value));
break;
case TICKS_MAX:
theTickLabel.set(atoi(value), theTickLabel.getMaxTicks());
break;
case TICKS:
default:
theTickLabel.set(atoi(value), atoiRight(value));
break;
}
theTickLabel.fireActionEvent();
}
public void actionPerformed(ActionEvent event) {
storeValues();
editorParent.remove(this);
}
public void changedUpdate(DocumentEvent event) {
theTickLabel.fireActionEvent();
}
public void insertUpdate(DocumentEvent event) {
theTickLabel.fireActionEvent();
}
public void removeUpdate(DocumentEvent event) {
theTickLabel.fireActionEvent();
}
public void focusGained(FocusEvent event) {
}
public void focusLost(FocusEvent event) {
storeValues();
}
}
}
}
|
package som.metascience.metrics;
import org.gephi.data.attributes.api.AttributeColumn;
import org.gephi.data.attributes.api.AttributeController;
import org.gephi.data.attributes.api.AttributeModel;
import org.gephi.data.attributes.api.AttributeTable;
import org.gephi.graph.api.*;
import org.gephi.io.importer.api.Container;
import org.gephi.io.importer.api.EdgeDefault;
import org.gephi.io.importer.api.ImportController;
import org.gephi.io.processor.plugin.DefaultProcessor;
import org.gephi.project.api.ProjectController;
import org.gephi.project.api.Workspace;
import org.gephi.statistics.plugin.Modularity;
import org.openide.util.Lookup;
import som.metascience.MetricData;
import java.io.File;
import java.util.HashMap;
/**
* Calculates the graph modularity classes
*/
public class GraphModularity extends Metric {
/**
* Attribute table in the graph holding the info for the nodes (it depends on the language of the system)
*/
public static final String ATTRIBUTE_TABLE = "Noeuds";
/**
* The column to get from the table
*/
public static final String ATTRIBUTE_COLUMN = "modularity_class";
public GraphModularity(MetricData metricData) {
super(metricData);
}
@Override
public String getResult() {
String graphModularityFull = calcualteGraphModularity(metricData.getFullGraph());
String graphModularityEdition1 = calcualteGraphModularity(metricData.getEditionGraphs().get(0));
String graphModularityEdition2 = calcualteGraphModularity(metricData.getEditionGraphs().get(1));
String graphModularityEdition3 = calcualteGraphModularity(metricData.getEditionGraphs().get(2));
String graphModularityEdition4 = calcualteGraphModularity(metricData.getEditionGraphs().get(3));
String graphModularityEdition5 = calcualteGraphModularity(metricData.getEditionGraphs().get(4));
return graphModularityFull + "," + graphModularityEdition1 + "," + graphModularityEdition2 + "," + graphModularityEdition3 + "," + graphModularityEdition4 + "," + graphModularityEdition5;
}
/**
* Calculates the graph modularity classes
* @param graph The path to the graph
* @return The result of the metric
*/
public String calcualteGraphModularity(File graph) {
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
pc.newProject();
Workspace workspace = pc.getCurrentWorkspace();
// Import file
ImportController importController = Lookup.getDefault().lookup(ImportController.class);
Container container;
try {
container = importController.importFile(graph);
container.getLoader().setEdgeDefault(EdgeDefault.UNDIRECTED); //Force DIRECTED
container.setAllowAutoNode(false); //Don't create missing nodes
importController.process(container, new DefaultProcessor(), workspace);
} catch (Exception ex) {
ex.printStackTrace();
}
GraphModel gm = Lookup.getDefault().lookup(GraphController.class).getModel();
AttributeModel am = Lookup.getDefault().lookup(AttributeController.class).getModel();
// Graph modularity
Modularity modularity = new Modularity();
//modularity.setRandom(true);
//modularity.setUseWeight(true);
//modularity.setResolution(1.0);
modularity.execute(gm, am);
//AttributeTable at = am.getTable(ATTRIBUTE_TABLE);
//AttributeColumn ac = at.getColumn(ATTRIBUTE_COLUMN);
NodeIterable ni = gm.getGraph().getNodes();
HashMap<Integer, Integer> classes = new HashMap<>();
for(Node node : ni.toArray()) {
Integer modularityClass = (Integer) node.getAttributes().getValue(ATTRIBUTE_COLUMN);
classes.put(modularityClass, null);
}
int totalClasses = classes.keySet().size();
return String.valueOf(totalClasses);
}
}
|
package com.silverpeas.jcrutil;
import java.util.Calendar;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
public class RandomGenerator {
protected static final String[] LANGUAGES = new String[] { "fr", "en", "de",
"ru", "cn", "se" };
protected static final Random random = new Random(10);
/**
* Generate a random int between 0 and 23.
* @return a random int between 0 and 23.
*/
public static int getRandomHour() {
return random.nextInt(24);
}
/**
* Generate a random int between 0 and 59.
* @return a random int between 0 and 59.
*/
public static int getRandomMinutes() {
return random.nextInt(60);
}
/**
* Generate a random int between 0 and 11.
* @return a random int between 0 and 11.
*/
public static int getRandomMonth() {
return random.nextInt(12);
}
/**
* Generate a random int between 2019 and 2019.
* @return a random int between 2019 and 2019.
*/
public static int getRandomYear() {
return 2000 + random.nextInt(20);
}
/**
* Generate a random int between 0 and 31.
* @return a random int between 0 and 31.
*/
public static int getRandomDay() {
return random.nextInt(32);
}
/**
* Generate a random long.
* @return a random long.
*/
public static long getRandomLong() {
return random.nextLong();
}
/**
* Generate a random float.
* @return a random float.
*/
public static float getRandomFloat() {
return random.nextFloat();
}
/**
* Generate a random String of size 32.
* @return a random String of 32 chars.
*/
public static String getRandomString() {
return RandomStringUtils.random(32, true, true);
}
/**
* Generate a random language
* @return a random valid language.
*/
public static String getRandomLanguage() {
return LANGUAGES[random.nextInt(LANGUAGES.length)];
}
/**
* Generate a random boolean.
* @return a random boolean.
*/
public static boolean getRandomBoolean() {
return random.nextBoolean();
}
/**
* Generate a random int.
* @return a random int.
*/
public static int getRandomInt() {
return random.nextInt();
}
/**
* Generate a random int in the 0 inclusive max exclusive.
* @param max the exclusive maximum of the random int.
* @return a random int.
*/
public static int getRandomInt(int max) {
return random.nextInt(max);
}
public static Calendar getOutdatedCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -(1 + random.nextInt(10)));
calendar.set(Calendar.HOUR_OF_DAY, getRandomHour());
calendar.set(Calendar.MINUTE, getRandomMinutes());
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
public static Calendar getFuturCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 1 + random.nextInt(10));
calendar.set(Calendar.HOUR_OF_DAY, getRandomHour());
calendar.set(Calendar.MINUTE, getRandomMinutes());
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
public static Calendar getRandomCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, getRandomDay());
calendar.set(Calendar.MONTH, getRandomMonth());
calendar.set(Calendar.YEAR, getRandomYear());
calendar.set(Calendar.HOUR_OF_DAY, getRandomHour());
calendar.set(Calendar.MINUTE, getRandomMinutes());
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
public static Calendar getCalendarAfter(Calendar date) {
Calendar endDate = Calendar.getInstance();
endDate.setTimeInMillis(date.getTimeInMillis());
endDate.add(Calendar.DAY_OF_MONTH, 1 + random.nextInt(10));
return endDate;
}
public static Calendar getCalendarBefore(Calendar date) {
Calendar beforeDate = Calendar.getInstance();
beforeDate.setTimeInMillis(date.getTimeInMillis());
beforeDate.add(Calendar.DAY_OF_MONTH, -1 - random.nextInt(10));
return date;
}
}
|
package dwarf.graphics;
import dwarf.util.Vector2;
import java.util.Objects;
import static dwarf.util.math.TWO_PI;
import static dwarf.util.math.sqr;
import static java.lang.Math.PI;
import static dwarf.graphics.draw.SHAPE_CIRCLE;
public class Circle extends Shape {
private double radius;
public Circle(double radius, Vector2 location, String mode, Colour colour) {
super(SHAPE_CIRCLE, ((TWO_PI * radius) / 60), location, mode, colour);
}
public Circle(Circle circle) {
super(SHAPE_CIRCLE, circle.getRadius(), circle.getPosition(), circle.getMode(), circle.getColour());
}
/**
* Returns true if the <code>this</code> is equal to the argument and false
* otherwise. Consequently, if both argument are null, true is returned,
* false is returned. Otherwise, equality is determined by using the equals
* method of the first argument.
*
* @return true if the argument is equal to <code>this</code> other and
* false otherwise
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (getClass() != obj.getClass()) {
return false;
} else if (!super.equals(obj)) {
return false;
}
final Circle other = (Circle) obj;
if (Double.doubleToLongBits(radius) != Double.doubleToLongBits(other.radius)) {
return false;
} else if (!Objects.equals(getColour(), other.getColour())) {
return false;
} else {
return Objects.equals(getColour(), other.getColour());
}
}
public double getCircumference() {
return TWO_PI * radius;
}
@Override
public double getArea() {
return PI * sqr(radius);
}
public double getDiameter() {
return radius * 2;
}
public double getCircularArcLength(double theta) {
return theta * (PI / 180) * radius;
}
public double getCircleSector(double theta) {
return (theta / 360) * this.getArea();
}
@Override
public double getRadius() {
return this.radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public float getHalfWidth() {
return (float) radius;
}
public float getHalfHeight() {
return (float) radius;
}
@Override
public Circle get() {
return this;
}
@Override
public Vector2 getCenterX() {
return new Vector2(
this.getPosition().getX() + this.getRadius(),
this.getPosition().getY()
);
}
@Override
public Vector2 getCenterY() {
return new Vector2(
this.getPosition().getX(),
this.getPosition().getY() + this.getRadius()
);
}
@Override
public Vector2 getCenter() {
return new Vector2(
this.getCenterX().getX(),
this.getCenterY().getY()
);
}
}
|
package cs437.som.learningrate;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class HyperbolicLearningRateFunctionTest {
private static final double MAXIMUM_DIFFERENCE = 0.0000000000000001;
private static final int ITERATIONS = 1000;
private static final double START_RATE = 0.8;
private static final double END_RATE = 0.01;
private static final int[] SAMPLES = {0,100,200,500,1000};
private static final double[] SAMPLE_RESULTS =
{0.8, 0.516156, 0.333021, 0.0894427, 0.01};
private static final double[] SAMPLE_ACCURACY =
{1.0e-1, 1.0e-6, 1.0e-6, 1.0e-7, 1.0e-2};
private HyperbolicLearningRateFunction hlrf;
@BeforeTest
public void setUp() {
hlrf = new HyperbolicLearningRateFunction(START_RATE, END_RATE);
hlrf.setExpectedIterations(ITERATIONS);
}
@Test
public void testEndpoints() {
assertEquals(hlrf.learningRate(0), START_RATE, MAXIMUM_DIFFERENCE);
assertEquals(hlrf.learningRate(ITERATIONS), END_RATE, MAXIMUM_DIFFERENCE);
}
@Test
public void testShape() throws Exception {
double last = hlrf.learningRate(1);
for (int i = 2; i < ITERATIONS; i += 10) {
double current = hlrf.learningRate(i);
assertTrue(current < last, "Should consistently decay.");
last = current;
}
}
@Test
public void testBySampling() {
// Verify the function fits known samples
for (int j = 0; j < SAMPLES.length; j++) {
assertEquals(hlrf.learningRate(SAMPLES[j]), SAMPLE_RESULTS[j],
SAMPLE_ACCURACY[j]);
}
}
}
|
package eg.utils;
import java.awt.Dimension;
import java.awt.Toolkit;
/**
* Static constants and methods to obtain quantities that depend on the
* screen size and resolution
*/
public class ScreenParams {
private final static boolean IS_WINDOWS
= System.getProperty("os.name").toLowerCase().contains("win");
private final static String VERSION = System.getProperty("java.version");
private final static boolean IS_JAVA_9_OR_HIGHER = !VERSION.startsWith("1.8");
private final static int SCREEN_RES
= Toolkit.getDefaultToolkit().getScreenResolution();
private final static double SCREEN_RES_RATIO = SCREEN_RES / 72.0;
/**
* The screen size */
public final static Dimension SCREEN_SIZE
= Toolkit.getDefaultToolkit().getScreenSize();
/**
* Returns a new <code>Dimension</code> that is scaled to the
* screen resolution ratio
* @see #scaledSize(double)
*
* @param width the width in pt
* @param height the height in pt
* @return the Dimension
*/
public static Dimension scaledDimension(int width, int height) {
width = scaledSize(width);
height = scaledSize(height);
return new Dimension(width, height);
}
/**
* Returns a scaled size that depends on the Java version, the OS or
* the screen resolution.
* <p>
* If the program is run using Java 8 the scaled size is the product
* of the specified size and the resolution ratio. This ratio is the
* screen resolution divided by the graphics resolution assumed by
* Java (72 dpi).
* <p>
* If the program is run using a higher Java version the specified size
* is returned unchanged or, if the OS is Windows, multiplied with the
* ratio 96/72.
*
* @param size the size to scale
* @return the rounded scaled size
*/
public static int scaledSize(double size) {
if (IS_JAVA_9_OR_HIGHER) {
if (IS_WINDOWS) {
return (int) (Math.round(size * 96 / 72));
}
else {
return (int) size;
}
}
else {
return (int) (Math.round(size * SCREEN_RES_RATIO));
}
}
/**
* Returns a size that reverts the scaling calculated by {@link #scaledSize}
*
* @param size the size to scale
* @return the rounded scaled size
*/
public static int invertedScaledSize(int size) {
if (IS_JAVA_9_OR_HIGHER) {
if (IS_WINDOWS) {
return (int) (Math.round(size / (96 / 72)));
}
else {
return (int) size;
}
}
else {
return (int) (Math.round(size / SCREEN_RES_RATIO));
}
}
}
|
package com.cloudera.impala.catalog;
import static com.cloudera.impala.thrift.ImpalaInternalServiceConstants.DEFAULT_PARTITION_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsData;
import org.junit.Test;
import com.cloudera.impala.analysis.FunctionName;
import com.cloudera.impala.analysis.HdfsUri;
import com.cloudera.impala.analysis.LiteralExpr;
import com.cloudera.impala.analysis.NumericLiteral;
import com.cloudera.impala.catalog.MetaStoreClientPool.MetaStoreClient;
import com.cloudera.impala.testutil.CatalogServiceTestCatalog;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class CatalogTest {
private static CatalogServiceCatalog catalog_ =
CatalogServiceTestCatalog.create();
private void checkTableCols(Db db, String tblName, int numClusteringCols,
String[] colNames, Type[] colTypes) throws TableLoadingException {
Table tbl = db.getTable(tblName);
assertEquals(tbl.getName(), tblName);
assertEquals(tbl.getNumClusteringCols(), numClusteringCols);
List<Column> cols = tbl.getColumns();
assertEquals(colNames.length, colTypes.length);
assertEquals(cols.size(), colNames.length);
Iterator<Column> it = cols.iterator();
int i = 0;
while (it.hasNext()) {
Column col = it.next();
assertEquals(col.getName(), colNames[i]);
assertTrue(col.getType().equals(colTypes[i]));
++i;
}
}
private void checkHBaseTableCols(Db db, String hiveTableName, String hbaseTableName,
String[] hiveColNames, String[] colFamilies, String[] colQualifiers,
Type[] colTypes) throws TableLoadingException{
checkTableCols(db, hiveTableName, 1, hiveColNames, colTypes);
HBaseTable tbl = (HBaseTable) db.getTable(hiveTableName);
assertEquals(tbl.getHBaseTableName(), hbaseTableName);
List<Column> cols = tbl.getColumns();
assertEquals(colFamilies.length, colTypes.length);
assertEquals(colQualifiers.length, colTypes.length);
Iterator<Column> it = cols.iterator();
int i = 0;
while (it.hasNext()) {
HBaseColumn col = (HBaseColumn)it.next();
assertEquals(col.getColumnFamily(), colFamilies[i]);
assertEquals(col.getColumnQualifier(), colQualifiers[i]);
++i;
}
}
@Test
public void TestColSchema() throws CatalogException {
Db functionalDb = catalog_.getDb("functional");
assertNotNull(functionalDb);
assertEquals(functionalDb.getName(), "functional");
assertNotNull(catalog_.getOrLoadTable("functional", "alltypes"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypes_view"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypes_view_sub"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypessmall"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypeserror"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypeserrornonulls"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypesagg"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypesaggnonulls"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypesnopart"));
assertNotNull(catalog_.getOrLoadTable("functional", "alltypesinsert"));
assertNotNull(catalog_.getOrLoadTable("functional", "complex_view"));
assertNotNull(catalog_.getOrLoadTable("functional", "testtbl"));
assertNotNull(catalog_.getOrLoadTable("functional", "dimtbl"));
assertNotNull(catalog_.getOrLoadTable("functional", "jointbl"));
assertNotNull(catalog_.getOrLoadTable("functional", "liketbl"));
assertNotNull(catalog_.getOrLoadTable("functional", "greptiny"));
assertNotNull(catalog_.getOrLoadTable("functional", "rankingssmall"));
assertNotNull(catalog_.getOrLoadTable("functional", "uservisitssmall"));
assertNotNull(catalog_.getOrLoadTable("functional", "view_view"));
// IMP-163 - table with string partition column does not load if there are partitions
assertNotNull(catalog_.getOrLoadTable("functional", "StringPartitionKey"));
// Test non-existent table
assertNull(catalog_.getOrLoadTable("functional", "nonexistenttable"));
// functional_seq contains the same tables as functional
Db testDb = catalog_.getDb("functional_seq");
assertNotNull(testDb);
assertEquals(testDb.getName(), "functional_seq");
assertNotNull(catalog_.getOrLoadTable("functional_seq", "alltypes"));
assertNotNull(catalog_.getOrLoadTable("functional_seq", "testtbl"));
Db hbaseDb = catalog_.getDb("functional_hbase");
assertNotNull(hbaseDb);
assertEquals(hbaseDb.getName(), "functional_hbase");
// Loading succeeds for an HBase table that has binary columns and an implicit key
// column mapping
assertNotNull(catalog_.getOrLoadTable(hbaseDb.getName(), "alltypessmallbinary"));
assertNotNull(catalog_.getOrLoadTable(hbaseDb.getName(), "alltypessmall"));
assertNotNull(catalog_.getOrLoadTable(hbaseDb.getName(), "hbasealltypeserror"));
assertNotNull(catalog_.getOrLoadTable(hbaseDb.getName(),
"hbasealltypeserrornonulls"));
assertNotNull(catalog_.getOrLoadTable(hbaseDb.getName(), "alltypesagg"));
assertNotNull(catalog_.getOrLoadTable(hbaseDb.getName(), "stringids"));
checkTableCols(functionalDb, "alltypes", 2,
new String[]
{"year", "month", "id", "bool_col", "tinyint_col", "smallint_col",
"int_col", "bigint_col", "float_col", "double_col", "date_string_col",
"string_col", "timestamp_col"},
new Type[]
{Type.INT, Type.INT, Type.INT,
Type.BOOLEAN, Type.TINYINT, Type.SMALLINT,
Type.INT, Type.BIGINT, Type.FLOAT,
Type.DOUBLE, Type.STRING, Type.STRING,
Type.TIMESTAMP});
checkTableCols(functionalDb, "testtbl", 0,
new String[] {"id", "name", "zip"},
new Type[]
{Type.BIGINT, Type.STRING, Type.INT});
checkTableCols(testDb, "testtbl", 0,
new String[] {"id", "name", "zip"},
new Type[]
{Type.BIGINT, Type.STRING, Type.INT});
checkTableCols(functionalDb, "liketbl", 0,
new String[] {
"str_col", "match_like_col", "no_match_like_col", "match_regex_col",
"no_match_regex_col"},
new Type[]
{Type.STRING, Type.STRING, Type.STRING,
Type.STRING, Type.STRING});
checkTableCols(functionalDb, "dimtbl", 0,
new String[] {"id", "name", "zip"},
new Type[]
{Type.BIGINT, Type.STRING, Type.INT});
checkTableCols(functionalDb, "jointbl", 0,
new String[] {"test_id", "test_name", "test_zip", "alltypes_id"},
new Type[]
{Type.BIGINT, Type.STRING, Type.INT,
Type.INT});
checkHBaseTableCols(hbaseDb, "alltypessmall", "functional_hbase.alltypessmall",
new String[]
{"id", "bigint_col", "bool_col", "date_string_col", "double_col", "float_col",
"int_col", "month", "smallint_col", "string_col", "timestamp_col",
"tinyint_col", "year"},
new String[]
{":key", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d"},
new String[]
{null, "bigint_col", "bool_col", "date_string_col", "double_col", "float_col",
"int_col", "month", "smallint_col", "string_col", "timestamp_col",
"tinyint_col", "year"},
new Type[]
{Type.INT, Type.BIGINT, Type.BOOLEAN,
Type.STRING, Type.DOUBLE, Type.FLOAT,
Type.INT, Type.INT, Type.SMALLINT,
Type.STRING, Type.TIMESTAMP,
Type.TINYINT, Type.INT});
checkHBaseTableCols(hbaseDb, "hbasealltypeserror",
"functional_hbase.hbasealltypeserror",
new String[]
{"id", "bigint_col", "bool_col","date_string_col", "double_col", "float_col",
"int_col", "smallint_col", "string_col","timestamp_col", "tinyint_col"},
new String[]
{":key", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d"},
new String[]
{null, "bigint_col", "bool_col","date_string_col", "double_col", "float_col",
"int_col", "smallint_col", "string_col","timestamp_col", "tinyint_col"},
new Type[]
{Type.INT, Type.BIGINT, Type.BOOLEAN,
Type.STRING, Type.DOUBLE, Type.FLOAT,
Type.INT, Type.SMALLINT, Type.STRING,
Type.TIMESTAMP, Type.TINYINT});
checkHBaseTableCols(hbaseDb, "hbasealltypeserrornonulls",
"functional_hbase.hbasealltypeserrornonulls",
new String[]
{"id", "bigint_col", "bool_col", "date_string_col", "double_col", "float_col",
"int_col", "smallint_col", "string_col","timestamp_col", "tinyint_col"},
new String[]
{":key", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d"},
new String[]
{null, "bigint_col", "bool_col", "date_string_col", "double_col", "float_col",
"int_col", "smallint_col", "string_col","timestamp_col", "tinyint_col"},
new Type[]
{Type.INT, Type.BIGINT, Type.BOOLEAN,
Type.STRING, Type.DOUBLE, Type.FLOAT,
Type.INT, Type.SMALLINT, Type.STRING,
Type.TIMESTAMP, Type.TINYINT});
checkHBaseTableCols(hbaseDb, "alltypesagg", "functional_hbase.alltypesagg",
new String[]
{"id", "bigint_col", "bool_col", "date_string_col", "day", "double_col",
"float_col", "int_col", "month", "smallint_col", "string_col",
"timestamp_col", "tinyint_col", "year"},
new String[]
{":key", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d"},
new String[]
{null, "bigint_col", "bool_col", "date_string_col", "day", "double_col",
"float_col", "int_col", "month", "smallint_col", "string_col",
"timestamp_col", "tinyint_col", "year"},
new Type[]
{Type.INT, Type.BIGINT, Type.BOOLEAN,
Type.STRING,Type.INT, Type.DOUBLE,
Type.FLOAT, Type.INT, Type.INT,
Type.SMALLINT, Type.STRING, Type.TIMESTAMP,
Type.TINYINT, Type.INT});
checkHBaseTableCols(hbaseDb, "stringids", "functional_hbase.alltypesagg",
new String[]
{"id", "bigint_col", "bool_col", "date_string_col", "day", "double_col",
"float_col", "int_col", "month", "smallint_col", "string_col",
"timestamp_col", "tinyint_col", "year"},
new String[]
{":key", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d"},
new String[]
{null, "bigint_col", "bool_col", "date_string_col", "day", "double_col",
"float_col", "int_col", "month", "smallint_col", "string_col",
"timestamp_col", "tinyint_col", "year"},
new Type[]
{Type.STRING, Type.BIGINT, Type.BOOLEAN,
Type.STRING,Type.INT, Type.DOUBLE,
Type.FLOAT, Type.INT, Type.INT,
Type.SMALLINT, Type.STRING, Type.TIMESTAMP,
Type.TINYINT, Type.INT});
checkTableCols(functionalDb, "greptiny", 0,
new String[]
{"field"},
new Type[]
{Type.STRING});
checkTableCols(functionalDb, "rankingssmall", 0,
new String[]
{"pagerank", "pageurl", "avgduration"},
new Type[]
{Type.INT, Type.STRING, Type.INT});
checkTableCols(functionalDb, "uservisitssmall", 0,
new String[]
{"sourceip", "desturl", "visitdate", "adrevenue", "useragent",
"ccode", "lcode", "skeyword", "avgtimeonsite"},
new Type[]
{Type.STRING, Type.STRING, Type.STRING,
Type.FLOAT, Type.STRING, Type.STRING,
Type.STRING, Type.STRING, Type.INT});
// case-insensitive lookup
assertEquals(catalog_.getOrLoadTable("functional", "alltypes"),
catalog_.getOrLoadTable("functional", "AllTypes"));
}
@Test
public void TestPartitions() throws CatalogException {
HdfsTable table =
(HdfsTable) catalog_.getOrLoadTable("functional", "AllTypes");
List<HdfsPartition> partitions = table.getPartitions();
// check that partition keys cover the date range 1/1/2009-12/31/2010
// and that we have one file per partition, plus the default partition
assertEquals(25, partitions.size());
Set<Long> months = Sets.newHashSet();
for (HdfsPartition p: partitions) {
if (p.getId() == DEFAULT_PARTITION_ID) {
continue;
}
assertEquals(2, p.getPartitionValues().size());
LiteralExpr key1Expr = p.getPartitionValues().get(0);
assertTrue(key1Expr instanceof NumericLiteral);
long key1 = ((NumericLiteral) key1Expr).getLongValue();
assertTrue(key1 == 2009 || key1 == 2010);
LiteralExpr key2Expr = p.getPartitionValues().get(1);
assertTrue(key2Expr instanceof NumericLiteral);
long key2 = ((NumericLiteral) key2Expr).getLongValue();
assertTrue(key2 >= 1 && key2 <= 12);
months.add(key1 * 100 + key2);
assertEquals(p.getFileDescriptors().size(), 1);
}
assertEquals(months.size(), 24);
}
// TODO: All Hive-stats related tests are temporarily disabled because of an unknown,
// sporadic issue causing stats of some columns to be absent in Jenkins runs.
// Investigate this issue further.
//@Test
public void testStats() throws TableLoadingException {
// make sure the stats for functional.alltypesagg look correct
HdfsTable table =
(HdfsTable) catalog_.getDb("functional").getTable("AllTypesAgg");
Column idCol = table.getColumn("id");
assertEquals(idCol.getStats().getAvgSerializedSize() -
PrimitiveType.INT.getSlotSize(),
PrimitiveType.INT.getSlotSize(), 0.0001);
assertEquals(idCol.getStats().getMaxSize(), PrimitiveType.INT.getSlotSize());
assertTrue(!idCol.getStats().hasNulls());
Column boolCol = table.getColumn("bool_col");
assertEquals(boolCol.getStats().getAvgSerializedSize() -
PrimitiveType.BOOLEAN.getSlotSize(),
PrimitiveType.BOOLEAN.getSlotSize(), 0.0001);
assertEquals(boolCol.getStats().getMaxSize(), PrimitiveType.BOOLEAN.getSlotSize());
assertTrue(!boolCol.getStats().hasNulls());
Column tinyintCol = table.getColumn("tinyint_col");
assertEquals(tinyintCol.getStats().getAvgSerializedSize() -
PrimitiveType.TINYINT.getSlotSize(),
PrimitiveType.TINYINT.getSlotSize(), 0.0001);
assertEquals(tinyintCol.getStats().getMaxSize(),
PrimitiveType.TINYINT.getSlotSize());
assertTrue(tinyintCol.getStats().hasNulls());
Column smallintCol = table.getColumn("smallint_col");
assertEquals(smallintCol.getStats().getAvgSerializedSize() -
PrimitiveType.SMALLINT.getSlotSize(),
PrimitiveType.SMALLINT.getSlotSize(), 0.0001);
assertEquals(smallintCol.getStats().getMaxSize(),
PrimitiveType.SMALLINT.getSlotSize());
assertTrue(smallintCol.getStats().hasNulls());
Column intCol = table.getColumn("int_col");
assertEquals(intCol.getStats().getAvgSerializedSize() -
PrimitiveType.INT.getSlotSize(),
PrimitiveType.INT.getSlotSize(), 0.0001);
assertEquals(intCol.getStats().getMaxSize(), PrimitiveType.INT.getSlotSize());
assertTrue(intCol.getStats().hasNulls());
Column bigintCol = table.getColumn("bigint_col");
assertEquals(bigintCol.getStats().getAvgSerializedSize() -
PrimitiveType.BIGINT.getSlotSize(),
PrimitiveType.BIGINT.getSlotSize(), 0.0001);
assertEquals(bigintCol.getStats().getMaxSize(), PrimitiveType.BIGINT.getSlotSize());
assertTrue(bigintCol.getStats().hasNulls());
Column floatCol = table.getColumn("float_col");
assertEquals(floatCol.getStats().getAvgSerializedSize() -
PrimitiveType.FLOAT.getSlotSize(),
PrimitiveType.FLOAT.getSlotSize(), 0.0001);
assertEquals(floatCol.getStats().getMaxSize(), PrimitiveType.FLOAT.getSlotSize());
assertTrue(floatCol.getStats().hasNulls());
Column doubleCol = table.getColumn("double_col");
assertEquals(doubleCol.getStats().getAvgSerializedSize() -
PrimitiveType.DOUBLE.getSlotSize(),
PrimitiveType.DOUBLE.getSlotSize(), 0.0001);
assertEquals(doubleCol.getStats().getMaxSize(), PrimitiveType.DOUBLE.getSlotSize());
assertTrue(doubleCol.getStats().hasNulls());
Column timestampCol = table.getColumn("timestamp_col");
assertEquals(timestampCol.getStats().getAvgSerializedSize() -
PrimitiveType.TIMESTAMP.getSlotSize(),
PrimitiveType.TIMESTAMP.getSlotSize(), 0.0001);
assertEquals(timestampCol.getStats().getMaxSize(),
PrimitiveType.TIMESTAMP.getSlotSize());
// this does not have nulls, it's not clear why this passes
// TODO: investigate and re-enable
//assertTrue(timestampCol.getStats().hasNulls());
Column stringCol = table.getColumn("string_col");
assertTrue(stringCol.getStats().getAvgSerializedSize() >=
PrimitiveType.STRING.getSlotSize());
assertTrue(stringCol.getStats().getAvgSerializedSize() > 0);
assertTrue(stringCol.getStats().getMaxSize() > 0);
assertTrue(!stringCol.getStats().hasNulls());
}
/**
* Verifies that updating column stats data for a type that isn't compatible with
* the column type results in the stats being set to "unknown". This is a regression
* test for IMPALA-588, where this used to result in a Preconditions failure.
*/
// TODO: All Hive-stats related tests are temporarily disabled because of an unknown,
// sporadic issue causing stats of some columns to be absent in Jenkins runs.
// Investigate this issue further.
//@Test
public void testColStatsColTypeMismatch() throws Exception {
// First load a table that has column stats.
//catalog_.refreshTable("functional", "alltypesagg", false);
HdfsTable table = (HdfsTable) catalog_.getOrLoadTable("functional", "alltypesagg");
// Now attempt to update a column's stats with mismatched stats data and ensure
// we get the expected results.
MetaStoreClient client = catalog_.getMetaStoreClient();
try {
// Load some string stats data and use it to update the stats of different
// typed columns.
ColumnStatisticsData stringColStatsData = client.getHiveClient()
.getTableColumnStatistics("functional", "alltypesagg",
Lists.newArrayList("string_col")).get(0).getStatsData();
assertTrue(!table.getColumn("int_col").updateStats(stringColStatsData));
assertStatsUnknown(table.getColumn("int_col"));
assertTrue(!table.getColumn("double_col").updateStats(stringColStatsData));
assertStatsUnknown(table.getColumn("double_col"));
assertTrue(!table.getColumn("bool_col").updateStats(stringColStatsData));
assertStatsUnknown(table.getColumn("bool_col"));
// Do the same thing, but apply bigint stats to a string column.
ColumnStatisticsData bigIntCol = client.getHiveClient()
.getTableColumnStatistics("functional", "alltypes",
Lists.newArrayList("bigint_col")).get(0).getStatsData();
assertTrue(!table.getColumn("string_col").updateStats(bigIntCol));
assertStatsUnknown(table.getColumn("string_col"));
// Now try to apply a matching column stats data and ensure it succeeds.
assertTrue(table.getColumn("string_col").updateStats(stringColStatsData));
assertEquals(1178, table.getColumn("string_col").getStats().getNumDistinctValues());
} finally {
// Make sure to invalidate the metadata so the next test isn't using bad col stats
//catalog_.refreshTable("functional", "alltypesagg", false);
client.release();
}
}
private void assertStatsUnknown(Column column) {
assertEquals(-1, column.getStats().getNumDistinctValues());
assertEquals(-1, column.getStats().getNumNulls());
double expectedSize = column.getType().isFixedLengthType() ?
column.getType().getSlotSize() : -1;
assertEquals(expectedSize, column.getStats().getAvgSerializedSize(), 0.0001);
assertEquals(expectedSize, column.getStats().getMaxSize(), 0.0001);
}
@Test
public void testInternalHBaseTable() throws CatalogException {
// Cast will fail if table not an HBaseTable
HBaseTable table = (HBaseTable)
catalog_.getOrLoadTable("functional_hbase", "internal_hbase_table");
assertNotNull("functional_hbase.internal_hbase_table was not found", table);
}
@Test
public void testDatabaseDoesNotExist() {
Db nonExistentDb = catalog_.getDb("doesnotexist");
assertNull(nonExistentDb);
}
@Test
public void testCreateTableMetadata() throws CatalogException {
Table table = catalog_.getOrLoadTable("functional", "alltypes");
// Tables are created via Impala so the metadata should have been populated properly.
// alltypes is an external table.
assertEquals(System.getProperty("user.name"), table.getMetaStoreTable().getOwner());
assertEquals(TableType.EXTERNAL_TABLE.toString(),
table.getMetaStoreTable().getTableType());
// alltypesinsert is created using CREATE TABLE LIKE and is a MANAGED table
table = catalog_.getOrLoadTable("functional", "alltypesinsert");
assertEquals(System.getProperty("user.name"), table.getMetaStoreTable().getOwner());
assertEquals(TableType.MANAGED_TABLE.toString(),
table.getMetaStoreTable().getTableType());
}
@Test
public void testLoadingUnsupportedTableTypes() throws CatalogException {
Table table = catalog_.getOrLoadTable("functional", "hive_index_tbl");
assertTrue(table instanceof IncompleteTable);
IncompleteTable incompleteTable = (IncompleteTable) table;
assertTrue(incompleteTable.getCause() instanceof TableLoadingException);
assertEquals("Unsupported table type 'INDEX_TABLE' for: functional.hive_index_tbl",
incompleteTable.getCause().getMessage());
// Table with unsupported SerDe library.
table = catalog_.getOrLoadTable("functional", "bad_serde");
assertTrue(table instanceof IncompleteTable);
incompleteTable = (IncompleteTable) table;
assertTrue(incompleteTable.getCause() instanceof TableLoadingException);
assertEquals("Impala does not support tables of this type. REASON: SerDe" +
" library 'org.apache.hadoop.hive.serde2.binarysortable.BinarySortableSerDe' " +
"is not supported.", incompleteTable.getCause().getCause().getMessage());
// Impala does not yet support Hive's LazyBinaryColumnarSerDe which can be
// used for RCFILE tables.
table = catalog_.getOrLoadTable("functional_rc", "rcfile_lazy_binary_serde");
assertTrue(table instanceof IncompleteTable);
incompleteTable = (IncompleteTable) table;
assertTrue(incompleteTable.getCause() instanceof TableLoadingException);
assertEquals("Impala does not support tables of this type. REASON: SerDe" +
" library 'org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe' " +
"is not supported.", incompleteTable.getCause().getCause().getMessage());
}
private List<String> getFunctionSignatures(String db) throws DatabaseNotFoundException {
List<Function> fns = catalog_.getFunctions(db);
List<String> names = Lists.newArrayList();
for (Function fn: fns) {
names.add(fn.signatureString());
}
return names;
}
@Test
public void TestUdf() throws CatalogException {
List<String> fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 0);
ArrayList<Type> args1 = Lists.newArrayList();
ArrayList<Type> args2 = Lists.<Type>newArrayList(Type.INT);
ArrayList<Type> args3 = Lists.<Type>newArrayList(Type.TINYINT);
catalog_.removeFunction(
new Function(new FunctionName("default", "Foo"), args1,
Type.INVALID, false));
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 0);
ScalarFunction udf1 = new ScalarFunction(new FunctionName("default", "Foo"),
args1, Type.INVALID, new HdfsUri("/Foo"), "Foo.class", null, null);
catalog_.addFunction(udf1);
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 1);
assertTrue(fnNames.contains("foo()"));
// Same function name, overloaded arguments
ScalarFunction udf2 = new ScalarFunction(new FunctionName("default", "Foo"),
args2, Type.INVALID, new HdfsUri("/Foo"), "Foo.class", null, null);
catalog_.addFunction(udf2);
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 2);
assertTrue(fnNames.contains("foo()"));
assertTrue(fnNames.contains("foo(INT)"));
// Add a function with a new name
ScalarFunction udf3 = new ScalarFunction(new FunctionName("default", "Bar"),
args2, Type.INVALID, new HdfsUri("/Foo"), "Foo.class", null, null);
catalog_.addFunction(udf3);
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 3);
assertTrue(fnNames.contains("foo()"));
assertTrue(fnNames.contains("foo(INT)"));
assertTrue(fnNames.contains("bar(INT)"));
// Drop Foo()
catalog_.removeFunction(new Function(
new FunctionName("default", "Foo"), args1, Type.INVALID, false));
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 2);
assertTrue(fnNames.contains("foo(INT)"));
assertTrue(fnNames.contains("bar(INT)"));
// Drop it again, no-op
catalog_.removeFunction(new Function(
new FunctionName("default", "Foo"), args1, Type.INVALID, false));
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 2);
assertTrue(fnNames.contains("foo(INT)"));
assertTrue(fnNames.contains("bar(INT)"));
// Drop bar(), no-op
catalog_.removeFunction(new Function(
new FunctionName("default", "Bar"), args1, Type.INVALID, false));
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 2);
assertTrue(fnNames.contains("foo(INT)"));
assertTrue(fnNames.contains("bar(INT)"));
// Drop bar(tinyint), no-op
catalog_.removeFunction(new Function(
new FunctionName("default", "Bar"), args3, Type.INVALID, false));
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 2);
assertTrue(fnNames.contains("foo(INT)"));
assertTrue(fnNames.contains("bar(INT)"));
// Drop bar(int)
catalog_.removeFunction(new Function(
new FunctionName("default", "Bar"), args2, Type.INVALID, false));
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 1);
assertTrue(fnNames.contains("foo(INT)"));
// Drop foo(int)
catalog_.removeFunction(new Function(
new FunctionName("default", "foo"), args2, Type.INVALID, false));
fnNames = getFunctionSignatures("default");
assertEquals(fnNames.size(), 0);
}
}
|
package com.cordovaplugincamerapreview;
import android.Manifest;
import android.content.pm.PackageManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.List;
import java.util.Arrays;
public class CameraPreview extends CordovaPlugin implements CameraActivity.CameraPreviewListener {
private final String TAG = "CameraPreview";
private final String setOnPictureTakenHandlerAction = "setOnPictureTakenHandler";
private final String setColorEffectAction = "setColorEffect";
private final String setZoomAction = "setZoom";
private final String setFlashModeAction = "setFlashMode";
private final String startCameraAction = "startCamera";
private final String stopCameraAction = "stopCamera";
private final String previewSizeAction = "setPreviewSize";
private final String switchCameraAction = "switchCamera";
private final String takePictureAction = "takePicture";
private final String showCameraAction = "showCamera";
private final String hideCameraAction = "hideCamera";
private final String getSupportedPreviewSizeAction = "getSupportedPreviewSize";
private final String getSupportedPictureSizeAction = "getSupportedPictureSize";
private final String [] permissions = {
Manifest.permission.CAMERA
};
private final int permissionsReqId = 0;
private CameraActivity fragment;
private CallbackContext takePictureCallbackContext;
private CallbackContext execCallback;
private JSONArray execArgs;
private int containerViewId = 1;
public CameraPreview(){
super();
Log.d(TAG, "Constructing");
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (setOnPictureTakenHandlerAction.equals(action)){
return setOnPictureTakenHandler(args, callbackContext);
} else if (startCameraAction.equals(action)) {
if (cordova.hasPermission(permissions[0])) {
return startCamera(args, callbackContext);
} else {
execCallback = callbackContext;
execArgs = args;
cordova.requestPermissions(this, 0, permissions);
}
} else if (takePictureAction.equals(action)) {
return takePicture(args, callbackContext);
} else if (setColorEffectAction.equals(action)) {
return setColorEffect(args, callbackContext);
} else if (setZoomAction.equals(action)) {
return setZoom(args, callbackContext);
} else if (previewSizeAction.equals(action)) {
return setPreviewSize(args, callbackContext);
} else if (setFlashModeAction.equals(action)) {
return setFlashMode(args, callbackContext);
} else if (stopCameraAction.equals(action)){
return stopCamera(args, callbackContext);
} else if (hideCameraAction.equals(action)) {
return hideCamera(args, callbackContext);
} else if (showCameraAction.equals(action)) {
return showCamera(args, callbackContext);
} else if (switchCameraAction.equals(action)) {
return switchCamera(args, callbackContext);
} else if (getSupportedPreviewSizeAction.equals(action)) {
return getSupportedResolutions("preview", callbackContext);
} else if (getSupportedPictureSizeAction.equals(action)) {
return getSupportedResolutions("picture", callbackContext);
}
return false;
}
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
for(int r:grantResults){
if(r == PackageManager.PERMISSION_DENIED){
execCallback.sendPluginResult(new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION));
return;
}
}
if (requestCode == permissionsReqId) {
startCamera(execArgs, execCallback);
}
}
private boolean getSupportedResolutions(final String type, CallbackContext callbackContext) {
List<Camera.Size> supportedSizes;
Camera camera = fragment.getCamera();
if (camera != null) {
supportedSizes = (type.equals("preview")) ? camera.getParameters().getSupportedPreviewSizes() : camera.getParameters().getSupportedPictureSizes();
if (supportedSizes != null) {
JSONArray sizes = new JSONArray();
for (int i=0; i<supportedSizes.size(); i++) {
Camera.Size size = supportedSizes.get(i);
int h = size.height;
int w = size.width;
JSONObject jsonSize = new JSONObject();
try {
jsonSize.put("height", new Integer(h));
jsonSize.put("width", new Integer(w));
}
catch(Exception e){
e.printStackTrace();
}
sizes.put(jsonSize);
}
callbackContext.success(sizes);
return true;
}
callbackContext.error("Camera Parameters access error");
return false;
}
callbackContext.error("Camera needs to be started first");
return false;
}
private boolean startCamera(final JSONArray args, CallbackContext callbackContext) {
Log.d(TAG, "start camera action");
if (fragment != null) {
callbackContext.error("Camera already started");
return false;
}
fragment = new CameraActivity();
fragment.setEventListener(this);
final CallbackContext cb = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
DisplayMetrics metrics = cordova.getActivity().getResources().getDisplayMetrics();
// offset
int x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(0), metrics);
int y = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(1), metrics);
// size
int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(2), metrics);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(3), metrics);
String defaultCamera = args.getString(4);
Boolean tapToTakePicture = args.getBoolean(5);
Boolean dragEnabled = args.getBoolean(6);
Boolean toBack = args.getBoolean(7);
fragment.defaultCamera = defaultCamera;
fragment.tapToTakePicture = tapToTakePicture;
fragment.dragEnabled = dragEnabled;
fragment.setRect(x, y, width, height);
//create or update the layout params for the container view
FrameLayout containerView = (FrameLayout)cordova.getActivity().findViewById(containerViewId);
if(containerView == null){
containerView = new FrameLayout(cordova.getActivity().getApplicationContext());
containerView.setId(containerViewId);
FrameLayout.LayoutParams containerLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
cordova.getActivity().addContentView(containerView, containerLayoutParams);
}
//display camera bellow the webview
if(toBack){
webView.getView().setBackgroundColor(0x00000000);
((ViewGroup)webView.getView()).bringToFront();
}else{
//set camera back to front
containerView.setAlpha(Float.parseFloat(args.getString(8)));
containerView.bringToFront();
}
//add the fragment to the container
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(containerView.getId(), fragment);
fragmentTransaction.commit();
cb.success("Camera started");
} catch (Exception e) {
e.printStackTrace();
cb.error("Camera start error");
}
}
});
return true;
}
private String invertCamera(String originalCamera){
return originalCamera == "front" ? "back" : "front";
}
private boolean takePicture(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
try {
DisplayMetrics metrics = cordova.getActivity().getResources().getDisplayMetrics();
double width = (double) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(0), metrics);
double height = (double) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(1), metrics);
int quality = args.getInt(2);
fragment.takePicture(width, height, quality);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("takePicture failed");
return false;
}
}
public void onPictureTaken(String originalPicture) {
JSONArray data = new JSONArray();
data.put(originalPicture);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data);
pluginResult.setKeepCallback(true);
Log.d(TAG, "returning picture");
takePictureCallbackContext.sendPluginResult(pluginResult);
}
private boolean setColorEffect(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null){
callbackContext.error("No camera");
return true;
}
Camera.Parameters params = camera.getParameters();
try {
String effect = args.getString(0);
if (effect.equals("aqua")) {
params.setColorEffect(Camera.Parameters.EFFECT_AQUA);
} else if (effect.equals("blackboard")) {
params.setColorEffect(Camera.Parameters.EFFECT_BLACKBOARD);
} else if (effect.equals("mono")) {
params.setColorEffect(Camera.Parameters.EFFECT_MONO);
} else if (effect.equals("negative")) {
params.setColorEffect(Camera.Parameters.EFFECT_NEGATIVE);
} else if (effect.equals("none")) {
params.setColorEffect(Camera.Parameters.EFFECT_NONE);
} else if (effect.equals("posterize")) {
params.setColorEffect(Camera.Parameters.EFFECT_POSTERIZE);
} else if (effect.equals("sepia")) {
params.setColorEffect(Camera.Parameters.EFFECT_SEPIA);
} else if (effect.equals("solarize")) {
params.setColorEffect(Camera.Parameters.EFFECT_SOLARIZE);
} else if (effect.equals("whiteboard")) {
params.setColorEffect(Camera.Parameters.EFFECT_WHITEBOARD);
}
fragment.setCameraParameters(params);
callbackContext.success(effect);
return true;
} catch(Exception e) {
e.printStackTrace();
callbackContext.error("Could not set effect");
return false;
}
}
private boolean setZoom(final JSONArray args, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null) {
callbackContext.error("No camera");
return false;
}
Camera.Parameters params = camera.getParameters();
try {
int zoom = (int) args.getInt(0);
if (camera.getParameters().isZoomSupported()) {
params.setZoom(zoom);
fragment.setCameraParameters(params);
callbackContext.success(zoom);
return true;
}else{
callbackContext.error("Zoom not supported");
return false;
}
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("Could not set zoom");
return false;
}
}
private boolean setPreviewSize(final JSONArray args, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null) {
callbackContext.error("No camera");
return false;
}
Camera.Parameters params = camera.getParameters();
try {
int width = (int) args.getInt(0);
int height = (int) args.getInt(1);
params.setPreviewSize(width, height);
fragment.setCameraParameters(params);
camera.startPreview();
callbackContext.success();
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("Could not set preview size");
return false;
}
}
private boolean setFlashMode(final JSONArray args, CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("No preview");
return false;
}
Camera camera = fragment.getCamera();
if (camera == null) {
callbackContext.error("No camera");
return false;
}
Camera.Parameters params = camera.getParameters();
try {
int mode = (int) args.getInt(0);
switch(mode) {
case 0:
params.setFlashMode(params.FLASH_MODE_OFF);
break;
case 1:
params.setFlashMode(params.FLASH_MODE_ON);
break;
case 2:
params.setFlashMode(params.FLASH_MODE_TORCH);
break;
case 3:
params.setFlashMode(params.FLASH_MODE_AUTO);
break;
}
fragment.setCameraParameters(params);
callbackContext.success(mode);
return true;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("Could not set flash mode");
return false;
}
}
private boolean stopCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
fragment = null;
callbackContext.success();
return true;
}
private boolean showCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
callbackContext.success();
return true;
}
private boolean hideCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null) {
callbackContext.error("No preview");
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fragment);
fragmentTransaction.commit();
callbackContext.success();
return true;
}
private boolean switchCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
callbackContext.error("No preview");
return false;
}
fragment.switchCamera();
callbackContext.success();
return true;
}
private boolean setOnPictureTakenHandler(JSONArray args, CallbackContext callbackContext) {
Log.d(TAG, "setOnPictureTakenHandler");
takePictureCallbackContext = callbackContext;
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
}
|
package me.schickling.ibeacon;
import org.apache.cordova.*;
import com.radiusnetworks.ibeacon.*;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.RemoteException;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collection;
import java.util.HashMap;
public class IBeaconPlugin extends CordovaPlugin implements IBeaconConsumer {
private Context context;
private IBeaconManager iBeaconManager;
private HashMap<Region,CallbackContext> rangingCallbacks = new HashMap<Region,CallbackContext>();
private HashMap<Region,CallbackContext> monitoringCallbacks = new HashMap<Region,CallbackContext>();
@Override
public void onIBeaconServiceConnect() {
initMonitorNotifier();
initRangeNotifier();
}
@Override
public Context getApplicationContext() {
return context;
}
@Override
public boolean bindService(Intent intent, ServiceConnection connection, int mode) {
return context.bindService(intent, connection, mode);
}
@Override
public void unbindService(ServiceConnection connection) {
context.unbindService(connection);
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
context = cordova.getActivity().getApplicationContext();
iBeaconManager = IBeaconManager.getInstanceForApplication(context);
iBeaconManager.bind(this);
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("startAdvertising")) {
startAdvertising(args, callbackContext);
return true;
} else if (action.equals("stopAdvertising")) {
stopAdvertising(args, callbackContext);
return true;
} else if (action.equals("isAdvertising")) {
isAdvertising(args, callbackContext);
return true;
} else if (action.equals("startMonitoringForRegion")) {
startMonitoringForRegion(args, callbackContext);
return true;
} else if (action.equals("stopMonitoringForRegion")) {
stopMonitoringForRegion(args, callbackContext);
return true;
} else if (action.equals("startRangingBeaconsInRegion")) {
startRangingBeaconsInRegion(args, callbackContext);
return true;
} else if (action.equals("stopRangingBeaconsInRegion")) {
stopRangingBeaconsInRegion(args, callbackContext);
return true;
} else {
return false;
}
}
private void startAdvertising(JSONArray args, final CallbackContext callbackContext) {
}
private void stopAdvertising(JSONArray args, final CallbackContext callbackContext) {
}
private void isAdvertising(JSONArray args, final CallbackContext callbackContext) {
}
private void startMonitoringForRegion(JSONArray args, final CallbackContext callbackContext) {
try {
Region region = JSONHelper.mapRegion(args.getJSONObject(0));
monitoringCallbacks.put(region, callbackContext);
iBeaconManager.startMonitoringBeaconsInRegion(region);
} catch (RemoteException e) {
} catch (JSONException e) {
}
}
private void stopMonitoringForRegion(JSONArray args, final CallbackContext callbackContext) {
try {
Region region = JSONHelper.mapRegion(args.getJSONObject(0));
monitoringCallbacks.remove(region);
iBeaconManager.stopMonitoringBeaconsInRegion(region);
} catch (RemoteException e) {
} catch (JSONException e) {
}
}
private void startRangingBeaconsInRegion(JSONArray args, final CallbackContext callbackContext) {
try {
Region region = JSONHelper.mapRegion(args.getJSONObject(0));
rangingCallbacks.put(region, callbackContext);
iBeaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
} catch (JSONException e) {
}
}
private void stopRangingBeaconsInRegion(JSONArray args, final CallbackContext callbackContext) {
try {
Region region = JSONHelper.mapRegion(args.getJSONObject(0));
rangingCallbacks.remove(region);
iBeaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
} catch (JSONException e) {
}
}
private void initMonitorNotifier() {
iBeaconManager.setMonitorNotifier(new MonitorNotifier() {
@Override
public void didEnterRegion(Region region) {}
@Override
public void didExitRegion(Region region) {}
@Override
public void didDetermineStateForRegion(int state, Region region) {
CallbackContext monitoringCallback = monitoringCallbacks.get(region);
if (monitoringCallback != null) {
try {
JSONObject jsonResult = new JSONObject();
jsonResult.put("state", (state == MonitorNotifier.INSIDE) ? "inside" : "outside");
PluginResult result = new PluginResult(PluginResult.Status.OK, jsonResult);
result.setKeepCallback(true);
monitoringCallback.sendPluginResult(result);
} catch (JSONException e) {
monitoringCallback.error("JSONException was thrown");
}
}
}
});
}
private void initRangeNotifier() {
iBeaconManager.setRangeNotifier(new RangeNotifier() {
@Override
public void didRangeBeaconsInRegion(Collection<IBeacon> iBeacons, Region region) {
CallbackContext rangingCallback = rangingCallbacks.get(region);
if (rangingCallback != null) {
try {
JSONObject jsonResult = new JSONObject();
jsonResult.put("beacons", JSONHelper.mapIBeacons(iBeacons));
jsonResult.put("region", JSONHelper.mapRegion(region));
PluginResult result = new PluginResult(PluginResult.Status.OK, jsonResult);
result.setKeepCallback(true);
rangingCallback.sendPluginResult(result);
} catch (JSONException e) {
rangingCallback.error("JSONException was thrown");
}
}
}
});
}
}
|
package edu.mtholyoke.cs341bd.writr;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author jfoley
*/
public class UtilTest {
@Test
public void testJoin() {
String[] data = new String[] {"the", "quick", "brown", "fox"};
assertEquals("the quick brown fox", Util.join(data));
assertEquals("", Util.join(new String[0]));
assertEquals(null, Util.join(null));
}
@Test
public void testMillisToString() {
// Who says java doesn't have macros?
//System.out.println("long date = "+System.currentTimeMillis()+"L;");
long date = 1485886411509L;
assertEquals("2017-1-31 13:13", Util.dateToEST(date));
}
}
|
package hudson.plugins.ec2;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AmazonEC2Exception;
import com.amazonaws.services.ec2.model.DescribeImagesRequest;
import com.amazonaws.services.ec2.model.DescribeImagesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult;
import com.amazonaws.services.ec2.model.DescribeSubnetsRequest;
import com.amazonaws.services.ec2.model.DescribeSubnetsResult;
import com.amazonaws.services.ec2.model.HttpTokensState;
import com.amazonaws.services.ec2.model.IamInstanceProfile;
import com.amazonaws.services.ec2.model.Image;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceMetadataEndpointState;
import com.amazonaws.services.ec2.model.InstanceMetadataOptionsRequest;
import com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification;
import com.amazonaws.services.ec2.model.InstanceState;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.KeyPair;
import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.SecurityGroup;
import com.amazonaws.services.ec2.model.Subnet;
import hudson.Util;
import hudson.model.Node;
import hudson.plugins.ec2.SlaveTemplate.ProvisionOptions;
import hudson.plugins.ec2.util.MinimumNumberOfInstancesTimeRangeConfig;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Basic test to validate SlaveTemplate.
*/
public class SlaveTemplateTest {
@Rule public JenkinsRule r = new JenkinsRule();
@Test
public void testConfigRoundtrip() throws Exception {
String description = "foo ami";
EC2Tag tag1 = new EC2Tag("name1", "value1");
EC2Tag tag2 = new EC2Tag("name2", "value2");
List<EC2Tag> tags = new ArrayList<>();
tags.add(tag1);
tags.add(tag2);
SlaveTemplate orig = new SlaveTemplate("ami-123", EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", tags, null, 0, 0, null, "iamInstanceProfile", true, false, "", false, "", false, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, null, Tenancy.Default, EbsEncryptRootVolume.DEFAULT);
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configureClouds").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(description);
r.assertEqualBeans(orig, received, "ami,zone,description,remoteFS,type,javaPath,jvmopts,stopOnTerminate,securityGroups,subnetId,tags,iamInstanceProfile,useEphemeralDevices,useDedicatedTenancy,connectionStrategy,hostKeyVerificationStrategy,tenancy,ebsEncryptRootVolume");
// For already existing strategies, the default is this one
assertEquals(HostKeyVerificationStrategyEnum.CHECK_NEW_SOFT, received.getHostKeyVerificationStrategy());
}
@Test
public void testConfigRoundtripWithCustomSSHHostKeyVerificationStrategy() throws Exception {
String ami = "ami1";
String description = "foo ami";
// We check this one is set
final HostKeyVerificationStrategyEnum STRATEGY_TO_CHECK = HostKeyVerificationStrategyEnum.OFF;
SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", null, null, 0, 0, null, "", true, false, false, "", false, "", false, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, STRATEGY_TO_CHECK);
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configureClouds").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(description);
r.assertEqualBeans(orig, received, "ami,zone,description,remoteFS,type,javaPath,jvmopts,stopOnTerminate,securityGroups,subnetId,useEphemeralDevices,useDedicatedTenancy,connectionStrategy,hostKeyVerificationStrategy");
assertEquals(STRATEGY_TO_CHECK, received.getHostKeyVerificationStrategy());
}
/**
* Tests to make sure the agent created has been configured properly. Also tests to make sure the spot max bid price
* has been set properly.
*
* @throws Exception
* - Exception that can be thrown by the Jenkins test harness
*/
@Test
public void testConfigWithSpotBidPrice() throws Exception {
String ami = "ami1";
String description = "foo ami";
SpotConfiguration spotConfig = new SpotConfiguration(true);
spotConfig.setSpotMaxBidPrice(".05");
spotConfig.setFallbackToOndemand(true);
spotConfig.setSpotBlockReservationDuration(0);
SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, spotConfig, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, "foo ami", "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", null, null, true, null, "", false, false, "", false, "");
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configureClouds").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(description);
r.assertEqualBeans(orig, received, "ami,zone,spotConfig,description,remoteFS,type,javaPath,jvmopts,stopOnTerminate,securityGroups,subnetId,tags,usePrivateDnsName");
}
/**
* Tests to make sure the agent created has been configured properly. Also tests to make sure the spot max bid price
* has been set properly.
*
* @throws Exception - Exception that can be thrown by the Jenkins test harness
*/
@Test
public void testSpotConfigWithoutBidPrice() throws Exception {
String ami = "ami1";
String description = "foo ami";
SpotConfiguration spotConfig = new SpotConfiguration(false);
SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, spotConfig, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, "foo ami", "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", null, null, true, null, "", false, false, "", false, "");
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configureClouds").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(description);
r.assertEqualBeans(orig, received, "ami,zone,spotConfig,description,remoteFS,type,javaPath,jvmopts,stopOnTerminate,securityGroups,subnetId,tags,usePrivateDnsName");
}
@Test
public void testWindowsConfigRoundTrip() throws Exception {
String ami = "ami1";
String description = "foo ami";
SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "rrr", new WindowsData("password", false, ""), "-Xmx1g", false, "subnet 456", null, null, false, null, "", true, false, "", false, "");
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configureClouds").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(description);
assertEquals(orig.getAdminPassword(), received.getAdminPassword());
assertEquals(orig.amiType, received.amiType);
r.assertEqualBeans(orig, received, "amiType");
}
@Test
public void testUnixConfigRoundTrip() throws Exception {
String ami = "ami1";
String description = "foo ami";
SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "rrr", new UnixData("sudo", "", "", "22", ""), "-Xmx1g", false, "subnet 456", null, null, false, null, "", true, false, "", false, "");
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configureClouds").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(description);
r.assertEqualBeans(orig, received, "amiType");
}
@Test
public void testMinimumNumberOfInstancesActiveRangeConfig() throws Exception {
MinimumNumberOfInstancesTimeRangeConfig minimumNumberOfInstancesTimeRangeConfig = new MinimumNumberOfInstancesTimeRangeConfig();
minimumNumberOfInstancesTimeRangeConfig.setMinimumNoInstancesActiveTimeRangeFrom("11:00");
minimumNumberOfInstancesTimeRangeConfig.setMinimumNoInstancesActiveTimeRangeTo("15:00");
minimumNumberOfInstancesTimeRangeConfig.setMonday(false);
minimumNumberOfInstancesTimeRangeConfig.setTuesday(true);
SpotConfiguration spotConfig = new SpotConfiguration(true);
spotConfig.setSpotMaxBidPrice("22");
spotConfig.setFallbackToOndemand(true);
spotConfig.setSpotBlockReservationDuration(1);
SlaveTemplate slaveTemplate = new SlaveTemplate("ami1", EC2AbstractSlave.TEST_ZONE, spotConfig, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, "foo ami", "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", null, null, 2, null, null, true, true, false, "", false, "", false, false, true, ConnectionStrategy.PRIVATE_IP, 0);
slaveTemplate.setMinimumNumberOfInstancesTimeRangeConfig(minimumNumberOfInstancesTimeRangeConfig);
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(slaveTemplate);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.configRoundtrip();
MinimumNumberOfInstancesTimeRangeConfig stored = r.jenkins.clouds.get(AmazonEC2Cloud.class).getTemplates().get(0).getMinimumNumberOfInstancesTimeRangeConfig();
Assert.assertNotNull(stored);
Assert.assertEquals("11:00", stored.getMinimumNoInstancesActiveTimeRangeFrom());
Assert.assertEquals("15:00", stored.getMinimumNoInstancesActiveTimeRangeTo());
Assert.assertEquals(false, stored.getDay("monday"));
Assert.assertEquals(true, stored.getDay("tuesday"));
}
@Test
public void provisionOndemandSetsAwsNetworkingOnEc2Request() throws Exception {
boolean associatePublicIp = false;
String ami = "ami1";
String description = "foo ami";
String subnetId = "some-subnet";
String securityGroups = "some security group";
String iamInstanceProfile = "some instance profile";
SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, securityGroups, "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, subnetId, null, null, false, null, iamInstanceProfile, true, false, "", associatePublicIp, "");
SlaveTemplate noSubnet = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, securityGroups, "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "", null, null, false, null, iamInstanceProfile, true, false, "", associatePublicIp, "");
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
templates.add(noSubnet);
for (SlaveTemplate template : templates) {
AmazonEC2 mockedEC2 = setupTestForProvisioning(template);
ArgumentCaptor<RunInstancesRequest> riRequestCaptor = ArgumentCaptor.forClass(RunInstancesRequest.class);
template.provision(2, EnumSet.noneOf(ProvisionOptions.class));
verify(mockedEC2).runInstances(riRequestCaptor.capture());
RunInstancesRequest actualRequest = riRequestCaptor.getValue();
List<InstanceNetworkInterfaceSpecification> actualNets = actualRequest.getNetworkInterfaces();
assertEquals(actualNets.size(), 0);
String templateSubnet = Util.fixEmpty(template.getSubnetId());
assertEquals(actualRequest.getSubnetId(), templateSubnet);
if (templateSubnet != null) {
assertEquals(actualRequest.getSecurityGroupIds(), Stream.of("some-group-id").collect(Collectors.toList()));
} else {
assertEquals(actualRequest.getSecurityGroups(), Stream.of(securityGroups).collect(Collectors.toList()));
}
}
}
@Test
public void provisionOndemandSetsAwsNetworkingOnNetworkInterface() throws Exception {
boolean associatePublicIp = true;
String ami = "ami1";
String description = "foo ami";
String subnetId = "some-subnet";
String securityGroups = "some security group";
String iamInstanceProfile = "some instance profile";
EC2Tag tag1 = new EC2Tag("name1", "value1");
EC2Tag tag2 = new EC2Tag("name2", "value2");
List<EC2Tag> tags = new ArrayList<>();
tags.add(tag1);
tags.add(tag2);
SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, securityGroups, "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, subnetId, tags, null, false, null, iamInstanceProfile, true, false, "", associatePublicIp, "");
SlaveTemplate noSubnet = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, securityGroups, "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "", tags, null, false, null, iamInstanceProfile, true, false, "", associatePublicIp, "");
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
templates.add(noSubnet);
for (SlaveTemplate template : templates) {
AmazonEC2 mockedEC2 = setupTestForProvisioning(template);
ArgumentCaptor<RunInstancesRequest> riRequestCaptor = ArgumentCaptor.forClass(RunInstancesRequest.class);
template.provision(2, EnumSet.noneOf(ProvisionOptions.class));
verify(mockedEC2).runInstances(riRequestCaptor.capture());
RunInstancesRequest actualRequest = riRequestCaptor.getValue();
InstanceNetworkInterfaceSpecification actualNet = actualRequest.getNetworkInterfaces().get(0);
assertEquals(actualNet.getSubnetId(), Util.fixEmpty(template.getSubnetId()));
assertEquals(actualNet.getGroups(), Stream.of("some-group-id").collect(Collectors.toList()));
assertEquals(actualRequest.getSubnetId(), null);
assertEquals(actualRequest.getSecurityGroupIds(), Collections.emptyList());
assertEquals(actualRequest.getSecurityGroups(), Collections.emptyList());
}
}
@Issue("JENKINS-64571")
@Test
public void provisionSpotFallsBackToOndemandWhenSpotQuotaExceeded() throws Exception {
boolean associatePublicIp = true;
String ami = "ami1";
String description = "foo ami";
String subnetId = "some-subnet";
String securityGroups = "some security group";
String iamInstanceProfile = "some instance profile";
SpotConfiguration spotConfig = new SpotConfiguration(true);
spotConfig.setSpotMaxBidPrice(".05");
spotConfig.setFallbackToOndemand(true);
spotConfig.setSpotBlockReservationDuration(0);
SlaveTemplate template = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, spotConfig, securityGroups, "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, subnetId, null, null, false, null, iamInstanceProfile, true, false, "", associatePublicIp, "");
AmazonEC2 mockedEC2 = setupTestForProvisioning(template);
AmazonEC2Exception quotaExceededException = new AmazonEC2Exception("Request has expired");
quotaExceededException.setServiceName("AmazonEC2");
quotaExceededException.setStatusCode(400);
quotaExceededException.setErrorCode("MaxSpotInstanceCountExceeded");
quotaExceededException.setRequestId("00000000-0000-0000-0000-000000000000");
when(mockedEC2.requestSpotInstances(any(RequestSpotInstancesRequest.class))).thenThrow(quotaExceededException);
template.provision(2, EnumSet.of(ProvisionOptions.ALLOW_CREATE));
verify(mockedEC2).runInstances(any(RunInstancesRequest.class));
}
private AmazonEC2 setupTestForProvisioning(SlaveTemplate template) throws Exception {
AmazonEC2Cloud mockedCloud = mock(AmazonEC2Cloud.class);
AmazonEC2 mockedEC2 = mock(AmazonEC2.class);
EC2PrivateKey mockedPrivateKey = mock(EC2PrivateKey.class);
KeyPair mockedKeyPair = new KeyPair();
mockedKeyPair.setKeyName("some-key-name");
when(mockedPrivateKey.find(mockedEC2)).thenReturn(mockedKeyPair);
when(mockedCloud.connect()).thenReturn(mockedEC2);
when(mockedCloud.resolvePrivateKey()).thenReturn(mockedPrivateKey);
template.parent = mockedCloud;
DescribeImagesResult mockedImagesResult = mock(DescribeImagesResult.class);
Image mockedImage = new Image();
mockedImage.setImageId(template.getAmi());
when(mockedImagesResult.getImages()).thenReturn(Stream.of(mockedImage).collect(Collectors.toList()));
when(mockedEC2.describeImages(any(DescribeImagesRequest.class))).thenReturn(mockedImagesResult);
DescribeSecurityGroupsResult mockedSecurityGroupsResult = mock(DescribeSecurityGroupsResult.class);
SecurityGroup mockedSecurityGroup = new SecurityGroup();
mockedSecurityGroup.setVpcId("some-vpc-id");
mockedSecurityGroup.setGroupId("some-group-id");
List<SecurityGroup> mockedSecurityGroups = Stream.of(mockedSecurityGroup).collect(Collectors.toList());
when(mockedSecurityGroupsResult.getSecurityGroups()).thenReturn(mockedSecurityGroups);
when(mockedEC2.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class))).thenReturn(mockedSecurityGroupsResult);
DescribeSubnetsResult mockedDescribeSubnetsResult = mock(DescribeSubnetsResult.class);
Subnet mockedSubnet = new Subnet();
List<Subnet> mockedSubnets = Stream.of(mockedSubnet).collect(Collectors.toList());
when(mockedDescribeSubnetsResult.getSubnets()).thenReturn(mockedSubnets);
when(mockedEC2.describeSubnets(any(DescribeSubnetsRequest.class))).thenReturn(mockedDescribeSubnetsResult);
IamInstanceProfile mockedInstanceProfile = new IamInstanceProfile();
mockedInstanceProfile.setArn(template.getIamInstanceProfile());
InstanceState mockInstanceState = new InstanceState();
mockInstanceState.setName("not terminated");
Instance mockedInstance = new Instance();
mockedInstance.setState(mockInstanceState);
mockedInstance.setIamInstanceProfile(mockedInstanceProfile);
Reservation mockedReservation = new Reservation();
mockedReservation.setInstances(Stream.of(mockedInstance).collect(Collectors.toList()));
List<Reservation> mockedReservations = Stream.of(mockedReservation).collect(Collectors.toList());
DescribeInstancesResult mockedDescribedInstancesResult = mock(DescribeInstancesResult.class);
when(mockedDescribedInstancesResult.getReservations()).thenReturn(mockedReservations);
when(mockedEC2.describeInstances(any(DescribeInstancesRequest.class))).thenReturn(mockedDescribedInstancesResult);
RunInstancesResult mockedResult = mock(RunInstancesResult.class);
when(mockedResult.getReservation()).thenReturn(mockedReservation);
when(mockedEC2.runInstances(any(RunInstancesRequest.class))).thenReturn(mockedResult);
return mockedEC2;
}
@Test
public void testMacConfig() throws Exception {
String description = "foo ami";
SlaveTemplate orig = new SlaveTemplate("ami-123", EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.Mac1Metal, false, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", new MacData("sudo", null, null, "22", null), "-Xmx1g", false, "subnet 456", null, null, 0, 0, null, "", true, false, "", false, "", false, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, null, Tenancy.Default);
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configureClouds").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(description);
r.assertEqualBeans(orig, received, "type,amiType");
}
@Issue("JENKINS-65569")
@Test
public void testAgentName() {
SlaveTemplate broken = new SlaveTemplate("ami-123", EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, "broken/description", "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", null, null, 0, 0, null, "", true, false, "", false, "", false, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, null, Tenancy.Default);
SlaveTemplate working = new SlaveTemplate("ami-123", EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, "working", "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", null, null, 0, 0, null, "", true, false, "", false, "", false, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, null, Tenancy.Default);
List<SlaveTemplate> templates = new ArrayList<>();
templates.add(broken);
templates.add(working);
AmazonEC2Cloud brokenCloud = new AmazonEC2Cloud("broken/cloud", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
assertThat(broken.getSlaveName("test"), is("test"));
assertThat(working.getSlaveName("test"), is("test"));
AmazonEC2Cloud workingCloud = new AmazonEC2Cloud("cloud", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
assertThat(broken.getSlaveName("test"), is("test"));
assertThat(working.getSlaveName("test"), is("EC2 (cloud) - working (test)"));
}
@Test
public void testMetadataV2Config() throws Exception {
final String slaveDescription = "foobar";
SlaveTemplate orig = new SlaveTemplate("ami-123", EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, slaveDescription, "bar", "bbb", "aaa", "10", "fff", null, "java", "-Xmx1g", false, "subnet 456", null, null, 0, 0, null, "", true, false, "", false, "", true, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, HostKeyVerificationStrategyEnum.CHECK_NEW_HARD, Tenancy.Default, EbsEncryptRootVolume.DEFAULT, true, true, 2);
List<SlaveTemplate> templates = Collections.singletonList(orig);
AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "us-east-1", "ghi", "3", templates, null, null);
r.jenkins.clouds.add(ac);
r.submit(r.createWebClient().goTo("configure").getFormByName("config"));
SlaveTemplate received = ((EC2Cloud) r.jenkins.clouds.iterator().next()).getTemplate(slaveDescription);
r.assertEqualBeans(orig, received, "ami,zone,description,remoteFS,type,javaPath,jvmopts,stopOnTerminate,securityGroups,subnetId,useEphemeralDevices,connectionStrategy,hostKeyVerificationStrategy,metadataEndpointEnabled,metadataTokensRequired,metadataHopsLimit");
}
@Test
public void provisionOnDemandSetsMetadataV2Options() throws Exception {
SlaveTemplate template = new SlaveTemplate("ami-123", EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, "", "bar", "bbb", "aaa", "10", "fff", null, "java", "-Xmx1g", false, "subnet 456", null, null, 0, 0, null, "", true, false, "", false, "", true, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, HostKeyVerificationStrategyEnum.CHECK_NEW_HARD, Tenancy.Default, EbsEncryptRootVolume.DEFAULT, true, true, 2);
AmazonEC2 mockedEC2 = setupTestForProvisioning(template);
ArgumentCaptor<RunInstancesRequest> riRequestCaptor = ArgumentCaptor.forClass(RunInstancesRequest.class);
template.provision(2, EnumSet.noneOf(ProvisionOptions.class));
verify(mockedEC2).runInstances(riRequestCaptor.capture());
RunInstancesRequest actualRequest = riRequestCaptor.getValue();
InstanceMetadataOptionsRequest metadataOptionsRequest = actualRequest.getMetadataOptions();
assertEquals(metadataOptionsRequest.getHttpEndpoint(), InstanceMetadataEndpointState.Enabled.toString());
assertEquals(metadataOptionsRequest.getHttpTokens(), HttpTokensState.Required.toString());
assertEquals(metadataOptionsRequest.getHttpPutResponseHopLimit(), Integer.valueOf(2));
}
@Test
public void provisionOnDemandSetsMetadataDefaultOptions() throws Exception {
SlaveTemplate template = new SlaveTemplate("ami-123", EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, false, "ttt", Node.Mode.NORMAL, "", "bar", "bbb", "aaa", "10", "fff", null, "java", "-Xmx1g", false, "subnet 456", null, null, 0, 0, null, "", true, false, "", false, "", true, false, false, ConnectionStrategy.PUBLIC_IP, -1, null, HostKeyVerificationStrategyEnum.CHECK_NEW_HARD, Tenancy.Default, EbsEncryptRootVolume.DEFAULT, null, true, null);
AmazonEC2 mockedEC2 = setupTestForProvisioning(template);
ArgumentCaptor<RunInstancesRequest> riRequestCaptor = ArgumentCaptor.forClass(RunInstancesRequest.class);
template.provision(2, EnumSet.noneOf(ProvisionOptions.class));
verify(mockedEC2).runInstances(riRequestCaptor.capture());
RunInstancesRequest actualRequest = riRequestCaptor.getValue();
InstanceMetadataOptionsRequest metadataOptionsRequest = actualRequest.getMetadataOptions();
assertEquals(metadataOptionsRequest.getHttpEndpoint(), InstanceMetadataEndpointState.Enabled.toString());
assertEquals(metadataOptionsRequest.getHttpTokens(), HttpTokensState.Required.toString());
assertEquals(metadataOptionsRequest.getHttpPutResponseHopLimit(), Integer.valueOf(1));
}
}
|
package org.cactoos.iterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.NoSuchElementException;
import org.cactoos.list.ListOf;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link Partitioned}.
*
* @author Sven Diedrichsen (sven.diedrichsen@gmail.com)
* @version $Id$
* @since 0.29
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle MagicNumber (500 lines)
*/
public final class PartitionedTest {
@Test
public void emptyPartitioned() {
MatcherAssert.assertThat(
"Can't generate an empty Partitioned.",
new LengthOf(
new Partitioned<>(1, Collections.emptyIterator())
).intValue(),
Matchers.equalTo(0)
);
}
@Test
public void partitionedOne() {
MatcherAssert.assertThat(
"Can't generate a Partitioned of partition size 1.",
new ArrayList<>(
new ListOf<>(
new Partitioned<>(1, Arrays.asList(1, 2, 3).iterator())
)
),
Matchers.equalTo(
Arrays.asList(
Collections.singletonList(1), Collections.singletonList(2),
Collections.singletonList(3)
)
)
);
}
@Test
public void partitionedEqualSize() {
MatcherAssert.assertThat(
"Can't generate a Partitioned of partition size 2.",
new ArrayList<>(
new ListOf<>(
new Partitioned<>(2, new ListOf<>(1, 2, 3, 4).iterator())
)
),
Matchers.equalTo(
Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4))
)
);
}
@Test
public void partitionedLastPartitionSmaller() {
MatcherAssert.assertThat(
"Can't generate a Partitioned of size 2 last partition smaller.",
new ArrayList<>(
new ListOf<>(
new Partitioned<>(2, new ListOf<>(1, 2, 3).iterator())
)
),
Matchers.equalTo(
Arrays.asList(
Arrays.asList(1, 2),
Collections.singletonList(3)
)
)
);
}
@Test(expected = IllegalArgumentException.class)
public void partitionedWithPartitionSizeSmallerOne() {
new Partitioned<>(0, new ListOf<>(1).iterator()).next();
}
@Test(expected = UnsupportedOperationException.class)
public void partitionedListsAreUnmodifiable() {
new Partitioned<>(
2, new ListOf<>(1, 2).iterator()
).next().clear();
}
@Test(expected = NoSuchElementException.class)
public void emptyPartitionedNextThrowsException() {
new Partitioned<>(
2, Collections.emptyList().iterator()
).next();
}
}
|
package org.mvel.tests.main;
import junit.framework.TestCase;
import org.mvel.ExpressionCompiler;
import org.mvel.MVEL;
import org.mvel.debug.DebugTools;
import org.mvel.tests.main.res.Bar;
import org.mvel.tests.main.res.Base;
import org.mvel.tests.main.res.DerivedClass;
import org.mvel.tests.main.res.Foo;
import java.io.Serializable;
import java.util.*;
public class CompiledUnitTest extends TestCase {
protected Foo foo = new Foo();
protected Map<String, Object> map = new HashMap<String, Object>();
protected Base base = new Base();
protected DerivedClass derived = new DerivedClass();
public CompiledUnitTest() {
foo.setBar(new Bar());
map.put("foo", foo);
map.put("a", null);
map.put("b", null);
map.put("c", "cat");
map.put("BWAH", "");
map.put("misc", new MiscTestClass());
map.put("pi", "3.14");
map.put("hour", "60");
map.put("zero", 0);
map.put("testImpl",
new ParserUnitTest.TestInterface() {
public String getName() {
return "FOOBAR!";
}
public boolean isFoo() {
return true;
}
});
map.put("derived", derived);
}
public void testSingleProperty() {
assertEquals(false, parseDirect("fun"));
}
public void testMethodOnValue() {
assertEquals("DOG", parseDirect("foo.bar.name.toUpperCase()"));
}
public void testSimpleProperty() {
assertEquals("dog", parseDirect("foo.bar.name"));
}
public void testPropertyViaDerivedClass() {
assertEquals("cat", parseDirect("derived.data"));
}
public void testThroughInterface() {
assertEquals("FOOBAR!", parseDirect("testImpl.name"));
}
public void testThroughInterface2() {
assertEquals(true, parseDirect("testImpl.foo"));
}
public void testMapAccessWithMethodCall() {
assertEquals("happyBar", parseDirect("funMap['foo'].happy()"));
}
public void testBooleanOperator() {
assertEquals(true, parseDirect("foo.bar.woof == true"));
}
public void testBooleanOperator2() {
assertEquals(false, parseDirect("foo.bar.woof == false"));
}
public void testTextComparison() {
assertEquals(true, parseDirect("foo.bar.name == 'dog'"));
}
public void testNETextComparison() {
assertEquals(true, parseDirect("foo.bar.name != 'foo'"));
}
public void testChor() {
assertEquals("cat", parseDirect("a or b or c"));
}
public void testChorWithLiteral() {
assertEquals("fubar", parseDirect("a or 'fubar'"));
}
public void testNullCompare() {
assertEquals(true, parseDirect("c != null"));
}
public void testUninitializedInt() {
assertEquals(0, parseDirect("sarahl"));
}
public void testAnd() {
assertEquals(true, parseDirect("c != null && foo.bar.name == 'dog' && foo.bar.woof"));
}
public void testMath() {
assertEquals(188.4f, parseDirect("pi * hour"));
}
public void testMath2() {
assertEquals(3, parseDirect("foo.number-1"));
}
public void testComplexExpression() {
assertEquals("bar", parseDirect("a = 'foo'; b = 'bar'; c = 'jim'; list = {a,b,c}; list[1]"));
}
public void testComplexAnd() {
assertEquals(true, parseDirect("(pi * hour) > 0 && foo.happy() == 'happyBar'"));
}
public void testShortPathExpression() {
assertEquals(null, parseDirect("3 > 4 && foo.toUC('test'); foo.register"));
}
public void testShortPathExpression2() {
assertEquals(true, parseDirect("4 > 3 || foo.toUC('test')"));
}
public void testShortPathExpression3() {
assertEquals(false, parseDirect("defnull != null && defnull.length() > 0"));
}
public void testModulus() {
assertEquals(38392 % 2,
parseDirect("38392 % 2"));
}
public void testLessThan() {
assertEquals(true, parseDirect("pi < 3.15"));
assertEquals(true, parseDirect("pi <= 3.14"));
assertEquals(false, parseDirect("pi > 3.14"));
assertEquals(true, parseDirect("pi >= 3.14"));
}
public void testMethodAccess() {
assertEquals("happyBar", parseDirect("foo.happy()"));
}
public void testMethodAccess2() {
assertEquals("FUBAR", parseDirect("foo.toUC('fubar')"));
}
public void testMethodAccess3() {
assertEquals(true, parseDirect("equalityCheck(c, 'cat')"));
}
public void testMethodAccess4() {
assertEquals(null, parseDirect("readBack(null)"));
}
public void testMethodAccess5() {
assertEquals("nulltest", parseDirect("appendTwoStrings(null, 'test')"));
}
public void testNegation() {
assertEquals(true, parseDirect("!fun && !fun"));
}
public void testNegation2() {
assertEquals(false, parseDirect("fun && !fun"));
}
public void testNegation3() {
assertEquals(true, parseDirect("!(fun && fun)"));
}
public void testNegation4() {
assertEquals(false, parseDirect("(fun && fun)"));
}
public void testMultiStatement() {
assertEquals(true, parseDirect("populate(); barfoo == 'sarah'"));
}
public void testAssignment() {
assertEquals(true, parseDirect("populate(); blahfoo = 'sarah'; blahfoo == 'sarah'"));
}
public void testAssignment2() {
assertEquals("sarah", parseDirect("populate(); blahfoo = barfoo"));
}
public void testAssignment3() {
assertEquals(java.lang.Integer.class, parseDirect("blah = 5").getClass());
}
public void testAssignment4() {
assertEquals(102, parseDirect("a = 100 + 1 + 1"));
}
public void testOr() {
assertEquals(true, parseDirect("fun || true"));
}
public void testLiteralPassThrough() {
assertEquals(true, parseDirect("true"));
}
public void testLiteralPassThrough2() {
assertEquals(false, parseDirect("false"));
}
public void testLiteralPassThrough3() {
assertEquals(null, parseDirect("null"));
}
public void testRegEx() {
assertEquals(true, parseDirect("foo.bar.name ~= '[a-z].+'"));
}
public void testRegExNegate() {
assertEquals(false, parseDirect("!(foo.bar.name ~= '[a-z].+')"));
}
public void testRegEx2() {
assertEquals(true, parseDirect("foo.bar.name ~= '[a-z].+' && foo.bar.name != null"));
}
public void testBlank() {
assertEquals(true, parseDirect("'' == empty"));
}
public void testBlank2() {
assertEquals(true, parseDirect("BWAH == empty"));
}
public void testBooleanModeOnly2() {
assertEquals(false, (Object) MVEL.evalToBoolean("BWAH", base, map));
}
public void testBooleanModeOnly4() {
assertEquals(true, (Object) MVEL.evalToBoolean("hour == (hour + 0)", base, map));
}
public void testTernary() {
assertEquals("foobie", parseDirect("zero==0?'foobie':zero"));
}
public void testTernary2() {
assertEquals("blimpie", parseDirect("zero==1?'foobie':'blimpie'"));
}
public void testTernary3() {
assertEquals("foobiebarbie", parseDirect("zero==1?'foobie':'foobie'+'barbie'"));
}
public void testStrAppend() {
assertEquals("foobarcar", parseDirect("'foo' + 'bar' + 'car'"));
}
public void testStrAppend2() {
assertEquals("foobarcar1", parseDirect("'foobar' + 'car' + 1"));
}
public void testInstanceCheck1() {
assertEquals(true, parseDirect("c is 'java.lang.String'"));
}
public void testInstanceCheck2() {
assertEquals(false, parseDirect("pi is 'java.lang.Integer'"));
}
public void testBitwiseOr1() {
assertEquals(6, parseDirect("2 | 4"));
}
public void testBitwiseOr2() {
assertEquals(true, parseDirect("(2 | 1) > 0"));
}
public void testBitwiseOr3() {
assertEquals(true, parseDirect("(2 | 1) == 3"));
}
public void testBitwiseAnd1() {
assertEquals(2, parseDirect("2 & 3"));
}
public void testShiftLeft() {
assertEquals(4, parseDirect("2 << 1"));
}
public void testUnsignedShiftLeft() {
assertEquals(2, parseDirect("-2 <<< 0"));
}
public void testShiftRight() {
assertEquals(128, parseDirect("256 >> 1"));
}
public void testXOR() {
assertEquals(3, parseDirect("1 ^ 2"));
}
public void testContains1() {
assertEquals(true, parseDirect("list contains 'Happy!'"));
}
public void testContains2() {
assertEquals(false, parseDirect("list contains 'Foobie'"));
}
public void testContains3() {
assertEquals(true, parseDirect("sentence contains 'fox'"));
}
public void testContains4() {
assertEquals(false, parseDirect("sentence contains 'mike'"));
}
public void testContains5() {
assertEquals(true, parseDirect("!(sentence contains 'mike')"));
}
public void testInvert() {
assertEquals(~10, parseDirect("~10"));
}
public void testInvert2() {
assertEquals(~(10 + 1), parseDirect("~(10 + 1)"));
}
public void testInvert3() {
assertEquals(~10 + (1 + ~50), parseDirect("~10 + (1 + ~50)"));
}
public void testListCreation2() {
assertTrue(parseDirect("[\"test\"]") instanceof List);
}
public void testListCreation3() {
assertTrue(parseDirect("[66]") instanceof List);
}
public void testListCreation4() {
List ar = (List) parseDirect("[ 66 , \"test\" ]");
assertEquals(2, ar.size());
assertEquals(66, ar.get(0));
assertEquals("test", ar.get(1));
}
public void testListCreationWithCall() {
assertEquals(1, parseDirect("[\"apple\"].size()"));
}
public void testArrayCreationWithLength() {
assertEquals(2, parseDirect("Array.getLength({'foo', 'bar'})"));
}
public void testEmptyList() {
assertTrue(parseDirect("[]") instanceof List);
}
public void testEmptyArray() {
assertTrue(((Object[]) parseDirect("{}")).length == 0);
}
public void testArrayCreation() {
assertEquals(0, parseDirect("arrayTest = {{1, 2, 3}, {2, 1, 0}}; arrayTest[1][2]"));
}
public void testMapCreation() {
assertEquals("sarah", parseDirect("map = ['mike':'sarah','tom':'jacquelin']; map['mike']"));
}
public void testMapCreation2() {
assertEquals("sarah", parseDirect("map = ['mike' :'sarah' ,'tom' :'jacquelin' ]; map['mike']"));
}
public void testProjectionSupport() {
assertEquals(true, parseDirect("(name in things) contains 'Bob'"));
}
public void testProjectionSupport2() {
assertEquals(3, parseDirect("(name in things).size()"));
}
public void testStaticMethodFromLiteral() {
assertEquals(String.class.getName(), parseDirect("String.valueOf(Class.forName('java.lang.String').getName())"));
}
public void testMethodCallsEtc() {
parseDirect("title = 1; " +
"frame = new javax.swing.JFrame; " +
"label = new javax.swing.JLabel; " +
"title = title + 1;" +
"frame.setTitle(title);" +
"label.setText('MVEL UNIT TEST PACKAGE -- IF YOU SEE THIS, THAT IS GOOD');" +
"frame.getContentPane().add(label);" +
"frame.pack();" +
"frame.setVisible(true);");
}
public void testObjectInstantiation() {
parseDirect("new java.lang.String('foobie')");
}
public void testObjectInstantiationWithMethodCall() {
parseDirect("new String('foobie').toString()");
}
public void testObjectInstantiation2() {
parseDirect("new String() is String");
}
public void testObjectInstantiation3() {
parseDirect("new java.text.SimpleDateFormat('yyyy').format(new java.util.Date(System.currentTimeMillis()))");
}
public void testArrayCoercion() {
assertEquals("gonk", parseDirect("funMethod( {'gonk', 'foo'} )"));
}
public void testArrayCoercion2() {
assertEquals(10, parseDirect("sum({2,2,2,2,2})"));
}
public void testMapAccess() {
assertEquals("dog", parseDirect("funMap['foo'].bar.name"));
}
public void testMapAccess2() {
assertEquals("dog", parseDirect("funMap.foo.bar.name"));
}
public void testSoundex() {
assertTrue((Boolean) parseDirect("'foobar' soundslike 'fubar'"));
}
public void testSoundex2() {
assertFalse((Boolean) parseDirect("'flexbar' soundslike 'fubar'"));
}
public void testThisReference() {
assertEquals(true, parseDirect("this") instanceof Base);
}
public void testThisReference2() {
assertEquals(true, parseDirect("this.funMap") instanceof Map);
}
public void testThisReference3() {
assertEquals(true, parseDirect("this is 'org.mvel.tests.main.res.Base'"));
}
public void testStringEscaping() {
assertEquals("\"Mike Brock\"", parseDirect("\"\\\"Mike Brock\\\"\""));
}
public void testStringEscaping2() {
assertEquals("MVEL's Parser is Fast", parseDirect("'MVEL\\'s Parser is Fast'"));
}
public void testEvalToBoolean() {
assertEquals(true, (boolean) MVEL.evalToBoolean("true ", "true"));
assertEquals(true, (boolean) MVEL.evalToBoolean("true ", "true"));
}
public void testCompiledMapStructures() {
Serializable compiled = MVEL.compileExpression("['foo':'bar'] contains 'foo'");
MVEL.executeExpression(compiled, null, null, Boolean.class);
}
public void testSubListInMap() {
assertEquals("pear", parseDirect("map = ['test' : 'poo', 'foo' : [c, 'pear']]; map['foo'][1]"));
}
public void testCompiledMethodCall() {
Serializable compiled = MVEL.compileExpression("c.getClass()");
assertEquals(String.class, MVEL.executeExpression(compiled, base, map));
}
public void testStaticNamespaceCall() {
assertEquals(java.util.ArrayList.class, parseDirect("java.util.ArrayList"));
}
public void testStaticNamespaceClassWithMethod() {
assertEquals("FooBar", parseDirect("java.lang.String.valueOf('FooBar')"));
}
public void testThisReferenceInMethodCall() {
assertEquals(101, parseDirect("Integer.parseInt(this.number)"));
}
public void testThisReferenceInConstructor() {
assertEquals("101", parseDirect("new String(this.number)"));
}
public void testStaticNamespaceClassWithField() {
assertEquals(Integer.MAX_VALUE, parseDirect("java.lang.Integer.MAX_VALUE"));
}
public void testStaticNamespaceClassWithField2() {
assertEquals(Integer.MAX_VALUE, parseDirect("Integer.MAX_VALUE"));
}
public void testStaticFieldAsMethodParm() {
assertEquals(String.valueOf(Integer.MAX_VALUE), parseDirect("String.valueOf(Integer.MAX_VALUE)"));
}
public void testIf() {
assertEquals(10, parseDirect("if (5 > 4) { return 10; } else { return 5; }"));
}
public void testIf2() {
assertEquals(10, parseDirect("if (5 < 4) { return 5; } else { return 10; }"));
}
public void testIfAndElse() {
assertEquals(true, parseDirect("if (false) { return false; } else { return true; }"));
}
public void testIfAndElseif() {
assertEquals(true, parseDirect("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;"));
}
public void testIfAndElseIfCondensedGrammar() {
assertEquals("Foo", parseDirect("if (false) return 'Bar'; else return 'Foo';"));
}
public void testForeEach2() {
assertEquals(6, parseDirect("total = 0; a = {1,2,3}; foreach(item : a) { total = total + item }; total"));
}
public void testForEach3() {
assertEquals(true, parseDirect("a = {1,2,3}; foreach (i : a) { if (i == 1) { return true; } }"));
}
public void testForEach4() {
assertEquals("OneTwoThreeFour", parseDirect("a = {1,2,3,4}; builder = ''; foreach (i : a) {" +
" if (i == 1) { builder = builder + 'One' } else if (i == 2) { builder = builder + 'Two' } " +
"else if (i == 3) { builder = builder + 'Three' } else { builder = builder + 'Four' }" +
"}; builder;"));
}
public void testWith() {
assertEquals("OneTwo", parseDirect("with (foo) {aValue = 'One',bValue='Two'}; foo.aValue + foo.bValue;"));
}
public void testAssertion() {
try {
parseDirect("assert false");
assertTrue(false);
}
catch (AssertionError error) {
}
}
public void testAssertion2() {
try {
parseDirect("assert true;");
}
catch (AssertionError error) {
assertTrue(false);
}
}
public void testVarInputs() {
ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); bleh = foo; twa = bleh");
compiler.compile(true);
assertTrue(compiler.getInputs().contains("test"));
assertTrue(compiler.getInputs().contains("foo"));
assertTrue(compiler.getInputs().contains("bo"));
assertTrue(compiler.getInputs().contains("trouble"));
assertTrue(compiler.getLocals().contains("bleh"));
assertTrue(compiler.getLocals().contains("twa"));
}
public Object parseDirect(String ex) {
return compiledExecute(ex);
}
public Object compiledExecute(String ex) {
Serializable compiled = MVEL.compileExpression(ex);
System.out.println(DebugTools.decompile(compiled));
Object first = MVEL.executeExpression(compiled, base, map);
Object second = MVEL.executeExpression(compiled, base, map);
if (first != null && !first.getClass().isArray())
assertEquals(first, second);
return second;
}
public Object compiledExecute(String ex, Object base, Map map) {
Serializable compiled = MVEL.compileExpression(ex);
Object first = MVEL.executeExpression(compiled, base, map);
Object second = MVEL.executeExpression(compiled, base, map);
if (first != null && !first.getClass().isArray())
assertSame(first, second);
return second;
}
public void testDifferentImplSameCompile() {
Serializable compiled = MVEL.compileExpression("a.funMap.hello");
Map testMap = new HashMap();
for (int i = 0; i < 100; i++) {
Base b = new Base();
b.funMap.put("hello", "dog");
testMap.put("a", b);
assertEquals("dog", MVEL.executeExpression(compiled, testMap));
b = new Base();
b.funMap.put("hello", "cat");
testMap.put("a", b);
assertEquals("cat", MVEL.executeExpression(compiled, testMap));
}
}
public void testToList() {
String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )";
List list = (List) parseDirect(text);
assertSame("dog", list.get(0));
assertEquals("hello", list.get(1));
assertEquals(new Integer(42), list.get(2));
Map map = (Map) list.get(3);
assertEquals("value1", map.get("key1"));
List nestedList = (List) map.get("cat");
assertEquals(14, nestedList.get(0));
assertEquals("car", nestedList.get(1));
assertEquals(42, nestedList.get(2));
nestedList = (List) list.get(4);
assertEquals(42, nestedList.get(0));
map = (Map) nestedList.get(1);
assertEquals("value1", map.get("cat"));
}
public void testToList2() {
for (int i = 0; i < 10; i++) {
testToList();
}
}
public static class MiscTestClass {
int exec = 0;
public List toList(Object object1, String string, int integer, Map map, List list) {
exec++;
List l = new ArrayList();
l.add(object1);
l.add(string);
l.add(new Integer(integer));
l.add(map);
l.add(list);
return l;
}
public int getExec() {
return exec;
}
}
public void testCalculateAge() {
// System.out.println("Calculating the Age");
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0, 10); // 1999 jan 20
Map objectMap = new HashMap(1);
Map propertyMap = new HashMap(1);
propertyMap.put("GEBDAT", c1.getTime());
objectMap.put("EV_VI_ANT1", propertyMap);
assertEquals("N", compiledExecute("new org.mvel.tests.main.res.PDFFieldUtil().calculateAge(EV_VI_ANT1.GEBDAT) >= 25 ? 'Y' : 'N'"
, null, objectMap));
}
}
|
package se.kits.gakusei.test_tools;
import se.kits.gakusei.content.model.Course;
import se.kits.gakusei.content.model.Fact;
import se.kits.gakusei.content.model.Lesson;
import se.kits.gakusei.content.model.Nugget;
import java.util.*;
public class TestTools {
public static List<Nugget> generateNuggets() {
List<Nugget> nuggets = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Nugget n = new Nugget("verb");
n.setId("nuggetid" + i);
Fact f1 = new Fact();
f1.setType("swedish");
f1.setData("swe_test" + i);
f1.setNugget(n);
Fact f2 = new Fact();
f2.setType("english");
f2.setData("eng_test" + i);
f2.setNugget(n);
n.setFacts(new ArrayList<Fact>(Arrays.asList(f1, f2)));
if (i % 3 == 0) {
n.setHidden(true);
}
nuggets.add(n);
}
return nuggets;
}
public static Nugget generateQuizNugget(String description, String correctData, String incorrectData) {
Nugget n = new Nugget("quiz");
n.setDescription(description);
Fact correctFact = new Fact();
correctFact.setType("correct");
correctFact.setData(correctData);
correctFact.setNugget(n);
List<Fact> facts = new ArrayList<>();
facts.add(correctFact);
for (int i = 0; i < 5; i++) {
Fact incorrectFact = new Fact();
incorrectFact.setType("incorrect");
incorrectFact.setData(incorrectData + i);
incorrectFact.setNugget(n);
facts.add(incorrectFact);
}
n.setFacts(facts);
return n;
}
public static Lesson generateQuizLesson(String lessonName, String description, String correctData, String incorrectData) {
Lesson lesson = new Lesson();
lesson.setName(lessonName);
List<Nugget> nuggets = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Nugget n = generateQuizNugget(description, correctData, incorrectData);
n.setLessons(Collections.singletonList(lesson));
nuggets.add(n);
}
return lesson;
}
public static HashMap<String, Object> generateQuestion() {
List<String> question = new ArrayList<>();
question.add("question");
List<String> alt1 = Arrays.asList("alternative1");
List<String> alt2 = Arrays.asList("alternative2");
List<String> alt3 = Arrays.asList("alternative3");
List<String> altCorrect = Arrays.asList("alternativeCorrect");
HashMap<String, Object> dto = new HashMap<>();
dto.put("question", question);
dto.put("alternative1", alt1);
dto.put("alternative2", alt2);
dto.put("alternative3", alt3);
dto.put("correctAlternative", altCorrect);
return dto;
}
public static Course generateCourse(){
Course course = new Course();
course.setName("Test course");
return course;
}
}
|
package seedu.manager.logic;
import com.google.common.eventbus.Subscribe;
import seedu.manager.commons.core.EventsCenter;
import seedu.manager.commons.events.model.TaskManagerChangedEvent;
import seedu.manager.commons.events.ui.JumpToListRequestEvent;
import seedu.manager.commons.events.ui.ShowHelpRequestEvent;
import seedu.manager.logic.Logic;
import seedu.manager.logic.LogicManager;
import seedu.manager.logic.commands.*;
import seedu.manager.model.TaskManager;
import seedu.manager.model.Model;
import seedu.manager.model.ModelManager;
import seedu.manager.model.ReadOnlyTaskManager;
import seedu.manager.model.tag.Tag;
import seedu.manager.model.tag.UniqueTagList;
import seedu.manager.model.task.*;
import seedu.manager.storage.StorageManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static seedu.manager.commons.core.Messages.*;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyTaskManager latestSavedTaskManager;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(TaskManagerChangedEvent abce) {
latestSavedTaskManager = new TaskManager(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setup() {
model = new ModelManager();
String tempTaskManagerFile = saveFolder.getRoot().getPath() + "TempTaskManager.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempTaskManagerFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedTaskManager = new TaskManager(model.getTaskManager()); // last saved assumed to be up to date before.
helpShown = false;
targetedJumpIndex = -1; // non yet
}
@After
public void teardown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() throws Exception {
String invalidCommand = " ";
assertCommandBehavior(invalidCommand,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command and confirms that the result message is correct.
* Both the 'task manager' and the 'last shown list' are expected to be empty.
* @see #assertCommandBehavior(String, String, ReadOnlyTaskManager, List)
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception {
assertCommandBehavior(inputCommand, expectedMessage, new TaskManager(), Collections.emptyList());
}
/**
* Executes the command and confirms that the result message is correct and
* also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal task manager data are same as those in the {@code expectedTaskManager} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedTaskManager} was saved to the storage file. <br>
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage,
ReadOnlyTaskManager expectedTaskManager,
List<? extends ReadOnlyTask> expectedShownList) throws Exception {
//Execute the command
CommandResult result = logic.execute(inputCommand);
//Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getFilteredTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTaskManager, model.getTaskManager());
assertEquals(expectedTaskManager, latestSavedTaskManager);
}
@Test
public void execute_unknownCommandWord() throws Exception {
String unknownCommand = "uicfhmowqewca";
assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() throws Exception {
assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
}
@Test
public void execute_exit() throws Exception {
assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT);
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new TaskManager(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
assertCommandBehavior(
"add wrong args wrong args", expectedMessage);
assertCommandBehavior(
"add Valid Desc 12345 e/valid@time.butNoVenuePrefix a/med", expectedMessage);
assertCommandBehavior(
"add Valid Desc p/12345 valid@time.butNoPrefix a/low", expectedMessage);
assertCommandBehavior(
"add Valid Desc p/12345 e/valid@time.butNoAddressPrefix low", expectedMessage);
}
@Test
public void execute_add_invalidTaskData() throws Exception {
assertCommandBehavior(
"add []\\[;] p/12345 e/valid@e.mail a/low", Desc.MESSAGE_DESC_CONSTRAINTS);
// assertCommandBehavior(
// "add Valid Desc p/not_numbers e/valid@e.mail a/low", Venue.MESSAGE_VENUE_CONSTRAINTS);
// assertCommandBehavior(
// "add Valid Desc p/12345 e/notAnTime a/med", Time.MESSAGE_CONSTRAINTS);
assertCommandBehavior(
"add Valid Desc p/12345 e/valid@e.mail a/med t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.adam();
TaskManager expectedAB = new TaskManager();
expectedAB.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.adam();
TaskManager expectedAB = new TaskManager();
expectedAB.addTask(toBeAdded);
// setup starting state
model.addTask(toBeAdded); // task already in internal task manager
// execute command and verify result
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_PERSON,
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_list_showsAllTasks() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
TaskManager expectedAB = helper.generateTaskManager(2);
List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList();
// prepare task manager state
helper.addToModel(model, 2);
assertCommandBehavior("list",
ListCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception {
assertCommandBehavior(commandWord , expectedMessage); //index missing
assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandBehavior(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_PERSON_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set AB state to 2 tasks
model.resetData(new TaskManager());
for (Task p : taskList) {
model.addTask(p);
}
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getTaskManager(), taskList);
}
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
@Test
public void execute_select_jumpsToCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
TaskManager expectedAB = helper.generateTaskManager(threeTasks);
helper.addToModel(model, threeTasks);
assertCommandBehavior("select 2",
String.format(SelectCommand.MESSAGE_SELECT_PERSON_SUCCESS, 2),
expectedAB,
expectedAB.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1));
}
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
@Test
public void execute_delete_removesCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
TaskManager expectedAB = helper.generateTaskManager(threeTasks);
expectedAB.removeTask(threeTasks.get(1));
helper.addToModel(model, threeTasks);
assertCommandBehavior("delete 2",
String.format(DeleteCommand.MESSAGE_DELETE_PERSON_SUCCESS, threeTasks.get(1)),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandBehavior("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInDescs() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithDesc("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithDesc("bla KEY bla bceofeia");
Task p1 = helper.generateTaskWithDesc("KE Y");
Task p2 = helper.generateTaskWithDesc("KEYKEYKEY sduauo");
List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2);
TaskManager expectedAB = helper.generateTaskManager(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2);
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithDesc("bla bla KEY bla");
Task p2 = helper.generateTaskWithDesc("bla KEY bla bceofeia");
Task p3 = helper.generateTaskWithDesc("key key");
Task p4 = helper.generateTaskWithDesc("KEy sduauo");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
TaskManager expectedAB = helper.generateTaskManager(fourTasks);
List<Task> expectedList = fourTasks;
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithDesc("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithDesc("bla rAnDoM bla bceofeia");
Task pTarget3 = helper.generateTaskWithDesc("key key");
Task p1 = helper.generateTaskWithDesc("sduauo");
List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3);
TaskManager expectedAB = helper.generateTaskManager(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3);
helper.addToModel(model, fourTasks);
assertCommandBehavior("find key rAnDoM",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper{
Task adam() throws Exception {
Desc desc = new Desc("Adam Brown");
Venue privateVenue = new Venue("111111");
Time time = new Time("adam@gmail.com");
Priority privatePriority = new Priority("med");
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("tag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new Task(desc, privateVenue, time, privatePriority, tags);
}
/**
* Generates a valid task using the given seed.
* Running this function with the same parameter values guarantees the returned task will have the same state.
* Each unique seed will generate a unique Task object.
*
* @param seed used to generate the task data field values
*/
Task generateTask(int seed) throws Exception {
return new Task(
new Desc("Task " + seed),
new Venue("" + Math.abs(seed)),
new Time(seed + "@time"),
new Priority(new String[] {"low", "med", "high"}[seed % 3]),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))
);
}
/** Generates the correct add command based on the task given */
String generateAddCommand(Task p) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append(p.getDesc().toString());
cmd.append(" p/").append(p.getVenue());
cmd.append(" e/").append(p.getTime());
cmd.append(" a/").append(p.getPriority());
UniqueTagList tags = p.getTags();
for(Tag t: tags){
cmd.append(" t/").append(t.tagName);
}
return cmd.toString();
}
/**
* Generates an TaskManager with auto-generated tasks.
*/
TaskManager generateTaskManager(int numGenerated) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, numGenerated);
return taskManager;
}
/**
* Generates an TaskManager based on the list of Tasks given.
*/
TaskManager generateTaskManager(List<Task> tasks) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, tasks);
return taskManager;
}
/**
* Adds auto-generated Task objects to the given TaskManager
* @param taskManager The TaskManager to which the Tasks will be added
*/
void addToTaskManager(TaskManager taskManager, int numGenerated) throws Exception{
addToTaskManager(taskManager, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given TaskManager
*/
void addToTaskManager(TaskManager taskManager, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
taskManager.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
* @param model The model to which the Tasks will be added
*/
void addToModel(Model model, int numGenerated) throws Exception{
addToModel(model, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given model
*/
void addToModel(Model model, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
model.addTask(p);
}
}
/**
* Generates a list of Tasks based on the flags.
*/
List<Task> generateTaskList(int numGenerated) throws Exception{
List<Task> tasks = new ArrayList<>();
for(int i = 1; i <= numGenerated; i++){
tasks.add(generateTask(i));
}
return tasks;
}
List<Task> generateTaskList(Task... tasks) {
return Arrays.asList(tasks);
}
/**
* Generates a Task object with given desc. Other fields will have some dummy values.
*/
Task generateTaskWithDesc(String desc) throws Exception {
return new Task(
new Desc(desc),
new Venue("1"),
new Time("1@time"),
new Priority("low"),
new UniqueTagList(new Tag("tag"))
);
}
}
}
|
package org.apache.lucene;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.lucene.store.*;
import org.apache.lucene.document.*;
import org.apache.lucene.analysis.*;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.queryParser.*;
class SearchTestForDuplicates {
static final String PRIORITY_FIELD ="priority";
static final String ID_FIELD ="id";
static final String HIGH_PRIORITY ="high";
static final String MED_PRIORITY ="medium";
static final String LOW_PRIORITY ="low";
public static void main(String[] args) {
try {
Directory directory = new RAMDirectory();
Analyzer analyzer = new SimpleAnalyzer();
IndexWriter writer = new IndexWriter(directory, analyzer, true);
final int MAX_DOCS = 225;
for (int j = 0; j < MAX_DOCS; j++) {
Document d = new Document();
d.add(Field.Text(PRIORITY_FIELD, HIGH_PRIORITY));
d.add(Field.Text(ID_FIELD, Integer.toString(j)));
writer.addDocument(d);
}
writer.close();
// try a search without OR
Searcher searcher = new IndexSearcher(directory);
Hits hits = null;
QueryParser parser = new QueryParser(PRIORITY_FIELD, analyzer);
Query query = parser.parse(HIGH_PRIORITY);
System.out.println("Query: " + query.toString(PRIORITY_FIELD));
hits = searcher.search(query);
printHits(hits);
searcher.close();
// try a new search with OR
searcher = new IndexSearcher(directory);
hits = null;
parser = new QueryParser(PRIORITY_FIELD, analyzer);
query = parser.parse(HIGH_PRIORITY + " OR " + MED_PRIORITY);
System.out.println("Query: " + query.toString(PRIORITY_FIELD));
hits = searcher.search(query);
printHits(hits);
searcher.close();
} catch (Exception e) {
System.out.println(" caught a " + e.getClass() +
"\n with message: " + e.getMessage());
}
}
private static void printHits( Hits hits ) throws IOException {
System.out.println(hits.length() + " total results\n");
for (int i = 0 ; i < hits.length(); i++) {
if ( i < 10 || (i > 94 && i < 105) ) {
Document d = hits.doc(i);
System.out.println(i + " " + d.get(ID_FIELD));
}
}
}
}
|
package us.kbase.typedobj.tests;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import us.kbase.typedobj.core.TypeDefId;
import us.kbase.typedobj.core.TypeDefName;
import us.kbase.typedobj.core.TypedObjectValidationReport;
import us.kbase.typedobj.core.TypedObjectValidator;
import us.kbase.typedobj.db.FileTypeStorage;
import us.kbase.typedobj.db.TypeDefinitionDB;
import us.kbase.workspace.kbase.Util;
import us.kbase.workspace.test.WorkspaceTestCommon;
/**
* Tests that ensure the proper subset is extracted from a typed object instance
*
* To add new tests of the ID processing machinery, add files named in the format:
* [ModuleName].[TypeName].instance.[label]
* - json encoding of a valid type instance
* [ModuleName].[TypeName].instance.[label].subset
* - json encoding of the expected '\@searchable ws_subset' output
*
* @author msneddon
*/
@RunWith(value = Parameterized.class)
public class TestWsSubsetExtraction {
/**
* location to stash the temporary database for testing
* WARNING: THIS DIRECTORY WILL BE WIPED OUT AFTER TESTS!!!!
*/
private final static String TEST_DB_LOCATION = "test/typedobj_temp_test_files/t3";
/**
* relative location to find the input files
*/
private final static String TEST_RESOURCE_LOCATION = "files/t3/";
private final static boolean VERBOSE = true;
private static TypeDefinitionDB db;
private static TypedObjectValidator validator;
/**
* List to stash the handle to the test case files
*/
private static List<TestInstanceInfo> instanceResources = new ArrayList <TestInstanceInfo> ();
private static class TestInstanceInfo {
public TestInstanceInfo(String resourceName, String moduleName, String typeName) {
this.resourceName = resourceName;
this.moduleName = moduleName;
this.typeName = typeName;
}
public String resourceName;
public String moduleName;
public String typeName;
}
/**
* As each test instance object is created, this sets which instance to actually test
*/
private TestInstanceInfo instance;
public TestWsSubsetExtraction(TestInstanceInfo tii) {
this.instance = tii;
}
/**
* This is invoked before anything else, so here we invoke the creation of the db
* @return
* @throws Exception
*/
@Parameters
public static Collection<Object[]> assembleTestInstanceList() throws Exception {
prepareDb();
Object [][] instanceInfo = new Object[instanceResources.size()][1];
for(int k=0; k<instanceResources.size(); k++) {
instanceInfo[k][0] = instanceResources.get(k);
}
return Arrays.asList(instanceInfo);
}
/**
* Setup the typedef database, load and release the types in the simple specs, and
* identify all the files containing instances to validate.
* @throws Exception
*/
public static void prepareDb() throws Exception
{
//ensure test location is available
File dir = new File(TEST_DB_LOCATION);
if (dir.exists()) {
//fail("database at location: "+TEST_DB_LOCATION+" already exists, remove/rename this directory first");
removeDb();
}
if(!dir.mkdirs()) {
fail("unable to create needed test directory: "+TEST_DB_LOCATION);
}
if(VERBOSE) System.out.println("setting up the typed obj database");
// point the type definition db to point there
File tempdir = new File("temp_files");
if (!dir.exists())
dir.mkdir();
db = new TypeDefinitionDB(new FileTypeStorage(TEST_DB_LOCATION), tempdir,
new Util().getKIDLpath(), WorkspaceTestCommon.getKidlSource());
// create a validator that uses the type def db
validator = new TypedObjectValidator(db);
String username = "wstester1";
String kbSpec = loadResourceFile(TEST_RESOURCE_LOCATION+"KB.spec");
List<String> kb_types = Arrays.asList("SimpleStructure","MappingStruct","ListStruct","DeepMaps","NestedData");
db.requestModuleRegistration("KB", username);
db.approveModuleRegistrationRequest(username, "KB", true);
db.registerModule(kbSpec ,kb_types, username);
db.releaseModule("KB", username, false);
if(VERBOSE) System.out.print("finding test instances...");
String [] resources = getResourceListing(TEST_RESOURCE_LOCATION);
for(int k=0; k<resources.length; k++) {
String [] tokens = resources[k].split("\\.");
if(tokens.length!=4) { continue; }
if(tokens[2].equals("instance")) {
instanceResources.add(new TestInstanceInfo(resources[k],tokens[0],tokens[1]));
}
}
if(VERBOSE) System.out.println(" " + instanceResources.size() + " found");
}
@AfterClass
public static void removeDb() throws IOException {
File dir = new File(TEST_DB_LOCATION);
FileUtils.deleteDirectory(dir);
if(VERBOSE) System.out.println("deleting typed obj database");
}
@Test
public void testValidInstances() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
//read the instance data
if(VERBOSE) System.out.println(" -("+instance.resourceName+")");
String instanceJson = loadResourceFile(TEST_RESOURCE_LOCATION+instance.resourceName);
JsonNode instanceRootNode = mapper.readTree(instanceJson);
// read the ids file, which provides the list of ids we expect to extract from the instance
String expectedSubsetString = loadResourceFile(TEST_RESOURCE_LOCATION+instance.resourceName+".subset");
JsonNode expectedSubset = mapper.readTree(expectedSubsetString);
// perform the initial validation, which must validate!
TypedObjectValidationReport report =
validator.validate(
instanceRootNode,
new TypeDefId(new TypeDefName(instance.moduleName,instance.typeName))
);
List <String> mssgs = report.getErrorMessagesAsList();
for(int i=0; i<mssgs.size(); i++) {
System.out.println(" ["+i+"]:"+mssgs.get(i));
}
assertTrue(" -("+instance.resourceName+") does not validate, but should",
report.isInstanceValid());
JsonNode actualSubset = report.extractSearchableWsSubset(-1);
// we can just check if they are equal like so:
//assertTrue(" -("+instance.resourceName+") extracted subset does not match expected extracted subset",
// actualSubset.equals(expectedSubset));
// this method generates a patch, so that if they differ you can see what's up
compare(expectedSubset, actualSubset, instance.resourceName);
}
public void compare(JsonNode expectedSubset, JsonNode actualSubset, String resourceName) throws IOException {
assertEquals(" -("+instance.resourceName+") extracted subset does not match expected extracted subset",
sortJson(expectedSubset), sortJson(actualSubset));
}
private static JsonNode sortJson(JsonNode tree) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
Object map = mapper.treeToValue(tree, Object.class);
String text = mapper.writeValueAsString(map);
return mapper.readTree(text);
}
/**
* helper method to load test files, mostly copied from TypeRegistering test
*/
private static String loadResourceFile(String resourceName) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
InputStream is = TestWsSubsetExtraction.class.getResourceAsStream(resourceName);
if (is == null)
throw new IllegalStateException("Resource not found: " + resourceName);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
String line = br.readLine();
if (line == null)
break;
pw.println(line);
}
br.close();
pw.close();
return sw.toString();
}
private static String[] getResourceListing(String path) throws URISyntaxException, IOException {
URL dirURL = TestWsSubsetExtraction.class.getResource(path);
if (dirURL != null && dirURL.getProtocol().equals("file")) {
/* A file path: easy enough */
return new File(dirURL.toURI()).list();
}
if (dirURL == null) {
// In case of a jar file, we can't actually find a directory.
// Have to assume the same jar as the class.
String me = TestWsSubsetExtraction.class.getName().replace(".", "/")+".class";
dirURL = TestWsSubsetExtraction.class.getResource(me);
}
if (dirURL.getProtocol().equals("jar")) {
/* A JAR path */
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
while(entries.hasMoreElements()) {
String name = entries.nextElement().getName();
// construct internal jar path relative to the class
String fullPath = TestWsSubsetExtraction.class.getPackage().getName().replace(".","/") + "/" + path;
if (name.startsWith(fullPath)) { //filter according to the path
String entry = name.substring(fullPath.length());
int checkSubdir = entry.indexOf("/");
if (checkSubdir >= 0) {
// if it is a subdirectory, we just return the directory name
entry = entry.substring(0, checkSubdir);
}
result.add(entry);
}
}
jar.close();
return result.toArray(new String[result.size()]);
}
throw new UnsupportedOperationException("Cannot list files for URL "+dirURL);
}
}
|
package timber.lint;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.tools.lint.checks.StringFormatDetector;
import com.android.tools.lint.client.api.JavaParser;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.ClassContext;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.Speed;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import lombok.ast.AstVisitor;
import lombok.ast.BinaryExpression;
import lombok.ast.BinaryOperator;
import lombok.ast.BooleanLiteral;
import lombok.ast.CharLiteral;
import lombok.ast.Expression;
import lombok.ast.ExpressionStatement;
import lombok.ast.FloatingPointLiteral;
import lombok.ast.If;
import lombok.ast.InlineIfExpression;
import lombok.ast.IntegralLiteral;
import lombok.ast.MethodInvocation;
import lombok.ast.Node;
import lombok.ast.NullLiteral;
import lombok.ast.StrictListAccessor;
import lombok.ast.StringLiteral;
import lombok.ast.VariableReference;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import static com.android.tools.lint.client.api.JavaParser.TYPE_BOOLEAN;
import static com.android.tools.lint.client.api.JavaParser.TYPE_BYTE;
import static com.android.tools.lint.client.api.JavaParser.TYPE_CHAR;
import static com.android.tools.lint.client.api.JavaParser.TYPE_DOUBLE;
import static com.android.tools.lint.client.api.JavaParser.TYPE_FLOAT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_INT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_LONG;
import static com.android.tools.lint.client.api.JavaParser.TYPE_NULL;
import static com.android.tools.lint.client.api.JavaParser.TYPE_OBJECT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_SHORT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_STRING;
public final class WrongTimberUsageDetector extends Detector implements Detector.JavaScanner,
Detector.ClassScanner {
private final static String GET_STRING_METHOD = "getString";
@NonNull @Override public Speed getSpeed() {
return Speed.NORMAL;
}
@Override public List<String> getApplicableCallNames() {
return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}
@Override public List<String> getApplicableMethodNames() {
return Arrays.asList("tag", "format", "v", "d", "i", "w", "e", "wtf");
}
@Override public void checkCall(@NonNull ClassContext context, @NonNull ClassNode classNode,
@NonNull MethodNode method, @NonNull MethodInsnNode call) {
String owner = call.owner;
if (owner.startsWith("android/util/Log")) {
context.report(ISSUE_LOG, method, call, context.getLocation(call),
"Using 'Log' instead of 'Timber'");
}
}
@Override public void visitMethod(@NonNull JavaContext context, AstVisitor visitor,
@NonNull MethodInvocation node) {
String methodName = node.astName().getDescription();
if ("format".equals(methodName)) {
if (!(node.astOperand() instanceof VariableReference)) {
return;
}
VariableReference ref = (VariableReference) node.astOperand();
if (!"String".equals(ref.astIdentifier().astValue())) {
return;
}
// Found a String.format call
// Look outside to see if we inside of a Timber call
Node current = node.getParent();
while (current != null && !(current instanceof ExpressionStatement)) {
current = current.getParent();
}
if (current == null) {
return;
}
ExpressionStatement statement = (ExpressionStatement) current;
if (!statement.toString().startsWith("Timber.")) {
return;
}
context.report(ISSUE_FORMAT, node, context.getLocation(node),
"Using 'String#format' inside of 'Timber'");
} else if ("tag".equals(methodName)) {
Node argument = node.astArguments().iterator().next();
String tag = findLiteralValue(context, argument);
if (tag.length() > 23) {
String message = String.format(
"The logging tag can be at most 23 characters, was %1$d (%2$s)",
tag.length(), tag);
context.report(ISSUE_TAG_LENGTH, node, context.getLocation(argument), message);
}
} else {
if (node.astOperand() instanceof VariableReference) {
VariableReference ref = (VariableReference) node.astOperand();
if (!"Timber".equals(ref.astIdentifier().astValue())) {
return;
}
checkThrowablePosition(context, node);
checkArguments(context, node);
}
}
}
private static void checkArguments(JavaContext context, MethodInvocation node) {
StrictListAccessor<Expression, MethodInvocation> astArguments = node.astArguments();
Iterator<Expression> iterator = astArguments.iterator();
if (!iterator.hasNext()) {
return;
}
int startIndexOfArguments = 1;
Expression formatStringArg = iterator.next();
if (formatStringArg instanceof VariableReference) {
if (isSubclassOf(context, (VariableReference) formatStringArg, Throwable.class)) {
formatStringArg = iterator.next();
startIndexOfArguments++;
}
}
String formatString = findLiteralValue(context, formatStringArg);
// We passed for example a method call
if (formatString == null) {
return;
}
int argumentCount = getFormatArgumentCount(formatString);
int passedArgCount = astArguments.size() - startIndexOfArguments;
if (argumentCount < passedArgCount) {
context.report(ISSUE_ARG_COUNT, node, context.getLocation(node), String.format(
"Wrong argument count, format string `%1$s` requires "
+ "`%2$d` but format call supplies `%3$d`", formatString, argumentCount,
passedArgCount));
return;
}
if (argumentCount == 0) {
return;
}
List<String> types = getStringArgumentTypes(formatString);
Expression argument = null;
boolean valid;
for (int i = 0; i < types.size(); i++) {
String formatType = types.get(i);
if (iterator.hasNext()) {
argument = iterator.next();
} else {
context.report(ISSUE_ARG_COUNT, node, context.getLocation(node), String.format(
"Wrong argument count, format string `%1$s` requires "
+ "`%2$d` but format call supplies `%3$d`", formatString, argumentCount,
passedArgCount));
}
char last = formatType.charAt(formatType.length() - 1);
if (formatType.length() >= 2
&& Character.toLowerCase(formatType.charAt(formatType.length() - 2)) == 't') {
// Date time conversion.
// TODO
continue;
}
Class type = getType(context, argument);
if (type != null) {
switch (last) {
case 'b':
case 'B':
valid = type == Boolean.TYPE;
break;
case 'x':
case 'X':
case 'd':
case 'o':
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
case 'a':
case 'A':
valid = type == Integer.TYPE
|| type == Float.TYPE
|| type == Double.TYPE
|| type == Long.TYPE
|| type == Byte.TYPE
|| type == Short.TYPE;
break;
case 'c':
case 'C':
valid = type == Character.TYPE;
break;
case 'h':
case 'H':
valid = type != Boolean.TYPE && !Number.class.isAssignableFrom(type);
break;
case 's':
case 'S':
default:
valid = true;
}
if (!valid) {
String message = String.format("Wrong argument type for formatting argument '
+ "in `%2$s`: conversion is '`%3$s`', received `%4$s` "
+ "(argument #%5$d in method call)", i + 1, formatString, formatType,
type.getSimpleName(), startIndexOfArguments + i + 1);
context.report(ISSUE_ARG_TYPES, node, context.getLocation(argument), message);
}
}
}
}
private static Class<?> getType(JavaContext context, Expression expression) {
if (expression == null) {
return null;
}
if (expression instanceof MethodInvocation) {
MethodInvocation method = (MethodInvocation) expression;
String methodName = method.astName().astValue();
if (methodName.equals(GET_STRING_METHOD)) {
return String.class;
}
} else if (expression instanceof StringLiteral) {
return String.class;
} else if (expression instanceof IntegralLiteral) {
return Integer.TYPE;
} else if (expression instanceof FloatingPointLiteral) {
return Float.TYPE;
} else if (expression instanceof CharLiteral) {
return Character.TYPE;
} else if (expression instanceof BooleanLiteral) {
return Boolean.TYPE;
} else if (expression instanceof NullLiteral) {
return Object.class;
}
if (context != null) {
JavaParser.TypeDescriptor type = context.getType(expression);
if (type != null) {
Class<?> typeClass = getTypeClass(type);
if (typeClass != null) {
return typeClass;
} else {
return Object.class;
}
}
}
return null;
}
private static Class<?> getTypeClass(@Nullable JavaParser.TypeDescriptor type) {
if (type != null) {
return getTypeClass(type.getName());
}
return null;
}
private static Class<?> getTypeClass(@Nullable String typeClassName) {
if (typeClassName == null) {
return null;
} else if (typeClassName.equals(TYPE_STRING) || "String".equals(typeClassName)) {
return String.class;
} else if (typeClassName.equals(TYPE_INT)) {
return Integer.TYPE;
} else if (typeClassName.equals(TYPE_BOOLEAN)) {
return Boolean.TYPE;
} else if (typeClassName.equals(TYPE_NULL)) {
return Object.class;
} else if (typeClassName.equals(TYPE_LONG)) {
return Long.TYPE;
} else if (typeClassName.equals(TYPE_FLOAT)) {
return Float.TYPE;
} else if (typeClassName.equals(TYPE_DOUBLE)) {
return Double.TYPE;
} else if (typeClassName.equals(TYPE_CHAR)) {
return Character.TYPE;
} else if ("BigDecimal".equals(typeClassName) || "java.math.BigDecimal".equals(typeClassName)) {
return Float.TYPE;
} else if ("BigInteger".equals(typeClassName) || "java.math.BigInteger".equals(typeClassName)) {
return Integer.TYPE;
} else if (typeClassName.equals(TYPE_OBJECT)) {
return null;
} else if (typeClassName.startsWith("java.lang.")) {
if ("java.lang.Integer".equals(typeClassName)
|| "java.lang.Short".equals(typeClassName)
|| "java.lang.Byte".equals(typeClassName)
|| "java.lang.Long".equals(typeClassName)) {
return Integer.TYPE;
} else if ("java.lang.Float".equals(typeClassName) || "java.lang.Double".equals(
typeClassName)) {
return Float.TYPE;
} else {
return null;
}
} else if (typeClassName.equals(TYPE_BYTE)) {
return Byte.TYPE;
} else if (typeClassName.equals(TYPE_SHORT)) {
return Short.TYPE;
} else {
return null;
}
}
private static boolean isSubclassOf(JavaContext context, VariableReference variableReference,
Class clazz) {
JavaParser.ResolvedNode resolved = context.resolve(variableReference);
if (resolved instanceof JavaParser.ResolvedVariable) {
JavaParser.ResolvedVariable resolvedVariable = (JavaParser.ResolvedVariable) resolved;
JavaParser.ResolvedClass typeClass = resolvedVariable.getType().getTypeClass();
return (typeClass != null && typeClass.isSubclassOf(clazz.getName(), false));
}
return false;
}
private static List<String> getStringArgumentTypes(String formatString) {
List<String> types = new ArrayList<String>();
Matcher matcher = StringFormatDetector.FORMAT.matcher(formatString);
int index = 0;
int prevIndex = 0;
while (true) {
if (matcher.find(index)) {
int matchStart = matcher.start();
while (prevIndex < matchStart) {
char c = formatString.charAt(prevIndex);
if (c == '\\') {
prevIndex++;
}
prevIndex++;
}
if (prevIndex > matchStart) {
index = prevIndex;
continue;
}
index = matcher.end();
String str = formatString.substring(matchStart, matcher.end());
if ("%%".equals(str) || "%n".equals(str)) {
continue;
}
types.add(matcher.group(6));
} else {
break;
}
}
return types;
}
private static String findLiteralValue(@NonNull JavaContext context, @NonNull Node argument) {
if (argument instanceof StringLiteral) {
return ((StringLiteral) argument).astValue();
} else if (argument instanceof BinaryExpression) {
BinaryExpression expression = (BinaryExpression) argument;
if (expression.astOperator() == BinaryOperator.PLUS) {
String left = findLiteralValue(context, expression.astLeft());
String right = findLiteralValue(context, expression.astRight());
if (left != null && right != null) {
return left + right;
}
}
} else {
JavaParser.ResolvedNode resolved = context.resolve(argument);
if (resolved instanceof JavaParser.ResolvedField) {
JavaParser.ResolvedField field = (JavaParser.ResolvedField) resolved;
Object value = field.getValue();
if (value instanceof String) {
return (String) value;
}
}
}
return null;
}
private static int getFormatArgumentCount(@NonNull String s) {
Matcher matcher = StringFormatDetector.FORMAT.matcher(s);
int index = 0;
int prevIndex = 0;
int nextNumber = 1;
int max = 0;
while (true) {
if (matcher.find(index)) {
String value = matcher.group(6);
if ("%".equals(value) || "n".equals(value)) {
index = matcher.end();
continue;
}
int matchStart = matcher.start();
for (; prevIndex < matchStart; prevIndex++) {
char c = s.charAt(prevIndex);
if (c == '\\') {
prevIndex++;
}
}
if (prevIndex > matchStart) {
index = prevIndex;
continue;
}
int number;
String numberString = matcher.group(1);
if (numberString != null) {
// Strip off trailing $
numberString = numberString.substring(0, numberString.length() - 1);
number = Integer.parseInt(numberString);
nextNumber = number + 1;
} else {
number = nextNumber++;
}
if (number > max) {
max = number;
}
index = matcher.end();
} else {
break;
}
}
return max;
}
private static void checkThrowablePosition(JavaContext context, MethodInvocation node) {
int index = 0;
for (Node argument : node.astArguments()) {
if (checkNode(context, node, argument)) {
break;
}
if (argument instanceof VariableReference) {
VariableReference variableReference = (VariableReference) argument;
if (isSubclassOf(context, variableReference, Throwable.class) && index > 0) {
context.report(ISSUE_THROWABLE, node, context.getLocation(node),
"Throwable should be first argument");
}
}
index++;
}
}
private static boolean checkNode(JavaContext context, MethodInvocation node, Node argument) {
if (argument instanceof BinaryExpression) {
Class argumentType = getType(context, (BinaryExpression) argument);
if (argumentType == String.class) {
context.report(ISSUE_BINARY, node, context.getLocation(argument),
"Replace String concatenation with Timber's string formatting");
return true;
}
} else if (argument instanceof If || argument instanceof InlineIfExpression) {
return checkConditionalUsage(context, node, argument);
}
return false;
}
private static boolean checkConditionalUsage(JavaContext context, MethodInvocation node,
Node arg) {
Node thenStatement;
Node elseStatement;
if (arg instanceof If) {
If ifArg = (If) arg;
thenStatement = ifArg.astStatement();
elseStatement = ifArg.astElseStatement();
} else if (arg instanceof InlineIfExpression) {
InlineIfExpression inlineIfArg = (InlineIfExpression) arg;
thenStatement = inlineIfArg.astIfFalse();
elseStatement = inlineIfArg.astIfTrue();
} else {
return false;
}
if (checkNode(context, node, thenStatement)) {
return false;
}
return checkNode(context, node, elseStatement);
}
public static final Issue ISSUE_LOG =
Issue.create("LogNotTimber", "Logging call to Log instead of Timber",
"Since Timber is included in the project, it is likely that calls to Log should instead"
+ " be going to Timber.", Category.MESSAGES, 5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.CLASS_FILE_SCOPE));
public static final Issue ISSUE_FORMAT =
Issue.create("StringFormatInTimber", "Logging call with Timber contains String#format()",
"Since Timber handles String.format automatically, you may not use String#format().",
Category.MESSAGES, 5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_THROWABLE =
Issue.create("ThrowableNotAtBeginning", "Exception in Timber not at the beginning",
"In Timber you have to pass a Throwable at the beginning of the call.", Category.MESSAGES,
5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_BINARY =
Issue.create("BinaryOperationInTimber", "Use String#format()",
"Since Timber handles String#format() automatically, use this instead of String"
+ " concatenation.", Category.MESSAGES, 5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_ARG_COUNT =
Issue.create("TimberArgCount", "Formatting argument types incomplete or inconsistent",
"When a formatted string takes arguments, you need to pass at least that amount of"
+ " arguments to the formatting call.", Category.MESSAGES, 9, Severity.ERROR,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_ARG_TYPES =
Issue.create("TimberArgTypes", "Formatting string doesn't match passed arguments",
"The argument types that you specified in your formatting string does not match the types"
+ " of the arguments that you passed to your formatting call.", Category.MESSAGES, 9,
Severity.ERROR,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_TAG_LENGTH =
Issue.create("TimberTagLength", "Too Long Log Tags", "Log tags are only allowed to be at most"
+ " 23 tag characters long.", Category.CORRECTNESS, 5, Severity.ERROR,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
}
|
package timber.lint;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.tools.lint.checks.StringFormatDetector;
import com.android.tools.lint.client.api.JavaParser;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.ClassContext;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.Speed;
import lombok.ast.AstVisitor;
import lombok.ast.BinaryExpression;
import lombok.ast.BinaryOperator;
import lombok.ast.BooleanLiteral;
import lombok.ast.CharLiteral;
import lombok.ast.Expression;
import lombok.ast.ExpressionStatement;
import lombok.ast.FloatingPointLiteral;
import lombok.ast.If;
import lombok.ast.InlineIfExpression;
import lombok.ast.IntegralLiteral;
import lombok.ast.MethodInvocation;
import lombok.ast.Node;
import lombok.ast.NullLiteral;
import lombok.ast.StrictListAccessor;
import lombok.ast.StringLiteral;
import lombok.ast.VariableReference;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import static com.android.tools.lint.client.api.JavaParser.TYPE_BOOLEAN;
import static com.android.tools.lint.client.api.JavaParser.TYPE_BYTE;
import static com.android.tools.lint.client.api.JavaParser.TYPE_CHAR;
import static com.android.tools.lint.client.api.JavaParser.TYPE_DOUBLE;
import static com.android.tools.lint.client.api.JavaParser.TYPE_FLOAT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_INT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_LONG;
import static com.android.tools.lint.client.api.JavaParser.TYPE_NULL;
import static com.android.tools.lint.client.api.JavaParser.TYPE_OBJECT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_SHORT;
import static com.android.tools.lint.client.api.JavaParser.TYPE_STRING;
public final class WrongTimberUsageDetector extends Detector implements Detector.JavaScanner,
Detector.ClassScanner {
private final static String GET_STRING_METHOD = "getString";
@NonNull @Override public Speed getSpeed() {
return Speed.NORMAL;
}
@Override public List<String> getApplicableCallNames() {
return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}
@Override public List<String> getApplicableMethodNames() {
return Arrays.asList("tag", "format", "v", "d", "i", "w", "e", "wtf");
}
@Override public void checkCall(@NonNull ClassContext context, @NonNull ClassNode classNode,
@NonNull MethodNode method, @NonNull MethodInsnNode call) {
String owner = call.owner;
if (owner.startsWith("android/util/Log")) {
context.report(ISSUE_LOG, method, call, context.getLocation(call),
"Using 'Log' instead of 'Timber'");
}
}
@Override public void visitMethod(@NonNull JavaContext context, AstVisitor visitor,
@NonNull MethodInvocation node) {
String methodName = node.astName().getDescription();
if ("format".equals(methodName)) {
if (!(node.astOperand() instanceof VariableReference)) {
return;
}
VariableReference ref = (VariableReference) node.astOperand();
if (!"String".equals(ref.astIdentifier().astValue())) {
return;
}
// Found a String.format call
// Look outside to see if we inside of a Timber call
Node current = node.getParent();
while (current != null && !(current instanceof ExpressionStatement)) {
current = current.getParent();
}
if (current == null) {
return;
}
ExpressionStatement statement = (ExpressionStatement) current;
if (!statement.toString().startsWith("Timber.")) {
return;
}
context.report(ISSUE_FORMAT, node, context.getLocation(node),
"Using 'String#format' inside of 'Timber'");
} else if ("tag".equals(methodName)) {
Node argument = node.astArguments().iterator().next();
String tag = findLiteralValue(context, argument);
if (tag.length() > 23) {
String message = String.format(
"The logging tag can be at most 23 characters, was %1$d (%2$s)",
tag.length(), tag);
context.report(ISSUE_TAG_LENGTH, node, context.getLocation(argument), message);
}
} else {
if (node.astOperand() instanceof VariableReference) {
VariableReference ref = (VariableReference) node.astOperand();
if (!"Timber".equals(ref.astIdentifier().astValue())) {
return;
}
checkThrowablePosition(context, node);
checkArguments(context, node);
}
}
}
private static void checkArguments(JavaContext context, MethodInvocation node) {
StrictListAccessor<Expression, MethodInvocation> astArguments = node.astArguments();
Iterator<Expression> iterator = astArguments.iterator();
if (!iterator.hasNext()) {
return;
}
int startIndexOfArguments = 1;
Expression formatStringArg = iterator.next();
if (formatStringArg instanceof VariableReference) {
if (isSubclassOf(context, (VariableReference) formatStringArg, Throwable.class)) {
formatStringArg = iterator.next();
startIndexOfArguments++;
}
}
String formatString = findLiteralValue(context, formatStringArg);
// We passed for example a method call
if (formatString == null) {
return;
}
int argumentCount = getFormatArgumentCount(formatString);
int passedArgCount = astArguments.size() - startIndexOfArguments;
if (argumentCount < passedArgCount) {
context.report(ISSUE_ARG_COUNT, node, context.getLocation(node), String.format(
"Wrong argument count, format string `%1$s` requires "
+ "`%2$d` but format call supplies `%3$d`", formatString, argumentCount,
passedArgCount));
return;
}
if (argumentCount == 0) {
return;
}
List<String> types = getStringArgumentTypes(formatString);
Expression argument = null;
boolean valid;
for (int i = 0; i < types.size(); i++) {
String formatType = types.get(i);
if (iterator.hasNext()) {
argument = iterator.next();
} else {
context.report(ISSUE_ARG_COUNT, node, context.getLocation(node), String.format(
"Wrong argument count, format string `%1$s` requires "
+ "`%2$d` but format call supplies `%3$d`", formatString, argumentCount,
passedArgCount));
}
char last = formatType.charAt(formatType.length() - 1);
if (formatType.length() >= 2
&& Character.toLowerCase(formatType.charAt(formatType.length() - 2)) == 't') {
// Date time conversion.
// TODO
continue;
}
Class type = getType(context, argument);
if (type != null) {
switch (last) {
case 'b':
case 'B':
valid = type == Boolean.TYPE;
break;
case 'x':
case 'X':
case 'd':
case 'o':
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
case 'a':
case 'A':
valid = type == Integer.TYPE
|| type == Float.TYPE
|| type == Double.TYPE
|| type == Long.TYPE
|| type == Byte.TYPE
|| type == Short.TYPE;
break;
case 'c':
case 'C':
valid = type == Character.TYPE;
break;
case 'h':
case 'H':
valid = type != Boolean.TYPE && !Number.class.isAssignableFrom(type);
break;
case 's':
case 'S':
default:
valid = true;
}
if (!valid) {
String message = String.format("Wrong argument type for formatting argument '
+ "in `%2$s`: conversion is '`%3$s`', received `%4$s` "
+ "(argument #%5$d in method call)", i, formatString, formatType,
type.getSimpleName(), startIndexOfArguments + i + 1);
context.report(ISSUE_ARG_TYPES, node, context.getLocation(argument), message);
}
}
}
}
private static Class<?> getType(JavaContext context, Expression expression) {
if (expression == null) {
return null;
}
if (expression instanceof MethodInvocation) {
MethodInvocation method = (MethodInvocation) expression;
String methodName = method.astName().astValue();
if (methodName.equals(GET_STRING_METHOD)) {
return String.class;
}
} else if (expression instanceof StringLiteral) {
return String.class;
} else if (expression instanceof IntegralLiteral) {
return Integer.TYPE;
} else if (expression instanceof FloatingPointLiteral) {
return Float.TYPE;
} else if (expression instanceof CharLiteral) {
return Character.TYPE;
} else if (expression instanceof BooleanLiteral) {
return Boolean.TYPE;
} else if (expression instanceof NullLiteral) {
return Object.class;
}
if (context != null) {
JavaParser.TypeDescriptor type = context.getType(expression);
if (type != null) {
Class<?> typeClass = getTypeClass(type);
if (typeClass != null) {
return typeClass;
} else {
return Object.class;
}
}
}
return null;
}
private static Class<?> getTypeClass(@Nullable JavaParser.TypeDescriptor type) {
if (type != null) {
return getTypeClass(type.getName());
}
return null;
}
private static Class<?> getTypeClass(@Nullable String typeClassName) {
if (typeClassName == null) {
return null;
} else if (typeClassName.equals(TYPE_STRING) || "String".equals(typeClassName)) {
return String.class;
} else if (typeClassName.equals(TYPE_INT)) {
return Integer.TYPE;
} else if (typeClassName.equals(TYPE_BOOLEAN)) {
return Boolean.TYPE;
} else if (typeClassName.equals(TYPE_NULL)) {
return Object.class;
} else if (typeClassName.equals(TYPE_LONG)) {
return Long.TYPE;
} else if (typeClassName.equals(TYPE_FLOAT)) {
return Float.TYPE;
} else if (typeClassName.equals(TYPE_DOUBLE)) {
return Double.TYPE;
} else if (typeClassName.equals(TYPE_CHAR)) {
return Character.TYPE;
} else if ("BigDecimal".equals(typeClassName) || "java.math.BigDecimal".equals(typeClassName)) {
return Float.TYPE;
} else if ("BigInteger".equals(typeClassName) || "java.math.BigInteger".equals(typeClassName)) {
return Integer.TYPE;
} else if (typeClassName.equals(TYPE_OBJECT)) {
return null;
} else if (typeClassName.startsWith("java.lang.")) {
if ("java.lang.Integer".equals(typeClassName)
|| "java.lang.Short".equals(typeClassName)
|| "java.lang.Byte".equals(typeClassName)
|| "java.lang.Long".equals(typeClassName)) {
return Integer.TYPE;
} else if ("java.lang.Float".equals(typeClassName) || "java.lang.Double".equals(
typeClassName)) {
return Float.TYPE;
} else {
return null;
}
} else if (typeClassName.equals(TYPE_BYTE)) {
return Byte.TYPE;
} else if (typeClassName.equals(TYPE_SHORT)) {
return Short.TYPE;
} else {
return null;
}
}
private static boolean isSubclassOf(JavaContext context, VariableReference variableReference,
Class clazz) {
JavaParser.ResolvedNode resolved = context.resolve(variableReference);
if (resolved instanceof JavaParser.ResolvedVariable) {
JavaParser.ResolvedVariable resolvedVariable = (JavaParser.ResolvedVariable) resolved;
JavaParser.ResolvedClass typeClass = resolvedVariable.getType().getTypeClass();
return (typeClass != null && typeClass.isSubclassOf(clazz.getName(), false));
}
return false;
}
private static List<String> getStringArgumentTypes(String formatString) {
List<String> types = new ArrayList<String>();
Matcher matcher = StringFormatDetector.FORMAT.matcher(formatString);
int index = 0;
int prevIndex = 0;
while (true) {
if (matcher.find(index)) {
int matchStart = matcher.start();
while (prevIndex < matchStart) {
char c = formatString.charAt(prevIndex);
if (c == '\\') {
prevIndex++;
}
prevIndex++;
}
if (prevIndex > matchStart) {
index = prevIndex;
continue;
}
index = matcher.end();
String str = formatString.substring(matchStart, matcher.end());
if ("%%".equals(str) || "%n".equals(str)) {
continue;
}
types.add(matcher.group(6));
} else {
break;
}
}
return types;
}
private static String findLiteralValue(@NonNull JavaContext context, @NonNull Node argument) {
if (argument instanceof StringLiteral) {
return ((StringLiteral) argument).astValue();
} else if (argument instanceof BinaryExpression) {
BinaryExpression expression = (BinaryExpression) argument;
if (expression.astOperator() == BinaryOperator.PLUS) {
String left = findLiteralValue(context, expression.astLeft());
String right = findLiteralValue(context, expression.astRight());
if (left != null && right != null) {
return left + right;
}
}
} else {
JavaParser.ResolvedNode resolved = context.resolve(argument);
if (resolved instanceof JavaParser.ResolvedField) {
JavaParser.ResolvedField field = (JavaParser.ResolvedField) resolved;
Object value = field.getValue();
if (value instanceof String) {
return (String) value;
}
}
}
return null;
}
private static int getFormatArgumentCount(@NonNull String s) {
Matcher matcher = StringFormatDetector.FORMAT.matcher(s);
int index = 0;
int prevIndex = 0;
int nextNumber = 1;
int max = 0;
while (true) {
if (matcher.find(index)) {
String value = matcher.group(6);
if ("%".equals(value) || "n".equals(value)) {
index = matcher.end();
continue;
}
int matchStart = matcher.start();
for (; prevIndex < matchStart; prevIndex++) {
char c = s.charAt(prevIndex);
if (c == '\\') {
prevIndex++;
}
}
if (prevIndex > matchStart) {
index = prevIndex;
continue;
}
int number;
String numberString = matcher.group(1);
if (numberString != null) {
// Strip off trailing $
numberString = numberString.substring(0, numberString.length() - 1);
number = Integer.parseInt(numberString);
nextNumber = number + 1;
} else {
number = nextNumber++;
}
if (number > max) {
max = number;
}
index = matcher.end();
} else {
break;
}
}
return max;
}
private static void checkThrowablePosition(JavaContext context, MethodInvocation node) {
int index = 0;
for (Node argument : node.astArguments()) {
if (checkNode(context, node, argument)) {
break;
}
if (argument instanceof VariableReference) {
VariableReference variableReference = (VariableReference) argument;
if (isSubclassOf(context, variableReference, Throwable.class) && index > 0) {
context.report(ISSUE_THROWABLE, node, context.getLocation(node),
"Throwable should be first argument");
}
}
index++;
}
}
private static boolean checkNode(JavaContext context, MethodInvocation node, Node argument) {
if (argument instanceof BinaryExpression) {
context.report(ISSUE_BINARY, node, context.getLocation(argument),
"Replace String concatenation with Timber's string formatting");
return true;
} else if (argument instanceof If || argument instanceof InlineIfExpression) {
return checkConditionalUsage(context, node, argument);
}
return false;
}
private static boolean checkConditionalUsage(JavaContext context, MethodInvocation node,
Node arg) {
Node thenStatement;
Node elseStatement;
if (arg instanceof If) {
If ifArg = (If) arg;
thenStatement = ifArg.astStatement();
elseStatement = ifArg.astElseStatement();
} else if (arg instanceof InlineIfExpression) {
InlineIfExpression inlineIfArg = (InlineIfExpression) arg;
thenStatement = inlineIfArg.astIfFalse();
elseStatement = inlineIfArg.astIfTrue();
} else {
return false;
}
if (checkNode(context, node, thenStatement)) {
return false;
}
return checkNode(context, node, elseStatement);
}
public static final Issue ISSUE_LOG =
Issue.create("LogNotTimber", "Logging call to Log instead of Timber",
"Since Timber is included in the project, it is likely that calls to Log should instead"
+ " be going to Timber.", Category.MESSAGES, 5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.CLASS_FILE_SCOPE));
public static final Issue ISSUE_FORMAT =
Issue.create("StringFormatInTimber", "Logging call with Timber contains String#format()",
"Since Timber handles String.format automatically, you may not use String#format().",
Category.MESSAGES, 5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_THROWABLE =
Issue.create("ThrowableNotAtBeginning", "Exception in Timber not at the beginning",
"In Timber you have to pass a Throwable at the beginning of the call.", Category.MESSAGES,
5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_BINARY =
Issue.create("BinaryOperationInTimber", "Use String#format()",
"Since Timber handles String#format() automatically, use this instead of String"
+ " concatenation.", Category.MESSAGES, 5, Severity.WARNING,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_ARG_COUNT =
Issue.create("TimberArgCount", "Formatting argument types incomplete or inconsistent",
"When a formatted string takes arguments, you need to pass at least that amount of"
+ " arguments to the formatting call.", Category.MESSAGES, 9, Severity.ERROR,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_ARG_TYPES =
Issue.create("TimberArgTypes", "Formatting string doesn't match passed arguments",
"The argument types that you specified in your formatting string does not match the types"
+ " of the arguments that you passed to your formatting call.", Category.MESSAGES, 9,
Severity.ERROR,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_TAG_LENGTH =
Issue.create("TimberTagLength", "Too Long Log Tags", "Log tags are only allowed to be at most"
+ " 23 tag characters long.", Category.CORRECTNESS, 5, Severity.ERROR,
new Implementation(WrongTimberUsageDetector.class, Scope.JAVA_FILE_SCOPE));
}
|
package org.bouncycastle.jsse.provider;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.jsse.BCSSLConnection;
import org.bouncycastle.jsse.BCSSLEngine;
import org.bouncycastle.tls.RecordFormat;
import org.bouncycastle.tls.TlsClientProtocol;
import org.bouncycastle.tls.TlsProtocol;
import org.bouncycastle.tls.TlsServerProtocol;
import org.bouncycastle.tls.TlsUtils;
/*
* TODO[jsse] Currently doesn't properly support NIO usage, or conform very well with SSLEngine javadoc
* - e.g. "The wrap() and unwrap() methods may execute concurrently of each other." is not true yet.
*/
class ProvSSLEngine
extends SSLEngine
implements BCSSLEngine, ProvTlsManager
{
protected final ProvSSLContextSpi context;
protected final ContextData contextData;
protected ProvSSLParameters sslParameters;
protected boolean enableSessionCreation = true;
protected boolean useClientMode = true;
protected boolean initialHandshakeBegun = false;
protected HandshakeStatus handshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
protected TlsProtocol protocol = null;
protected ProvTlsPeer protocolPeer = null;
protected BCSSLConnection connection = null;
protected SSLSession handshakeSession = null;
protected SSLException deferredException = null;
protected ProvSSLEngine(ProvSSLContextSpi context, ContextData contextData)
{
super();
this.context = context;
this.contextData = contextData;
this.sslParameters = ProvSSLParameters.extractDefaultParameters(context);
}
protected ProvSSLEngine(ProvSSLContextSpi context, ContextData contextData, String host, int port)
{
super(host, port);
this.context = context;
this.contextData = contextData;
this.sslParameters = ProvSSLParameters.extractDefaultParameters(context);;
}
public ProvSSLContextSpi getContext()
{
return context;
}
public ContextData getContextData()
{
return contextData;
}
@Override
public synchronized void beginHandshake()
throws SSLException
{
if (initialHandshakeBegun)
{
throw new UnsupportedOperationException("Renegotiation not supported");
}
this.initialHandshakeBegun = true;
// TODO[jsse] Check for session to re-use and apply to handshake
// TODO[jsse] Allocate this.handshakeSession and update it during handshake
try
{
if (this.useClientMode)
{
TlsClientProtocol clientProtocol = new TlsClientProtocol();
this.protocol = clientProtocol;
ProvTlsClient client = new ProvTlsClient(this);
this.protocolPeer = client;
clientProtocol.connect(client);
this.handshakeStatus = HandshakeStatus.NEED_WRAP;
}
else
{
TlsServerProtocol serverProtocol = new TlsServerProtocol();
this.protocol = serverProtocol;
ProvTlsServer server = new ProvTlsServer(this);
this.protocolPeer = server;
serverProtocol.accept(server);
this.handshakeStatus = HandshakeStatus.NEED_UNWRAP;
}
}
catch (SSLException e)
{
throw e;
}
catch (IOException e)
{
throw new SSLException(e);
}
}
@Override
public synchronized void closeInbound()
throws SSLException
{
// TODO How to behave when protocol is still null?
try
{
protocol.closeInput();
}
catch (IOException e)
{
throw new SSLException(e);
}
}
@Override
public synchronized void closeOutbound()
{
// TODO How to behave when protocol is still null?
try
{
protocol.close();
}
catch (IOException e)
{
// TODO[logging]
}
}
public synchronized BCSSLConnection getConnection()
{
return connection;
}
@Override
public synchronized Runnable getDelegatedTask()
{
return null;
}
@Override
public synchronized String[] getEnabledCipherSuites()
{
return sslParameters.getCipherSuites();
}
@Override
public synchronized String[] getEnabledProtocols()
{
return sslParameters.getProtocols();
}
@Override
public synchronized boolean getEnableSessionCreation()
{
return enableSessionCreation;
}
@Override
public synchronized SSLSession getHandshakeSession()
{
// TODO[jsse] this.handshakeSession needs to be reset (to null) whenever not handshaking
return handshakeSession;
}
@Override
public synchronized SSLEngineResult.HandshakeStatus getHandshakeStatus()
{
return handshakeStatus;
}
@Override
public synchronized boolean getNeedClientAuth()
{
return sslParameters.getNeedClientAuth();
}
@Override
public synchronized SSLSession getSession()
{
return connection == null ? ProvSSLSessionImpl.NULL_SESSION.getExportSession() : connection.getSession();
}
@Override
public synchronized SSLParameters getSSLParameters()
{
return SSLParametersUtil.toSSLParameters(sslParameters);
}
public synchronized ProvSSLParameters getProvSSLParameters()
{
return sslParameters;
}
@Override
public synchronized String[] getSupportedCipherSuites()
{
return context.getSupportedCipherSuites();
}
@Override
public synchronized String[] getSupportedProtocols()
{
return context.getSupportedProtocols();
}
@Override
public synchronized boolean getUseClientMode()
{
return useClientMode;
}
@Override
public synchronized boolean getWantClientAuth()
{
return sslParameters.getWantClientAuth();
}
@Override
public synchronized boolean isInboundDone()
{
return protocol != null && protocol.isClosed();
}
@Override
public synchronized boolean isOutboundDone()
{
return protocol != null && protocol.isClosed() && protocol.getAvailableOutputBytes() < 1;
}
@Override
public synchronized void setEnabledCipherSuites(String[] suites)
{
if (!context.isSupportedCipherSuites(suites))
{
throw new IllegalArgumentException("'suites' cannot be null, or contain unsupported cipher suites");
}
sslParameters.setCipherSuites(suites);
}
@Override
public synchronized void setEnabledProtocols(String[] protocols)
{
if (!context.isSupportedProtocols(protocols))
{
throw new IllegalArgumentException("'protocols' cannot be null, or contain unsupported protocols");
}
sslParameters.setProtocols(protocols);
}
@Override
public synchronized void setEnableSessionCreation(boolean flag)
{
this.enableSessionCreation = flag;
}
@Override
public synchronized void setNeedClientAuth(boolean need)
{
sslParameters.setNeedClientAuth(need);
}
@Override
public synchronized void setSSLParameters(SSLParameters sslParameters)
{
this.sslParameters = SSLParametersUtil.toProvSSLParameters(sslParameters);
}
@Override
public synchronized void setUseClientMode(boolean mode)
{
if (initialHandshakeBegun && mode != this.useClientMode)
{
throw new IllegalArgumentException("Mode cannot be changed after the initial handshake has begun");
}
this.useClientMode = mode;
}
@Override
public synchronized void setWantClientAuth(boolean want)
{
sslParameters.setWantClientAuth(want);
}
@Override
public synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length)
throws SSLException
{
// TODO[jsse] Argument checks - see javadoc
if (!initialHandshakeBegun)
{
beginHandshake();
}
int bytesConsumed = 0, bytesProduced = 0;
if (!protocol.isClosed())
{
if (src.remaining() >= RecordFormat.FRAGMENT_OFFSET)
{
byte[] recordHeader = new byte[RecordFormat.FRAGMENT_OFFSET];
src.slice().get(recordHeader);
int recordSize = RecordFormat.FRAGMENT_OFFSET + TlsUtils.readUint16(recordHeader, RecordFormat.LENGTH_OFFSET);
if (recordSize > ProvSSLSessionImpl.NULL_SESSION.getPacketBufferSize())
{
/*
* TODO[jsse] Prefer to have the TLS layer raise a record_overflow alert
*/
throw new SSLException("Input record has invalid size: " + recordSize);
}
if (src.remaining() >= recordSize)
{
byte[] buf = new byte[recordSize];
src.get(buf);
try
{
protocol.offerInput(buf);
}
catch (IOException e)
{
/*
* TODO[jsse] 'deferredException' is a workaround for Apache Tomcat's (as of
* 8.5.13) SecureNioChannel behaviour when exceptions are thrown from
* SSLEngine during the handshake. In the case of SSLEngine.wrap throwing,
* Tomcat will call wrap again, allowing any buffered outbound alert to be
* flushed. For unwrap, this doesn't happen. So we pretend this unwrap was
* OK and ask for NEED_WRAP, then throw in wrap.
*
* Note that the SSLEngine javadoc clearly describes a process of flushing
* via wrap calls after any closure events, to include thrown exceptions.
*/
if (handshakeStatus != HandshakeStatus.NEED_UNWRAP)
{
throw new SSLException(e);
}
if (this.deferredException == null)
{
this.deferredException = new SSLException(e);
}
handshakeStatus = HandshakeStatus.NEED_WRAP;
return new SSLEngineResult(Status.OK, HandshakeStatus.NEED_WRAP, bytesConsumed, bytesProduced);
}
bytesConsumed += recordSize;
}
}
}
int inputAvailable = protocol.getAvailableInputBytes();
for (int dstIndex = 0; dstIndex < length && inputAvailable > 0; ++dstIndex)
{
ByteBuffer dst = dsts[dstIndex];
int count = Math.min(dst.remaining(), inputAvailable);
byte[] input = new byte[count];
int numRead = protocol.readInput(input, 0, count);
assert numRead == count;
dst.put(input);
bytesProduced += count;
inputAvailable -= count;
}
Status resultStatus = Status.OK;
if (inputAvailable > 0)
{
resultStatus = Status.BUFFER_OVERFLOW;
}
else if (protocol.isClosed())
{
resultStatus = Status.CLOSED;
}
else if (bytesConsumed == 0)
{
resultStatus = Status.BUFFER_UNDERFLOW;
}
/*
* We only ever change the handshakeStatus here if we started in NEED_UNWRAP
*/
HandshakeStatus resultHandshakeStatus = handshakeStatus;
if (handshakeStatus == HandshakeStatus.NEED_UNWRAP)
{
if (protocol.getAvailableOutputBytes() > 0)
{
handshakeStatus = HandshakeStatus.NEED_WRAP;
resultHandshakeStatus = HandshakeStatus.NEED_WRAP;
}
else if (protocolPeer.isHandshakeComplete())
{
handshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
resultHandshakeStatus = HandshakeStatus.FINISHED;
}
else if (protocol.isClosed())
{
handshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
resultHandshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
}
else
{
// Still NEED_UNWRAP
}
}
return new SSLEngineResult(resultStatus, resultHandshakeStatus, bytesConsumed, bytesProduced);
}
@Override
public synchronized SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int length, ByteBuffer dst)
throws SSLException
{
if (deferredException != null)
{
SSLException e = deferredException;
deferredException = null;
throw e;
}
// TODO[jsse] Argument checks - see javadoc
if (!initialHandshakeBegun)
{
beginHandshake();
}
Status resultStatus = Status.OK;
int bytesConsumed = 0, bytesProduced = 0;
/*
* If handshake complete and the connection still open, send the application data in 'srcs'
*/
if (handshakeStatus == HandshakeStatus.NOT_HANDSHAKING)
{
if (protocol.isClosed())
{
resultStatus = Status.CLOSED;
}
else
{
/*
* Limit the app data that we will process in one call
*/
int srcLimit = ProvSSLSessionImpl.NULL_SESSION.getApplicationBufferSize();
for (int srcIndex = 0; srcIndex < length && srcLimit > 0; ++srcIndex)
{
ByteBuffer src = srcs[srcIndex];
int count = Math.min(src.remaining(), srcLimit);
if (count > 0)
{
byte[] input = new byte[count];
src.get(input);
try
{
protocol.writeApplicationData(input, 0, count);
}
catch (IOException e)
{
// TODO[jsse] Throw a subclass of SSLException?
throw new SSLException(e);
}
bytesConsumed += count;
srcLimit -= count;
}
}
}
}
/*
* Send any available output
*/
int outputAvailable = protocol.getAvailableOutputBytes();
if (outputAvailable > 0)
{
int count = Math.min(dst.remaining(), outputAvailable);
if (count > 0)
{
byte[] output = new byte[count];
int numRead = protocol.readOutput(output, 0, count);
assert numRead == count;
dst.put(output);
bytesProduced += count;
outputAvailable -= count;
}
if (outputAvailable > 0)
{
resultStatus = Status.BUFFER_OVERFLOW;
}
}
/*
* We only ever change the handshakeStatus here if we started in NEED_WRAP
*/
HandshakeStatus resultHandshakeStatus = handshakeStatus;
if (handshakeStatus == HandshakeStatus.NEED_WRAP)
{
if (outputAvailable > 0)
{
// Still NEED_WRAP
}
else if (protocolPeer.isHandshakeComplete())
{
handshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
resultHandshakeStatus = HandshakeStatus.FINISHED;
}
else if (protocol.isClosed())
{
handshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
resultHandshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
}
else
{
handshakeStatus = HandshakeStatus.NEED_UNWRAP;
resultHandshakeStatus = HandshakeStatus.NEED_UNWRAP;
}
}
return new SSLEngineResult(resultStatus, resultHandshakeStatus, bytesConsumed, bytesProduced);
}
public String getPeerHost()
{
return super.getPeerHost();
}
public int getPeerPort()
{
return super.getPeerPort();
}
public boolean isClientTrusted(X509Certificate[] chain, String authType)
{
// TODO[jsse] Consider X509ExtendedTrustManager and/or HostnameVerifier functionality
X509TrustManager tm = contextData.getTrustManager();
if (tm != null)
{
try
{
tm.checkClientTrusted(chain, authType);
return true;
}
catch (CertificateException e)
{
}
}
return false;
}
public boolean isServerTrusted(X509Certificate[] chain, String authType)
{
// TODO[jsse] Consider X509ExtendedTrustManager and/or HostnameVerifier functionality
X509TrustManager tm = contextData.getTrustManager();
if (tm != null)
{
try
{
tm.checkServerTrusted(chain, authType);
return true;
}
catch (CertificateException e)
{
}
}
return false;
}
public synchronized void notifyHandshakeComplete(ProvSSLConnection connection)
{
this.connection = connection;
}
}
|
package org.bouncycastle.jsse.provider;
import java.io.IOException;
import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLException;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.jsse.BCSNIMatcher;
import org.bouncycastle.jsse.BCSNIServerName;
import org.bouncycastle.tls.AlertDescription;
import org.bouncycastle.tls.AlertLevel;
import org.bouncycastle.tls.Certificate;
import org.bouncycastle.tls.CertificateRequest;
import org.bouncycastle.tls.ClientCertificateType;
import org.bouncycastle.tls.CompressionMethod;
import org.bouncycastle.tls.DefaultTlsServer;
import org.bouncycastle.tls.KeyExchangeAlgorithm;
import org.bouncycastle.tls.ProtocolVersion;
import org.bouncycastle.tls.ServerNameList;
import org.bouncycastle.tls.SignatureAndHashAlgorithm;
import org.bouncycastle.tls.TlsCredentials;
import org.bouncycastle.tls.TlsDHUtils;
import org.bouncycastle.tls.TlsExtensionsUtils;
import org.bouncycastle.tls.TlsFatalAlert;
import org.bouncycastle.tls.TlsSession;
import org.bouncycastle.tls.TlsUtils;
import org.bouncycastle.tls.crypto.TlsCrypto;
import org.bouncycastle.tls.crypto.TlsCryptoParameters;
import org.bouncycastle.tls.crypto.TlsDHConfig;
import org.bouncycastle.tls.crypto.impl.jcajce.JcaDefaultTlsCredentialedSigner;
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto;
import org.bouncycastle.tls.crypto.impl.jcajce.JceDefaultTlsCredentialedAgreement;
import org.bouncycastle.tls.crypto.impl.jcajce.JceDefaultTlsCredentialedDecryptor;
class ProvTlsServer
extends DefaultTlsServer
implements ProvTlsPeer
{
private static Logger LOG = Logger.getLogger(ProvTlsServer.class.getName());
private static final int provEphemeralDHKeySize = PropertyUtils.getIntegerSystemProperty("jdk.tls.ephemeralDHKeySize", 2048, 1024, 8192);
protected final ProvTlsManager manager;
protected final ProvSSLParameters sslParameters;
protected ProvSSLSessionImpl sslSession = null;
protected BCSNIServerName matchedSNIServerName = null;
protected Set<String> keyManagerMissCache = null;
protected TlsCredentials credentials = null;
protected boolean handshakeComplete = false;
ProvTlsServer(ProvTlsManager manager) throws SSLException
{
super(manager.getContextData().getCrypto());
this.manager = manager;
this.sslParameters = manager.getProvSSLParameters();
if (!manager.getEnableSessionCreation())
{
throw new SSLException("Session resumption not implemented yet and session creation is disabled");
}
}
@Override
protected int getMaximumNegotiableCurveBits()
{
// NOTE: BC supports all the current set of point formats so we don't check them here
return SupportedGroups.getServerMaximumNegotiableCurveBits(manager.getContext().isFips(), clientSupportedGroups);
}
@Override
protected int getMaximumNegotiableFiniteFieldBits()
{
int maxBits = SupportedGroups.getServerMaximumNegotiableFiniteFieldBits(manager.getContext().isFips(), clientSupportedGroups);
return maxBits >= provEphemeralDHKeySize ? maxBits : 0;
}
@Override
protected ProtocolVersion getMaximumVersion()
{
return manager.getContext().getMaximumVersion(sslParameters.getProtocols());
}
@Override
protected boolean selectCipherSuite(int cipherSuite) throws IOException
{
if (!selectCredentials(cipherSuite))
{
return false;
}
manager.getContext().validateNegotiatedCipherSuite(cipherSuite);
return super.selectCipherSuite(cipherSuite);
}
@Override
protected int selectCurve(int minimumCurveBits)
{
if (clientSupportedGroups == null)
{
return selectDefaultCurve(minimumCurveBits);
}
boolean isFips = manager.getContext().isFips();
return SupportedGroups.getServerSelectedCurve(isFips, minimumCurveBits, clientSupportedGroups);
}
@Override
protected int selectDefaultCurve(int minimumCurveBits)
{
return SupportedGroups.getServerDefaultCurve(manager.getContext().isFips(), minimumCurveBits);
}
@Override
protected TlsDHConfig selectDefaultDHConfig(int minimumFiniteFieldBits)
{
return SupportedGroups.getServerDefaultDHConfig(manager.getContext().isFips(), minimumFiniteFieldBits);
}
@Override
protected TlsDHConfig selectDHConfig(int minimumFiniteFieldBits)
{
minimumFiniteFieldBits = Math.max(minimumFiniteFieldBits, provEphemeralDHKeySize);
if (clientSupportedGroups == null)
{
return selectDefaultDHConfig(minimumFiniteFieldBits);
}
boolean isFips = manager.getContext().isFips();
int namedGroup = SupportedGroups.getServerSelectedFiniteField(isFips, minimumFiniteFieldBits,
clientSupportedGroups);
return TlsDHUtils.createNamedDHConfig(namedGroup);
}
public synchronized boolean isHandshakeComplete()
{
return handshakeComplete;
}
@Override
public TlsCredentials getCredentials()
throws IOException
{
return credentials;
}
@Override
public int[] getCipherSuites()
{
return TlsUtils.getSupportedCipherSuites(manager.getContextData().getCrypto(),
manager.getContext().convertCipherSuites(sslParameters.getCipherSuites()));
}
@Override
protected short[] getCompressionMethods()
{
return manager.getContext().isFips()
? new short[]{ CompressionMethod._null }
: super.getCompressionMethods();
}
// public TlsKeyExchange getKeyExchange() throws IOException
// // TODO[jsse] Check that all key exchanges used in JSSE supportedCipherSuites are handled
// return super.getKeyExchange();
@Override
public CertificateRequest getCertificateRequest() throws IOException
{
boolean shouldRequest = sslParameters.getNeedClientAuth() || sslParameters.getWantClientAuth();
if (!shouldRequest)
{
return null;
}
short[] certificateTypes = new short[]{ ClientCertificateType.rsa_sign,
ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign };
Vector serverSigAlgs = null;
if (TlsUtils.isSignatureAlgorithmsExtensionAllowed(serverVersion))
{
serverSigAlgs = JsseUtils.getSupportedSignatureAlgorithms(getCrypto());
}
Vector certificateAuthorities = new Vector();
X509TrustManager tm = manager.getContextData().getTrustManager();
if (tm != null)
{
for (X509Certificate caCert : tm.getAcceptedIssuers())
{
certificateAuthorities.addElement(X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()));
}
}
return new CertificateRequest(certificateTypes, serverSigAlgs, certificateAuthorities);
}
@Override
public int getSelectedCipherSuite() throws IOException
{
keyManagerMissCache = new HashSet<String>();
int selectedCipherSuite = super.getSelectedCipherSuite();
LOG.fine("Server selected cipher suite: " + manager.getContext().getCipherSuiteString(selectedCipherSuite));
keyManagerMissCache = null;
return selectedCipherSuite;
}
@Override
public Hashtable getServerExtensions() throws IOException
{
super.getServerExtensions();
/*
* TODO[jsse] RFC 6066 When resuming a session, the server MUST NOT include a server_name
* extension in the server hello.
*/
if (matchedSNIServerName != null)
{
checkServerExtensions().put(TlsExtensionsUtils.EXT_server_name, TlsExtensionsUtils.createEmptyExtensionData());
}
return serverExtensions;
}
@Override
public TlsSession getSessionToResume(byte[] sessionID)
{
ProvSSLSessionContext sessionContext = manager.getContextData().getServerSessionContext();
this.sslSession = sessionContext.getSessionImpl(sessionID);
if (sslSession != null)
{
TlsSession sessionToResume = sslSession.getTlsSession();
if (sessionToResume != null)
{
return sessionToResume;
}
}
if (!manager.getEnableSessionCreation())
{
throw new IllegalStateException("No resumable sessions and session creation is disabled");
}
return null;
}
@Override
public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause)
{
Level level = alertLevel == AlertLevel.warning ? Level.FINE
: alertDescription == AlertDescription.internal_error ? Level.WARNING
: Level.INFO;
if (LOG.isLoggable(level))
{
String msg = JsseUtils.getAlertLogMessage("Server raised", alertLevel, alertDescription);
if (message != null)
{
msg = msg + ": " + message;
}
LOG.log(level, msg, cause);
}
}
@Override
public void notifyAlertReceived(short alertLevel, short alertDescription)
{
super.notifyAlertReceived(alertLevel, alertDescription);
Level level = alertLevel == AlertLevel.warning ? Level.FINE
: Level.INFO;
if (LOG.isLoggable(level))
{
String msg = JsseUtils.getAlertLogMessage("Server received", alertLevel, alertDescription);
LOG.log(level, msg);
}
}
@Override
public ProtocolVersion getServerVersion() throws IOException
{
/*
* TODO[jsse] It may be best to just require the "protocols" list to be a contiguous set
* (especially in light of TLS_FALLBACK_SCSV), then just determine the minimum/maximum,
* and keep the super class implementation of this.
*/
String[] protocols = sslParameters.getProtocols();
if (protocols != null && protocols.length > 0)
{
for (ProtocolVersion version = clientVersion; version != null; version = version.getPreviousVersion())
{
String versionString = manager.getContext().getProtocolString(version);
if (versionString != null && JsseUtils.contains(protocols, versionString))
{
LOG.fine("Server selected protocol version: " + version);
return serverVersion = version;
}
}
}
throw new TlsFatalAlert(AlertDescription.protocol_version);
}
@Override
public void notifyClientCertificate(Certificate clientCertificate) throws IOException
{
// NOTE: This method isn't called unless we returned non-null from getCertificateRequest() earlier
assert sslParameters.getNeedClientAuth() || sslParameters.getWantClientAuth();
boolean noClientCert = clientCertificate == null || clientCertificate.isEmpty();
if (noClientCert)
{
if (sslParameters.getNeedClientAuth())
{
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
}
else
{
X509Certificate[] chain = JsseUtils.getX509CertificateChain(manager.getContextData().getCrypto(), clientCertificate);
short clientCertificateType = clientCertificate.getCertificateAt(0).getClientCertificateType();
String authType = JsseUtils.getAuthTypeClient(clientCertificateType);
if (!manager.isClientTrusted(chain, authType))
{
/*
* TODO[jsse] The low-level TLS API currently doesn't provide a way to indicate that
* we wish to proceed with an untrusted client certificate, so we always fail here.
*/
throw new TlsFatalAlert(AlertDescription.bad_certificate);
}
}
}
@Override
public synchronized void notifyHandshakeComplete() throws IOException
{
this.handshakeComplete = true;
TlsSession handshakeSession = context.getSession();
if (sslSession == null || sslSession.getTlsSession() != handshakeSession)
{
sslSession = manager.getContextData().getServerSessionContext().reportSession(handshakeSession, null, -1);
}
manager.notifyHandshakeComplete(new ProvSSLConnection(context, sslSession));
}
@Override
public void notifySecureRenegotiation(boolean secureRenegotiation) throws IOException
{
if (!secureRenegotiation)
{
boolean allowLegacyHelloMessages = PropertyUtils.getBooleanSystemProperty("sun.security.ssl.allowLegacyHelloMessages", true);
if (!allowLegacyHelloMessages)
{
/*
* RFC 5746 3.4/3.6. In this case, some clients/servers may want to terminate the handshake instead
* of continuing; see Section 4.1/4.3 for discussion.
*/
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
}
}
@Override
public void processClientExtensions(Hashtable clientExtensions) throws IOException
{
super.processClientExtensions(clientExtensions);
if (clientExtensions != null)
{
/*
* TODO[jsse] RFC 6066 A server that implements this extension MUST NOT accept the
* request to resume the session if the server_name extension contains a different name.
*/
Collection<BCSNIMatcher> sniMatchers = manager.getProvSSLParameters().getSNIMatchers();
if (sniMatchers != null && !sniMatchers.isEmpty())
{
ServerNameList serverNameList = TlsExtensionsUtils.getServerNameExtension(clientExtensions);
if (serverNameList != null)
{
matchedSNIServerName = JsseUtils.findMatchingSNIServerName(serverNameList, sniMatchers);
if (matchedSNIServerName == null)
{
throw new TlsFatalAlert(AlertDescription.unrecognized_name);
}
}
}
}
}
protected boolean selectCredentials(int cipherSuite) throws IOException
{
this.credentials = null;
int keyExchangeAlgorithm = TlsUtils.getKeyExchangeAlgorithm(cipherSuite);
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DH_anon:
case KeyExchangeAlgorithm.ECDH_anon:
return true;
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.DHE_RSA:
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDH_RSA:
case KeyExchangeAlgorithm.ECDHE_ECDSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
case KeyExchangeAlgorithm.RSA:
break;
default:
return false;
}
X509KeyManager km = manager.getContextData().getKeyManager();
if (km == null)
{
return false;
}
String keyType = JsseUtils.getAuthTypeServer(keyExchangeAlgorithm);
if (keyManagerMissCache.contains(keyType))
{
return false;
}
// TODO[jsse] Is there some extension where the client can specify these (SNI maybe)?
Principal[] issuers = null;
// TODO[jsse] How is this used?
Socket socket = null;
String alias = km.chooseServerAlias(keyType, issuers, socket);
if (alias == null)
{
keyManagerMissCache.add(keyType);
return false;
}
TlsCrypto crypto = getCrypto();
if (!(crypto instanceof JcaTlsCrypto))
{
// TODO[jsse] Need to have TlsCrypto construct the credentials from the certs/key
throw new UnsupportedOperationException();
}
PrivateKey privateKey = km.getPrivateKey(alias);
Certificate certificate = JsseUtils.getCertificateMessage(crypto, km.getCertificateChain(alias));
if (privateKey == null
|| !JsseUtils.isUsableKeyForServer(keyExchangeAlgorithm, privateKey)
|| certificate.isEmpty())
{
keyManagerMissCache.add(keyType);
return false;
}
/*
* TODO[jsse] Before proceeding with EC credentials, should we check (TLS 1.2+) that the
* used curve is supported by the client according to the elliptic_curves/named_groups
* extension?
*/
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDH_RSA:
{
// TODO[jsse] Need to have TlsCrypto construct the credentials from the certs/key
this.credentials = new JceDefaultTlsCredentialedAgreement((JcaTlsCrypto)crypto, certificate, privateKey);
return true;
}
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.DHE_RSA:
case KeyExchangeAlgorithm.ECDHE_ECDSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
{
short signatureAlgorithm = TlsUtils.getSignatureAlgorithm(keyExchangeAlgorithm);
SignatureAndHashAlgorithm sigAlg = TlsUtils.chooseSignatureAndHashAlgorithm(context,
supportedSignatureAlgorithms, signatureAlgorithm);
// TODO[jsse] Need to have TlsCrypto construct the credentials from the certs/key
this.credentials = new JcaDefaultTlsCredentialedSigner(new TlsCryptoParameters(context), (JcaTlsCrypto)crypto,
privateKey, certificate, sigAlg);
return true;
}
case KeyExchangeAlgorithm.RSA:
{
// TODO[jsse] Need to have TlsCrypto construct the credentials from the certs/key
this.credentials = new JceDefaultTlsCredentialedDecryptor((JcaTlsCrypto)crypto, certificate, privateKey);
return true;
}
default:
return false;
}
}
}
|
package ontology;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.ClassExpressionType;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import util.Table2Set;
import util.Table3List;
public class GeneOntology
{
//Attributes
//The OWL Ontology Manager and Data Factory
private OWLOntologyManager manager;
//The entity expansion limit property
private final String LIMIT = "entityExpansionLimit";
//The uri <-> numeric index map of ontology classes
protected HashMap<String,Integer> uriClasses;
protected HashMap<Integer,String> classUris;
//The local name <-> numeric index map of ontology classes
protected HashMap<String,Integer> nameClasses;
protected HashMap<Integer,String> classNames;
//The numeric index -> label map of ontology classes
protected HashMap<Integer,String> classLabels;
protected HashMap<String,Integer> labelClasses;
//The uri <-> numeric index map of ontology object properties
protected HashMap<String,Integer> uriProperties;
protected HashMap<Integer,String> propertyUris;
protected HashMap<Integer,String> propertyNames;
//Map of object properties that are transitive over other object properties
//(including themselves)
protected Table2Set<Integer,Integer> transitiveOver;
//Map between ancestor classes and their descendants (with transitive closure)
private Table3List<Integer,Integer,Relationship> descendantMap;
//Map between descendant classes and their ancestors (with transitive closure)
private Table3List<Integer,Integer,Relationship> ancestorMap;
//The map of term indexes -> GOType indexes in the ontology
private HashMap<Integer,Integer> termTypes;
//The array of term indexes of the GOType roots
private int[] rootIndexes;
private HashSet<String> deprecated;
private HashMap<String,String> alternatives;
//Constructors
/**
* Constructs an empty ontology
*/
public GeneOntology()
{
//Initialize the data structures
uriClasses = new HashMap<String,Integer>();
classUris = new HashMap<Integer,String>();
nameClasses = new HashMap<String,Integer>();
classNames = new HashMap<Integer,String>();
classLabels = new HashMap<Integer,String>();
labelClasses = new HashMap<String,Integer>();
uriProperties = new HashMap<String,Integer>();
propertyUris = new HashMap<Integer,String>();
propertyNames = new HashMap<Integer,String>();
transitiveOver = new Table2Set<Integer,Integer>();
descendantMap = new Table3List<Integer,Integer,Relationship>();
ancestorMap = new Table3List<Integer,Integer,Relationship>();
termTypes = new HashMap<Integer,Integer>();
rootIndexes = new int[3];
deprecated = new HashSet<String>();
alternatives = new HashMap<String,String>();
//Increase the entity expansion limit to allow large ontologies
System.setProperty(LIMIT, "1000000");
//Get an Ontology Manager
manager = OWLManager.createOWLOntologyManager();
}
/**
* Constructs an Ontology from file
* @param path: the path to the input Ontology file
* @throws OWLOntologyCreationException
*/
public GeneOntology(String path) throws OWLOntologyCreationException
{
this();
//Load the local ontology
File f = new File(path);
OWLOntology o;
o = manager.loadOntologyFromOntologyDocument(f);
init(o);
//Close the OntModel
manager.removeOntology(o);
//Reset the entity expansion limit
System.clearProperty(LIMIT);
}
/**
* Constructs an Ontology from an URI
* @param uri: the URI of the input Ontology
* @throws OWLOntologyCreationException
*/
public GeneOntology(URI uri) throws OWLOntologyCreationException
{
this();
OWLOntology o;
//Check if the URI is local
if(uri.toString().startsWith("file:"))
{
File f = new File(uri);
o = manager.loadOntologyFromOntologyDocument(f);
}
else
{
IRI i = IRI.create(uri);
o = manager.loadOntology(i);
}
init(o);
//Close the OntModel
manager.removeOntology(o);
//Reset the entity expansion limit
System.clearProperty(LIMIT);
}
//Public Methods
/**
* @return the number of Classes in the Ontology
*/
public int classCount()
{
return classUris.size();
}
/**
* @param index: the index of the class in the ontology
* @return whether the class belongs to the ontology
*/
public boolean containsIndex(int index)
{
return classUris.containsKey(index);
}
/**
* @param name: the local name of the class in the ontology
* @return whether the class belongs to the ontology
*/
public boolean containsName(String name)
{
return nameClasses.containsKey(name) || alternatives.containsKey(name);
}
/**
* @param child: the index of the child class
* @param parent: the index of the parent class
* @return whether the ontology contains a relationship between child and parent
*/
public boolean containsRelationship(int child, int parent)
{
return descendantMap.contains(parent,child);
}
/**
* @param child: the index of the child class
* @param parent: the index of the parent class
* @return whether the ontology contains an 'is_a' relationship between child and parent
*/
public boolean containsSubClass(int child, int parent)
{
if(!descendantMap.contains(parent,child))
return false;
Vector<Relationship> rels = descendantMap.get(parent,child);
for(Relationship r : rels)
if(r.getProperty() == -1)
return true;
return false;
}
/**
* @param uri: the URI of the class in the ontology
* @return whether the class belongs to the ontology
*/
public boolean containsUri(String uri)
{
return uriClasses.containsKey(uri);
}
/**
* @param classId: the id of the class to search in the map
* @return the list of ancestors of the given class
*/
public Set<Integer> getAncestors(int classId)
{
if(ancestorMap.contains(classId))
return ancestorMap.keySet(classId);
return new HashSet<Integer>();
}
/**
* @param classId: the id of the class to search in the map
* @param distance: the distance between the class and its ancestors
* @return the list of ancestors at the given distance from the input class
*/
public Set<Integer> getAncestors(int classId, int distance)
{
HashSet<Integer> asc = new HashSet<Integer>();
if(!ancestorMap.contains(classId))
return asc;
for(Integer i : ancestorMap.keySet(classId))
for(Relationship r : ancestorMap.get(classId, i))
if(r.getDistance() == distance)
asc.add(i);
return asc;
}
/**
* @param classId: the id of the class to search in the map
* @param distance: the distance between the class and its ancestors
* @param prop: the relationship property between the class and its ancestors
* @return the list of ancestors of the input class that are at the given
* distance and with the given property
*/
public Set<Integer> getAncestors(int classId, int distance, int prop)
{
HashSet<Integer> asc = new HashSet<Integer>();
if(!ancestorMap.contains(classId))
return asc;
for(Integer i : ancestorMap.keySet(classId))
for(Relationship r : ancestorMap.get(classId, i))
if(r.getDistance() == distance && r.getProperty() == prop)
asc.add(i);
return asc;
}
/**
* @param classId: the id of the class to search in the map
* @param prop: the relationship property between the class and its ancestors
* @return the list of ancestors at the given distance from the input class
*/
public Set<Integer> getAncestorsProperty(int classId, int prop)
{
HashSet<Integer> asc = new HashSet<Integer>();
if(!ancestorMap.contains(classId))
return asc;
for(Integer i : ancestorMap.keySet(classId))
for(Relationship r : ancestorMap.get(classId, i))
if(r.getProperty() == prop)
asc.add(i);
return asc;
}
/**
* @return the set of classes with ancestors in the map
*/
public Set<Integer> getChildren()
{
if(ancestorMap != null)
return ancestorMap.keySet();
return new HashSet<Integer>();
}
/**
* @param classId: the id of the class to search in the map
* @return the list of direct children of the given class
*/
public Set<Integer> getChildren(int classId)
{
return getDescendants(classId,1);
}
/**
* @param classes: the set the class to search in the map
* @return the list of direct subclasses shared by the set of classes
*/
public Set<Integer> getCommonSubClasses(Set<Integer> classes)
{
if(classes == null || classes.size() == 0)
return null;
Iterator<Integer> it = classes.iterator();
Vector<Integer> subclasses = new Vector<Integer>(getSubClasses(it.next(),false));
while(it.hasNext())
{
HashSet<Integer> s = new HashSet<Integer>(getSubClasses(it.next(),false));
for(int i = 0; i < subclasses.size(); i++)
{
if(!s.contains(subclasses.get(i)))
{
subclasses.remove(i);
i
}
}
}
for(int i = 0; i < subclasses.size()-1; i++)
{
for(int j = i+1; j < subclasses.size(); j++)
{
if(containsSubClass(subclasses.get(i),subclasses.get(j)))
{
subclasses.remove(i);
i
j
}
if(containsSubClass(subclasses.get(j),subclasses.get(i)))
{
subclasses.remove(j);
j
}
}
}
return new HashSet<Integer>(subclasses);
}
/**
* @param classId: the id of the class to search in the map
* @return the list of descendants of the input class
*/
public Set<Integer> getDescendants(int classId)
{
if(descendantMap.contains(classId))
return descendantMap.keySet(classId);
return new HashSet<Integer>();
}
/**
* @param classId: the id of the class to search in the map
* @param distance: the distance between the class and its ancestors
* @return the list of descendants at the given distance from the input class
*/
public Set<Integer> getDescendants(int classId, int distance)
{
HashSet<Integer> desc = new HashSet<Integer>();
if(!descendantMap.contains(classId))
return desc;
for(Integer i : descendantMap.keySet(classId))
for(Relationship r : descendantMap.get(classId, i))
if(r.getDistance() == distance)
desc.add(i);
return desc;
}
/**
* @param classId: the id of the class to search in the map
* @param distance: the distance between the class and its ancestors
* @param prop: the relationship property between the class and its ancestors
* @return the list of descendants of the input class at the given distance
* and with the given property
*/
public Set<Integer> getDescendants(int classId, int distance, int prop)
{
HashSet<Integer> desc = new HashSet<Integer>();
if(!descendantMap.contains(classId))
return desc;
for(Integer i : descendantMap.keySet(classId))
for(Relationship r : descendantMap.get(classId, i))
if(r.getDistance() == distance && r.getProperty() == prop)
desc.add(i);
return desc;
}
/**
* @param classId: the id of the class to search in the map
* @param prop: the relationship property between the class and its ancestors
* @return the list of descendants at the given distance from the input class
*/
public Set<Integer> getDescendantsProperty(int classId, int prop)
{
HashSet<Integer> desc = new HashSet<Integer>();
if(!descendantMap.contains(classId))
return desc;
for(Integer i : descendantMap.keySet(classId))
for(Relationship r : descendantMap.get(classId, i))
if(r.getProperty() == prop)
desc.add(i);
return desc;
}
/**
* @param child: the index of the child class
* @param parent: the index of the parent class
* @return the minimal distance between the child and parent,
* or 0 if child==parent, or -1 if they aren't related
*/
public int getDistance(int child, int parent)
{
if(child == parent)
return 0;
if(!ancestorMap.contains(child, parent))
return -1;
Vector<Relationship> rels = ancestorMap.get(child,parent);
int distance = rels.get(0).getDistance();
for(Relationship r : rels)
if(r.getDistance() < distance)
distance = r.getDistance();
return distance;
}
/**
* @param classId: the id of the class to search in the map
* @return the list of equivalences of the given class
*/
public Set<Integer> getEquivalences(int classId)
{
return getDescendants(classId, 0);
}
/**
* @param classId: the id of the class to search in the map
* @return the list of classes equivalent to the given class
*/
public Set<Integer> getEquivalentClasses(int classId)
{
return getDescendants(classId,0,-1);
}
/**
* @param name: the local name of the class to get from the Ontology
* @return the index of the corresponding name in the Ontology
*/
public int getIndexName(String name)
{
if(nameClasses.containsKey(name))
return nameClasses.get(name);
if(alternatives.containsKey(name) &&
nameClasses.containsKey(alternatives.get(name)))
return nameClasses.get(alternatives.get(name));
return -1;
}
/**
* @param uri: the URI of the class to get from the Ontology
* @return the index of the corresponding name in the Ontology
*/
public int getIndexUri(String uri)
{
return uriClasses.get(uri);
}
/**
* @param term: the integer representing a term, from the Ontology
* @return the information content of the given term
*/
public double getInfoContent(int term) {
return 1-Math.log(1+getSubClasses(term,false).size())/
Math.log(1+getSubClasses(rootIndexes[getTypeIndex(term)],false).size());
}
/**
* @param index: the index of the class to get the label
* @return the label of the class with the given index
*/
public String getLabel(int index)
{
return classLabels.get(index);
}
/**
* @param index: the index of the class to get the name
* @return the local name of the class with the given index
*/
public String getLocalName(int index)
{
return classNames.get(index);
}
/**
* @return the set of classes with ancestors in the map
*/
public Set<Integer> getParents()
{
if(descendantMap != null)
return descendantMap.keySet();
return new HashSet<Integer>();
}
/**
* @param class: the id of the class to search in the map
* @return the list of direct parents of the given class
*/
public Set<Integer> getParents(int classId)
{
return getAncestors(classId,1);
}
/**
* @param index: the index of the class to get the name
* @return the local name of the class with the given index
*/
public String getPropertyName(int index)
{
if(index == -1)
return "is_a";
else
return propertyNames.get(index);
}
/**
* @param child: the id of the child class to search in the map
* @param parent: the id of the parent class to search in the map
* @return the 'best' relationship between the two classes
*/
public Relationship getRelationship(int child, int parent)
{
if(!ancestorMap.contains(child, parent))
return null;
Relationship rel = ancestorMap.get(child).get(parent).get(0);
for(Relationship r : ancestorMap.get(child).get(parent))
if(r.compareTo(rel) > 0)
rel = r;
return rel;
}
/**
* @param child: the id of the child class to search in the map
* @param parent: the id of the parent class to search in the map
* @return the relationships between the two classes
*/
public Vector<Relationship> getRelationships(int child, int parent)
{
return ancestorMap.get(child).get(parent);
}
/**
* @param index: the GOType index (0 = MF; 1 = BP; 2 = CC)
* @return the Ontology index of the root term for that GOType
*/
public int getRoot(int index)
{
return rootIndexes[index];
}
/**
* @param classId: the id of the class to search in the map
* @param direct: whether to return just the direct subclasses or all subclasses
* @return the list of direct or indirect subclasses of the input class
*/
public Set<Integer> getSubClasses(int classId, boolean direct)
{
if(direct)
return getDescendants(classId,1,-1);
else
return getDescendantsProperty(classId,-1);
}
/**
* @param classId: the id of the class to search in the map
* @param direct: whether to return just the direct superclasses or all superclasses
* @return the list of direct or indirect superclasses of the input class
*/
public Set<Integer> getSuperClasses(int classId, boolean direct)
{
if(direct)
return getAncestors(classId,1,-1);
else
return getAncestorsProperty(classId,-1);
}
/**
* @param index: the index of the GO term to get
* @return the GOType of the GO term with the given index
*/
public GOType getType(int index)
{
return GOType.values()[termTypes.get(index)];
}
/**
* @param index: the index of the GO term to get
* @return the GOType index of the GO term with the given index
* (0 = MF; 1 = BP; 2 = CC)
*/
public int getTypeIndex(int index)
{
if(termTypes.containsKey(index))
return termTypes.get(index);
else
{
//System.out.println(classNames.get(index));
return 1;
}
}
/**
* @param child: the id of the child class to search in the map
* @param parent: the id of the parent class to search in the map
* @param property: the id of the property between child and parent
* @return whether there is a relationship between child and parent
* with the given property
*/
public boolean hasProperty(int child, int parent, int property)
{
Vector<Relationship> rels = getRelationships(child,parent);
for(Relationship r : rels)
if(r.getProperty() == property)
return true;
return false;
}
/**
* @return the number of relationships in the map
*/
public int relationshipCount()
{
return ancestorMap.size();
}
/**
* @param classId: the id of the class to search in the map
* @param direct: whether to return all subclasses or just the direct ones
* @return the number of direct or indirect subclasses of the input class
*/
public int subClassCount(int classId, boolean direct)
{
return getSubClasses(classId,direct).size();
}
/**
* @param classId: the id of the class to search in the map
* @param direct: whether to return all superclasses or just the direct ones
* @return the number of direct or indirect superclasses of the input class
*/
public int superClassCount(int classId, boolean direct)
{
return getSuperClasses(classId,direct).size();
}
//Private Methods
//Builds the ontology data structures
private void init(OWLOntology o)
{
//Get the classes and their names and synonyms
getClasses(o);
//Get the properties
getProperties(o);
//Build the relationship map
getRelationships(o);
//Extend the relationship map
transitiveClosure();
}
//Processes the classes, their lexical information and cross-references
private void getClasses(OWLOntology o)
{
int index = 0;
//Get an iterator over the ontology classes
Set<OWLClass> classes = o.getClassesInSignature(true);
for(OWLClass c : classes)
{
//Then get the URI for each class
String classUri = c.getIRI().toString();
if(classUri == null || classUri.endsWith("owl#Thing") || classUri.endsWith("owl:Thing"))
continue;
//Check if the class is deprecated
boolean dep = false;
for(OWLAnnotation a : c.getAnnotations(o))
{
if(a.getProperty().toString().equals("owl:deprecated") && ((OWLLiteral)a.getValue()).parseBoolean())
{
dep = true;
break;
}
}
//If it is, record it and skip it
if(dep)
{
deprecated.add(getLocalName(classUri).replace('_', ':'));
continue;
}
classUris.put(++index,classUri);
uriClasses.put(classUri, index);
//Get the local name from the URI
String name = getLocalName(classUri).replace('_', ':');
classNames.put(index,name);
nameClasses.put(name, index);
//Now get the class's label and type
Set<OWLAnnotation> annots = c.getAnnotations(o);
for(OWLOntology ont : o.getImports())
annots.addAll(c.getAnnotations(ont));
for(OWLAnnotation annotation : annots)
{
//Label
if(annotation.getProperty().toString().equals("rdfs:label") && annotation.getValue() instanceof OWLLiteral)
{
OWLLiteral val = (OWLLiteral) annotation.getValue();
String lab = val.getLiteral();
classLabels.put(index,lab);
labelClasses.put(lab, index);
//If the label is a GOType, then the term is a root
int typeIndex = GOType.index(lab);
if(typeIndex > -1)
rootIndexes[typeIndex] = index;
}
//Type
else if(annotation.getProperty().toString().contains("hasOBONamespace") && annotation.getValue() instanceof OWLLiteral)
{
OWLLiteral val = (OWLLiteral) annotation.getValue();
String type = val.getLiteral();
int typeIndex = GOType.index(type);
if(typeIndex > -1)
termTypes.put(index, typeIndex);
}
//Alternative
if(annotation.getProperty().toString().contains("hasAlternativeId") && annotation.getValue() instanceof OWLLiteral)
{
OWLLiteral val = (OWLLiteral) annotation.getValue();
String alt = val.getLiteral();
alternatives.put(alt, name);
}
}
}
}
//Reads the object properties
private void getProperties(OWLOntology o)
{
int index = 0;
//Get the Object Properties
Set<OWLObjectProperty> oProps = o.getObjectPropertiesInSignature(true);
for(OWLObjectProperty op : oProps)
{
//Get the URI of each property
String propUri = op.getIRI().toString();
if(propUri == null)
continue;
propertyUris.put(++index,propUri);
uriProperties.put(propUri, index);
//Get its label
Set<OWLAnnotation> annots = op.getAnnotations(o);
for(OWLOntology ont : o.getImports())
annots.addAll(op.getAnnotations(ont));
for(OWLAnnotation annotation : annots)
{
//Label
if(annotation.getProperty().toString().equals("rdfs:label") && annotation.getValue() instanceof OWLLiteral)
{
OWLLiteral val = (OWLLiteral) annotation.getValue();
String lab = val.getLiteral();
propertyNames.put(index,lab);
break;
}
}
//If it is transitive, add it to the transitiveOver map
//(as transitive over itself)
if(op.isTransitive(o))
transitiveOver.add(index,index);
}
//Process transitive_over relations (this needs to be done
//in a 2nd loop as all properties must already be indexed)
for(OWLObjectProperty op : oProps)
{
//Transitive over relations go to the transitiveOver map
for(OWLAxiom e : op.getReferencingAxioms(o))
{
//In OWL, the OBO transitive_over relation is encoded as a sub-property chain of
//the form: "SubObjectPropertyOf(ObjectPropertyChain( <p1> <p2> ) <this_p> )"
//in which 'this_p' is usually 'p1' but can also be 'p2' (in case you want to
//define that another property is transitive over this one, which may happen when
//the other property is imported and this property occurs only in this ontology)
if(!e.isOfType(AxiomType.SUB_PROPERTY_CHAIN_OF))
continue;
//Unfortunately, there isn't much support for "ObjectPropertyChain"s in the OWL
//API, so the only way to get the referenced properties while preserving their
//order is to parse the String representation of the sub-property chain
//(getObjectPropertiesInSignature() does NOT preserve the order)
String[] chain = e.toString().split("[\\(\\)]");
//Make sure the structure of the sub-property chain is in the expected format
if(!chain[0].equals("SubObjectPropertyOf") || !chain[1].equals("ObjectPropertyChain"))
continue;
//Get the indexes of the tags surrounding the URIs
int index1 = chain[2].indexOf("<")+1;
int index2 = chain[2].indexOf(">");
int index3 = chain[2].lastIndexOf("<")+1;
int index4 = chain[2].lastIndexOf(">");
//Make sure the indexes check up
if(index1 < 0 || index2 <= index1 || index3 <= index2 || index4 <= index3)
continue;
String uri1 = chain[2].substring(index1,index2);
String uri2 = chain[2].substring(index3,index4);
//Make sure the URIs are listed object properties
if(!uriProperties.containsKey(uri1) || !uriProperties.containsKey(uri2))
continue;
//If everything checks up, add the relation to the transitiveOver map
transitiveOver.add(uriProperties.get(uri1), uriProperties.get(uri2));
}
}
}
//Reads all class relationships
private void getRelationships(OWLOntology o)
{
//Get an iterator over the ontology classes
Set<OWLClass> classes = o.getClassesInSignature(true);
//For each term index (from 'termURIs' list)
for(OWLClass c : classes)
{
if(!uriClasses.containsKey(c.getIRI().toString()))
continue;
//Get the subclass expressions to capture and add relationships
Set<OWLClassExpression> superClasses = c.getSuperClasses(o);
for(OWLOntology ont : o.getDirectImports())
superClasses.addAll(c.getSuperClasses(ont));
for(OWLClassExpression e : superClasses)
addRelationship(o,c,e,true);
//Get the equivalence expressions to capture and add relationships
Set<OWLClassExpression> equivClasses = c.getEquivalentClasses(o);
for(OWLOntology ont : o.getDirectImports())
equivClasses.addAll(c.getEquivalentClasses(ont));
for(OWLClassExpression e : equivClasses)
addRelationship(o,c,e,false);
}
}
//Get the local name of an entity from its URI
private String getLocalName(String uri)
{
int index = uri.indexOf("
if(index == 0)
index = uri.lastIndexOf("/") + 1;
return uri.substring(index);
}
private void addRelationship(OWLOntology o, OWLClass c, OWLClassExpression e, boolean sub)
{
int child = uriClasses.get(c.getIRI().toString());
int parent = -1;
int distance = (sub) ? 1 : 0;
int prop = -1;
ClassExpressionType type = e.getClassExpressionType();
//If it is a class, process it here
if(type.equals(ClassExpressionType.OWL_CLASS))
{
String par = e.asOWLClass().getIRI().toString();
if(!uriClasses.containsKey(par))
return;
parent = uriClasses.get(par);
}
//If it is a 'some values' object property restriction, process it
else if(type.equals(ClassExpressionType.OBJECT_SOME_VALUES_FROM) ||
type.equals(ClassExpressionType.OBJECT_ALL_VALUES_FROM))
{
Set<OWLObjectProperty> props = e.getObjectPropertiesInSignature();
if(props == null || props.size() != 1)
return;
OWLObjectProperty p = props.iterator().next();
String propUri = p.getIRI().toString();
if(!uriProperties.containsKey(propUri))
return;
prop = uriProperties.get(propUri);
Set<OWLClass> sup = e.getClassesInSignature();
if(sup == null || sup.size() != 1)
return;
OWLClass cls = sup.iterator().next();
String par = cls.getIRI().toString();
if(!uriClasses.containsKey(par))
return;
parent = uriClasses.get(par);
}
//If it is an intersection of classes, capture the implied subclass relationships
else if(type.equals(ClassExpressionType.OBJECT_INTERSECTION_OF))
{
Set<OWLClassExpression> inter = e.asConjunctSet();
for(OWLClassExpression cls : inter)
addRelationship(o,c,cls,true);
}
if(parent < 1)
return;
Relationship r = new Relationship(distance,prop);
descendantMap.add(parent,child,r);
ancestorMap.add(child,parent,r);
}
/**
* Compute the transitive closure of the RelationshipMap
* by adding inherited relationships (and their distances)
* This is an implementation of the Semi-Naive Algorithm
*/
public void transitiveClosure()
{
Set<Integer> t = descendantMap.keySet();
int lastCount = 0;
for(int distance = 1; lastCount != descendantMap.size(); distance++)
{
lastCount = descendantMap.size();
for(Integer i : t)
{
Set<Integer> childs = getChildren(i);
childs.addAll(getEquivalences(i));
Set<Integer> pars = getAncestors(i,distance);
for(Integer j : pars)
{
Vector<Relationship> rel1 = getRelationships(i,j);
for(int k = 0; k < rel1.size(); k++)
{
Relationship r1 = rel1.get(k);
int p1 = r1.getProperty();
for(Integer h : childs)
{
Vector<Relationship> rel2 = getRelationships(h,i);
for(int l = 0; l < rel2.size(); l++)
{
Relationship r2 = rel2.get(l);
int p2 = r2.getProperty();
//We only do transitive closure if at least one of the properties
//is 'is_a' (-1) or the child property is transitive over the parent
//(which covers the case where they are both the same transitive
//property)
if(!(p1 == -1 || p2 == -1 || transitiveOver.contains(p2,p1)))
continue;
int dist = r1.getDistance() + r2.getDistance();
//The child property wins in most cases: if p2 = p1,
//if p2 transitive_over p1, and otherwise if p1 = is_a
int prop = p2;
//The parent property only wins if p2 = is_a and p1 != is_a
if(p2 == -1 || p1 != -1)
prop = p1;
Relationship r = new Relationship(dist,prop);
descendantMap.add(j,h,r);
ancestorMap.add(h,j,r);
}
}
}
}
}
}
}
}
|
// Revision 1.1 1999-01-31 13:33:08+00 sm11td
// Initial revision
package Debrief.Wrappers;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import Debrief.ReaderWriter.Replay.FormatTracks;
import Debrief.Wrappers.Track.AbsoluteTMASegment;
import Debrief.Wrappers.Track.CoreTMASegment;
import Debrief.Wrappers.Track.PlanningSegment;
import Debrief.Wrappers.Track.RelativeTMASegment;
import Debrief.Wrappers.Track.SplittableLayer;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support;
import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import Debrief.Wrappers.Track.WormInHoleOffset;
import MWC.GUI.BaseLayer;
import MWC.GUI.CanvasType;
import MWC.GUI.DynamicPlottable;
import MWC.GUI.Editable;
import MWC.GUI.FireExtended;
import MWC.GUI.FireReformatted;
import MWC.GUI.Layer;
import MWC.GUI.Canvas.CanvasTypeUtilities;
import MWC.GUI.Layer.ProvidesContiguousElements;
import MWC.GUI.Layers;
import MWC.GUI.MessageProvider;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Properties.LineStylePropertyEditor;
import MWC.GUI.Properties.TimeFrequencyPropertyEditor;
import MWC.GUI.Shapes.DraggableItem;
import MWC.GUI.Shapes.HasDraggableComponents;
import MWC.GUI.Shapes.TextLabel;
import MWC.GUI.Shapes.Symbols.Vessels.WorldScaledSym;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.Watchable;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldDistance.ArrayLength;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldSpeed;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
/**
* the TrackWrapper maintains the GUI and data attributes of the whole track
* iteself, but the responsibility for the fixes within the track are demoted to
* the FixWrapper
*/
public class TrackWrapper extends MWC.GUI.PlainWrapper implements
WatchableList, DynamicPlottable, MWC.GUI.Layer, DraggableItem,
HasDraggableComponents, ProvidesContiguousElements, ISecondaryTrack
{
// member variables
/**
* class containing editable details of a track
*/
public final class trackInfo extends Editable.EditorType implements
Editable.DynamicDescriptors
{
/**
* constructor for this editor, takes the actual track as a parameter
*
* @param data
* track being edited
*/
public trackInfo(final TrackWrapper data)
{
super(data, data.getName(), "");
}
@Override
public final MethodDescriptor[] getMethodDescriptors()
{
// just add the reset color field first
final Class<TrackWrapper> c = TrackWrapper.class;
final MethodDescriptor[] mds =
{
method(c, "exportThis", null, "Export Shape"),
method(c, "resetLabels", null, "Reset DTG Labels"),
method(c, "calcCourseSpeed", null/* no params */,
"Generate calculated Course and Speed") };
return mds;
}
@Override
public final String getName()
{
return super.getName();
}
@Override
public final PropertyDescriptor[] getPropertyDescriptors()
{
try
{
PropertyDescriptor[] res =
{
expertProp("SymbolType",
"the type of symbol plotted for this label", FORMAT),
expertProp("LineThickness", "the width to draw this track", FORMAT),
expertProp("Name", "the track name"),
expertProp("InterpolatePoints",
"whether to interpolate points between known data points",
SPATIAL),
expertProp("Color", "the track color", FORMAT),
expertProp("SymbolColor", "the color of the symbol (when used)",
FORMAT),
expertProp(
"PlotArrayCentre",
"highlight the sensor array centre when non-zero array length provided",
FORMAT),
expertProp("TrackFont", "the track label font", FORMAT),
expertProp("NameVisible", "show the track label", VISIBILITY),
expertProp("PositionsVisible", "show individual Positions",
VISIBILITY),
expertProp("NameAtStart",
"whether to show the track name at the start (or end)",
VISIBILITY),
expertProp("LinkPositions", "whether to join the track points",
FORMAT),
expertProp("Visible", "whether the track is visible", VISIBILITY),
expertLongProp("NameLocation", "relative location of track label",
MWC.GUI.Properties.LocationPropertyEditor.class),
expertLongProp("LabelFrequency", "the label frequency",
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
expertLongProp("SymbolFrequency", "the symbol frequency",
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
expertLongProp("ResampleDataAt", "the data sample rate",
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
expertLongProp("ArrowFrequency", "the direction marker frequency",
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
expertLongProp("LineStyle",
"the line style used to join track points",
MWC.GUI.Properties.LineStylePropertyEditor.class),
};
res[0]
.setPropertyEditorClass(MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor.class);
res[1]
.setPropertyEditorClass(MWC.GUI.Properties.LineWidthPropertyEditor.class);
// SPECIAL CASE: if we have a world scaled symbol, provide
// editors for
// the symbol size
final TrackWrapper item = (TrackWrapper) this.getData();
if (item._theSnailShape instanceof WorldScaledSym)
{
// yes = better create height/width editors
final PropertyDescriptor[] res2 = new PropertyDescriptor[res.length + 2];
System.arraycopy(res, 0, res2, 2, res.length);
res2[0] = expertProp("SymbolLength", "Length of symbol", FORMAT);
res2[1] = expertProp("SymbolWidth", "Width of symbol", FORMAT);
// and now use the new value
res = res2;
}
return res;
}
catch (final IntrospectionException e)
{
return super.getPropertyDescriptors();
}
}
}
private static final String SOLUTIONS_LAYER_NAME = "Solutions";
public static final String SENSORS_LAYER_NAME = "Sensors";
/**
* keep track of versions - version id
*/
static final long serialVersionUID = 1;
/**
* put the other objects into this one as children
*
* @param wrapper
* whose going to receive it
* @param theLayers
* the top level layers object
* @param parents
* the track wrapppers containing the children
* @param subjects
* the items to insert.
*/
public static void groupTracks(final TrackWrapper target,
final Layers theLayers, final Layer[] parents, final Editable[] subjects)
{
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
target.add(ts);
}
}
else
{
if (obj instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) obj;
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
// and remember it
target.add(ts);
}
}
}
}
else
{
// get it's data, and add it to the target
target.add(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
}
/**
* perform a merge of the supplied tracks.
*
* @param target
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @return sufficient information to undo the merge
*/
public static int mergeTracks(final Editable target, final Layers theLayers,
final Layer[] parents, final Editable[] subjects)
{
// where we dump the new data points
Layer receiver = (Layer) target;
// first, check they don't overlap.
// start off by collecting the periods
final TimePeriod[] _periods = new TimePeriod.BaseTimePeriod[subjects.length];
for (int i = 0; i < subjects.length; i++)
{
final Editable editable = subjects[i];
TimePeriod thisPeriod = null;
if (editable instanceof TrackWrapper)
{
final TrackWrapper tw = (TrackWrapper) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(tw.getStartDTG(),
tw.getEndDTG());
}
else if (editable instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG());
}
_periods[i] = thisPeriod;
}
// now test them.
String failedMsg = null;
for (int i = 0; i < _periods.length; i++)
{
final TimePeriod timePeriod = _periods[i];
for (int j = 0; j < _periods.length; j++)
{
final TimePeriod timePeriod2 = _periods[j];
// check it's not us
if (timePeriod2 != timePeriod)
{
if (timePeriod.overlaps(timePeriod2))
{
failedMsg = "'" + subjects[i].getName() + "' and '"
+ subjects[j].getName() + "'";
break;
}
}
}
}
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// right, if the target is a TMA track, we have to change it into a
// proper
// track, since
// the merged tracks probably contain manoeuvres
if (target instanceof CoreTMASegment)
{
final CoreTMASegment tma = (CoreTMASegment) target;
final TrackSegment newSegment = new TrackSegment(tma);
// now do some fancy footwork to remove the target from the wrapper,
// and
// replace it with our new segment
newSegment.getWrapper().removeElement(target);
newSegment.getWrapper().add(newSegment);
// store the new segment into the receiver
receiver = newSegment;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
// is this the target item (note we're comparing against the item
// passed
// in, not our
// temporary receiver, since the receiver may now be a tracksegment,
// not a
// TMA segment
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
receiver.add(ts);
}
}
else
{
final Layer ts = (Layer) obj;
receiver.append(ts);
}
}
}
else
{
// get it's data, and add it to the target
receiver.append(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
return MessageProvider.OK;
}
/**
* whether to interpolate points in this track
*/
private boolean _interpolatePoints = false;
/**
* the end of the track to plot the label
*/
private boolean _LabelAtStart = true;
private HiResDate _lastLabelFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
private HiResDate _lastSymbolFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
private HiResDate _lastArrowFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
private HiResDate _lastDataFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
/**
* the width of this track
*/
private int _lineWidth = 2;
/**
* the style of this line
*
*/
private int _lineStyle = CanvasType.SOLID;
/**
* whether or not to link the Positions
*/
private boolean _linkPositions;
/**
* whether to show a highlight for the array centre
*
*/
private boolean _plotArrayCentre;
/**
* our editable details
*/
protected transient Editable.EditorType _myEditor = null;
/**
* keep a list of points waiting to be plotted
*
*/
transient int[] _myPts;
/**
* the sensor tracks for this vessel
*/
final private BaseLayer _mySensors;
/**
* the TMA solutions for this vessel
*/
final private BaseLayer _mySolutions;
/**
* keep track of how far we are through our array of points
*
*/
transient int _ptCtr = 0;
/**
* whether or not to show the Positions
*/
private boolean _showPositions;
/**
* the label describing this track
*/
private final MWC.GUI.Shapes.TextLabel _theLabel;
/**
* the list of wrappers we hold
*/
protected SegmentList _thePositions;
/**
* the symbol to pass on to a snail plotter
*/
private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape;
/**
* working ZERO location value, to reduce number of working values
*/
final private WorldLocation _zeroLocation = new WorldLocation(0, 0, 0);
// member functions
transient private FixWrapper finisher;
transient private HiResDate lastDTG;
transient private FixWrapper lastFix;
// for getNearestTo
transient private FixWrapper nearestFix;
/**
* working parameters
*/
// for getFixesBetween
transient private FixWrapper starter;
transient private TimePeriod _myTimePeriod;
transient private WorldArea _myWorldArea;
transient private final PropertyChangeListener _locationListener;
// constructors
/**
* Wrapper for a Track (a series of position fixes). It combines the data with
* the formatting details
*/
public TrackWrapper()
{
_mySensors = new SplittableLayer(true);
_mySensors.setName(SENSORS_LAYER_NAME);
_mySolutions = new BaseLayer(true);
_mySolutions.setName(SOLUTIONS_LAYER_NAME);
// create a property listener for when fixes are moved
_locationListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent arg0)
{
fixMoved();
}
};
// declare our arrays
_thePositions = new TrackWrapper_Support.SegmentList();
_thePositions.setWrapper(this);
_linkPositions = true;
// start off with positions showing (although the default setting for a
// fix
// is to not show a symbol anyway). We need to make this "true" so that
// when a fix position is set to visible it is not over-ridden by this
// setting
_showPositions = true;
_theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null);
// set an initial location for the label
_theLabel.setRelativeLocation(new Integer(
MWC.GUI.Properties.LocationPropertyEditor.RIGHT));
// initialise the symbol to use for plotting this track in snail mode
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory
.createSymbol("Submarine");
}
/**
* add the indicated point to the track
*
* @param point
* the point to add
*/
@Override
public void add(final MWC.GUI.Editable point)
{
boolean done = false;
// see what type of object this is
if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
fw.setTrackWrapper(this);
addFix(fw);
done = true;
}
// is this a sensor?
else if (point instanceof SensorWrapper)
{
final SensorWrapper swr = (SensorWrapper) point;
// add to our list
_mySensors.add(swr);
// tell the sensor about us
swr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
swr.setTrackName(this.getName());
// indicate success
done = true;
}
// is this a TMA solution track?
else if (point instanceof TMAWrapper)
{
final TMAWrapper twr = (TMAWrapper) point;
// add to our list
_mySolutions.add(twr);
// tell the sensor about us
twr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
twr.setTrackName(this.getName());
// indicate success
done = true;
}
else if (point instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) point;
seg.setWrapper(this);
_thePositions.addSegment((TrackSegment) point);
done = true;
// hey, sort out the positions
sortOutRelativePositions();
}
if (!done)
{
MWC.GUI.Dialogs.DialogFactory.showMessage(
"Add point",
"Sorry it is not possible to add:" + point.getName() + " to "
+ this.getName());
}
}
/**
* add the fix wrapper to the track
*
* @param theFix
* the Fix to be added
*/
public void addFix(final FixWrapper theFix)
{
// do we have any track segments
if (_thePositions.size() == 0)
{
// nope, add one
final TrackSegment firstSegment = new TrackSegment();
firstSegment.setName("Positions");
_thePositions.addSegment(firstSegment);
}
// add fix to last track segment
final TrackSegment last = (TrackSegment) _thePositions.last();
last.addFix(theFix);
// tell the fix about it's daddy
theFix.setTrackWrapper(this);
// and extend the start/end DTGs
if (_myTimePeriod == null)
{
_myTimePeriod = new TimePeriod.BaseTimePeriod(theFix.getDateTimeGroup(),
theFix.getDateTimeGroup());
}
else
{
_myTimePeriod.extend(theFix.getDateTimeGroup());
}
if (_myWorldArea == null)
{
_myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation());
}
else
{
_myWorldArea.extend(theFix.getLocation());
}
// we want to listen out for the fix being moved. better listen in to it
// theFix.addPropertyChangeListener(PlainWrapper.LOCATION_CHANGED,
// _locationListener);
}
/**
* append this other layer to ourselves (although we don't really bother with
* it)
*
* @param other
* the layer to add to ourselves
*/
@Override
public void append(final Layer other)
{
// is it a track?
if ((other instanceof TrackWrapper) || (other instanceof TrackSegment))
{
// yes, break it down.
final java.util.Enumeration<Editable> iter = other.elements();
while (iter.hasMoreElements())
{
final Editable nextItem = iter.nextElement();
if (nextItem instanceof Layer)
{
append((Layer) nextItem);
}
else
{
add(nextItem);
}
}
}
else
{
// nope, just add it to us.
add(other);
}
}
/**
* instruct this object to clear itself out, ready for ditching
*/
@Override
public final void closeMe()
{
// and my objects
// first ask them to close themselves
final Enumeration<Editable> it = getPositions();
while (it.hasMoreElements())
{
final Object val = it.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_thePositions.removeAllElements();
_thePositions = null;
// and my objects
// first ask the sensors to close themselves
if (_mySensors != null)
{
final Enumeration<Editable> it2 = _mySensors.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySensors.removeAllElements();
}
// now ask the solutions to close themselves
if (_mySolutions != null)
{
final Enumeration<Editable> it2 = _mySolutions.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySolutions.removeAllElements();
}
// and our utility objects
finisher = null;
lastFix = null;
nearestFix = null;
starter = null;
// and our editor
_myEditor = null;
// now get the parent to close itself
super.closeMe();
}
/**
* switch the two track sections into one track section
*
* @param res
* the previously split track sections
*/
public void combineSections(final Vector<TrackSegment> res)
{
// ok, remember the first
final TrackSegment keeper = res.firstElement();
// now remove them all, adding them to the first
final Iterator<TrackSegment> iter = res.iterator();
while (iter.hasNext())
{
final TrackSegment pl = iter.next();
if (pl != keeper)
{
keeper.append((Layer) pl);
}
_thePositions.removeElement(pl);
}
// and put the keepers back in
_thePositions.addSegment(keeper);
}
/**
* return our tiered data as a single series of elements
*
* @return
*/
@Override
public Enumeration<Editable> contiguousElements()
{
final Vector<Editable> res = new Vector<Editable>(0, 1);
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// is it visible?
if (sw.getVisible())
{
res.addAll(sw._myContacts);
}
}
}
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
if (sw.getVisible())
{
res.addAll(sw._myContacts);
}
}
}
if (_thePositions != null)
{
res.addAll(getRawPositions());
}
return res.elements();
}
/**
* get an enumeration of the points in this track
*
* @return the points in this track
*/
@Override
public Enumeration<Editable> elements()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
if (_mySensors.size() > 0)
{
res.add(_mySensors);
}
if (_mySolutions.size() > 0)
{
res.add(_mySolutions);
}
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
/**
* export this track to REPLAY file
*/
@Override
public final void exportShape()
{
// call the method in PlainWrapper
this.exportThis();
}
/**
* filter the list to the specified time period, then inform any listeners
* (such as the time stepper)
*
* @param start
* the start dtg of the period
* @param end
* the end dtg of the period
*/
@Override
public final void filterListTo(final HiResDate start, final HiResDate end)
{
final Enumeration<Editable> fixWrappers = getPositions();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
final HiResDate dtg = fw.getTime();
if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end)))
{
fw.setVisible(true);
}
else
{
fw.setVisible(false);
}
}
// now do the same for our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// and our solution data
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// do we have any property listeners?
if (getSupport() != null)
{
final Debrief.GUI.Tote.StepControl.somePeriod newPeriod = new Debrief.GUI.Tote.StepControl.somePeriod(
start, end);
getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null,
newPeriod);
}
}
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final ComponentConstruct currentNearest,
final Layer parentLayer)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositions();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
// only check it if it's visible
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
final WorldLocation fixLocation = new WorldLocation(thisF.getLocation())
{
private static final long serialVersionUID = 1L;
@Override
public void addToMe(final WorldVector delta)
{
super.addToMe(delta);
thisF.setFixLocation(this);
}
};
// try range
currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation);
}
}
}
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final LocationConstruct currentNearest,
final Layer parentLayer, final Layers theData)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositions();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
// is it closer?
currentNearest.checkMe(this, thisDist, null, parentLayer);
}
}
}
public void findNearestSegmentHotspotFor(final WorldLocation cursorLoc,
final Point cursorPt, final LocationConstruct currentNearest)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist;
// cycle through the track segments
final Collection<Editable> segments = _thePositions.getData();
for (final Iterator<Editable> iterator = segments.iterator(); iterator
.hasNext();)
{
final TrackSegment thisSeg = (TrackSegment) iterator.next();
if (thisSeg.getVisible())
{
// how far away is it?
thisDist = new WorldDistance(thisSeg.rangeFrom(cursorLoc),
WorldDistance.DEGS);
// is it closer?
currentNearest.checkMe(thisSeg, thisDist, null, this);
}
}
}
/**
* one of our fixes has moved. better tell any bits that rely on the locations
* of our bits
*
* @param theFix
* the fix that moved
*/
public void fixMoved()
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper nextS = (SensorWrapper) iter.nextElement();
nextS.setHost(this);
}
}
}
/**
* return the arrow frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getArrowFrequency()
{
return _lastArrowFrequency;
}
/**
* calculate a position the specified distance back along the ownship track
* (note, we always interpolate the parent track position)
*
* @param searchTime
* the time we're looking at
* @param sensorOffset
* how far back the sensor should be
* @param wormInHole
* whether to plot a straight line back, or make sensor follow
* ownship
* @return the location
*/
public FixWrapper getBacktraceTo(final HiResDate searchTime,
final ArrayLength sensorOffset, final boolean wormInHole)
{
FixWrapper res = null;
if (wormInHole && sensorOffset != null)
{
res = WormInHoleOffset.getWormOffsetFor(this, searchTime, sensorOffset);
}
else
{
final boolean parentInterpolated = getInterpolatePoints();
setInterpolatePoints(true);
final MWC.GenericData.Watchable[] list = getNearestTo(searchTime);
// and restore the interpolated value
setInterpolatePoints(parentInterpolated);
FixWrapper wa = null;
if (list.length > 0)
{
wa = (FixWrapper) list[0];
}
// did we find it?
if (wa != null)
{
// yes, store it
res = new FixWrapper(wa.getFix().makeCopy());
// ok, are we dealing with an offset?
if (sensorOffset != null)
{
// get the current heading
final double hdg = wa.getCourse();
// and calculate where it leaves us
final WorldVector vector = new WorldVector(hdg, sensorOffset, null);
// now apply this vector to the origin
res.setLocation(new WorldLocation(res.getLocation().add(vector)));
}
}
}
return res;
}
// editing parameters
/**
* what geographic area is covered by this track?
*
* @return get the outer bounds of the area
*/
@Override
public final WorldArea getBounds()
{
// we no longer just return the bounds of the track, because a portion
// of the track may have been made invisible.
// instead, we will pass through the full dataset and find the outer
// bounds
// of the visible area
WorldArea res = null;
if (!getVisible())
{
// hey, we're invisible, return null
}
else
{
final Enumeration<Editable> it = getPositions();
while (it.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) it.nextElement();
// is this point visible?
if (fw.getVisible())
{
// has our data been initialised?
if (res == null)
{
// no, initialise it
res = new WorldArea(fw.getLocation(), fw.getLocation());
}
else
{
// yes, extend to include the new area
res.extend(fw.getLocation());
}
}
}
// also extend to include our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
// and our solution data
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
} // whether we're visible
return res;
}
/**
* the time of the last fix
*
* @return the DTG
*/
@Override
public final HiResDate getEndDTG()
{
HiResDate dtg = null;
final TimePeriod res = getTimePeriod();
if (res != null)
{
dtg = res.getEndDTG();
}
return dtg;
}
/**
* the editable details for this track
*
* @return the details
*/
@Override
public Editable.EditorType getInfo()
{
if (_myEditor == null)
{
_myEditor = new trackInfo(this);
}
return _myEditor;
}
/**
* create a new, interpolated point between the two supplied
*
* @param previous
* the previous point
* @param next
* the next point
* @return and interpolated point
*/
private final FixWrapper getInterpolatedFix(final FixWrapper previous,
final FixWrapper next, final HiResDate requestedDTG)
{
FixWrapper res = null;
// do we have a start point
if (previous == null)
{
res = next;
}
// hmm, or do we have an end point?
if (next == null)
{
res = previous;
}
// did we find it?
if (res == null)
{
res = FixWrapper.interpolateFix(previous, next, requestedDTG);
}
return res;
}
public final boolean getInterpolatePoints()
{
return _interpolatePoints;
}
/**
* get the set of fixes contained within this time period (inclusive of both
* end values)
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
@Override
public final Collection<Editable> getItemsBetween(final HiResDate start,
final HiResDate end)
{
SortedSet<Editable> set = null;
// does our track contain any data at all
if (_thePositions.size() > 0)
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
// don't bother with it.
}
else
{
// SPECIAL CASE! If we've been asked to show interpolated data
// points,
// then
// we should produce a series of items between the indicated
// times. How
// about 1 minute resolution?
if (getInterpolatePoints())
{
final long ourInterval = 1000 * 60; // one minute
set = new TreeSet<Editable>();
for (long newTime = start.getDate().getTime(); newTime < end
.getDate().getTime(); newTime += ourInterval)
{
final HiResDate newD = new HiResDate(newTime);
final Watchable[] nearestOnes = getNearestTo(newD);
if (nearestOnes.length > 0)
{
final FixWrapper nearest = (FixWrapper) nearestOnes[0];
set.add(nearest);
}
}
}
else
{
// bugger that - get the real data
// have a go..
if (starter == null)
{
starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0));
}
else
{
starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1));
}
if (finisher == null)
{
finisher = new FixWrapper(new Fix(new HiResDate(0,
end.getMicros() + 1), _zeroLocation, 0.0, 0.0));
}
else
{
finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1));
}
// ok, ready, go for it.
set = getPositionsBetween(starter, finisher);
}
}
}
return set;
}
/**
* method to allow the setting of label frequencies for the track
*
* @return frequency to use
*/
public final HiResDate getLabelFrequency()
{
return this._lastLabelFrequency;
}
/**
* what is the style used for plotting this track?
*
* @return
*/
public int getLineStyle()
{
return _lineStyle;
}
/**
* the line thickness (convenience wrapper around width)
*
* @return
*/
@Override
public int getLineThickness()
{
return _lineWidth;
}
/**
* whether to link points
*
* @return
*/
public boolean getLinkPositions()
{
return _linkPositions;
}
/**
* just have the one property listener - rather than an anonymous class
*
* @return
*/
public PropertyChangeListener getLocationListener()
{
return _locationListener;
}
/**
* name of this Track (normally the vessel name)
*
* @return the name
*/
@Override
public final String getName()
{
return _theLabel.getString();
}
/**
* get our child segments
*
* @return
*/
public SegmentList getSegments()
{
return _thePositions;
}
/**
* whether to show the track label at the start or end of the track
*
* @return yes/no to indicate <I>At Start</I>
*/
public final boolean getNameAtStart()
{
return _LabelAtStart;
}
/**
* the relative location of the label
*
* @return the relative location
*/
public final Integer getNameLocation()
{
return _theLabel.getRelativeLocation();
}
/**
* whether the track label is visible or not
*
* @return yes/no
*/
public final boolean getNameVisible()
{
return _theLabel.getVisible();
}
/**
* find the fix nearest to this time (or the first fix for an invalid time)
*
* @param DTG
* the time of interest
* @return the nearest fix
*/
@Override
public final Watchable[] getNearestTo(final HiResDate srchDTG)
{
/**
* we need to end up with a watchable, not a fix, so we need to work our way
* through the fixes
*/
FixWrapper res = null;
// check that we do actually contain some data
if (_thePositions.size() == 0)
{
return new MWC.GenericData.Watchable[]
{};
}
// special case - if we've been asked for an invalid time value
if (srchDTG == TimePeriod.INVALID_DATE)
{
final TrackSegment seg = (TrackSegment) _thePositions.first();
final FixWrapper fix = (FixWrapper) seg.first();
// just return our first location
return new MWC.GenericData.Watchable[]
{ fix };
}
// see if this is the DTG we have just requestsed
if ((srchDTG.equals(lastDTG)) && (lastFix != null))
{
res = lastFix;
}
else
{
final TrackSegment firstSeg = (TrackSegment) _thePositions.first();
final TrackSegment lastSeg = (TrackSegment) _thePositions.last();
if ((firstSeg != null) && (firstSeg.size() > 0))
{
// see if this DTG is inside our data range
// in which case we will just return null
final FixWrapper theFirst = (FixWrapper) firstSeg.first();
final FixWrapper theLast = (FixWrapper) lastSeg.last();
if ((srchDTG.greaterThan(theFirst.getTime()))
&& (srchDTG.lessThanOrEqualTo(theLast.getTime())))
{
// yes it's inside our data range, find the first fix
// after the indicated point
// right, increment the time, since we want to allow matching
// points
// HiResDate DTG = new HiResDate(0, srchDTG.getMicros() + 1);
// see if we have to create our local temporary fix
if (nearestFix == null)
{
nearestFix = new FixWrapper(new Fix(srchDTG, _zeroLocation, 0.0,
0.0));
}
else
{
nearestFix.getFix().setTime(srchDTG);
}
// right, we really should be filtering the list according to if
// the
// points are visible.
// how do we do filters?
// get the data. use tailSet, since it's inclusive...
SortedSet<Editable> set = getRawPositions().tailSet(nearestFix);
// see if the requested DTG was inside the range of the data
if (!set.isEmpty() && (set.size() > 0))
{
res = (FixWrapper) set.first();
// is this one visible?
if (!res.getVisible())
{
// right, the one we found isn't visible. duplicate the
// set, so that
// we can remove items
// without affecting the parent
set = new TreeSet<Editable>(set);
// ok, start looping back until we find one
while ((!res.getVisible()) && (set.size() > 0))
{
// the first one wasn't, remove it
set.remove(res);
if (set.size() > 0)
{
res = (FixWrapper) set.first();
}
}
}
}
// right, that's the first points on or before the indicated
// DTG. Are we
// meant
// to be interpolating?
if (res != null)
{
if (getInterpolatePoints())
{
// right - just check that we aren't actually on the
// correct time
// point.
// HEY, USE THE ORIGINAL SEARCH TIME, NOT THE
// INCREMENTED ONE,
// SINCE WE DON'T WANT TO COMPARE AGAINST A MODIFIED
// TIME
if (!res.getTime().equals(srchDTG))
{
// right, we haven't found an actual data point.
// Better calculate
// one
// hmm, better also find the point before our one.
// the
// headSet operation is exclusive - so we need to
// find the one
// after the first
final SortedSet<Editable> otherSet = getRawPositions().headSet(
nearestFix);
FixWrapper previous = null;
if (!otherSet.isEmpty())
{
previous = (FixWrapper) otherSet.last();
}
// did it work?
if (previous != null)
{
// cool, sort out the interpolated point USING
// THE ORIGINAL
// SEARCH TIME
res = getInterpolatedFix(previous, res, srchDTG);
}
}
}
}
}
else if (srchDTG.equals(theFirst.getDTG()))
{
// aaah, special case. just see if we're after a data point
// that's the
// same
// as our start time
res = theFirst;
}
}
// and remember this fix
lastFix = res;
lastDTG = srchDTG;
}
if (res != null)
{
return new MWC.GenericData.Watchable[]
{ res };
}
else
{
return new MWC.GenericData.Watchable[]
{};
}
}
public boolean getPlotArrayCentre()
{
return _plotArrayCentre;
}
/**
* get the position data, not all the sensor/contact/position data mixed
* together
*
* @return
*/
public final Enumeration<Editable> getPositions()
{
final SortedSet<Editable> res = getRawPositions();
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
private SortedSet<Editable> getPositionsBetween(final FixWrapper starter2,
final FixWrapper finisher2)
{
// first get them all as one list
final SortedSet<Editable> pts = getRawPositions();
// now do the sort
return pts.subSet(starter2, finisher2);
}
/**
* whether positions are being shown
*
* @return
*/
public final boolean getPositionsVisible()
{
return _showPositions;
}
private SortedSet<Editable> getRawPositions()
{
SortedSet<Editable> res = null;
// do we just have the one list?
if (_thePositions.size() == 1)
{
final TrackSegment p = (TrackSegment) _thePositions.first();
res = (SortedSet<Editable>) p.getData();
}
else
{
// loop through them
res = new TreeSet<Editable>();
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
// get this segment
final TrackSegment seg = (TrackSegment) segs.nextElement();
// add all the points
res.addAll(seg.getData());
}
}
return res;
}
/**
* method to allow the setting of data sampling frequencies for the track &
* sensor data
*
* @return frequency to use
*/
public final HiResDate getResampleDataAt()
{
return this._lastDataFrequency;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSensors()
{
return _mySensors;
}
/**
* return the symbol to be used for plotting this track in snail mode
*/
@Override
public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape()
{
return _theSnailShape;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSolutions()
{
return _mySolutions;
}
// watchable (tote related) parameters
/**
* the earliest fix in the track
*
* @return the DTG
*/
@Override
public final HiResDate getStartDTG()
{
HiResDate res = null;
final TimePeriod period = getTimePeriod();
if (period != null)
{
res = period.getStartDTG();
}
return res;
}
/**
* get the color used to plot the symbol
*
* @return the color
*/
public final Color getSymbolColor()
{
return _theSnailShape.getColor();
}
/**
* return the symbol frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getSymbolFrequency()
{
return _lastSymbolFrequency;
}
public WorldDistance getSymbolLength()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getLength();
}
return res;
}
/**
* get the type of this symbol
*/
public final String getSymbolType()
{
return _theSnailShape.getType();
}
public WorldDistance getSymbolWidth()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getWidth();
}
return res;
}
private TimePeriod getTimePeriod()
{
TimePeriod res = null;
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segs.nextElement();
// do we have a dtg?
if ((seg.startDTG() != null) && (seg.endDTG() != null))
{
// yes, get calculating
if (res == null)
{
res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG());
}
else
{
res.extend(seg.startDTG());
res.extend(seg.endDTG());
}
}
}
return res;
}
/**
* the colour of the points on the track
*
* @return the colour
*/
public final Color getTrackColor()
{
return getColor();
}
/**
* font handler
*
* @return the font to use for the label
*/
public final java.awt.Font getTrackFont()
{
return _theLabel.getFont();
}
/**
* get the set of fixes contained within this time period which haven't been
* filtered, and which have valid depths. The isVisible flag indicates whether
* a track has been filtered or not. We also have the getVisibleFixesBetween
* method (below) which decides if a fix is visible if it is set to Visible,
* and it's label or symbol are visible.
* <p/>
* We don't have to worry about a valid depth, since 3d doesn't show points
* with invalid depth values
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
public final Collection<Editable> getUnfilteredItems(final HiResDate start,
final HiResDate end)
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
return null;
}
if (this.getVisible() == false)
{
return null;
}
// get ready for the output
final Vector<Editable> res = new Vector<Editable>(0, 1);
// put the data into a period
final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end);
// step through our fixes
final Enumeration<Editable> iter = getPositions();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
if (fw.getVisible())
{
// is it visible?
if (thePeriod.contains(fw.getTime()))
{
// hey, it's valid - continue
res.add(fw);
}
}
}
return res;
}
/**
* whether this object has editor details
*
* @return yes/no
*/
@Override
public final boolean hasEditor()
{
return true;
}
@Override
public boolean hasOrderedChildren()
{
return false;
}
/**
* quick accessor for how many fixes we have
*
* @return
*/
public int numFixes()
{
return getRawPositions().size();
}
private void checkPointsArray()
{
// is our points store long enough?
if ((_myPts == null) || (_myPts.length < numFixes() * 2))
{
_myPts = new int[numFixes() * 2];
}
// reset the points counter
_ptCtr = 0;
}
private boolean paintFixes(final CanvasType dest)
{
// we need an array to store the polyline of points in. Check it's big
// enough
checkPointsArray();
// keep track of if we have plotted any points (since
// we won't be plotting the name if none of the points are visible).
// this typically occurs when filtering is applied and a short
// track is completely outside the time period
boolean plotted_anything = false;
// java.awt.Point lastP = null;
Color lastCol = null;
final int defaultlineStyle = getLineStyle();
boolean locatedTrack = false;
WorldLocation lastLocation = null;
FixWrapper lastFix = null;
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// how shall we plot this segment?
final int thisLineStyle;
// is the parent using the default style?
if (defaultlineStyle == CanvasType.SOLID)
{
// yes, let's override it, if the segment wants to
thisLineStyle = seg.getLineStyle();
}
else
{
// no, we're using a custom style - don't override it.
thisLineStyle = defaultlineStyle;
}
// SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN
// RELATIVE MODE
final boolean isRelative = seg.getPlotRelative();
WorldLocation tmaLastLoc = null;
long tmaLastDTG = 0;
// if it's not a relative track, and it's not visible, we don't
// need to work with ut
if (!getVisible() && !isRelative)
{
continue;
}
// is this segment visible?
if (!seg.getVisible())
{
continue;
}
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// now there's a chance that our fix has forgotten it's
// parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
// is this fix visible?
if (!fw.getVisible())
{
// nope. Don't join it to the last position.
// ok, if we've built up a polygon, we need to write it
// now
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// Note: we're carrying on working with this position even
// if it isn't visible,
// since we need to use non-visible positions to build up a
// DR track.
// ok, so we have plotted something
plotted_anything = true;
// ok, are we in relative?
if (isRelative)
{
final long thisTime = fw.getDateTimeGroup().getDate().getTime();
// ok, is this our first location?
if (tmaLastLoc == null)
{
tmaLastLoc = new WorldLocation(seg.getTrackStart());
lastLocation = tmaLastLoc;
}
else
{
// calculate a new vector
final long timeDelta = thisTime - tmaLastDTG;
if (lastFix != null)
{
final double speedKts = lastFix.getSpeed();
final double courseRads = lastFix.getCourse();
final double depthM = lastFix.getDepth();
// use the value of depth as read in from the
// file
tmaLastLoc.setDepth(depthM);
final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts,
courseRads);
tmaLastLoc.addToMe(thisVec);
lastLocation = tmaLastLoc;
}
}
lastFix = fw;
tmaLastDTG = thisTime;
// dump the location into the fix
fw.setFixLocationSilent(new WorldLocation(tmaLastLoc));
}
else
{
// this is an absolute position
lastLocation = fw.getLocation();
}
// ok, we only do this writing to screen if the actual
// position is visible
if (!fw.getVisible())
continue;
final java.awt.Point thisP = dest.toScreen(lastLocation);
// just check that there's enough GUI to create the plot
// (i.e. has a point been returned)
if (thisP == null)
{
return false;
}
// so, we're looking at the first data point. Do
// we want to use this to locate the track name?
// or have we already sorted out the location
if (_LabelAtStart && !locatedTrack)
{
locatedTrack = true;
_theLabel.setLocation(new WorldLocation(lastLocation));
}
// are we
if (getLinkPositions()
&& (getLineStyle() != LineStylePropertyEditor.UNCONNECTED))
{
// right, just check if we're a different colour to
// the previous one
final Color thisCol = fw.getColor();
// do we know the previous colour
if (lastCol == null)
{
lastCol = thisCol;
}
// is this to be joined to the previous one?
if (fw.getLineShowing())
{
// so, grow the the polyline, unless we've got a
// colour change...
if (thisCol != lastCol)
{
// add our position to the list - so it
// finishes on us
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
// yup, better get rid of the previous
// polygon
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// add our position to the list - we'll output
// the polyline at the end
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
else
{
// nope, output however much line we've got so
// far - since this
// line won't be joined to future points
paintSetOfPositions(dest, thisCol, thisLineStyle);
// start off the next line
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
/*
* set the colour of the track from now on to this colour, so that the
* "link" to the next fix is set to this colour if left unchanged
*/
dest.setColor(fw.getColor());
// and remember the last colour
lastCol = thisCol;
}
if (_showPositions && fw.getVisible())
{
// this next method just paints the fix. we've put the
// call into paintThisFix so we can override the painting
// in the CompositeTrackWrapper class
paintThisFix(dest, lastLocation, fw);
}
}// while fixWrappers has more elements
// SPECIAL HANDLING, IF IT'S A TMA SEGMENT PLOT THE VECTOR LABEL
if(seg instanceof CoreTMASegment)
{
CoreTMASegment tma = (CoreTMASegment) seg;
WorldLocation firstLoc = seg.first().getBounds().getCentre();
WorldLocation lastLoc = seg.last().getBounds().getCentre();
Font f = new Font("Sans Serif", Font.PLAIN, 11);
Color c = _theLabel.getColor();
// tell the segment it's being stretched
final String spdTxt = MWC.Utilities.TextFormatting.GeneralFormat
.formatOneDecimalPlace(tma.getSpeed().getValueIn(WorldSpeed.Kts));
// copied this text from RelativeTMASegment
String textLabel = "[" + spdTxt + " kts " + (int) tma.getCourse() + "\u00B0]";
// ok, now plot it
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, true);
textLabel = tma.getName().replace(TextLabel.NEWLINE_MARKER, " ");
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, false);
}
// ok, just see if we have any pending polylines to paint
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// are we trying to put the label at the end of the track?
// have we found at least one location to plot?
if (!_LabelAtStart && lastLocation != null)
{
_theLabel.setLocation(new WorldLocation(lastLocation));
}
return plotted_anything;
}
private void paintSingleTrackLabel(final CanvasType dest)
{
// check that we have found a location for the label
if (_theLabel.getLocation() == null)
return;
// is the first track a DR track?
final TrackSegment t1 = (TrackSegment) _thePositions.first();
if (t1.getPlotRelative())
{
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC));
}
else if (_theLabel.getFont().isItalic())
{
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN));
}
// check that we have set the name for the label
if (_theLabel.getString() == null)
{
_theLabel.setString(getName());
}
// does the first label have a colour?
if (_theLabel.getColor() == null)
{
// check we have a colour
Color labelColor = getColor();
// did we ourselves have a colour?
if (labelColor == null)
{
// nope - do we have any legs?
final Enumeration<Editable> numer = this.getPositions();
if (numer.hasMoreElements())
{
// ok, use the colour of the first point
final FixWrapper pos = (FixWrapper) numer.nextElement();
labelColor = pos.getColor();
}
}
_theLabel.setColor(labelColor);
}
// and paint it
_theLabel.paint(dest);
}
private void paintMultipleSegmentLabel(final CanvasType dest)
{
final Enumeration<Editable> posis = _thePositions.elements();
while (posis.hasMoreElements())
{
final TrackSegment thisE = (TrackSegment) posis.nextElement();
// is this segment visible?
if (!thisE.getVisible())
{
continue;
}
// is the first track a DR track?
if (thisE.getPlotRelative())
{
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC));
}
else if (_theLabel.getFont().isItalic())
{
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN));
}
final WorldLocation theLoc = thisE.getTrackStart();
final String oldTxt = _theLabel.getString();
_theLabel.setString(thisE.getName());
// just see if this is a planning segment, with its own colors
if (thisE instanceof PlanningSegment)
{
final PlanningSegment ps = (PlanningSegment) thisE;
_theLabel.setColor(ps.getColor());
}
else
{
_theLabel.setColor(getColor());
}
_theLabel.setLocation(theLoc);
_theLabel.paint(dest);
_theLabel.setString(oldTxt);
}
}
/**
* draw this track (we can leave the Positions to draw themselves)
*
* @param dest
* the destination
*/
@Override
public final void paint(final CanvasType dest)
{
// check we are visible and have some track data, else we won't work
if (!getVisible() || this.getStartDTG() == null)
{
return;
}
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
if (getColor() != null)
dest.setColor(getColor());
// firstly plot the solutions
if (_mySolutions.getVisible())
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the solutions
} // whether the solutions are visible
// now plot the sensors
if (_mySensors.getVisible())
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the sensors
} // whether the sensor layer is visible
// and now the track itself
// just check if we are drawing anything at all
if ((!getLinkPositions() || getLineStyle() == LineStylePropertyEditor.UNCONNECTED)
&& (!_showPositions))
{
return;
}
// let the fixes draw themselves in
final boolean plotted_anything = paintFixes(dest);
// and draw the track label
// still, we only plot the track label if we have plotted any
// points
if (_theLabel.getVisible() && plotted_anything)
{
// just see if we have multiple segments. if we do,
// name them individually
if (this._thePositions.size() <= 1)
{
paintSingleTrackLabel(dest);
}
else
{
// we've got multiple segments, name them
paintMultipleSegmentLabel(dest);
}
} // if the label is visible
// paint vector label
if (plotted_anything)
{
paintVectorLabel(dest);
}
}
private void paintVectorLabel(final CanvasType dest)
{
if (getVisible())
{
final Enumeration<Editable> posis = _thePositions.elements();
while (posis.hasMoreElements())
{
final TrackSegment thisE = (TrackSegment) posis.nextElement();
// paint only visible planning segments
if ((thisE instanceof PlanningSegment) && thisE.getVisible())
{
PlanningSegment ps = (PlanningSegment) thisE;
ps.paintLabel(dest);
}
}
}
}
/**
* get the fix to paint itself
*
* @param dest
* @param lastLocation
* @param fw
*/
protected void paintThisFix(final CanvasType dest,
final WorldLocation lastLocation, final FixWrapper fw)
{
fw.paintMe(dest, lastLocation, fw.getColor());
}
/**
* this accessor is present for debug/testing purposes only. Do not use
* outside testing!
*
* @return the list of screen locations about to be plotted
*/
public int[] debug_GetPoints()
{
return _myPts;
}
/**
* this accessor is present for debug/testing purposes only. Do not use
* outside testing!
*
* @return the length of the list of screen points waiting to be plotted
*/
public int debug_GetPointCtr()
{
return _ptCtr;
}
/**
* paint any polyline that we've built up
*
* @param dest
* - where we're painting to
* @param thisCol
* @param lineStyle
*/
private void paintSetOfPositions(final CanvasType dest, final Color thisCol,
final int lineStyle)
{
if (_ptCtr > 0)
{
dest.setColor(thisCol);
dest.setLineStyle(lineStyle);
final int[] poly = new int[_ptCtr];
System.arraycopy(_myPts, 0, poly, 0, _ptCtr);
dest.drawPolyline(poly);
dest.setLineStyle(CanvasType.SOLID);
// and reset the counter
_ptCtr = 0;
}
}
/**
* return the range from the nearest corner of the track
*
* @param other
* the other location
* @return the range
*/
@Override
public final double rangeFrom(final WorldLocation other)
{
double nearest = -1;
// do we have a track?
if (_myWorldArea != null)
{
// find the nearest point on the track
nearest = _myWorldArea.rangeFrom(other);
}
return nearest;
}
/**
* remove the requested item from the track
*
* @param point
* the point to remove
*/
@Override
public final void removeElement(final Editable point)
{
// just see if it's a sensor which is trying to be removed
if (point instanceof SensorWrapper)
{
_mySensors.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
}
else if (point instanceof TMAWrapper)
{
_mySolutions.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
}
else if (point instanceof SensorContactWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// try to remove it from this one...
sw.removeElement(point);
}
}
else if (point instanceof TrackSegment)
{
_thePositions.removeElement(point);
// and clear the parent item
final TrackSegment ts = (TrackSegment) point;
ts.setWrapper(null);
}
else if (point == _mySensors)
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySensors.removeAllElements();
}
else if (point == _mySolutions)
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySolutions.removeAllElements();
}
else
{
// loop through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.removeElement(point);
// and stop listening to it (if it's a fix)
if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED,
_locationListener);
}
}
}
}
// LAYER support methods
/**
* pass through the track, resetting the labels back to their original DTG
*/
@FireReformatted
public void resetLabels()
{
FormatTracks.formatTrack(this);
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setArrowFrequency(final HiResDate theVal)
{
this._lastArrowFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setArrowShowing(val);
}
};
setFixes(setSymbols, theVal);
}
/**
* set the colour of this track label
*
* @param theCol
* the colour
*/
@Override
@FireReformatted
public final void setColor(final Color theCol)
{
// do the parent
super.setColor(theCol);
// now do our processing
_theLabel.setColor(theCol);
}
/**
* the setter function which passes through the track
*/
private void setFixes(final FixSetter setter, final HiResDate theVal)
{
final long freq = theVal.getMicros();
// briefly check if we are revealing/hiding all times (ie if freq is 1
// or 0)
if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY)
{
// show all of the labels
final Enumeration<Editable> iter = getPositions();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
setter.execute(fw, true);
}
}
else
{
// no, we're not just blindly doing all of them. do them at the
// correct
// frequency
// hide all of the labels/symbols first
final Enumeration<Editable> enumA = getPositions();
while (enumA.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) enumA.nextElement();
setter.execute(fw, false);
}
if (freq == 0)
{
// we can ignore this, since we have just hidden all of the
// points
}
else
{
if (getStartDTG() != null)
{
// pass through the track setting the values
// sort out the start and finish times
long start_time = getStartDTG().getMicros();
final long end_time = getEndDTG().getMicros();
// first check that there is a valid time period between start
// time
// and end time
if (start_time + freq < end_time)
{
long num = start_time / freq;
// we need to add one to the quotient if it has rounded down
if (start_time % freq == 0)
{
// start is at our freq, so we don't need to increment
}
else
{
num++;
}
// calculate new start time
start_time = num * freq;
}
else
{
// there is not one of our 'intervals' between the start and
// the end,
// so use the start time
}
while (start_time <= end_time)
{
// right, increment the start time by one, because we were
// getting the
// fix immediately before the requested time
final HiResDate thisDTG = new HiResDate(0, start_time);
final MWC.GenericData.Watchable[] list = this.getNearestTo(thisDTG);
// check we found some
if (list.length > 0)
{
final FixWrapper fw = (FixWrapper) list[0];
setter.execute(fw, true);
}
// produce the next time step
start_time += freq;
}
}
}
}
}
public final void setInterpolatePoints(final boolean val)
{
_interpolatePoints = val;
}
/**
* set the label frequency (in seconds)
*
* @param theVal
* frequency to use
*/
public final void setLabelFrequency(final HiResDate theVal)
{
this._lastLabelFrequency = theVal;
final FixSetter setLabel = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setLabelShowing(val);
}
};
setFixes(setLabel, theVal);
}
// track-shifting operation
// support for dragging the track around
/**
* set the style used for plotting the lines for this track
*
* @param val
*/
public void setLineStyle(final int val)
{
_lineStyle = val;
}
/**
* the line thickness (convenience wrapper around width)
*/
public void setLineThickness(final int val)
{
_lineWidth = val;
}
/**
* whether to link points
*
* @param linkPositions
*/
public void setLinkPositions(final boolean linkPositions)
{
_linkPositions = linkPositions;
}
/**
* set the name of this track (normally the name of the vessel
*
* @param theName
* the name as a String
*/
@Override
@FireReformatted
public final void setName(final String theName)
{
_theLabel.setString(theName);
}
/**
* whether to show the track name at the start or end of the track
*
* @param val
* yes no for <I>show label at start</I>
*/
public final void setNameAtStart(final boolean val)
{
_LabelAtStart = val;
}
/**
* the relative location of the label
*
* @param val
* the relative location
*/
public final void setNameLocation(final Integer val)
{
_theLabel.setRelativeLocation(val);
}
/**
* whether to show the track name
*
* @param val
* yes/no
*/
public final void setNameVisible(final boolean val)
{
_theLabel.setVisible(val);
}
public void setPlotArrayCentre(final boolean plotArrayCentre)
{
_plotArrayCentre = plotArrayCentre;
}
/**
* whether to show the position fixes
*
* @param val
* yes/no
*/
public final void setPositionsVisible(final boolean val)
{
_showPositions = val;
}
/**
* set the data frequency (in seconds) for the track & sensor data
*
* @param theVal
* frequency to use
*/
@FireExtended
public final void setResampleDataAt(final HiResDate theVal)
{
this._lastDataFrequency = theVal;
// have a go at trimming the start time to a whole number of intervals
final long interval = theVal.getMicros();
// do we have a start time (we may just be being tested...)
if (this.getStartDTG() == null)
{
return;
}
final long currentStart = this.getStartDTG().getMicros();
long startTime = (currentStart / interval) * interval;
// just check we're in the range
if (startTime < currentStart)
{
startTime += interval;
}
// just check it's not a barking frequency
if (theVal.getDate().getTime() <= 0)
{
// ignore, we don't need to do anything for a zero or a -1
}
else
{
final SegmentList segments = _thePositions;
final Enumeration<Editable> theEnum = segments.elements();
while (theEnum.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) theEnum.nextElement();
seg.decimate(theVal, this, startTime);
}
// start off with the sensor data
if (_mySensors != null)
{
for (final Enumeration<Editable> iterator = _mySensors.elements(); iterator
.hasMoreElements();)
{
final SensorWrapper thisS = (SensorWrapper) iterator.nextElement();
thisS.decimate(theVal, startTime);
}
}
// now the solutions
if (_mySolutions != null)
{
for (final Enumeration<Editable> iterator = _mySolutions.elements(); iterator
.hasMoreElements();)
{
final TMAWrapper thisT = (TMAWrapper) iterator.nextElement();
thisT.decimate(theVal, startTime);
}
}
}
}
public final void setSymbolColor(final Color col)
{
_theSnailShape.setColor(col);
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setSymbolFrequency(final HiResDate theVal)
{
this._lastSymbolFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setSymbolShowing(val);
}
};
setFixes(setSymbols, theVal);
}
public void setSymbolLength(final WorldDistance symbolLength)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setLength(symbolLength);
}
}
public final void setSymbolType(final String val)
{
// is this the type of our symbol?
if (val.equals(_theSnailShape.getType()))
{
// don't bother we're using it already
}
else
{
// remember the size of the symbol
final double scale = _theSnailShape.getScaleVal();
// remember the color of the symbol
final Color oldCol = _theSnailShape.getColor();
// replace our symbol with this new one
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val);
_theSnailShape.setColor(oldCol);
_theSnailShape.setScaleVal(scale);
}
}
public void setSymbolWidth(final WorldDistance symbolWidth)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setHeight(symbolWidth);
}
}
// note we are putting a track-labelled wrapper around the colour
// parameter, to make the properties window less confusing
/**
* the colour of the points on the track
*
* @param theCol
* the colour to use
*/
@FireReformatted
public final void setTrackColor(final Color theCol)
{
setColor(theCol);
}
/**
* font handler
*
* @param font
* the font to use for the label
*/
public final void setTrackFont(final java.awt.Font font)
{
_theLabel.setFont(font);
}
@Override
public void shift(final WorldLocation feature, final WorldVector vector)
{
feature.addToMe(vector);
// right, one of our fixes has moved. get the sensors to update
// themselves
fixMoved();
}
@Override
public void shift(final WorldVector vector)
{
this.shiftTrack(elements(), vector);
}
/**
* move the whole of the track be the provided offset
*/
public final void shiftTrack(final Enumeration<Editable> theEnum,
final WorldVector offset)
{
Enumeration<Editable> enumA = theEnum;
// keep track of if the track contains something that doesn't get
// dragged
boolean handledData = false;
if (enumA == null)
{
enumA = elements();
}
while (enumA.hasMoreElements())
{
final Object thisO = enumA.nextElement();
if (thisO instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) thisO;
seg.shift(offset);
// ok - job well done
handledData = true;
}
else if (thisO instanceof SegmentList)
{
final SegmentList list = (SegmentList) thisO;
final Collection<Editable> items = list.getData();
for (final Iterator<Editable> iterator = items.iterator(); iterator
.hasNext();)
{
final TrackSegment segment = (TrackSegment) iterator.next();
segment.shift(offset);
}
handledData = true;
}
else if (thisO instanceof SensorWrapper)
{
final SensorWrapper sw = (SensorWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final SensorContactWrapper scw = (SensorContactWrapper) enumS
.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin != null)
{
// create new object to contain the updated location
final WorldLocation newSensorLocation = new WorldLocation(
sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a sensor wrapper
else if (thisO instanceof TrackSegment)
{
final TrackSegment tw = (TrackSegment) thisO;
final Enumeration<Editable> enumS = tw.elements();
// fire recursively, smart-arse.
shiftTrack(enumS, offset);
// ok - job well done
handledData = true;
} // whether this is a sensor wrapper
} // looping through this track
// ok, did we handle the data?
if (!handledData)
{
System.err.println("TrackWrapper problem; not able to shift:" + enumA);
}
}
/**
* if we've got a relative track segment, it only learns where its individual
* fixes are once they've been initialised. This is where we do it.
*/
private void sortOutRelativePositions()
{
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN
// RELATIVE MODE
final boolean isRelative = seg.getPlotRelative();
WorldLocation tmaLastLoc = null;
long tmaLastDTG = 0;
// if it's not a relative track, and it's not visible, we don't
// need to
// work with ut
if (!isRelative)
{
continue;
}
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// now there's a chance that our fix has forgotten it's parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
// ok, are we in relative?
if (isRelative)
{
final long thisTime = fw.getDateTimeGroup().getDate().getTime();
// ok, is this our first location?
if (tmaLastLoc == null)
{
tmaLastLoc = new WorldLocation(seg.getTrackStart());
}
else
{
// calculate a new vector
final long timeDelta = thisTime - tmaLastDTG;
if (lastFix != null)
{
final double speedKts = lastFix.getSpeed();
final double courseRads = lastFix.getCourse();
final double depthM = lastFix.getDepth();
// use the value of depth as read in from the file
tmaLastLoc.setDepth(depthM);
final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts,
courseRads);
tmaLastLoc.addToMe(thisVec);
}
}
lastFix = fw;
tmaLastDTG = thisTime;
// dump the location into the fix
fw.setFixLocationSilent(new WorldLocation(tmaLastLoc));
}
}
}
}
/**
* split this whole track into two sub-tracks
*
* @param splitPoint
* the point at which we perform the split
* @param splitBeforePoint
* whether to put split before or after specified point
* @return a list of the new track segments (used for subsequent undo
* operations)
*/
public Vector<TrackSegment> splitTrack(final FixWrapper splitPoint,
final boolean splitBeforePoint)
{
FixWrapper splitPnt = splitPoint;
Vector<TrackSegment> res = null;
TrackSegment relevantSegment = null;
// are we still in one section?
if (_thePositions.size() == 1)
{
relevantSegment = (TrackSegment) _thePositions.first();
// yup, looks like we're going to be splitting it.
// better give it a proper name
relevantSegment.setName(relevantSegment.startDTG().getDate().toString());
}
else
{
// ok, find which segment contains our data
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
if (seg.getData().contains(splitPnt))
{
relevantSegment = seg;
break;
}
}
}
if (relevantSegment == null)
{
throw new RuntimeException(
"failed to provide relevant segment, alg will break");
}
// hmm, if we're splitting after the point, we need to move along the
// bus by
// one
if (!splitBeforePoint)
{
final Collection<Editable> items = relevantSegment.getData();
final Iterator<Editable> theI = items.iterator();
Editable previous = null;
while (theI.hasNext())
{
final Editable thisE = theI.next();
// have we chosen to remember the previous item?
if (previous != null)
{
// yes, this must be the one we're after
splitPnt = (FixWrapper) thisE;
break;
}
// is this the one we're looking for?
if (thisE == splitPnt)
{
// yup, remember it - we want to use the next value
previous = thisE;
}
}
}
// yup, do our first split
final SortedSet<Editable> p1 = relevantSegment.headSet(splitPnt);
final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPnt);
// get our results ready
final TrackSegment ts1, ts2;
// aaah, just sort out if we are splitting a TMA segment, in which case
// want to create two
// tma segments, not track segments
if (relevantSegment instanceof RelativeTMASegment)
{
final RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment;
// aah, sort out if we are splitting before or after.
// find out the offset at the split point, so we can initiate it for
// the
// second part of the track
final WorldLocation refTrackLoc = theTMA.getReferenceTrack()
.getNearestTo(splitPnt.getDateTimeGroup())[0].getLocation();
final WorldVector secondOffset = splitPnt.getLocation().subtract(
refTrackLoc);
// put the lists back into plottable layers
final RelativeTMASegment tr1 = new RelativeTMASegment(theTMA, p1,
theTMA.getOffset());
final RelativeTMASegment tr2 = new RelativeTMASegment(theTMA, p2,
secondOffset);
// update the freq's
tr1.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
tr2.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else if (relevantSegment instanceof AbsoluteTMASegment)
{
final AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment;
// aah, sort out if we are splitting before or after.
// find out the offset at the split point, so we can initiate it for
// the
// second part of the track
final Watchable[] matches = this
.getNearestTo(splitPnt.getDateTimeGroup());
final WorldLocation origin = matches[0].getLocation();
final FixWrapper t1Start = (FixWrapper) p1.first();
// put the lists back into plottable layers
final AbsoluteTMASegment tr1 = new AbsoluteTMASegment(theTMA, p1,
t1Start.getLocation(), null, null);
final AbsoluteTMASegment tr2 = new AbsoluteTMASegment(theTMA, p2, origin,
null, null);
// update the freq's
tr1.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
tr2.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else
{
// put the lists back into plottable layers
ts1 = new TrackSegment(p1);
ts2 = new TrackSegment(p2);
}
// now clear the positions
_thePositions.removeElement(relevantSegment);
// and put back our new layers
_thePositions.addSegment(ts1);
_thePositions.addSegment(ts2);
// remember them
res = new Vector<TrackSegment>();
res.add(ts1);
res.add(ts2);
return res;
}
/**
* extra parameter, so that jvm can produce a sensible name for this
*
* @return the track name, as a string
*/
@Override
public final String toString()
{
return "Track:" + getName();
}
/**
* is this track visible between these time periods?
*
* @param start
* start DTG
* @param end
* end DTG
* @return yes/no
*/
@Override
public final boolean visibleBetween(final HiResDate start, final HiResDate end)
{
boolean visible = false;
if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start)))
{
visible = true;
}
return visible;
}
/**
* Calculates Course & Speed for the track.
*/
public void calcCourseSpeed()
{
// step through our fixes
final Enumeration<Editable> iter = getPositions();
FixWrapper prevFw = null;
while (iter.hasMoreElements())
{
final FixWrapper currFw = (FixWrapper) iter.nextElement();
if (prevFw == null)
prevFw = currFw;
else
{
// calculate the course
final WorldVector wv = currFw.getLocation().subtract(
prevFw.getLocation());
prevFw.getFix().setCourse(wv.getBearing());
// calculate the speed
// get distance in meters
final WorldDistance wd = new WorldDistance(wv);
final double distance = wd.getValueIn(WorldDistance.METRES);
// get time difference in seconds
final long timeDifference = (currFw.getTime().getMicros() - prevFw
.getTime().getMicros()) / 1000000;
// get speed in meters per second and convert it to knots
final WorldSpeed speed = new WorldSpeed(distance / timeDifference,
WorldSpeed.M_sec);
final double knots = WorldSpeed.convert(WorldSpeed.M_sec,
WorldSpeed.Kts, speed.getValue());
prevFw.setSpeed(knots);
prevFw = currFw;
}
}
}
public void trimTo(TimePeriod period)
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_thePositions != null)
{
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.trimTo(period);
}
}
}
}
|
// Revision 1.1 1999-01-31 13:33:08+00 sm11td
// Initial revision
package Debrief.Wrappers;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import Debrief.ReaderWriter.Replay.FormatTracks;
import Debrief.Wrappers.Track.AbsoluteTMASegment;
import Debrief.Wrappers.Track.CoreTMASegment;
import Debrief.Wrappers.Track.RelativeTMASegment;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support;
import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import MWC.Algorithms.Conversions;
import MWC.GUI.CanvasType;
import MWC.GUI.DynamicPlottable;
import MWC.GUI.Editable;
import MWC.GUI.FireExtended;
import MWC.GUI.FireReformatted;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.MessageProvider;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Plottable;
import MWC.GUI.Canvas.MockCanvasType;
import MWC.GUI.Layer.ProvidesContiguousElements;
import MWC.GUI.Properties.TimeFrequencyPropertyEditor;
import MWC.GUI.Shapes.DraggableItem;
import MWC.GUI.Shapes.HasDraggableComponents;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.Watchable;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
/**
* the TrackWrapper maintains the GUI and data attributes of the whole track
* iteself, but the responsibility for the fixes within the track are demoted to
* the FixWrapper
*/
public final class TrackWrapper extends MWC.GUI.PlainWrapper implements
WatchableList, DynamicPlottable, MWC.GUI.Layer, DraggableItem,
HasDraggableComponents, ProvidesContiguousElements
{
// member variables
// testing for this class
static public final class testMe extends junit.framework.TestCase
{
protected static class TestMockCanvas extends MockCanvasType
{
public void drawPolyline(int[] points)
{
callCount++;
pointCount += points.length;
}
}
/**
* utility to track number of calls
*
*/
static int callCount = 0;
/**
* utility to track number of points passed to paint polyline method
*
*/
static int pointCount = 0;
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public testMe(final String val)
{
super(val);
}
@SuppressWarnings("synthetic-access")
private int countVisibleFixes(TrackWrapper tw)
{
int ctr = 0;
final Enumeration<Editable> iter = tw.getPositions();
while (iter.hasMoreElements())
{
final Plottable thisE = (Plottable) iter.nextElement();
if (thisE.getVisible())
ctr++;
}
return ctr;
}
@SuppressWarnings("synthetic-access")
private int countVisibleSensorWrappers(TrackWrapper tw)
{
final Iterator<SensorWrapper> iter2 = tw._mySensors.iterator();
int sCtr = 0;
while (iter2.hasNext())
{
final SensorWrapper sw = iter2.next();
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final Plottable pl = (Plottable) enumS.nextElement();
if (pl.getVisible())
sCtr++;
}
}
return sCtr;
}
@SuppressWarnings("synthetic-access")
private int countVisibleSolutionWrappers(TrackWrapper tw)
{
final Iterator<TMAWrapper> iter2 = tw._mySolutions.iterator();
int sCtr = 0;
while (iter2.hasNext())
{
final TMAWrapper sw = iter2.next();
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final Plottable pl = (Plottable) enumS.nextElement();
if (pl.getVisible())
sCtr++;
}
}
return sCtr;
}
private TrackWrapper getDummyTrack()
{
final TrackWrapper tw = new TrackWrapper();
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(100, 10000),
loc_1.add(new WorldVector(33, new WorldDistance(100,
WorldDistance.METRES), null)), 10, 110));
fw1.setLabel("fw1");
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(200, 20000),
loc_1.add(new WorldVector(33, new WorldDistance(200,
WorldDistance.METRES), null)), 20, 120));
fw2.setLabel("fw2");
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(300, 30000),
loc_1.add(new WorldVector(33, new WorldDistance(300,
WorldDistance.METRES), null)), 30, 130));
fw3.setLabel("fw3");
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(400, 40000),
loc_1.add(new WorldVector(33, new WorldDistance(400,
WorldDistance.METRES), null)), 40, 140));
fw4.setLabel("fw4");
final FixWrapper fw5 = new FixWrapper(new Fix(new HiResDate(500, 50000),
loc_1.add(new WorldVector(33, new WorldDistance(500,
WorldDistance.METRES), null)), 50, 150));
fw5.setLabel("fw5");
tw.addFix(fw1);
tw.addFix(fw2);
tw.addFix(fw3);
tw.addFix(fw4);
tw.addFix(fw5);
// also give it some sensor data
final SensorWrapper swa = new SensorWrapper("title one");
final SensorContactWrapper scwa1 = new SensorContactWrapper("aaa",
new HiResDate(150, 0), null, 0, null, null, null, 0, null);
final SensorContactWrapper scwa2 = new SensorContactWrapper("bbb",
new HiResDate(180, 0), null, 0, null, null, null, 0, null);
final SensorContactWrapper scwa3 = new SensorContactWrapper("ccc",
new HiResDate(250, 0), null, 0, null, null, null, 0, null);
swa.add(scwa1);
swa.add(scwa2);
swa.add(scwa3);
tw.add(swa);
final SensorWrapper sw = new SensorWrapper("title two");
final SensorContactWrapper scw1 = new SensorContactWrapper("ddd",
new HiResDate(260, 0), null, 0, null, null, null, 0, null);
final SensorContactWrapper scw2 = new SensorContactWrapper("eee",
new HiResDate(280, 0), null, 0, null, null, null, 0, null);
final SensorContactWrapper scw3 = new SensorContactWrapper("fff",
new HiResDate(350, 0), null, 0, null, null, null, 0, null);
sw.add(scw1);
sw.add(scw2);
sw.add(scw3);
tw.add(sw);
final TMAWrapper mwa = new TMAWrapper("bb");
final TMAContactWrapper tcwa1 = new TMAContactWrapper("aaa", "bbb",
new HiResDate(130), null, 0, 0, 0, null, null, null, null);
final TMAContactWrapper tcwa2 = new TMAContactWrapper("bbb", "bbb",
new HiResDate(190), null, 0, 0, 0, null, null, null, null);
final TMAContactWrapper tcwa3 = new TMAContactWrapper("ccc", "bbb",
new HiResDate(230), null, 0, 0, 0, null, null, null, null);
mwa.add(tcwa1);
mwa.add(tcwa2);
mwa.add(tcwa3);
tw.add(mwa);
final TMAWrapper mw = new TMAWrapper("cc");
final TMAContactWrapper tcw1 = new TMAContactWrapper("ddd", "bbb",
new HiResDate(230), null, 0, 0, 0, null, null, null, null);
final TMAContactWrapper tcw2 = new TMAContactWrapper("eee", "bbb",
new HiResDate(330), null, 0, 0, 0, null, null, null, null);
final TMAContactWrapper tcw3 = new TMAContactWrapper("fff", "bbb",
new HiResDate(390), null, 0, 0, 0, null, null, null, null);
mw.add(tcw1);
mw.add(tcw2);
mw.add(tcw3);
tw.add(mw);
return tw;
}
@SuppressWarnings("synthetic-access")
public final void testFilterToTimePeriod()
{
TrackWrapper tw = getDummyTrack();
HiResDate startH = new HiResDate(150, 0);
HiResDate endH = new HiResDate(450, 0);
tw.filterListTo(startH, endH);
int ctr = countVisibleFixes(tw);
int sCtr = countVisibleSensorWrappers(tw);
int tCtr = countVisibleSolutionWrappers(tw);
assertEquals("contains correct number of entries", 3, ctr);
assertEquals("contains correct number of sensor entries", 6, sCtr);
assertEquals("contains correct number of sensor entries", 5, tCtr);
tw = getDummyTrack();
startH = new HiResDate(350, 0);
endH = new HiResDate(550, 0);
tw.filterListTo(startH, endH);
ctr = countVisibleFixes(tw);
sCtr = countVisibleSensorWrappers(tw);
tCtr = countVisibleSolutionWrappers(tw);
assertEquals("contains correct number of entries", 2, ctr);
assertEquals("contains correct number of sensor entries", 1, sCtr);
assertEquals("contains correct number of sensor entries", 1, tCtr);
tw = getDummyTrack();
startH = new HiResDate(0, 0);
endH = new HiResDate(450, 0);
tw.filterListTo(startH, endH);
ctr = countVisibleFixes(tw);
sCtr = countVisibleSensorWrappers(tw);
tCtr = countVisibleSolutionWrappers(tw);
assertEquals("contains correct number of entries", 4, ctr);
assertEquals("contains correct number of sensor entries", 6, sCtr);
assertEquals("contains correct number of sensor entries", 6, tCtr);
}
public void testGetItemsBetween_Second()
{
final TrackWrapper tw = new TrackWrapper();
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(0, 1), loc_1,
0, 0));
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(0, 2), loc_1,
0, 0));
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(0, 3), loc_1,
0, 0));
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(0, 4), loc_1,
0, 0));
final FixWrapper fw5 = new FixWrapper(new Fix(new HiResDate(0, 5), loc_1,
0, 0));
final FixWrapper fw6 = new FixWrapper(new Fix(new HiResDate(0, 6), loc_1,
0, 0));
final FixWrapper fw7 = new FixWrapper(new Fix(new HiResDate(0, 7), loc_1,
0, 0));
tw.addFix(fw1);
tw.addFix(fw2);
tw.addFix(fw3);
tw.addFix(fw4);
tw.addFix(fw5);
tw.addFix(fw6);
tw.addFix(fw7);
fw1.setLabelShowing(true);
fw2.setLabelShowing(true);
fw3.setLabelShowing(true);
fw4.setLabelShowing(true);
fw5.setLabelShowing(true);
fw6.setLabelShowing(true);
fw7.setLabelShowing(true);
Collection<Editable> col = tw.getItemsBetween(new HiResDate(0, 3),
new HiResDate(0, 5));
assertEquals("found correct number of items", 3, col.size());
// make the fourth item not visible
fw4.setVisible(false);
col = tw.getUnfilteredItems(new HiResDate(0, 3), new HiResDate(0, 5));
assertEquals("found correct number of items", 2, col.size());
final Watchable[] pts2 = tw.getNearestTo(new HiResDate(0, 3));
assertEquals("found something", 1, pts2.length);
assertEquals("found the third item", fw3, pts2[0]);
final Watchable[] pts = tw.getNearestTo(new HiResDate(0, 1));
assertEquals("found something", 1, pts.length);
assertEquals("found the first item", fw1, pts[0]);
}
public final void testGettingTimes()
{
// Enumeration<SensorContactWrapper>
final TrackWrapper tw = new TrackWrapper();
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final WorldLocation loc_2 = new WorldLocation(1, 1, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(0, 100),
loc_1, 0, 0));
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(0, 300),
loc_2, 0, 0));
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(0, 500),
loc_2, 0, 0));
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(0, 700),
loc_2, 0, 0));
// check returning empty data
Collection<Editable> coll = tw.getItemsBetween(new HiResDate(0, 0),
new HiResDate(0, 40));
assertEquals("Return empty when empty", coll, null);
tw.addFix(fw1);
// check returning single field
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 40));
assertEquals("Return empty when out of range", coll, null);
coll = tw.getItemsBetween(new HiResDate(0, 520), new HiResDate(0, 540));
assertEquals("Return empty when out of range", coll, null);
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 140));
assertEquals("Return valid point", coll.size(), 1);
coll = tw.getItemsBetween(new HiResDate(0, 100), new HiResDate(0, 100));
assertEquals("Return valid point", coll.size(), 1);
tw.addFix(fw2);
// check returning with fields
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 40));
assertEquals("Return empty when out of range", coll, null);
coll = tw.getItemsBetween(new HiResDate(0, 520), new HiResDate(0, 540));
assertEquals("Return empty when out of range", coll, null);
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 140));
assertEquals("Return valid point", coll.size(), 1);
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 440));
assertEquals("Return valid point", coll.size(), 2);
coll = tw.getItemsBetween(new HiResDate(0, 150), new HiResDate(0, 440));
assertEquals("Return valid point", coll.size(), 1);
coll = tw.getItemsBetween(new HiResDate(0, 300), new HiResDate(0, 440));
assertEquals("Return valid point", coll.size(), 1);
tw.addFix(fw3);
// check returning with fields
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 40));
assertEquals("Return empty when out of range", coll, null);
coll = tw.getItemsBetween(new HiResDate(0, 520), new HiResDate(0, 540));
assertEquals("Return empty when out of range", coll, null);
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 140));
assertEquals("Return valid point", coll.size(), 1);
coll = tw.getItemsBetween(new HiResDate(0, 0), new HiResDate(0, 440));
assertEquals("Return valid point", coll.size(), 2);
coll = tw.getItemsBetween(new HiResDate(0, 150), new HiResDate(0, 440));
assertEquals("Return valid point", coll.size(), 1);
coll = tw.getItemsBetween(new HiResDate(0, 300), new HiResDate(0, 440));
assertEquals("Return valid point", coll.size(), 1);
coll = tw.getItemsBetween(new HiResDate(0, 100), new HiResDate(0, 300));
assertEquals("Return valid point", coll.size(), 2);
coll = tw.getItemsBetween(new HiResDate(0, 300), new HiResDate(0, 500));
assertEquals("Return valid point", coll.size(), 2);
tw.addFix(fw4);
}
public final void testInterpolation()
{
final TrackWrapper tw = new TrackWrapper();
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(100, 10000),
loc_1.add(new WorldVector(33, new WorldDistance(100,
WorldDistance.METRES), null)), 10, 110));
fw1.setLabel("fw1");
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(200, 20000),
loc_1.add(new WorldVector(33, new WorldDistance(200,
WorldDistance.METRES), null)), 20, 120));
fw2.setLabel("fw2");
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(300, 30000),
loc_1.add(new WorldVector(33, new WorldDistance(300,
WorldDistance.METRES), null)), 30, 130));
fw3.setLabel("fw3");
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(400, 40000),
loc_1.add(new WorldVector(33, new WorldDistance(400,
WorldDistance.METRES), null)), 40, 140));
fw4.setLabel("fw4");
final FixWrapper fw5 = new FixWrapper(new Fix(new HiResDate(500, 50000),
loc_1.add(new WorldVector(33, new WorldDistance(500,
WorldDistance.METRES), null)), 50, 150));
fw5.setLabel("fw5");
tw.addFix(fw1);
tw.addFix(fw2);
// tw.addFix(fw3);
tw.addFix(fw4);
tw.addFix(fw5);
// check that we're not interpolating
assertFalse("interpolating switched off by default", tw
.getInterpolatePoints());
// ok, get on with it.
Watchable[] list = tw.getNearestTo(new HiResDate(200, 20000));
assertNotNull("found list", list);
assertEquals("contains something", list.length, 1);
assertEquals("right answer", list[0], fw2);
// and the end
list = tw.getNearestTo(new HiResDate(500, 50000));
assertNotNull("found list", list);
assertEquals("contains something", list.length, 1);
assertEquals("right answer", list[0], fw5);
// and now an in-between point
// ok, get on with it.
list = tw.getNearestTo(new HiResDate(230, 23000));
assertNotNull("found list", list);
assertEquals("contains something", list.length, 1);
assertEquals("right answer", list[0], fw4);
// ok, with interpolation on
tw.setInterpolatePoints(true);
assertTrue("interpolating now switched on", tw.getInterpolatePoints());
// ok, get on with it.
list = tw.getNearestTo(new HiResDate(200, 20000));
assertNotNull("found list", list);
assertEquals("contains something", list.length, 1);
assertEquals("right answer", list[0], fw2);
// and the end
list = tw.getNearestTo(new HiResDate(500, 50000));
assertNotNull("found list", list);
assertEquals("contains something", list.length, 1);
assertEquals("right answer", list[0], fw5);
// hey
// and now an in-between point
// ok, get on with it.
list = tw.getNearestTo(new HiResDate(300, 30000));
assertNotNull("found list", list);
assertEquals("contains something", list.length, 1);
// have a look at them
final FixWrapper res = (FixWrapper) list[0];
final WorldVector rangeError = res.getFixLocation().subtract(
fw3.getFixLocation());
assertEquals("right answer", 0,
Conversions.Degs2m(rangeError.getRange()), 0.0001);
// assertEquals("right speed", res.getSpeed(), fw3.getSpeed(), 0);
// assertEquals("right course", res.getCourse(), fw3.getCourse(),
}
public final void testMyParams()
{
TrackWrapper ed = new TrackWrapper();
ed.setName("blank");
editableTesterSupport.testParams(ed, this);
ed = null;
}
public void testPaintingColChange()
{
final TrackWrapper tw = new TrackWrapper();
tw.setColor(Color.RED);
tw.setName("test track");
/**
* intention of this test: line is broken into three segments (red,
* yellow, green). - first of 2 points, next of 2 points, last of 3 points
* (14 values)
*/
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(100, 10000),
loc_1.add(new WorldVector(33, new WorldDistance(100,
WorldDistance.METRES), null)), 10, 110));
fw1.setLabel("fw1");
fw1.setColor(Color.red);
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(200, 20000),
loc_1.add(new WorldVector(33, new WorldDistance(200,
WorldDistance.METRES), null)), 20, 120));
fw2.setLabel("fw2");
fw2.setColor(Color.yellow);
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(300, 30000),
loc_1.add(new WorldVector(33, new WorldDistance(300,
WorldDistance.METRES), null)), 30, 130));
fw3.setLabel("fw3");
fw3.setColor(Color.green);
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(400, 40000),
loc_1.add(new WorldVector(33, new WorldDistance(400,
WorldDistance.METRES), null)), 40, 140));
fw4.setLabel("fw4");
fw4.setColor(Color.green);
final FixWrapper fw5 = new FixWrapper(new Fix(new HiResDate(500, 50000),
loc_1.add(new WorldVector(33, new WorldDistance(500,
WorldDistance.METRES), null)), 50, 150));
fw5.setLabel("fw5");
fw5.setColor(Color.green);
tw.addFix(fw1);
tw.addFix(fw2);
tw.addFix(fw3);
tw.addFix(fw4);
tw.addFix(fw5);
callCount = 0;
pointCount = 0;
assertNull("our array of points starts empty", tw._myPts);
assertEquals("our point array counter is zero", tw._ptCtr, 0);
final CanvasType dummyDest = new TestMockCanvas();
tw.paint(dummyDest);
assertEquals("our array has correct number of points", 10,
tw._myPts.length);
assertEquals("the pointer counter has been reset", 0, tw._ptCtr);
// check it got called the correct number of times
assertEquals("We didnt paint enough polygons", 3, callCount);
assertEquals("We didnt paint enough polygons points", 14, pointCount);
}
public void testPaintingLineJoinedChange()
{
final TrackWrapper tw = new TrackWrapper();
tw.setColor(Color.RED);
tw.setName("test track");
/**
* intention of this test: line is broken into two segments - one of two
* points, the next of three, thus two polygons should be drawn - 10
* points total (4 then 6).
*/
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(100, 10000),
loc_1.add(new WorldVector(33, new WorldDistance(100,
WorldDistance.METRES), null)), 10, 110));
fw1.setLabel("fw1");
fw1.setColor(Color.red);
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(200, 20000),
loc_1.add(new WorldVector(33, new WorldDistance(200,
WorldDistance.METRES), null)), 20, 120));
fw2.setLabel("fw2");
fw2.setColor(Color.red);
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(300, 30000),
loc_1.add(new WorldVector(33, new WorldDistance(300,
WorldDistance.METRES), null)), 30, 130));
fw3.setLabel("fw3");
fw3.setColor(Color.red);
fw3.setLineShowing(false);
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(400, 40000),
loc_1.add(new WorldVector(33, new WorldDistance(400,
WorldDistance.METRES), null)), 40, 140));
fw4.setLabel("fw4");
fw4.setColor(Color.red);
final FixWrapper fw5 = new FixWrapper(new Fix(new HiResDate(500, 50000),
loc_1.add(new WorldVector(33, new WorldDistance(500,
WorldDistance.METRES), null)), 50, 150));
fw5.setLabel("fw5");
fw5.setColor(Color.red);
tw.addFix(fw1);
tw.addFix(fw2);
tw.addFix(fw3);
tw.addFix(fw4);
tw.addFix(fw5);
callCount = 0;
pointCount = 0;
assertNull("our array of points starts empty", tw._myPts);
assertEquals("our point array counter is zero", tw._ptCtr, 0);
final CanvasType dummyDest = new TestMockCanvas();
tw.paint(dummyDest);
assertEquals("our array has correct number of points", 10,
tw._myPts.length);
assertEquals("the pointer counter has been reset", 0, tw._ptCtr);
// check it got called the correct number of times
assertEquals("We didnt paint enough polygons", 2, callCount);
assertEquals("We didnt paint enough polygons points", 10, pointCount);
}
public void testPaintingVisChange()
{
final TrackWrapper tw = new TrackWrapper();
tw.setColor(Color.RED);
tw.setName("test track");
/**
* intention of this test: line is broken into two segments of two points,
* thus two polygons should be drawn, each with 4 points - 8 points total.
*/
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(100, 10000),
loc_1.add(new WorldVector(33, new WorldDistance(100,
WorldDistance.METRES), null)), 10, 110));
fw1.setLabel("fw1");
fw1.setColor(Color.red);
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(200, 20000),
loc_1.add(new WorldVector(33, new WorldDistance(200,
WorldDistance.METRES), null)), 20, 120));
fw2.setLabel("fw2");
fw2.setColor(Color.red);
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(300, 30000),
loc_1.add(new WorldVector(33, new WorldDistance(300,
WorldDistance.METRES), null)), 30, 130));
fw3.setLabel("fw3");
fw3.setColor(Color.red);
fw3.setVisible(false);
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(400, 40000),
loc_1.add(new WorldVector(33, new WorldDistance(400,
WorldDistance.METRES), null)), 40, 140));
fw4.setLabel("fw4");
fw4.setColor(Color.red);
final FixWrapper fw5 = new FixWrapper(new Fix(new HiResDate(500, 50000),
loc_1.add(new WorldVector(33, new WorldDistance(500,
WorldDistance.METRES), null)), 50, 150));
fw5.setLabel("fw5");
fw5.setColor(Color.red);
tw.addFix(fw1);
tw.addFix(fw2);
tw.addFix(fw3);
tw.addFix(fw4);
tw.addFix(fw5);
callCount = 0;
pointCount = 0;
assertNull("our array of points starts empty", tw._myPts);
assertEquals("our point array counter is zero", tw._ptCtr, 0);
final CanvasType dummyDest = new TestMockCanvas();
tw.paint(dummyDest);
assertEquals("our array has correct number of points", 10,
tw._myPts.length);
assertEquals("the pointer counter has been reset", 0, tw._ptCtr);
// check it got called the correct number of times
assertEquals("We didnt paint enough polygons", 2, callCount);
assertEquals("We didnt paint enough polygons points", 8, pointCount);
}
}
/**
* class containing editable details of a track
*/
public final class trackInfo extends Editable.EditorType
{
/**
* constructor for this editor, takes the actual track as a parameter
*
* @param data
* track being edited
*/
public trackInfo(final TrackWrapper data)
{
super(data, data.getName(), "");
}
public final MethodDescriptor[] getMethodDescriptors()
{
// just add the reset color field first
final Class<TrackWrapper> c = TrackWrapper.class;
final MethodDescriptor[] mds =
{ method(c, "exportThis", null, "Export Shape"),
method(c, "resetLabels", null, "Reset DTG Labels") };
return mds;
}
public final String getName()
{
return super.getName();
}
public final PropertyDescriptor[] getPropertyDescriptors()
{
try
{
final PropertyDescriptor[] res =
{
expertProp("SymbolType",
"the type of symbol plotted for this label", FORMAT),
expertProp("LineThickness", "the width to draw this track", FORMAT),
expertProp("Name", "the track name"),
expertProp("InterpolatePoints",
"whether to interpolate points between known data points",
SPATIAL),
expertProp("Color", "the track color", FORMAT),
expertProp("TrackFont", "the track label font", FORMAT),
expertProp("NameVisible", "show the track label", VISIBILITY),
expertProp("PositionsVisible", "show individual Positions",
VISIBILITY),
expertProp("NameAtStart",
"whether to show the track name at the start (or end)",
VISIBILITY),
expertProp("Visible", "whether the track is visible", VISIBILITY),
expertLongProp("NameLocation", "relative location of track label",
MWC.GUI.Properties.LocationPropertyEditor.class),
expertLongProp("LabelFrequency", "the label frequency",
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
expertLongProp("SymbolFrequency", "the symbol frequency",
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
expertLongProp("ResampleDataAt", "the data sample rate",
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class)
};
res[0]
.setPropertyEditorClass(MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor.class);
res[1]
.setPropertyEditorClass(MWC.GUI.Properties.LineWidthPropertyEditor.class);
return res;
}
catch (final IntrospectionException e)
{
e.printStackTrace();
return super.getPropertyDescriptors();
}
}
}
/**
* keep track of versions - version id
*/
static final long serialVersionUID = 1;
/**
* put the other objects into this one as children
*
* @param wrapper
* whose going to receive it
* @param theLayers
* the top level layers object
* @param parents
* the track wrapppers containing the children
* @param subjects
* the items to insert.
*/
public static void groupTracks(TrackWrapper target, Layers theLayers,
Layer[] parents, Editable[] subjects)
{
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
target.add(ts);
}
}
else
{
if (obj instanceof TrackSegment)
{
TrackSegment ts = (TrackSegment) obj;
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
// and remember it
target.add(ts);
}
}
}
}
else
{
// get it's data, and add it to the target
target.add(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
}
/**
* perform a merge of the supplied tracks.
*
* @param target
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @return sufficient information to undo the merge
*/
public static int mergeTracks(final Editable target, Layers theLayers,
final Layer[] parents, final Editable[] subjects)
{
// where we dump the new data points
Layer receiver = (Layer) target;
// first, check they don't overlap.
// start off by collecting the periods
TimePeriod[] _periods = new TimePeriod.BaseTimePeriod[subjects.length];
for (int i = 0; i < subjects.length; i++)
{
Editable editable = subjects[i];
TimePeriod thisPeriod = null;
if (editable instanceof TrackWrapper)
{
TrackWrapper tw = (TrackWrapper) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(tw.getStartDTG(), tw
.getEndDTG());
}
else if (editable instanceof TrackSegment)
{
TrackSegment ts = (TrackSegment) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG());
}
_periods[i] = thisPeriod;
}
// now test them.
String failedMsg = null;
for (int i = 0; i < _periods.length; i++)
{
TimePeriod timePeriod = _periods[i];
for (int j = 0; j < _periods.length; j++)
{
TimePeriod timePeriod2 = _periods[j];
// check it's not us
if (timePeriod2 != timePeriod)
{
if (timePeriod.overlaps(timePeriod2))
{
failedMsg = "'" + subjects[i].getName() + "' and '"
+ subjects[j].getName() + "'";
break;
}
}
}
}
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// right, if the target is a TMA track, we have to change it into a proper
// track, since
// the merged tracks probably contain manoeuvres
if (target instanceof CoreTMASegment)
{
CoreTMASegment tma = (CoreTMASegment) target;
TrackSegment newSegment = new TrackSegment(tma);
// now do some fancy footwork to remove the target from the wrapper, and
// replace it with our new segment
newSegment.getWrapper().removeElement(target);
newSegment.getWrapper().add(newSegment);
// store the new segment into the receiver
receiver = newSegment;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
// is this the target item (note we're comparing against the item passed
// in, not our
// temporary receiver, since the receiver may now be a tracksegment, not a
// TMA segment
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
receiver.add(ts);
}
}
else
{
final Layer ts = (Layer) obj;
receiver.append(ts);
}
}
}
else
{
// get it's data, and add it to the target
receiver.append(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
return MessageProvider.OK;
}
/**
* whether to interpolate points in this track
*/
private boolean _interpolatePoints = false;
/**
* the end of the track to plot the label
*/
private boolean _LabelAtStart = true;
private HiResDate _lastLabelFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
private HiResDate _lastSymbolFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
private HiResDate _lastDataFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
/**
* the width of this track
*/
private int _lineWidth = 2;
/**
* whether or not to link the Positions
*/
private final boolean _linkPositions;
/**
* our editable details
*/
transient private Editable.EditorType _myEditor = null;
/**
* keep a list of points waiting to be plotted
*
*/
transient int[] _myPts;
/**
* the sensor tracks for this vessel
*/
private Vector<SensorWrapper> _mySensors = null;
/**
* the TMA solutions for this vessel
*/
private Vector<TMAWrapper> _mySolutions = null;
/**
* keep track of how far we are through our array of points
*
*/
transient int _ptCtr = 0;
/**
* whether or not to show the Positions
*/
private boolean _showPositions;
/**
* the label describing this track
*/
private final MWC.GUI.Shapes.TextLabel _theLabel;
/**
* the list of wrappers we hold
*/
private SegmentList _thePositions;
/**
* the symbol to pass on to a snail plotter
*/
private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape;
/**
* working ZERO location value, to reduce number of working values
*/
final private WorldLocation _zeroLocation = new WorldLocation(0, 0, 0);
// member functions
transient private FixWrapper finisher;
transient private HiResDate lastDTG;
transient private FixWrapper lastFix;
// for getNearestTo
transient private FixWrapper nearestFix;
/**
* working parameters
*/
// for getFixesBetween
transient private FixWrapper starter;
transient private TimePeriod _myTimePeriod;
transient private WorldArea _myWorldArea;
transient private final PropertyChangeListener _locationListener;
// constructors
/**
* Wrapper for a Track (a series of position fixes). It combines the data with
* the formatting details
*/
public TrackWrapper()
{
// create a property listener for when fixes are moved
_locationListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent arg0)
{
fixMoved();
}
};
// declare our arrays
_thePositions = new TrackWrapper_Support.SegmentList();
_thePositions.setWrapper(this);
_linkPositions = true;
// start off with positions showing (although the default setting for a
// fix
// is to not show a symbol anyway). We need to make this "true" so that
// when a fix position is set to visible it is not over-ridden by this
// setting
_showPositions = true;
_theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null);
// set an initial location for the label
_theLabel.setRelativeLocation(new Integer(
MWC.GUI.Properties.LocationPropertyEditor.RIGHT));
// initialise the symbol to use for plotting this track in snail mode
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory
.createSymbol("Submarine");
}
/**
* add the indicated point to the track
*
* @param point
* the point to add
*/
public final void add(final MWC.GUI.Editable point)
{
boolean done = false;
// see what type of object this is
if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
fw.setTrackWrapper(this);
addFix(fw);
done = true;
}
// is this a sensor?
else if (point instanceof SensorWrapper)
{
final SensorWrapper swr = (SensorWrapper) point;
if (_mySensors == null)
{
_mySensors = new Vector<SensorWrapper>(0, 1);
}
// add to our list
_mySensors.add(swr);
// tell the sensor about us
swr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
swr.setTrackName(this.getName());
// indicate success
done = true;
}
// is this a TMA solution track?
else if (point instanceof TMAWrapper)
{
final TMAWrapper twr = (TMAWrapper) point;
if (_mySolutions == null)
{
_mySolutions = new Vector<TMAWrapper>(0, 1);
}
// add to our list
_mySolutions.add(twr);
// tell the sensor about us
twr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
twr.setTrackName(this.getName());
// indicate success
done = true;
}
else if (point instanceof TrackSegment)
{
TrackSegment seg = (TrackSegment) point;
seg.setWrapper(this);
_thePositions.addSegment((TrackSegment) point);
done = true;
}
if (!done)
{
MWC.GUI.Dialogs.DialogFactory.showMessage("Add point",
"Sorry it is not possible to add:" + point.getName() + " to "
+ this.getName());
}
}
/**
* add the fix wrapper to the track
*
* @param theFix
* the Fix to be added
*/
public final void addFix(final FixWrapper theFix)
{
// do we have any track segments
if (_thePositions.size() == 0)
{
// nope, add one
final TrackSegment firstSegment = new TrackSegment();
firstSegment.setName("Positions");
_thePositions.addSegment(firstSegment);
}
// add fix to last track segment
final TrackSegment last = (TrackSegment) _thePositions.last();
last.addFix(theFix);
// tell the fix about it's daddy
theFix.setTrackWrapper(this);
// and extend the start/end DTGs
if (_myTimePeriod == null)
_myTimePeriod = new TimePeriod.BaseTimePeriod(theFix.getDateTimeGroup(),
theFix.getDateTimeGroup());
else
_myTimePeriod.extend(theFix.getDateTimeGroup());
if (_myWorldArea == null)
_myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation());
else
_myWorldArea.extend(theFix.getLocation());
// we want to listen out for the fix being moved. better listen in to it
// theFix.addPropertyChangeListener(PlainWrapper.LOCATION_CHANGED,
// _locationListener);
}
/**
* append this other layer to ourselves (although we don't really bother with
* it)
*
* @param other
* the layer to add to ourselves
*/
public final void append(final Layer other)
{
// is it a track?
if ((other instanceof TrackWrapper) || (other instanceof TrackSegment))
{
// yes, break it down.
final java.util.Enumeration<Editable> iter = other.elements();
while (iter.hasMoreElements())
{
final Editable nextItem = iter.nextElement();
if (nextItem instanceof Layer)
append((Layer) nextItem);
else
add(nextItem);
}
}
else
{
// nope, just add it to us.
add(other);
}
}
/**
* instruct this object to clear itself out, ready for ditching
*/
public final void closeMe()
{
// do the parent
super.closeMe();
// and my objects
// first ask them to close themselves
final Enumeration<Editable> it = getPositions();
while (it.hasMoreElements())
{
final Object val = it.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_thePositions.removeAllElements();
_thePositions = null;
// and my objects
// first ask the sensors to close themselves
if (_mySensors != null)
{
final Iterator<SensorWrapper> it2 = _mySensors.iterator();
while (it2.hasNext())
{
final Object val = it2.next();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySensors.clear();
}
// now ask the solutions to close themselves
if (_mySolutions != null)
{
final Iterator<TMAWrapper> it2 = _mySolutions.iterator();
while (it2.hasNext())
{
final Object val = it2.next();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySolutions.clear();
}
// and our utility objects
finisher = null;
lastFix = null;
nearestFix = null;
starter = null;
// and our editor
_myEditor = null;
}
/**
* switch the two track sections into one track section
*
* @param res
* the previously split track sections
*/
public void combineSections(Vector<TrackSegment> res)
{
// ok, remember the first
final TrackSegment keeper = res.firstElement();
// now remove them all, adding them to the first
final Iterator<TrackSegment> iter = res.iterator();
while (iter.hasNext())
{
final TrackSegment pl = iter.next();
if (pl != keeper)
{
keeper.append((Layer) pl);
}
_thePositions.removeElement(pl);
}
// and put the keepers back in
_thePositions.addSegment(keeper);
}
/**
* return our tiered data as a single series of elements
*
* @return
*/
public final Enumeration<Editable> contiguousElements()
{
final Vector<Editable> res = new Vector<Editable>(0, 1);
if (_mySensors != null)
{
final Enumeration<SensorWrapper> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = iter.nextElement();
// is it visible?
if (sw.getVisible())
{
res.addAll(sw._myContacts);
}
}
}
if (_mySolutions != null)
{
final Enumeration<TMAWrapper> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = iter.nextElement();
if (sw.getVisible())
{
res.addAll(sw._myContacts);
}
}
}
if (_thePositions != null)
{
res.addAll(getRawPositions());
}
return res.elements();
}
/**
* get an enumeration of the points in this track
*
* @return the points in this track
*/
public final Enumeration<Editable> elements()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
if (_mySensors != null)
{
final Enumeration<SensorWrapper> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
res.add(iter.nextElement());
}
}
if (_mySolutions != null)
{
final Enumeration<TMAWrapper> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
res.add(iter.nextElement());
}
}
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
/**
* export this track to REPLAY file
*/
public final void exportShape()
{
// call the method in PlainWrapper
this.exportThis();
}
/**
* filter the list to the specified time period, then inform any listeners
* (such as the time stepper)
*
* @param start
* the start dtg of the period
* @param end
* the end dtg of the period
*/
public final void filterListTo(final HiResDate start, final HiResDate end)
{
final Enumeration<Editable> fixWrappers = getPositions();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
final HiResDate dtg = fw.getTime();
if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end)))
{
fw.setVisible(true);
}
else
{
fw.setVisible(false);
}
}
// now do the same for our sensor data
if (_mySensors != null)
{
final Enumeration<SensorWrapper> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// and our solution data
if (_mySolutions != null)
{
final Enumeration<TMAWrapper> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// do we have any property listeners?
if (getSupport() != null)
{
final Debrief.GUI.Tote.StepControl.somePeriod newPeriod = new Debrief.GUI.Tote.StepControl.somePeriod(
start, end);
getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null,
newPeriod);
}
}
public void findNearestHotSpotIn(Point cursorPos, WorldLocation cursorLoc,
ComponentConstruct currentNearest, Layer parentLayer)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositions();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
// only check it if it's visible
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
final WorldLocation fixLocation = new WorldLocation(thisF.getLocation())
{
private static final long serialVersionUID = 1L;
public void addToMe(WorldVector delta)
{
super.addToMe(delta);
thisF.setFixLocation(this);
}
};
// try range
currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation);
}
}
}
public void findNearestHotSpotIn(Point cursorPos, WorldLocation cursorLoc,
LocationConstruct currentNearest, Layer parentLayer, Layers theData)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositions();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
// is it closer?
currentNearest.checkMe(this, thisDist, null, parentLayer);
}
}
}
public void findNearestSegmentHotspotFor(WorldLocation cursorLoc,
Point cursorPt, LocationConstruct currentNearest)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the track segments
final Collection<Editable> segments = _thePositions.getData();
for (final Iterator<Editable> iterator = segments.iterator(); iterator
.hasNext();)
{
final TrackSegment thisSeg = (TrackSegment) iterator.next();
if (thisSeg.getVisible())
{
// how far away is it?
thisDist = new WorldDistance(thisSeg.rangeFrom(cursorLoc),
WorldDistance.DEGS);
// is it closer?
currentNearest.checkMe(thisSeg, thisDist, null, this);
}
}
}
/**
* one of our fixes has moved. better tell any bits that rely on the locations
* of our bits
*
* @param theFix
* the fix that moved
*/
public void fixMoved()
{
if (_mySensors != null)
{
final Iterator<SensorWrapper> iter = _mySensors.iterator();
while (iter.hasNext())
{
final SensorWrapper nextS = iter.next();
nextS.setHost(this);
}
}
}
/**
* what geographic area is covered by this track?
*
* @return get the outer bounds of the area
*/
public final WorldArea getBounds()
{
// we no longer just return the bounds of the track, because a portion
// of the track may have been made invisible.
// instead, we will pass through the full dataset and find the outer
// bounds
// of the visible area
WorldArea res = null;
if (!getVisible())
{
// hey, we're invisible, return null
}
else
{
final Enumeration<Editable> it = getPositions();
while (it.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) it.nextElement();
// is this point visible?
if (fw.getVisible())
{
// has our data been initialised?
if (res == null)
{
// no, initialise it
res = new WorldArea(fw.getLocation(), fw.getLocation());
}
else
{
// yes, extend to include the new area
res.extend(fw.getLocation());
}
}
}
// also extend to include our sensor data
if (_mySensors != null)
{
final Enumeration<SensorWrapper> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
res = new WorldArea(theseBounds);
else
res.extend(sw.getBounds());
}
} // step through the sensors
} // whether we have any sensors
// and our solution data
if (_mySolutions != null)
{
final Enumeration<TMAWrapper> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
res = new WorldArea(theseBounds);
else
res.extend(sw.getBounds());
}
} // step through the sensors
} // whether we have any sensors
} // whether we're visible
return res;
}
/**
* the time of the last fix
*
* @return the DTG
*/
public final HiResDate getEndDTG()
{
TimePeriod res = getTimePeriod();
return res.getEndDTG();
}
// editing parameters
/**
* the editable details for this track
*
* @return the details
*/
public final Editable.EditorType getInfo()
{
if (_myEditor == null)
_myEditor = new trackInfo(this);
return _myEditor;
}
/**
* create a new, interpolated point between the two supplied
*
* @param previous
* the previous point
* @param next
* the next point
* @return and interpolated point
*/
private final FixWrapper getInterpolatedFix(final FixWrapper previous,
final FixWrapper next, HiResDate requestedDTG)
{
FixWrapper res = null;
// do we have a start point
if (previous == null)
res = next;
// hmm, or do we have an end point?
if (next == null)
res = previous;
// did we find it?
if (res == null)
{
res = FixWrapper.interpolateFix(previous, next, requestedDTG);
}
return res;
}
public final boolean getInterpolatePoints()
{
return _interpolatePoints;
}
/**
* get the set of fixes contained within this time period (inclusive of both
* end values)
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
public final Collection<Editable> getItemsBetween(final HiResDate start,
final HiResDate end)
{
SortedSet<Editable> set = null;
// does our track contain any data at all
if (_thePositions.size() > 0)
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
// don't bother with it.
}
else
{
// SPECIAL CASE! If we've been asked to show interpolated data
// points,
// then
// we should produce a series of items between the indicated
// times. How
// about 1 minute resolution?
if (getInterpolatePoints())
{
final long ourInterval = 1000 * 60; // one minute
set = new TreeSet<Editable>();
for (long newTime = start.getDate().getTime(); newTime < end
.getDate().getTime(); newTime += ourInterval)
{
final HiResDate newD = new HiResDate(newTime);
final Watchable[] nearestOnes = getNearestTo(newD);
if (nearestOnes.length > 0)
{
final FixWrapper nearest = (FixWrapper) nearestOnes[0];
set.add(nearest);
}
}
}
else
{
// bugger that - get the real data
// have a go..
if (starter == null)
{
starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0));
}
else
{
starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1));
}
if (finisher == null)
{
finisher = new FixWrapper(new Fix(new HiResDate(0,
end.getMicros() + 1), _zeroLocation, 0.0, 0.0));
}
else
{
finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1));
}
// ok, ready, go for it.
set = getPositionsBetween(starter, finisher);
}
}
}
return set;
}
/**
* just have the one property listener - rather than an anonymous class
*
* @return
*/
public PropertyChangeListener getLocationListener()
{
return _locationListener;
}
/**
* method to allow the setting of label frequencies for the track
*
* @return frequency to use
*/
public final HiResDate getLabelFrequency()
{
return this._lastLabelFrequency;
}
/**
* method to allow the setting of data sampling frequencies for the track &
* sensor data
*
* @return frequency to use
*/
public final HiResDate getResampleDataAt()
{
return this._lastDataFrequency;
}
/**
* the line thickness (convenience wrapper around width)
*
* @return
*/
public int getLineThickness()
{
return _lineWidth;
}
/**
* name of this Track (normally the vessel name)
*
* @return the name
*/
public final String getName()
{
return _theLabel.getString();
}
/**
* whether to show the track label at the start or end of the track
*
* @return yes/no to indicate <I>At Start</I>
*/
public final boolean getNameAtStart()
{
return _LabelAtStart;
}
/**
* the relative location of the label
*
* @return the relative location
*/
public final Integer getNameLocation()
{
return _theLabel.getRelativeLocation();
}
/**
* whether the track label is visible or not
*
* @return yes/no
*/
public final boolean getNameVisible()
{
return _theLabel.getVisible();
}
/**
* find the fix nearest to this time (or the first fix for an invalid time)
*
* @param DTG
* the time of interest
* @return the nearest fix
*/
public final Watchable[] getNearestTo(final HiResDate srchDTG)
{
/**
* we need to end up with a watchable, not a fix, so we need to work our way
* through the fixes
*/
FixWrapper res = null;
// check that we do actually contain some data
if (_thePositions.size() == 0)
return new MWC.GenericData.Watchable[]
{};
// special case - if we've been asked for an invalid time value
if (srchDTG == TimePeriod.INVALID_DATE)
{
final TrackSegment seg = (TrackSegment) _thePositions.first();
final FixWrapper fix = (FixWrapper) seg.first();
// just return our first location
return new MWC.GenericData.Watchable[]
{ (Watchable) fix };
}
// see if this is the DTG we have just requestsed
if ((srchDTG.equals(lastDTG)) && (lastFix != null))
{
res = lastFix;
}
else
{
final TrackSegment firstSeg = (TrackSegment) _thePositions.first();
final TrackSegment lastSeg = (TrackSegment) _thePositions.last();
// see if this DTG is inside our data range
// in which case we will just return null
final FixWrapper theFirst = (FixWrapper) firstSeg.first();
final FixWrapper theLast = (FixWrapper) lastSeg.last();
if ((srchDTG.greaterThanOrEqualTo(theFirst.getTime()))
&& (srchDTG.lessThanOrEqualTo(theLast.getTime())))
{
// yes it's inside our data range, find the first fix
// after the indicated point
// right, increment the time, since we want to allow matching
// points
// HiResDate DTG = new HiResDate(0, srchDTG.getMicros() + 1);
// see if we have to create our local temporary fix
if (nearestFix == null)
{
nearestFix = new FixWrapper(new Fix(srchDTG, _zeroLocation, 0.0, 0.0));
}
else
nearestFix.getFix().setTime(srchDTG);
// right, we really should be filtering the list according to if
// the
// points are visible.
// how do we do filters?
// get the data. use tailSet, since it's inclusive...
SortedSet<Editable> set = getRawPositions().tailSet(nearestFix);
// see if the requested DTG was inside the range of the data
if (!set.isEmpty())
{
res = (FixWrapper) set.first();
// is this one visible?
if (!res.getVisible())
{
// right, the one we found isn't visible. duplicate the
// set, so that
// we can remove items
// without affecting the parent
set = new TreeSet<Editable>(set);
// ok, start looping back until we find one
while ((!res.getVisible()) && (set.size() > 0))
{
// the first one wasn't, remove it
set.remove(res);
if (set.size() > 0)
res = (FixWrapper) set.first();
}
}
}
// right, that's the first points on or before the indicated
// DTG. Are we
// meant
// to be interpolating?
if (res != null)
if (getInterpolatePoints())
{
// right - just check that we aren't actually on the
// correct time
// point.
// HEY, USE THE ORIGINAL SEARCH TIME, NOT THE
// INCREMENTED ONE,
// SINCE WE DON'T WANT TO COMPARE AGAINST A MODIFIED
// TIME
if (!res.getTime().equals(srchDTG))
{
// right, we haven't found an actual data point.
// Better calculate
// one
// hmm, better also find the point before our one.
// the
// headSet operation is exclusive - so we need to
// find the one
// after the first
final SortedSet<Editable> otherSet = getRawPositions().headSet(
nearestFix);
FixWrapper previous = null;
if (!set.isEmpty())
{
previous = (FixWrapper) otherSet.last();
}
// did it work?
if (previous != null)
{
// cool, sort out the interpolated point USING
// THE ORIGINAL
// SEARCH TIME
res = getInterpolatedFix(previous, res, srchDTG);
}
}
}
}
// and remember this fix
lastFix = res;
lastDTG = srchDTG;
}
if (res != null)
return new MWC.GenericData.Watchable[]
{ res };
else
return new MWC.GenericData.Watchable[]
{};
}
/**
* get the position data, not all the sensor/contact/position data mixed
* together
*
* @return
*/
public final Enumeration<Editable> getPositions()
{
final SortedSet<Editable> res = getRawPositions();
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
private SortedSet<Editable> getPositionsBetween(FixWrapper starter2,
FixWrapper finisher2)
{
// first get them all as one list
final SortedSet<Editable> pts = getRawPositions();
// now do the sort
return pts.subSet(starter2, finisher2);
}
/**
* whether positions are being shown
*
* @return
*/
public final boolean getPositionsVisible()
{
return _showPositions;
}
private SortedSet<Editable> getRawPositions()
{
SortedSet<Editable> res = null;
// do we just have the one list?
if (_thePositions.size() == 1)
{
final TrackSegment p = (TrackSegment) _thePositions.first();
res = (SortedSet<Editable>) p.getData();
}
else
{
// loop through them
res = new TreeSet<Editable>();
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
// get this segment
final TrackSegment seg = (TrackSegment) segs.nextElement();
// add all the points
res.addAll(seg.getData());
}
}
return res;
}
/**
* get the list of sensors for this track
*/
public final Enumeration<SensorWrapper> getSensors()
{
Enumeration<SensorWrapper> res = null;
if (_mySensors != null)
res = _mySensors.elements();
return res;
}
/**
* return the symbol to be used for plotting this track in snail mode
*/
public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape()
{
return _theSnailShape;
}
/**
* get the list of sensors for this track
*/
public final Enumeration<TMAWrapper> getSolutions()
{
Enumeration<TMAWrapper> res = null;
if (_mySolutions != null)
res = _mySolutions.elements();
return res;
}
// watchable (tote related) parameters
/**
* the earliest fix in the track
*
* @return the DTG
*/
public final HiResDate getStartDTG()
{
TimePeriod res = getTimePeriod();
return res.getStartDTG();
}
private TimePeriod getTimePeriod()
{
TimePeriod res = null;
Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
TrackSegment seg = (TrackSegment) segs.nextElement();
if (res == null)
res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG());
else
{
res.extend(seg.startDTG());
res.extend(seg.endDTG());
}
}
return res;
}
/**
* return the symbol frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getSymbolFrequency()
{
return _lastSymbolFrequency;
}
/**
* get the type of this symbol
*/
public final String getSymbolType()
{
return _theSnailShape.getType();
}
/**
* the colour of the points on the track
*
* @return the colour
*/
public final Color getTrackColor()
{
return getColor();
}
/**
* font handler
*
* @return the font to use for the label
*/
public final java.awt.Font getTrackFont()
{
return _theLabel.getFont();
}
/**
* get the set of fixes contained within this time period which haven't been
* filtered, and which have valid depths. The isVisible flag indicates whether
* a track has been filtered or not. We also have the getVisibleFixesBetween
* method (below) which decides if a fix is visible if it is set to Visible,
* and it's label or symbol are visible.
* <p/>
* We don't have to worry about a valid depth, since 3d doesn't show points
* with invalid depth values
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
public final Collection<Editable> getUnfilteredItems(final HiResDate start,
final HiResDate end)
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
return null;
if (this.getVisible() == false)
return null;
// get ready for the output
final Vector<Editable> res = new Vector<Editable>(0, 1);
// put the data into a period
final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end);
// step through our fixes
final Enumeration<Editable> iter = getPositions();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
if (fw.getVisible())
{
// is it visible?
if (thePeriod.contains(fw.getTime()))
{
// hey, it's valid - continue
res.add(fw);
}
}
}
return res;
}
/**
* whether this object has editor details
*
* @return yes/no
*/
public final boolean hasEditor()
{
return true;
}
public boolean hasOrderedChildren()
{
return false;
}
/**
* quick accessor for how many fixes we have
*
* @return
*/
public int numFixes()
{
return getRawPositions().size();
}
/**
* draw this track (we can leave the Positions to draw themselves)
*
* @param dest
* the destination
*/
public final void paint(final CanvasType dest)
{
if (getVisible())
{
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
dest.setColor(getColor());
// firstly plot the solutions
if (_mySolutions != null)
{
final Enumeration<TMAWrapper> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
sw.setHost(this);
// and do the paint
sw.paint(dest);
} // through the solutions
} // whether we have any solutions
// now plot the sensors
if (_mySensors != null)
{
final Enumeration<SensorWrapper> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
sw.setHost(this);
// and do the paint
sw.paint(dest);
} // through the sensors
} // whether we have any sensors
// and now the track itself
// is our points store long enough?
if ((_myPts == null) || (_myPts.length < numFixes() * 2))
{
_myPts = new int[numFixes() * 2];
}
// reset the points counter
_ptCtr = 0;
// java.awt.Point lastP = null;
Color lastCol = null;
int lineStyle = CanvasType.SOLID;
boolean locatedTrack = false;
WorldLocation lastLocation = null;
FixWrapper lastFix = null;
// just check if we are drawing anything at all
if ((!_linkPositions) && (!_showPositions))
return;
// keep track of if we have plotted any points (since
// we won't be plotting the name if none of the points are visible).
// this typically occurs when filtering is applied and a short
// track is completely outside the time period
boolean plotted_anything = false;
// let the fixes draw themselves in
Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
TrackSegment seg = (TrackSegment) segments.nextElement();
lineStyle = seg.getLineStyle();
// SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN
// RELATIVE
// MODE
boolean isRelative = seg.getPlotRelative();
WorldLocation tmaLastLoc = null;
long tmaLastDTG = 0;
// if it's not a relative track, and it's not visible, we don't
// need to
// work with ut
if (!getVisible() && !isRelative)
continue;
// is this segment visible?
if(!seg.getVisible())
continue;
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// now there's a chance that our fix has forgotten it's parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
// is this fix visible?
if (!fw.getVisible())
{
// nope. Don't join it to the last position.
// ok, if we've built up a polygon, we need to write it
// now
paintTrack(dest, lastCol, lineStyle);
}
// Note: we're carrying on working with this position even
// if it isn't
// visible,
// since we need to use non-visible positions to build up a
// DR track.
// ok, so we have plotted something
plotted_anything = true;
// ok, are we in relative?
if (isRelative)
{
long thisTime = fw.getDateTimeGroup().getDate().getTime();
// ok, is this our first location?
if (tmaLastLoc == null)
{
tmaLastLoc = new WorldLocation(seg.getTrackStart());
lastLocation = tmaLastLoc;
}
else
{
// calculate a new vector
long timeDelta = thisTime - tmaLastDTG;
if (lastFix != null)
{
double speedKts = lastFix.getSpeed();
double courseRads = lastFix.getCourse();
double depthM = lastFix.getDepth();
// use the value of depth as read in from the file
tmaLastLoc.setDepth(depthM);
WorldVector thisVec = seg.vectorFor(timeDelta, speedKts,
courseRads);
tmaLastLoc.addToMe(thisVec);
lastLocation = tmaLastLoc;
}
}
lastFix = fw;
tmaLastDTG = thisTime;
// dump the location into the fix
fw.setFixLocationSilent(new WorldLocation(tmaLastLoc));
}
else
{
// this is an absolute position
lastLocation = fw.getLocation();
}
// ok, we only do this writing to screen if the actual
// position is
// visible
if (getVisible())
{
final java.awt.Point thisP = dest.toScreen(lastLocation);
// just check that there's enough GUI to create the plot
// (i.e. has a point been returned)
if (thisP == null)
return;
// so, we're looking at the first data point. Do
// we want to use this to locate the track name?
if (_LabelAtStart)
{
// or have we already sorted out the location
if (!locatedTrack)
{
locatedTrack = true;
_theLabel.setLocation(new WorldLocation(lastLocation));
}
}
// are we
if (_linkPositions)
{
// right, just check if we're a different colour to
// the
// previous one
final Color thisCol = fw.getColor();
// do we know the previous colour
if (lastCol == null)
{
lastCol = thisCol;
}
// is this to be joined to the previous one?
if (fw.getLineShowing())
{
// so, grow the the polyline, unless we've got a
// colour
// change...
if (thisCol != lastCol)
{
// add our position to the list - so it
// finishes on us
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
// yup, better get rid of the previous
// polygon
paintTrack(dest, lastCol, lineStyle);
}
// add our position to the list - we'll output
// the
// polyline at the end
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
else
{
// nope, output however much line we've got so
// far -
// since this
// line won't be joined to future points
paintTrack(dest, thisCol, lineStyle);
// start off the next line
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
/*
* set the colour of the track from now on to this colour, so that
* the "link" to the next fix is set to this colour if left
* unchanged
*/
dest.setColor(fw.getColor());
// and remember the last colour
lastCol = thisCol;
}
if (_showPositions && fw.getVisible())
{
fw.paintMe(dest, lastLocation);
}
}
}
// ok, just see if we have any pending polylines to paint
paintTrack(dest, lastCol, lineStyle);
}
// are we trying to put the label at the end of the track?
if (!_LabelAtStart)
{
// check that we have found at least one location to plot.
if (lastLocation != null)
_theLabel.setLocation(new WorldLocation(lastLocation));
}
// and draw the track label
if (_theLabel.getVisible())
{
// still, we only plot the track label if we have plotted any
// points
if (plotted_anything)
{
// just see if we have multiple segments. if we do,
// name them individually
if (this._thePositions.size() <= 1)
{
// check that we have found a location for the lable
if (_theLabel.getLocation() != null)
{
// is the first track a DR track?
TrackSegment t1 = (TrackSegment) _thePositions.first();
if (t1.getPlotRelative())
{
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC));
}
else
{
if (_theLabel.getFont().isItalic())
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN));
}
// check that we have set the name for the label
if (_theLabel.getString() == null)
{
_theLabel.setString(getName());
}
if (_theLabel.getColor() == null)
{
_theLabel.setColor(getColor());
}
// and paint it
_theLabel.paint(dest);
}// if the label has a location
}
else
{
// we've got multiple segments, name them
Enumeration<Editable> posis = _thePositions.elements();
while (posis.hasMoreElements())
{
TrackSegment thisE = (TrackSegment) posis.nextElement();
// is this segment visible?
if(!thisE.getVisible())
continue;
// is the first track a DR track?
if (thisE.getPlotRelative())
{
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC));
}
else
{
if (_theLabel.getFont().isItalic())
_theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN));
}
WorldLocation theLoc = thisE.getTrackStart();
String oldTxt = _theLabel.getString();
_theLabel.setString(thisE.getName());
_theLabel.setLocation(theLoc);
_theLabel.paint(dest);
_theLabel.setString(oldTxt);
}
} // whether there's only one track
}
} // if the label is visible
} // if visible
}
/**
* paint any polyline that we've built up
*
* @param dest
* - where we're painting to
* @param thisCol
* @param lineStyle
*/
private void paintTrack(final CanvasType dest, final Color thisCol,
int lineStyle)
{
if (_ptCtr > 0)
{
dest.setColor(thisCol);
dest.setLineStyle(lineStyle);
final int[] poly = new int[_ptCtr];
System.arraycopy(_myPts, 0, poly, 0, _ptCtr);
dest.drawPolyline(poly);
dest.setLineStyle(CanvasType.SOLID);
// and reset the counter
_ptCtr = 0;
}
}
/**
* return the range from the nearest corner of the track
*
* @param other
* the other location
* @return the range
*/
public final double rangeFrom(final WorldLocation other)
{
double nearest = -1;
// do we have a track?
if (_myWorldArea != null)
{
// find the nearest point on the track
nearest = _myWorldArea.rangeFrom(other);
}
return nearest;
}
/**
* remove the requested item from the track
*
* @param point
* the point to remove
*/
public final void removeElement(final Editable point)
{
// just see if it's a sensor which is trying to be removed
if (point instanceof SensorWrapper)
{
_mySensors.remove(point);
// tell the sensor wrapper to forget about us
TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
}
else if (point instanceof TMAWrapper)
{
_mySolutions.remove(point);
// tell the sensor wrapper to forget about us
TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
}
else if (point instanceof SensorContactWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Iterator<SensorWrapper> iter = _mySensors.iterator();
while (iter.hasNext())
{
final SensorWrapper sw = iter.next();
// try to remove it from this one...
sw.removeElement(point);
}
}
else if (point instanceof TrackSegment)
{
_thePositions.removeElement(point);
// and clear the parent item
TrackSegment ts = (TrackSegment) point;
ts.setWrapper(null);
}
else
{
// loop through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.removeElement(point);
// and stop listening to it (if it's a fix)
if (point instanceof FixWrapper)
{
FixWrapper fw = (FixWrapper) point;
fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED,
_locationListener);
}
}
}
}
/**
* pass through the track, resetting the labels back to their original DTG
*/
public void resetLabels()
{
FormatTracks.formatTrack(this);
}
// LAYER support methods
/**
* set the colour of this track label
*
* @param theCol
* the colour
*/
@FireReformatted
public final void setColor(final Color theCol)
{
// do the parent
super.setColor(theCol);
// now do our processing
_theLabel.setColor(theCol);
_theSnailShape.setColor(theCol);
}
/**
* the setter function which passes through the track
*/
private void setFixes(final FixSetter setter, final HiResDate theVal)
{
final long freq = theVal.getMicros();
// briefly check if we are revealing/hiding all times (ie if freq is 1
// or 0)
if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY)
{
// show all of the labels
final Enumeration<Editable> iter = getPositions();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
setter.execute(fw, true);
}
}
else
{
// no, we're not just blindly doing all of them. do them at the
// correct
// frequency
// hide all of the labels/symbols first
final Enumeration<Editable> enumA = getPositions();
while (enumA.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) enumA.nextElement();
setter.execute(fw, false);
}
if (freq == 0)
{
// we can ignore this, since we have just hidden all of the
// points
}
else
{
// pass through the track setting the values
// sort out the start and finish times
long start_time = getStartDTG().getMicros();
final long end_time = getEndDTG().getMicros();
// first check that there is a valid time period between start
// time
// and end time
if (start_time + freq < end_time)
{
long num = start_time / freq;
// we need to add one to the quotient if it has rounded down
if (start_time % freq == 0)
{
// start is at our freq, so we don't need to increment
}
else
{
num++;
}
// calculate new start time
start_time = num * freq;
}
else
{
// there is not one of our 'intervals' between the start and
// the end,
// so use the start time
}
while (start_time <= end_time)
{
// right, increment the start time by one, because we were
// getting the
// fix immediately before the requested time
final HiResDate thisDTG = new HiResDate(0, start_time);
final MWC.GenericData.Watchable[] list = this.getNearestTo(thisDTG);
// check we found some
if (list.length > 0)
{
final FixWrapper fw = (FixWrapper) list[0];
setter.execute(fw, true);
}
// produce the next time step
start_time += freq;
}
}
}
}
public final void setInterpolatePoints(boolean val)
{
_interpolatePoints = val;
}
/**
* set the data frequency (in seconds) for the track & sensor data
*
* @param theVal
* frequency to use
*/
@FireExtended
public final void setResampleDataAt(final HiResDate theVal)
{
this._lastDataFrequency = theVal;
// have a go at trimming the start time to a whole number of intervals
final long interval = theVal.getMicros();
final long currentStart = this.getStartDTG().getMicros();
long startTime = (currentStart / interval) * interval;
// just check we're in the range
if (startTime < currentStart)
startTime += interval;
// just check it's not a barking frequency
if (theVal.getDate().getTime() <= 0)
{
// ignore, we don't need to do anything for a zero or a -1
}
else
{
SegmentList segments = _thePositions;
Enumeration<Editable> theEnum = segments.elements();
while (theEnum.hasMoreElements())
{
TrackSegment seg = (TrackSegment) theEnum.nextElement();
seg.decimate(theVal, this, startTime);
}
// start off with the sensor data
if (_mySensors != null)
{
for (Iterator<SensorWrapper> iterator = _mySensors.iterator(); iterator
.hasNext();)
{
SensorWrapper thisS = (SensorWrapper) iterator.next();
thisS.decimate(theVal, startTime);
}
}
// now the solutions
if (_mySolutions != null)
{
for (Iterator<TMAWrapper> iterator = _mySolutions.iterator(); iterator
.hasNext();)
{
TMAWrapper thisT = (TMAWrapper) iterator.next();
thisT.decimate(theVal, startTime);
}
}
}
}
/**
* set the label frequency (in seconds)
*
* @param theVal
* frequency to use
*/
public final void setLabelFrequency(final HiResDate theVal)
{
this._lastLabelFrequency = theVal;
final FixSetter setLabel = new FixSetter()
{
public void execute(final FixWrapper fix, final boolean val)
{
fix.setLabelShowing(val);
}
};
setFixes(setLabel, theVal);
}
/**
* the line thickness (convenience wrapper around width)
*/
public void setLineThickness(final int val)
{
_lineWidth = val;
}
// track-shifting operation
// support for dragging the track around
/**
* set the name of this track (normally the name of the vessel
*
* @param theName
* the name as a String
*/
public final void setName(final String theName)
{
_theLabel.setString(theName);
}
/**
* whether to show the track name at the start or end of the track
*
* @param val
* yes no for <I>show label at start</I>
*/
public final void setNameAtStart(final boolean val)
{
_LabelAtStart = val;
}
/**
* the relative location of the label
*
* @param val
* the relative location
*/
public final void setNameLocation(final Integer val)
{
_theLabel.setRelativeLocation(val);
}
/**
* whether to show the track name
*
* @param val
* yes/no
*/
public final void setNameVisible(final boolean val)
{
_theLabel.setVisible(val);
}
/**
* whether to show the position fixes
*
* @param val
* yes/no
*/
public final void setPositionsVisible(final boolean val)
{
_showPositions = val;
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setSymbolFrequency(final HiResDate theVal)
{
this._lastSymbolFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
public void execute(final FixWrapper fix, final boolean val)
{
fix.setSymbolShowing(val);
}
};
setFixes(setSymbols, theVal);
}
public final void setSymbolType(final String val)
{
// is this the type of our symbol?
if (val.equals(_theSnailShape.getType()))
{
// don't bother we're using it already
}
else
{
// remember the size of the symbol
final double scale = _theSnailShape.getScaleVal();
// replace our symbol with this new one
_theSnailShape = null;
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val);
_theSnailShape.setColor(this.getColor());
_theSnailShape.setScaleVal(scale);
}
}
// note we are putting a track-labelled wrapper around the colour
// parameter, to make the properties window less confusing
/**
* the colour of the points on the track
*
* @param theCol
* the colour to use
*/
public final void setTrackColor(final Color theCol)
{
setColor(theCol);
}
/**
* font handler
*
* @param font
* the font to use for the label
*/
public final void setTrackFont(final java.awt.Font font)
{
_theLabel.setFont(font);
}
public void shift(WorldLocation feature, WorldVector vector)
{
feature.addToMe(vector);
// right, one of our fixes has moved. get the sensors to update
// themselves
fixMoved();
}
public void shift(WorldVector vector)
{
this.shiftTrack(elements(), vector);
}
/**
* move the whole of the track be the provided offset
*/
public final void shiftTrack(Enumeration<Editable> theEnum,
final WorldVector offset)
{
// keep track of if the track contains something that doesn't get
// dragged
boolean handledData = false;
if (theEnum == null)
theEnum = elements();
while (theEnum.hasMoreElements())
{
final Object thisO = theEnum.nextElement();
if (thisO instanceof TrackSegment)
{
TrackSegment seg = (TrackSegment) thisO;
seg.shift(offset);
// ok - job well done
handledData = true;
}
else if (thisO instanceof SegmentList)
{
SegmentList list = (SegmentList) thisO;
Collection<Editable> items = list.getData();
for (Iterator<Editable> iterator = items.iterator(); iterator.hasNext();)
{
TrackSegment segment = (TrackSegment) iterator.next();
segment.shift(offset);
}
handledData = true;
}
else if (thisO instanceof SensorWrapper)
{
final SensorWrapper sw = (SensorWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final SensorContactWrapper scw = (SensorContactWrapper) enumS
.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin != null)
{
// create new object to contain the updated location
final WorldLocation newSensorLocation = new WorldLocation(
sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a sensor wrapper
else if (thisO instanceof TrackSegment)
{
final TrackSegment tw = (TrackSegment) thisO;
final Enumeration<Editable> enumS = tw.elements();
// fire recursively, smart-arse.
shiftTrack(enumS, offset);
// ok - job well done
handledData = true;
} // whether this is a sensor wrapper
} // looping through this track
// ok, did we handle the data?
if (!handledData)
{
System.err.println("TrackWrapper problem; not able to shift:" + theEnum);
}
}
/**
* split this whole track into two sub-tracks
*
* @param splitPoint
* the point at which we perform the split
* @param splitBeforePoint
* whether to put split before or after specified point
* @return a list of the new track segments (used for subsequent undo
* operations)
*/
public Vector<TrackSegment> splitTrack(FixWrapper splitPoint,
boolean splitBeforePoint)
{
Vector<TrackSegment> res = null;
TrackSegment relevantSegment = null;
// are we still in one section?
if (_thePositions.size() == 1)
{
relevantSegment = (TrackSegment) _thePositions.first();
// yup, looks like we're going to be splitting it.
// better give it a proper name
relevantSegment.setName(relevantSegment.startDTG().getDate().toString());
}
else
{
// ok, find which segment contains our data
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
if (seg.getData().contains(splitPoint))
{
relevantSegment = seg;
break;
}
}
}
if (relevantSegment == null)
{
throw new RuntimeException(
"failed to provide relevant segment, alg will break");
}
// hmm, if we're splitting after the point, we need to move along the
// bus by
// one
if (!splitBeforePoint)
{
Collection<Editable> items = relevantSegment.getData();
Iterator<Editable> theI = items.iterator();
Editable previous = null;
while (theI.hasNext())
{
Editable thisE = (Editable) theI.next();
// have we chosen to remember the previous item?
if (previous != null)
{
// yes, this must be the one we're after
splitPoint = (FixWrapper) thisE;
break;
}
// is this the one we're looking for?
if (thisE == splitPoint)
{
// yup, remember it - we want to use the next value
previous = (FixWrapper) thisE;
}
}
}
// yup, do our first split
final SortedSet<Editable> p1 = relevantSegment.headSet(splitPoint);
final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPoint);
// get our results ready
final TrackSegment ts1, ts2;
// aaah, just sort out if we are splitting a TMA segment, in which case
// want to create two
// tma segments, not track segments
if (relevantSegment instanceof RelativeTMASegment)
{
RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment;
// aah, sort out if we are splitting before or after.
// find out the offset at the split point, so we can initiate it for
// the
// second part of the track
WorldLocation refTrackLoc = theTMA.getReferenceTrack().getNearestTo(
splitPoint.getDateTimeGroup())[0].getLocation();
WorldVector secondOffset = splitPoint.getLocation().subtract(refTrackLoc);
// put the lists back into plottable layers
RelativeTMASegment tr1 = new RelativeTMASegment(theTMA, p1, theTMA
.getOffset());
RelativeTMASegment tr2 = new RelativeTMASegment(theTMA, p2, secondOffset);
// update the freq's
tr1.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
tr2.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else if (relevantSegment instanceof AbsoluteTMASegment)
{
AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment;
// aah, sort out if we are splitting before or after.
// find out the offset at the split point, so we can initiate it for
// the
// second part of the track
Watchable[] matches = this.getNearestTo(splitPoint.getDateTimeGroup());
WorldLocation origin = matches[0].getLocation();
FixWrapper t1Start = (FixWrapper) p1.first();
// put the lists back into plottable layers
AbsoluteTMASegment tr1 = new AbsoluteTMASegment(theTMA, p1, t1Start
.getLocation(), null, null);
AbsoluteTMASegment tr2 = new AbsoluteTMASegment(theTMA, p2, origin, null,
null);
// update the freq's
tr1.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
tr2.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else
{
// put the lists back into plottable layers
ts1 = new TrackSegment(p1);
ts2 = new TrackSegment(p2);
}
// now clear the positions
_thePositions.removeElement(relevantSegment);
// and put back our new layers
_thePositions.addSegment(ts1);
_thePositions.addSegment(ts2);
// remember them
res = new Vector<TrackSegment>();
res.add(ts1);
res.add(ts2);
return res;
}
/**
* extra parameter, so that jvm can produce a sensible name for this
*
* @return the track name, as a string
*/
public final String toString()
{
return "Track:" + getName();
}
/**
* is this track visible between these time periods?
*
* @param start
* start DTG
* @param end
* end DTG
* @return yes/no
*/
public final boolean visibleBetween(final HiResDate start, final HiResDate end)
{
boolean visible = false;
if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start)))
{
visible = true;
}
return visible;
}
}
|
package org.broad.igv.ui;
import com.jidesoft.plaf.LookAndFeelFactory;
import htsjdk.samtools.seekablestream.SeekableStreamFactory;
import jargs.gnu.CmdLineParser;
import org.apache.log4j.Logger;
import org.broad.igv.DirectoryManager;
import org.broad.igv.Globals;
import org.broad.igv.prefs.IGVPreferences;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.HttpUtils;
import org.broad.igv.util.RuntimeUtils;
import org.broad.igv.util.stream.IGVSeekableStreamFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashSet;
import static org.broad.igv.prefs.Constants.*;
/**
* Utility class for launching IGV. Provides a "main" method and an "open" method for opening IGV in a supplied Frame.
* <p/>
* Note: The "open" methods must be executed on the event thread, for example
* <p/>
* public static void main(String[] args) {
* EventQueue.invokeLater(new Runnable() {
* public void run() {
* Frame frame = new Frame();
* org.broad.igv.ui.Main.open(frame);
* }
* );
* }
*
* @author jrobinso
* @date Feb 7, 2011
*/
public class Main {
private static Logger log = Logger.getLogger(Main.class);
/**
* Launch an igv instance as a stand-alone application in its own Frame.
*
* @param args
*/
public static void main(final String args[]) {
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
final Main.IGVArgs igvArgs = new Main.IGVArgs(args);
// Do this early
if (igvArgs.igvDirectory != null) {
setIgvDirectory(igvArgs);
}
Runnable runnable = new Runnable() {
public void run() {
// This is a workaround for an internal JVM crash that was happening on Windows 10 (Creators Update).
// TODO: remove when enough users have migrated to Java 8u141 or greater.
if (Globals.IS_WINDOWS && System.getProperty("os.name").contains("10")) {
UIManager.put("FileChooser.useSystemExtensionHiding", false);
}
initApplication();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon(Main.class.getResource("mainframeicon.png"));
if (icon != null) frame.setIconImage(icon.getImage());
open(frame, igvArgs);
}
};
SwingUtilities.invokeLater(runnable);
}
private static void setIgvDirectory(IGVArgs igvArgs) {
File dir = new File(igvArgs.igvDirectory);
if (!dir.exists()) {
// doesn't exist -- try to create it
try {
dir.mkdir();
} catch (Exception e) {
log.error("Error creating igv directory " + dir.getAbsolutePath(), e);
return;
}
if (dir.isDirectory()) {
if (dir.canWrite()) {
DirectoryManager.setIgvDirectory(dir);
} else {
log.error("IGV directory '" + dir.getAbsolutePath() + "'is not writable");
}
} else {
log.error("'" + dir.getAbsolutePath() + "' is not a directory");
}
} else {
log.error("'" + dir.getAbsolutePath() + "' not found");
}
}
private static void initApplication() {
long mem = RuntimeUtils.getAvailableMemory();
int MB = 1000000;
if (mem < 400 * MB) {
int mb = (int) (mem / MB);
JOptionPane.showMessageDialog(null, "Warning: IGV is running with low available memory (" + mb + " mb)");
}
DirectoryManager.initializeLog();
log.info("Startup " + Globals.applicationString());
log.info("Java " + System.getProperty(Globals.JAVA_VERSION_STRING));
log.info("Default User Directory: " + DirectoryManager.getUserDirectory());
log.info("OS: " + System.getProperty("os.name"));
System.setProperty("http.agent", Globals.applicationString());
Runtime.getRuntime().addShutdownHook(new ShutdownThread());
updateTooltipSettings();
// Anti alias settings. TODO = Are these neccessary anymore ?
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
checkVersion();
}
public static void updateTooltipSettings() {
ToolTipManager.sharedInstance().setEnabled(true);
final IGVPreferences prefMgr = PreferencesManager.getPreferences();
ToolTipManager.sharedInstance().setInitialDelay(prefMgr.getAsInt(TOOLTIP_INITIAL_DELAY));
ToolTipManager.sharedInstance().setReshowDelay(prefMgr.getAsInt(TOOLTIP_RESHOW_DELAY));
ToolTipManager.sharedInstance().setDismissDelay(prefMgr.getAsInt(TOOLTIP_DISMISS_DELAY));
}
private static void checkVersion() {
Runnable runnable = () -> {
try {
Version thisVersion = Version.getVersion(Globals.VERSION);
if (thisVersion != null) {
final String serverVersionString = HttpUtils.getInstance().getContentsAsString(new URL(Globals.getVersionURL())).trim();
// See if user has specified to skip this update
final String skipString = PreferencesManager.getPreferences().get(SKIP_VERSION);
HashSet<String> skipVersion = new HashSet<String>(Arrays.asList(skipString.split(",")));
if (skipVersion.contains(serverVersionString)) return;
Version serverVersion = Version.getVersion(serverVersionString.trim());
if (serverVersion == null) return;
if (thisVersion.lessThan(serverVersion)) {
log.info("A later version of IGV is available (" + serverVersionString + ")");
}
} else if (Globals.VERSION.contains("3.0_beta") || Globals.VERSION.contains("snapshot")) {
HttpUtils.getInstance().getContentsAsString(new URL(Globals.getVersionURL())).trim();
} else {
log.info("Unknown version: " + Globals.VERSION);
}
} catch (Exception e) {
log.error("Error checking version", e);
} finally {
}
};
(new Thread(runnable)).start();
}
/**
* Open an IGV instance in the supplied Frame. This method used by unit tests
*
* @param frame
*/
public static void open(Frame frame) {
open(frame, new IGVArgs(new String[]{}));
}
/**
* Open an IGV instance in the supplied frame.
*
* @param frame
* @param igvArgs command-line arguments
*/
public static void open(Frame frame, Main.IGVArgs igvArgs) {
// Add a listener for the "close" icon, unless its a JFrame
if (!(frame instanceof JFrame)) {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
windowEvent.getComponent().setVisible(false);
}
});
}
// Turn on tooltip in case it was disabled for a temporary keyboard event, e.g. alt-tab
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
ToolTipManager.sharedInstance().setEnabled(true);
}
@Override
public void windowGainedFocus(WindowEvent windowEvent) {
this.windowActivated(windowEvent);
}
});
initializeLookAndFeel();
// Optional arguments
if (igvArgs.getPropertyOverrides() != null) {
PreferencesManager.loadOverrides(igvArgs.getPropertyOverrides());
}
if (igvArgs.getDataServerURL() != null) {
PreferencesManager.getPreferences().overrideDataServerURL(igvArgs.getDataServerURL());
}
if (igvArgs.getGenomeServerURL() != null) {
PreferencesManager.getPreferences().overrideGenomeServerURL(igvArgs.getGenomeServerURL());
}
HttpUtils.getInstance().updateProxySettings();
//AbstractFeatureReader.setComponentMethods(new IGVComponentMethods());
SeekableStreamFactory.setInstance(IGVSeekableStreamFactory.getInstance());
RuntimeUtils.loadPluginJars();
IGV.createInstance(frame).startUp(igvArgs);
// TODO Should this be done here? Will this step on other key dispatchers?
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new GlobalKeyDispatcher());
}
private static void initializeLookAndFeel() {
try {
String lnf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lnf);
} catch (Exception e) {
e.printStackTrace();
}
double resolutionScale = Toolkit.getDefaultToolkit().getScreenResolution() / Globals.DESIGN_DPI;
final IGVPreferences prefMgr = PreferencesManager.getPreferences();
if (resolutionScale > 1.5) {
if (prefMgr.getAsBoolean(SCALE_FONTS)) {
FontManager.scaleFontSize(resolutionScale);
} else if (prefMgr.hasExplicitValue(DEFAULT_FONT_SIZE)) {
int fs = prefMgr.getAsInt(DEFAULT_FONT_SIZE);
FontManager.updateSystemFontSize(fs);
}
}
if (Globals.IS_LINUX) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.put("JideSplitPane.dividerSize", 5);
UIManager.put("JideSplitPaneDivider.background", Color.darkGray);
} catch (Exception exception) {
exception.printStackTrace();
}
}
// Todo -- what does this do?
LookAndFeelFactory.installJideExtension();
}
/**
* Class to represent the IGV version. The version numbering follows Microsoft conventions. This class is public
* to allow unit tests.
* <p/>
* Example internal version string: 2.3.27 (31)02/18/2014 11:42 PM
* Example server version string: 2.3.27
*/
public static class Version {
private int major;
private int minor;
private int build;
public static Version getVersion(String versionString) {
String[] tokens = versionString.split("\\.");
if (tokens.length < 2) {
return null; // Unknown version
} else {
try {
int major = Integer.parseInt(tokens[0]);
int minor = Integer.parseInt(tokens[1]);
int build = tokens.length <= 2 ? 0 : Integer.parseInt(tokens[2]);
return new Version(major, minor, build);
} catch (NumberFormatException e) {
log.error("Error parsing version string: " + versionString);
return null;
}
}
}
private Version(int major, int minor, int build) {
this.major = major;
this.minor = minor;
this.build = build;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getBuild() {
return build;
}
public boolean lessThan(Version anotherVersion) {
if (anotherVersion.major > this.major) return true;
else if (anotherVersion.major < this.major) return false;
else if (anotherVersion.minor > this.minor) return true;
else if (anotherVersion.minor < this.minor) return false;
else return anotherVersion.build > this.build;
}
}
/**
* Class to encapsulate IGV command line arguments.
*/
static public class IGVArgs {
private String batchFile = null;
private String sessionFile = null;
private String dataFileString = null;
private String locusString = null;
private String propertyOverrides = null;
private String genomeId = null;
private String port = null;
private String dataServerURL = null;
private String genomeServerURL = null;
private String indexFile = null;
private String coverageFile = null;
private String name = null;
public String igvDirectory = null;
IGVArgs(String[] args) {
if (args != null) {
parseArgs(args);
}
}
/**
* Parse arguments. All arguments are optional, a full set of arguments are
* firstArg locusString -b batchFile -p preferences
*/
private void parseArgs(String[] args) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option propertyFileOption = parser.addStringOption('o', "preferences");
CmdLineParser.Option batchFileOption = parser.addStringOption('b', "batch");
CmdLineParser.Option portOption = parser.addStringOption('p', "port");
CmdLineParser.Option genomeOption = parser.addStringOption('g', "genome");
CmdLineParser.Option dataServerOption = parser.addStringOption('d', "dataServerURL");
CmdLineParser.Option genomeServerOption = parser.addStringOption('u', "genomeServerURL");
CmdLineParser.Option indexFileOption = parser.addStringOption('i', "indexFile");
CmdLineParser.Option coverageFileOption = parser.addStringOption('c', "coverageFile");
CmdLineParser.Option nameOption = parser.addStringOption('n', "name");
CmdLineParser.Option igvDirectoryOption = parser.addStringOption("igvDirectory");
try {
parser.parse(args);
} catch (CmdLineParser.IllegalOptionValueException e) {
e.printStackTrace(); // This is not logged because the logger is not initialized yet.
} catch (CmdLineParser.UnknownOptionException e) {
e.printStackTrace();
}
propertyOverrides = getDecodedValue(parser, propertyFileOption);
batchFile = getDecodedValue(parser, batchFileOption);
port = (String) parser.getOptionValue(portOption);
genomeId = (String) parser.getOptionValue(genomeOption);
dataServerURL = getDecodedValue(parser, dataServerOption);
genomeServerURL = getDecodedValue(parser, genomeServerOption);
name = (String) parser.getOptionValue(nameOption);
String indexFilePath = (String) parser.getOptionValue(indexFileOption);
if (indexFilePath != null) {
indexFile = maybeDecodePath(indexFilePath);
}
String coverageFilePath = (String) parser.getOptionValue(coverageFileOption);
if (coverageFilePath != null) {
coverageFile = maybeDecodePath(coverageFilePath);
}
String igvDirectoryPath = (String) parser.getOptionValue(igvDirectoryOption);
if (igvDirectoryPath != null) {
igvDirectory = maybeDecodePath(igvDirectoryPath);
}
String[] nonOptionArgs = parser.getRemainingArgs();
if (nonOptionArgs != null && nonOptionArgs.length > 0) {
String firstArg = maybeDecodePath(nonOptionArgs[0]);
if (firstArg != null && !firstArg.equals("ignore")) {
log.info("Loading: " + firstArg);
if (firstArg.endsWith(".xml") || firstArg.endsWith(".php") || firstArg.endsWith(".php3")
|| firstArg.endsWith(".session")) {
sessionFile = firstArg;
} else {
dataFileString = firstArg;
}
}
if (nonOptionArgs.length > 1) {
locusString = nonOptionArgs[1];
}
}
}
private String maybeDecodePath(String path) {
if (FileUtils.isRemote(path)) {
return URLDecoder.decode(path);
} else {
if (FileUtils.resourceExists(path)) {
return path;
} else {
return URLDecoder.decode(path);
}
}
}
private String getDecodedValue(CmdLineParser parser, CmdLineParser.Option option) {
String value = (String) parser.getOptionValue(option);
if (value == null) return null;
try {
return URLDecoder.decode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(e);
return value;
}
}
private String checkEqualsAndExtractParamter(String arg) {
if (arg == null) return null;
int eq = arg.indexOf("=");
if (eq > 0) {
// we got a key=value
String key = arg.substring(0, eq);
String val = arg.substring(eq + 1);
if (key.equalsIgnoreCase("sessionURL") || key.equalsIgnoreCase("file")) {
if (val.endsWith(".xml") || val.endsWith(".php") || val.endsWith(".php3")
|| val.endsWith(".session")) {
log.info("Got session: " + key + "=" + val);
sessionFile = val;
} else {
log.info("Got dataFileString: " + key + "=" + val);
dataFileString = val;
}
return null;
} else if (key.equalsIgnoreCase("locus") || key.equalsIgnoreCase("position")) {
log.info("Got locus: " + key + "=" + val);
locusString = val;
return null;
} else {
log.info("Currently not handled: " + key + "=" + val);
return null;
}
}
return arg;
}
public String getBatchFile() {
return batchFile;
}
public String getSessionFile() {
return sessionFile;
}
public String getDataFileString() {
return dataFileString;
}
public String getLocusString() {
return locusString;
}
public String getPropertyOverrides() {
return propertyOverrides;
}
public String getGenomeId() {
return genomeId;
}
public String getPort() {
return port;
}
public String getDataServerURL() {
return dataServerURL;
}
public String getGenomeServerURL() {
return genomeServerURL;
}
public String getIndexFile() {
return indexFile;
}
public String getCoverageFile() {
return coverageFile;
}
public String getName() {
return name;
}
}
}
|
package fourmiz.abillity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.newdawn.slick.geom.Shape;
import fourmiz.collision.Entity;
import fourmiz.engine.Abillity;
import fourmiz.touch.marker.LifeMarker;
public class Life extends Abillity{
private static Logger log=LogManager.getLogger(Life.class);
private static int INTERVAL_TIME=1000;
private MyLifeMarker lifeMarker=new MyLifeMarker();
//vie instantane
private int life_current;
//vie maximum
private int life_max;
//quantit de vie perdue chaque actualisation
private int life_tic;
private int time=0;
public Life(Entity owner) {
super(owner);
addTouchMarker(lifeMarker);
}
@Override
public void update(int delta) {
time+=delta;
if(time>=INTERVAL_TIME){
life_current=life_current-life_tic;
time-=INTERVAL_TIME;
}
//You are dead, life empty
if(life_current<=0){
log.info("entity ID: "+getOwner().getID()+" die cause to has no health");
getOwner().getEngine().removeEntityToBuff(getOwner());
}
}
//retourne la vie actuelle
public int getCurrentLife() {
return life_current;
}
//met jour la vie actuelle en vrifiant qu'elle est conforme aux bornes
public void setCurrentLife(int life_current) {
if(life_current<0 || life_current>life_max) throw new IllegalArgumentException();
this.life_current = life_current;
}
//retourne la vie maximum
public int getMaxLife() {
if(life_max<=0) throw new IllegalArgumentException();
return life_max;
}
//met jour la valeur maximale de vie possible
public void setMaxLife(int life_max) {
this.life_max = life_max;
}
//retourne la perte de vie priodique
public int getUptake() {
return life_tic;
}
//met jour la perte de vie priodique
public void setUptake(int uptake) {
this.life_tic = uptake;
}
private class MyLifeMarker extends LifeMarker{
@Override
public int getLife() {
return life_current;
}
@Override
public int getMaxLife() {
return life_max;
}
@Override
public void setLife(int life) {
setCurrentLife(life);
}
@Override
//augmente la vie actuelle de la valeur de life
public void addLife(int life) {
life_current+=life;
if(life_current>life_max) life_current=life_max;
}
@Override
//diminue la vie actuelle de la valeur de life
public void withdrawLife(int life) {
life_current-=life;
if(life_current<0) life_current=0;
}
@Override
//retourne l'entit qui appartient cette vie
public Entity getOwner() {
return Life.this.getOwner();
}
//retourne la zone d'influence autour de l'entit
@Override
public Shape getArea() {
return Life.this.getOwner().getCollisionShape();
}
}
}
|
package com.coillighting.udder.scene;
import com.coillighting.udder.effect.woven.WovenEffect;
import com.coillighting.udder.geometry.Interpolator;
import com.coillighting.udder.mix.StatefulAnimator;
import com.coillighting.udder.mix.Layer;
import com.coillighting.udder.mix.Mixer;
import com.coillighting.udder.mix.TimePoint;
import java.awt.geom.Point2D;
import static com.coillighting.udder.geometry.Interpolator.Interpolation;
/** Implements a 'shuffle' mode specifically tailored to the Boulder Dairy
* Archway's scene. Cross-fades layers in groups that look good together,
* periodically stopping to fade everything out and fade in the Woven effect,
* with synchronized startup of the Woven effect from its opening queue
* (a blackout of several seconds).
*
* When not displaying the Woven scene, shows 1 incoming look + 1 primary
* look + 1 outgoing look. Fade-in of the incoming look and fade-out of
* the outgoing look have their own easing curves, randomly selected from
* the available modes.
*/
public class DairyShuffler implements StatefulAnimator {
protected Mixer mixer;
protected Interpolator interpolator;
int wovenLayerIndex;
int shuffleLayerStartIndex; // inclusive
int shuffleLayerEndIndex; // inclusive
long cueStartTimeMillis;
long textureCueDurationMillis;
long wovenCueDurationMillis;
long cueDurationMillis;
private DairyShufflerFadeTiming[] fadeTimings;
boolean enabled;
boolean wovenMode;
protected Interpolation interpolationModeIncoming;
protected Interpolation interpolationModeOutgoing;
protected int incomingLayerIndex;
protected double incomingLevel;
protected double primaryLevel;
protected double outgoingLevel;
protected double wovenLevel;
// temp variables we don't want to keep reallocating in every event
private Point2D.Double off;
private Point2D.Double current;
private Point2D.Double on;
public DairyShuffler(Mixer mixer, int wovenLayerIndex, int shuffleLayerStartIndex, int shuffleLayerEndIndex,
DairyShufflerFadeTiming[] timings)
{
if(mixer == null) {
throw new NullPointerException("DairyShuffler requires a Mixer before it can shuffle.");
} else {
int ct = mixer.size();
if(wovenLayerIndex < 0 || wovenLayerIndex >= ct) {
throw new IllegalArgumentException(
"This mixer contains no layer at wovenLayerIndex="
+ wovenLayerIndex);
} else if(shuffleLayerStartIndex < 0 || shuffleLayerStartIndex >= ct) {
throw new IllegalArgumentException(
"This mixer contains no layer at shuffleLayerStartIndex="
+ shuffleLayerStartIndex);
} else if(shuffleLayerEndIndex < 0 || shuffleLayerEndIndex >= ct) {
throw new IllegalArgumentException(
"This mixer contains no layer at shuffleLayerEndIndex="
+ shuffleLayerStartIndex);
} else if(shuffleLayerEndIndex <= shuffleLayerStartIndex) {
throw new IllegalArgumentException(
"A shuffler's shuffleLayerStartIndex may not exceed its shuffleLayerEndIndex.");
} else if(shuffleLayerStartIndex <= wovenLayerIndex
&& wovenLayerIndex <= shuffleLayerEndIndex) {
throw new IllegalArgumentException(
"A shuffler's woven layer may not also be a shuffled layer.");
} else if(timings == null) {
throw new IllegalArgumentException("A list of fade times is required.");
} else if(timings.length != ct) {
throw new IllegalArgumentException("Exactly " + ct +
" fade times slots are required, because that's how many layers are in your mixer, but you supplied "
+ timings.length + " of them.");
} else {
for(int i=0; i<timings.length; i++) {
if(timings[i] == null) {
if(i >= shuffleLayerStartIndex && i <= shuffleLayerEndIndex) {
throw new IllegalArgumentException("Every shuffled layer must have a DairyShufflerFadeTiming "
+ "object which is not null, but timings[" + i + "] is null.");
} else {
throw new IllegalArgumentException("A non-shuffled layer must never have a DairyShufflerFadeTiming "
+ "object, but timings[" + i + "] is not null.");
}
}
}
this.fadeTimings = timings;
}
}
// These interpolator curve settings favor a strong three-way mix
// over what looks almost like a one-way mix.
// 0.15: fade in quick, linger for a while and fade out quick
// 2.5: relatively brighter, more gradual fade in and out in POWER mode
this.interpolator = new Interpolator(0.15, 2.5);
this.mixer = mixer;
this.wovenLayerIndex = wovenLayerIndex;
this.shuffleLayerStartIndex = shuffleLayerStartIndex;
this.shuffleLayerEndIndex = shuffleLayerEndIndex;
textureCueDurationMillis = 60000;
this.reset();
off = new Point2D.Double(0.0, 0.0);
current = new Point2D.Double(0.0, 0.0);
on = new Point2D.Double(1.0, 1.0);
enabled = true;
this.mixer.subscribeAnimator(this);
}
public void reset() throws ClassCastException {
wovenMode = true;
Layer wovenLayer = (Layer) mixer.getLayer(wovenLayerIndex);
WovenEffect wovenEffect = (WovenEffect) wovenLayer.getEffect();
wovenCueDurationMillis = wovenEffect.getDurationMillis();
wovenEffect.reset();
cueDurationMillis = wovenCueDurationMillis;
incomingLayerIndex = -1; // < 0: nothing incoming
incomingLevel = 0.0;
primaryLevel = 0.0;
outgoingLevel=0.0;
wovenLevel = 0.0;
interpolationModeIncoming = Interpolation.SINUSOIDAL;
interpolationModeOutgoing = Interpolation.SINUSOIDAL;
cueStartTimeMillis = -1; // < 0: not started
}
// switch off woven vs. other layers only at the transition point,
// so human operators can play around with transient looks,
// like woven + textures
public void animate(TimePoint timePoint) {
if(enabled) {
// Step forward or rewind and start over if needed.
long now = timePoint.sceneTimeMillis();
if (cueStartTimeMillis < 0) {
cueStartTimeMillis = now;
}
long end = cueStartTimeMillis + cueDurationMillis;
if (end < now) {
// Step forward to the next track in the playlist.
if (wovenMode) {
// Switch from woven to texture mode
cueDurationMillis = textureCueDurationMillis;
wovenMode = false;
wovenLevel = 0.0f;
mixer.getLayer(wovenLayerIndex).setLevel(wovenLevel);
incomingLayerIndex = shuffleLayerStartIndex;
interpolationModeIncoming = Interpolation.ROOT; // fade in quick, don't leave it black
} else if (incomingLayerIndex >= shuffleLayerEndIndex + 2) {
// Switch to woven mode
for (int i = shuffleLayerStartIndex; i <= shuffleLayerEndIndex; i++) {
this.setTextureLevelConditionally(0.0f, i);
}
this.reset();
// level will be set below on transition into Woven effect
} else {
// Start fading in the next texture.
// Choose a new easing curve each time.
// We used to favor a brighter, three-way mix, but since
// we added many open patterns, we've increased the probability
// of a thinner, mostly solo or duet mix, by increasing the
// chance of a POWER mix to 50/50.
interpolationModeIncoming = interpolator.randomMode(20, 75, 95);
interpolationModeOutgoing = interpolator.randomMode(20, 75, 95);
cueDurationMillis = textureCueDurationMillis;
if(incomingLayerIndex > shuffleLayerEndIndex) {
// At this point there is only one outgoing layer, so
// make it quick to avoid spooking the client.
// (The gallery staff gets antsy that the rig has failed
// and calls BV whenever they observe a long-tail
// fade to black, so we cut the final cue short in order
// to loop promptly back to the Woven effect.)
cueDurationMillis *= 0.20;
}
// finish fading out the outgoing track if needed:
this.setTextureLevelConditionally(0.0f, incomingLayerIndex - 2);
outgoingLevel = primaryLevel;
primaryLevel = incomingLevel;
incomingLevel = 0.0f;
incomingLayerIndex++;
}
cueStartTimeMillis = now;
}
if (wovenMode) {
// Don't crossfade into the Woven cue. It builds from black
// without any help from this Shuffler.
if (cueStartTimeMillis == now) {
wovenLevel = 1.0;
mixer.getLayer(wovenLayerIndex).setLevel(wovenLevel);
}
} else {
// texture mode only, not in woven mode
int li = incomingLayerIndex;
DairyShufflerFadeTiming inTiming, outTiming;
// N.B. Fade in and out are not applied to Woven mode thanks to
// the range check in setTextureLevelConditionally.
// TODO the following code is a recent edition, probably not too robust. TEST.
if(li - 2 < shuffleLayerStartIndex) {
// won't matter, but must be not null
outTiming = fadeTimings[shuffleLayerStartIndex];
} else {
outTiming = fadeTimings[li - 2];
}
if(li > shuffleLayerEndIndex) {
// likewise won't matter, but must be not null
inTiming = fadeTimings[shuffleLayerEndIndex];
} else {
inTiming = fadeTimings[li];
}
// Crossfade out of the outgoing cue and into the incoming cue.
// Do not change the primary cue, which is like the current track.
double cuePct = (double) (now - cueStartTimeMillis) / cueDurationMillis;
// To fade out faster, make this number smaller.
// Range: 0 - 1.0 for 0% to 100% of cue time spent fading.
double cueFadeOutPct = outTiming.out;
double outPct;
// To fade in faster, make this number smaller.
double cueFadeInPct = inTiming.in;
double inPct;
if(cuePct >= cueFadeOutPct || cueFadeOutPct == 0.0) {
// Done fading out already.
outPct = 0.0;
} else {
// Keep fading out, aiming to be done cueFadeOutPct of the
// way along the cue's timeline.
outPct = cuePct / cueFadeOutPct;
}
double inThreshold = 1.0 - cueFadeInPct;
if(cuePct <= inThreshold || cueFadeInPct == 0.0) {
// Don't start fading in yet.
inPct = 0.0;
} else {
// Continue fading in, beginning cueFadeInPct of the way
// along the cue's timeline.
inPct = (cuePct - inThreshold) / cueFadeInPct;
}
// incoming look (if applicable)
interpolator.interpolate2D(interpolationModeIncoming, inPct, off, current, on);
// FUTURE: implement a 1D Interpolator API, but for now just
// piggyback on the existing 2D API and ignore y.
// FIXME: convert all layer levels to doubles.
incomingLevel = current.x;
this.setTextureLevelConditionally(incomingLevel, li);
// primary look (if applicable)
li -= 1;
primaryLevel = 1.0;
this.setTextureLevelConditionally(primaryLevel, li);
// outgoing look (if applicable)
li -= 1;
interpolator.interpolate2D(interpolationModeOutgoing, outPct, on, current, off);
outgoingLevel = current.x;
this.setTextureLevelConditionally(outgoingLevel, li);
}
}
}
/** Only try to fade in or out a texture layer. Allow Woven to handle its
* own dynamics, and ignore out of range layers. Simplifies the impl of
* animate somewhat.
*/
private void setTextureLevelConditionally(double level, int layerIndex) {
if(layerIndex >= shuffleLayerStartIndex
&& layerIndex <= shuffleLayerEndIndex) {
mixer.getLayer(layerIndex).setLevel(level);
}
}
public Class getStateClass() {
return DairyShufflerState.class;
}
public Object getState() {
return new DairyShufflerState(enabled, textureCueDurationMillis);
}
public void setState(Object state) throws ClassCastException {
DairyShufflerState command = (DairyShufflerState) state;
this.enabled = command.getEnabled();
long millis = command.getCueDurationMillis();
if(millis > 0) {
this.textureCueDurationMillis = millis;
}
}
}
|
// $Id: Util.java,v 1.40 2005/06/03 07:44:23 belaban Exp $
package org.jgroups.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.*;
import org.jgroups.protocols.FD;
import org.jgroups.protocols.PingHeader;
import org.jgroups.protocols.UdpHeader;
import org.jgroups.protocols.pbcast.NakAckHeader;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.stack.IpAddress;
import java.io.*;
import java.net.BindException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.*;
/**
* Collection of various utility routines that can not be assigned to other classes.
*/
public class Util {
private static final Object mutex=new Object();
private static final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
protected static final Log log=LogFactory.getLog(Util.class);
// constants
public static final int MAX_PORT=65535; // highest port allocatable
public static final String DIAG_GROUP="DIAG_GROUP-BELA-322649"; // unique
static boolean resolve_dns=false;
static {
try {
resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();
}
catch (SecurityException ex){
resolve_dns=false;
}
}
public static void closeInputStream(InputStream inp) {
if(inp != null)
try {inp.close();} catch(IOException e) {}
}
public static void closeOutputStream(OutputStream out) {
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
synchronized(mutex) {
if(buffer == null) return null;
Object retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=in.readObject();
in.close();
if(retval == null)
return null;
return retval;
}
}
/**
* Serializes an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
result=out_stream.toByteArray();
out.close();
}
return result;
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
if(addr == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if(addr instanceof IpAddress) {
// regular case, we don't need to include class information about the type of Address, e.g. JmsAddress
out.writeBoolean(true);
addr.writeTo(out);
}
else {
out.writeBoolean(false);
writeOtherAddress(addr, out);
}
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Address addr=null;
if(in.readBoolean() == false)
return null;
if(in.readBoolean()) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int b=in.read();
int magic_number;
String classname;
Class cl=null;
Address addr;
if(b == 1) {
magic_number=in.readInt();
cl=conf.get(magic_number);
}
else {
classname=in.readUTF();
cl=conf.get(classname);
}
addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1;
// write the class info
if(magic_number == -1) {
out.write(0);
out.writeUTF(addr.getClass().getName());
}
else {
out.write(1);
out.writeInt(magic_number);
}
// write the data itself
addr.writeTo(out);
}
public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {
if(obj == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
obj.writeTo(out);
}
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Streamable retval=null;
if(in.readBoolean() == false)
return null;
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {
int magic_number;
String classname;
if(obj == null) {
out.write(0);
return;
}
try {
out.write(1);
magic_number=ClassConfigurator.getInstance(false).getMagicNumber(obj.getClass());
// write the magic number or the class name
if(magic_number == -1) {
out.write(0);
classname=obj.getClass().getName();
out.writeUTF(classname);
}
else {
out.write(1);
out.writeInt(magic_number);
}
// write the contents
obj.writeTo(out);
}
catch(ChannelException e) {
throw new IOException("failed writing object of type " + obj.getClass() + " to stream: " + e.toString());
}
}
public static Streamable readGenericStreamable(DataInputStream in) throws IOException {
Streamable retval=null;
int b=in.read();
if(b == 0)
return null;
int use_magic_number=in.read(), magic_number;
String classname;
Class clazz;
try {
if(use_magic_number == 1) {
magic_number=in.readInt();
clazz=ClassConfigurator.getInstance(false).get(magic_number);
}
else {
classname=in.readUTF();
clazz=ClassConfigurator.getInstance(false).get(classname);
}
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
catch(Exception ex) {
throw new IOException("failed reading object: " + ex.toString());
}
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {
if(buf != null) {
out.write(1);
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.write(0);
}
}
public static byte[] readByteBuffer(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1) {
b=in.readInt();
byte[] buf=new byte[b];
in.read(buf, 0, buf.length);
return buf;
}
return null;
}
/**
* Marshalls a list of messages
* @param xmit_list LinkedList<Message>
* @return
* @throws IOException
*/
public static Buffer msgListToByteBuffer(LinkedList xmit_list) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
Message msg;
Buffer retval=null;
out.writeInt(xmit_list.size());
for(Iterator it=xmit_list.iterator(); it.hasNext();) {
msg=(Message)it.next();
msg.writeTo(out);
}
out.flush();
retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static LinkedList byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {
LinkedList retval=null;
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
int size=in.readInt();
if(size == 0)
return null;
Message msg;
retval=new LinkedList();
for(int i=0; i < size; i++) {
msg=new Message();
msg.readFrom(in);
retval.add(msg);
}
return retval;
}
public static boolean match(Object obj1, Object obj2) {
if(obj1 == null && obj2 == null)
return true;
if(obj1 != null)
return obj1.equals(obj2);
else
return obj2.equals(obj1);
}
public static boolean match(long[] a1, long[] a2) {
if(a1 == null && a2 == null)
return true;
if(a1 == null || a2 == null)
return false;
if(a1 == a2) // identity
return true;
// at this point, a1 != null and a2 != null
if(a1.length != a2.length)
return false;
for(int i=0; i < a1.length; i++) {
if(a1[i] != a2[i])
return false;
}
return true;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(Exception e) {
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * 100000) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
log.error("timeout must be > 0 !");
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
if(r < cutoff)
return true;
else
return false;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
/**
* Debugging method used to dump the content of a protocol queue in a condensed form. Useful
* to follow the evolution of the queue's content in time.
*/
public static String dumpQueue(Queue q) {
StringBuffer sb=new StringBuffer();
LinkedList values=q.values();
if(values.size() == 0) {
sb.append("empty");
}
else {
for(Iterator it=values.iterator(); it.hasNext();) {
Object o=it.next();
String s=null;
if(o instanceof Event) {
Event event=(Event)o;
int type=event.getType();
s=Event.type2String(type);
if(type == Event.VIEW_CHANGE)
s+=" " + event.getArg();
if(type == Event.MSG)
s+=" " + event.getArg();
if(type == Event.MSG) {
s+="[";
Message m=(Message)event.getArg();
Map headers=m.getHeaders();
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
Object headerKey=i.next();
Object value=headers.get(headerKey);
String headerToString=null;
if(value instanceof FD.FdHeader) {
headerToString=value.toString();
}
else
if(value instanceof PingHeader) {
headerToString=headerKey + "-";
if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) {
headerToString+="GMREQ";
}
else
if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) {
headerToString+="GMRSP";
}
else {
headerToString+="UNKNOWN";
}
}
else {
headerToString=headerKey + "-" + (value == null ? "null" : value.toString());
}
s+=headerToString;
if(i.hasNext()) {
s+=",";
}
}
s+="]";
}
}
else {
s=o.toString();
}
sb.append(s).append("\n");
}
}
return sb.toString();
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace() {
try {
throw new Exception("Dumping stack:");
}
catch(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("
}
public static String activeThreads() {
StringBuffer sb=new StringBuffer();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("
for(int i=0; i < threads.length; i++) {
sb.append("#" + i + ": " + threads[i] + '\n');
}
sb.append("
return sb.toString();
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, int length) {
byte[] retval[];
long total_size=length;
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < total_size) {
if(accumulated_size + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - accumulated_size);
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
return fragmentBuffer(buf, frag_size, buf.length);
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static java.util.List computeFragOffsets(int offset, int length, int frag_size) {
java.util.List retval=new ArrayList();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static java.util.List computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
// /**
// Peeks for view on the channel until n views have been received or timeout has elapsed.
// Used to determine the view in which we want to start work. Usually, we start as only
// member in our own view (1st view) and the next view (2nd view) will be the full view
// of all members, or a timeout if we're the first member. If a non-view (a message or
// block) is received, the method returns immediately.
// @param channel The channel used to peek for views. Has to be operational.
// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,
// if there are other members, we start working with them included in our view.
// @param timeout Number of milliseconds to wait until view is forced to return. A value
// of <= 0 means wait forever.
// */
// public static View peekViews(Channel channel, int number_of_views, long timeout) {
// View retval=null;
// Object obj=null;
// int num=0;
// long start_time=System.currentTimeMillis();
// if(timeout <= 0) {
// while(true) {
// try {
// obj=channel.peek(0);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(0);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// else {
// while(timeout > 0) {
// try {
// obj=channel.peek(timeout);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(timeout);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// timeout=timeout - (System.currentTimeMillis() - start_time);
// return retval;
public static String array2String(long[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i] + " ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i] + " ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i] + " ");
}
ret.append(']');
return ret.toString();
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector pickSubset(Vector members, double subset_percentage) {
Vector ret=new Vector(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector)members.clone();
for(int i=subset_size; i > 0 && tmp_mbrs.size() > 0; i
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
public static Object pickRandomElement(Vector list) {
if(list == null) return null;
int size=list.size();
int index=(int)((Math.random() * size * 10) % size);
return list.get(index);
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector determineLeftMembers(Vector old_mbrs, Vector new_mbrs) {
Vector retval=new Vector();
Object mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printMembers(Vector v) {
StringBuffer sb=new StringBuffer("(");
boolean first=true;
Object el;
if(v != null) {
for(int i=0; i < v.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
el=v.elementAt(i);
if(el instanceof Address)
sb.append(el);
else
sb.append(el);
}
}
sb.append(')');
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). 2 writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
// use thread context class loader
ClassLoader loader=Thread.currentThread().getContextClassLoader();
inst=loader.loadClass(classname).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception=" + ex);
return 0;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception+" + ex);
return 0;
}
}
public static long sizeOf(Streamable inst) {
byte[] data;
ByteArrayOutputStream output;
DataOutputStream out;
try {
output=new ByteArrayOutputStream();
out=new DataOutputStream(output);
inst.writeTo(out);
out.flush();
data=output.toByteArray();
return data.length;
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception+" + ex);
return 0;
}
}
/**
* Tries to load a class from the thread's context classloader first, then from an object's
* classloader (if not null).
* @param clname
* @param obj
* @return The loaded class, or null if class could not be loaded
*/
public static Class loadClass(String clname, Class clazz) {
Class cl=null;
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
}
catch(Throwable t) {
loader=null;
}
if(loader != null) {
try {
return loader.loadClass(clname);
}
catch(ClassNotFoundException e) {
loader=null;
}
}
loader=clazz != null? clazz.getClassLoader() : null;
if(loader != null) {
try {
return loader.loadClass(clname);
}
catch(ClassNotFoundException e) {
}
}
return cl;
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
if(log.isErrorEnabled()) log.error("addresses have to be of type IpAddress to be compared");
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static void removeFile(String fname) {
if(fname == null) return;
try {
new File(fname).delete();
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception=" + ex);
}
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
E.g. 2000,4000,8000
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector v=new Vector();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.size() == 0) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=((Long)v.elementAt(i)).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static java.util.List parseCommaDelimitedStrings(String l) {
java.util.List tmp=new ArrayList();
StringTokenizer tok=new StringTokenizer(l, ",");
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t);
}
return tmp;
}
public static String shortName(String hostname) {
int index;
StringBuffer sb=new StringBuffer();
if(hostname == null) return null;
index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
sb.append(hostname.substring(0, index));
else
sb.append(hostname);
return sb.toString();
}
public static String shortName(InetAddress hostname) {
if(hostname == null) return null;
StringBuffer sb=new StringBuffer();
if(resolve_dns)
sb.append(hostname.getHostName());
else
sb.append(hostname.getHostAddress());
return sb.toString();
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
if(log.isErrorEnabled()) log.error("exception is " + io_ex);
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
if(log.isErrorEnabled()) log.error("exception is " + io_ex);
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
continue;
}
catch(Exception ex) {
throw ex;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
continue;
}
catch(Exception ex) {
throw ex;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static boolean checkForLinux() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("linux") ? true : false;
}
public static boolean checkForSolaris() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("sun") ? true : false;
}
public static boolean checkForWindows() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("win") ? true : false;
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static int getJavaVersion() {
String version=System.getProperty("java.version");
int retval=0;
if(version != null) {
if(version.startsWith("1.2"))
return 12;
if(version.startsWith("1.3"))
return 13;
if(version.startsWith("1.4"))
return 14;
if(version.startsWith("1.5"))
return 15;
if(version.startsWith("5"))
return 15;
if(version.startsWith("1.6"))
return 16;
if(version.startsWith("6"))
return 16;
}
return retval;
}
public static String memStats(boolean gc) {
StringBuffer sb=new StringBuffer();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
/*
public static void main(String[] args) {
DatagramSocket sock;
InetAddress addr=null;
int port=0;
for(int i=0; i < args.length; i++) {
if(args[i].equals("-help")) {
System.out.println("Util [-help] [-addr] [-port]");
return;
}
if(args[i].equals("-addr")) {
try {
addr=InetAddress.getByName(args[++i]);
continue;
}
catch(Exception ex) {
log.error(ex);
return;
}
}
if(args[i].equals("-port")) {
port=Integer.parseInt(args[++i]);
continue;
}
System.out.println("Util [-help] [-addr] [-port]");
return;
}
try {
sock=createDatagramSocket(addr, port);
System.out.println("sock: local address is " + sock.getLocalAddress() + ":" + sock.getLocalPort() +
", remote address is " + sock.getInetAddress() + ":" + sock.getPort());
System.in.read();
}
catch(Exception ex) {
log.error(ex);
}
}
*/
public static void main(String args[]) throws Exception {
ClassConfigurator.getInstance(true);
Message msg=new Message(null, new IpAddress("127.0.0.1", 4444), "Bela");
long size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
msg.putHeader("belaban", new NakAckHeader((byte)1, 23, 34));
size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
msg.putHeader("bla", new UdpHeader("groupname"));
size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
IpAddress a1=new IpAddress(1234), a2=new IpAddress("127.0.0.1", 3333);
a1.setAdditionalData("Bela".getBytes());
size=Util.sizeOf(a1);
System.out.println("size=" + a1.size() + ", streamable size of a1=" + size);
size=Util.sizeOf(a2);
System.out.println("size=" + a2.size() + ", streamable size of a2=" + size);
// System.out.println("Check for Linux: " + checkForLinux());
// System.out.println("Check for Solaris: " + checkForSolaris());
// System.out.println("Check for Windows: " + checkForWindows());
}
}
|
package com.coillighting.udder.scene;
import com.coillighting.udder.effect.woven.WovenEffect;
import com.coillighting.udder.geometry.Interpolator;
import com.coillighting.udder.mix.StatefulAnimator;
import com.coillighting.udder.mix.Layer;
import com.coillighting.udder.mix.Mixer;
import com.coillighting.udder.mix.TimePoint;
import java.awt.geom.Point2D;
import static com.coillighting.udder.geometry.Interpolator.Interpolation;
/** Implements a 'shuffle' mode specifically tailored to the Boulder Dairy
* Archway's scene. Cross-fades layers in groups that look good together,
* periodically stopping to fade everything out and fade in the Woven effect,
* with synchronized startup of the Woven effect from its opening queue
* (a blackout of several seconds).
*
* When not displaying the Woven scene, shows 1 incoming look + 1 primary
* look + 1 outgoing look. Fade-in of the incoming look and fade-out of
* the outgoing look have their own easing curves, randomly selected from
* the available modes.
*/
public class DairyShuffler implements StatefulAnimator {
protected Mixer mixer;
protected Interpolator interpolator;
int wovenLayerIndex;
int shuffleLayerStartIndex; // inclusive
int shuffleLayerEndIndex; // inclusive
long cueStartTimeMillis;
long textureCueDurationMillis;
long wovenCueDurationMillis;
long cueDurationMillis;
private DairyShufflerFadeTiming[] fadeTimings;
boolean enabled;
boolean wovenMode;
protected Interpolation interpolationModeIncoming;
protected Interpolation interpolationModeOutgoing;
protected int incomingLayerIndex;
protected double incomingLevel;
protected double primaryLevel;
protected double outgoingLevel;
protected double wovenLevel;
// temp variables we don't want to keep reallocating in every event
private Point2D.Double off;
private Point2D.Double current;
private Point2D.Double on;
public DairyShuffler(Mixer mixer, int wovenLayerIndex, int shuffleLayerStartIndex, int shuffleLayerEndIndex,
DairyShufflerFadeTiming[] timings)
{
if(mixer == null) {
throw new NullPointerException("DairyShuffler requires a Mixer before it can shuffle.");
} else {
int ct = mixer.size();
if(wovenLayerIndex < 0 || wovenLayerIndex >= ct) {
throw new IllegalArgumentException(
"This mixer contains no layer at wovenLayerIndex="
+ wovenLayerIndex);
} else if(shuffleLayerStartIndex < 0 || shuffleLayerStartIndex >= ct) {
throw new IllegalArgumentException(
"This mixer contains no layer at shuffleLayerStartIndex="
+ shuffleLayerStartIndex);
} else if(shuffleLayerEndIndex < 0 || shuffleLayerEndIndex >= ct) {
throw new IllegalArgumentException(
"This mixer contains no layer at shuffleLayerEndIndex="
+ shuffleLayerStartIndex);
} else if(shuffleLayerEndIndex <= shuffleLayerStartIndex) {
throw new IllegalArgumentException(
"A shuffler's shuffleLayerStartIndex may not exceed its shuffleLayerEndIndex.");
} else if(shuffleLayerStartIndex <= wovenLayerIndex
&& wovenLayerIndex <= shuffleLayerEndIndex) {
throw new IllegalArgumentException(
"A shuffler's woven layer may not also be a shuffled layer.");
} else if(timings == null) {
throw new IllegalArgumentException("A list of fade times is required.");
} else if(timings.length != ct) {
throw new IllegalArgumentException("Exactly " + ct +
" fade times slots are required, because that's how many layers are in your mixer, but you supplied "
+ timings.length + " of them.");
} else {
for(int i=0; i<timings.length; i++) {
boolean inRange = i >= shuffleLayerStartIndex && i <= shuffleLayerEndIndex;
if(timings[i] == null && inRange) {
throw new IllegalArgumentException("Every shuffled layer must have a DairyShufflerFadeTiming "
+ "object which is not null, but timings[" + i + "] is null.");
} else if(timings[i] != null && ! inRange) {
throw new IllegalArgumentException("A non-shuffled layer must never have a DairyShufflerFadeTiming "
+ "object, but timings[" + i + "] is not null.");
}
}
this.fadeTimings = timings;
}
}
// These interpolator curve settings favor a strong three-way mix
// over what looks almost like a one-way mix.
// 0.15: fade in quick, linger for a while and fade out quick
// 2.5: relatively brighter, more gradual fade in and out in POWER mode
this.interpolator = new Interpolator(0.15, 2.5);
this.mixer = mixer;
this.wovenLayerIndex = wovenLayerIndex;
this.shuffleLayerStartIndex = shuffleLayerStartIndex;
this.shuffleLayerEndIndex = shuffleLayerEndIndex;
textureCueDurationMillis = 60000;
this.reset();
off = new Point2D.Double(0.0, 0.0);
current = new Point2D.Double(0.0, 0.0);
on = new Point2D.Double(1.0, 1.0);
enabled = true;
this.mixer.subscribeAnimator(this);
}
public void reset() throws ClassCastException {
wovenMode = true;
Layer wovenLayer = (Layer) mixer.getLayer(wovenLayerIndex);
WovenEffect wovenEffect = (WovenEffect) wovenLayer.getEffect();
wovenCueDurationMillis = wovenEffect.getDurationMillis();
wovenEffect.reset();
cueDurationMillis = wovenCueDurationMillis;
incomingLayerIndex = -1; // < 0: nothing incoming
incomingLevel = 0.0;
primaryLevel = 0.0;
outgoingLevel=0.0;
wovenLevel = 0.0;
interpolationModeIncoming = Interpolation.SINUSOIDAL;
interpolationModeOutgoing = Interpolation.SINUSOIDAL;
cueStartTimeMillis = -1; // < 0: not started
}
// switch off woven vs. other layers only at the transition point,
// so human operators can play around with transient looks,
// like woven + textures
public void animate(TimePoint timePoint) {
if(enabled) {
// Step forward or rewind and start over if needed.
long now = timePoint.sceneTimeMillis();
if (cueStartTimeMillis < 0) {
cueStartTimeMillis = now;
}
long end = cueStartTimeMillis + cueDurationMillis;
if (end < now) {
// Step forward to the next track in the playlist.
if (wovenMode) {
// Switch from woven to texture mode
cueDurationMillis = textureCueDurationMillis;
wovenMode = false;
wovenLevel = 0.0f;
mixer.getLayer(wovenLayerIndex).setLevel(wovenLevel);
incomingLayerIndex = shuffleLayerStartIndex;
interpolationModeIncoming = Interpolation.ROOT; // fade in quick, don't leave it black
} else if (incomingLayerIndex >= shuffleLayerEndIndex + 2) {
// Switch to woven mode
for (int i = shuffleLayerStartIndex; i <= shuffleLayerEndIndex; i++) {
this.setTextureLevelConditionally(0.0f, i);
}
this.reset();
// level will be set below on transition into Woven effect
} else {
// Start fading in the next texture.
// Choose a new easing curve each time.
// We used to favor a brighter, three-way mix, but since
// we added many open patterns, we've increased the probability
// of a thinner, mostly solo or duet mix, by increasing the
// chance of a POWER mix to 50/50.
interpolationModeIncoming = interpolator.randomMode(20, 75, 95);
interpolationModeOutgoing = interpolator.randomMode(20, 75, 95);
cueDurationMillis = textureCueDurationMillis;
if(incomingLayerIndex > shuffleLayerEndIndex) {
// At this point there is only one outgoing layer, so
// make it quick to avoid spooking the client.
// (The gallery staff gets antsy that the rig has failed
// and calls BV whenever they observe a long-tail
// fade to black, so we cut the final cue short in order
// to loop promptly back to the Woven effect.)
cueDurationMillis *= 0.20;
}
// finish fading out the outgoing track if needed:
this.setTextureLevelConditionally(0.0f, incomingLayerIndex - 2);
outgoingLevel = primaryLevel;
primaryLevel = incomingLevel;
incomingLevel = 0.0f;
incomingLayerIndex++;
}
cueStartTimeMillis = now;
}
if (wovenMode) {
// Don't crossfade into the Woven cue. It builds from black
// without any help from this Shuffler.
if (cueStartTimeMillis == now) {
wovenLevel = 1.0;
mixer.getLayer(wovenLayerIndex).setLevel(wovenLevel);
}
} else {
// texture mode only, not in woven mode
int li = incomingLayerIndex;
DairyShufflerFadeTiming inTiming, outTiming;
// N.B. Fade in and out are not applied to Woven mode thanks to
// the range check in setTextureLevelConditionally.
// TODO the following code is a recent edition, probably not too robust. TEST.
if(li - 2 < shuffleLayerStartIndex) {
// won't matter, but must be not null
outTiming = fadeTimings[shuffleLayerStartIndex];
} else {
outTiming = fadeTimings[li - 2];
}
if(li > shuffleLayerEndIndex) {
// likewise won't matter, but must be not null
inTiming = fadeTimings[shuffleLayerEndIndex];
} else {
inTiming = fadeTimings[li];
}
// Crossfade out of the outgoing cue and into the incoming cue.
// Do not change the primary cue, which is like the current track.
double cuePct = (double) (now - cueStartTimeMillis) / cueDurationMillis;
// To fade out faster, make this number smaller.
// Range: 0 - 1.0 for 0% to 100% of cue time spent fading.
double cueFadeOutPct = outTiming.out;
double outPct;
// To fade in faster, make this number smaller.
double cueFadeInPct = inTiming.in;
double inPct;
if(cuePct >= cueFadeOutPct || cueFadeOutPct == 0.0) {
// Done fading out already.
outPct = 0.0;
} else {
// Keep fading out, aiming to be done cueFadeOutPct of the
// way along the cue's timeline.
outPct = cuePct / cueFadeOutPct;
}
double inThreshold = 1.0 - cueFadeInPct;
if(cuePct <= inThreshold || cueFadeInPct == 0.0) {
// Don't start fading in yet.
inPct = 0.0;
} else {
// Continue fading in, beginning cueFadeInPct of the way
// along the cue's timeline.
inPct = (cuePct - inThreshold) / cueFadeInPct;
}
// incoming look (if applicable)
interpolator.interpolate2D(interpolationModeIncoming, inPct, off, current, on);
// FUTURE: implement a 1D Interpolator API, but for now just
// piggyback on the existing 2D API and ignore y.
// FIXME: convert all layer levels to doubles.
incomingLevel = current.x;
this.setTextureLevelConditionally(incomingLevel, li);
// primary look (if applicable)
li -= 1;
primaryLevel = 1.0;
this.setTextureLevelConditionally(primaryLevel, li);
// outgoing look (if applicable)
li -= 1;
interpolator.interpolate2D(interpolationModeOutgoing, outPct, on, current, off);
outgoingLevel = current.x;
this.setTextureLevelConditionally(outgoingLevel, li);
}
}
}
/** Only try to fade in or out a texture layer. Allow Woven to handle its
* own dynamics, and ignore out of range layers. Simplifies the impl of
* animate somewhat.
*/
private void setTextureLevelConditionally(double level, int layerIndex) {
if(layerIndex >= shuffleLayerStartIndex
&& layerIndex <= shuffleLayerEndIndex) {
mixer.getLayer(layerIndex).setLevel(level);
}
}
public Class getStateClass() {
return DairyShufflerState.class;
}
public Object getState() {
return new DairyShufflerState(enabled, textureCueDurationMillis);
}
public void setState(Object state) throws ClassCastException {
DairyShufflerState command = (DairyShufflerState) state;
this.enabled = command.getEnabled();
long millis = command.getCueDurationMillis();
if(millis > 0) {
this.textureCueDurationMillis = millis;
}
}
}
|
package org.jgroups.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.*;
import org.jgroups.auth.AuthToken;
import org.jgroups.blocks.Connection;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.FD;
import org.jgroups.protocols.PingHeader;
import org.jgroups.protocols.PingRsp;
import org.jgroups.stack.IpAddress;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.security.MessageDigest;
import java.text.NumberFormat;
import java.util.*;
/**
* Collection of various utility routines that can not be assigned to other classes.
* @author Bela Ban
* @version $Id: Util.java,v 1.180 2008/11/06 13:41:58 belaban Exp $
*/
public class Util {
private static NumberFormat f;
private static Map<Class,Byte> PRIMITIVE_TYPES=new HashMap<Class,Byte>(10);
private static final byte TYPE_NULL = 0;
private static final byte TYPE_STREAMABLE = 1;
private static final byte TYPE_SERIALIZABLE = 2;
private static final byte TYPE_BOOLEAN = 10;
private static final byte TYPE_BYTE = 11;
private static final byte TYPE_CHAR = 12;
private static final byte TYPE_DOUBLE = 13;
private static final byte TYPE_FLOAT = 14;
private static final byte TYPE_INT = 15;
private static final byte TYPE_LONG = 16;
private static final byte TYPE_SHORT = 17;
private static final byte TYPE_STRING = 18;
private static final byte TYPE_BYTEARRAY = 19;
// constants
public static final int MAX_PORT=65535; // highest port allocatable
static boolean resolve_dns=false;
static boolean JGROUPS_COMPAT=false;
/**
* Global thread group to which all (most!) JGroups threads belong
*/
private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") {
public void uncaughtException(Thread t, Throwable e) {
LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e);
}
};
public static ThreadGroup getGlobalThreadGroup() {
return GLOBAL_GROUP;
}
static {
try {
resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();
}
catch (SecurityException ex){
resolve_dns=false;
}
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
try {
String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false");
JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue();
}
catch (SecurityException ex){
}
PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN));
PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE));
PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR));
PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE));
PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT));
PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT));
PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG));
PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT));
PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING));
PRIMITIVE_TYPES.put(byte[].class, new Byte(TYPE_BYTEARRAY));
}
public static void assertTrue(boolean condition) {
assert condition;
}
public static void assertTrue(String message, boolean condition) {
if(message != null)
assert condition : message;
else
assert condition;
}
public static void assertFalse(boolean condition) {
assertFalse(null, condition);
}
public static void assertFalse(String message, boolean condition) {
if(message != null)
assert !condition : message;
else
assert !condition;
}
public static void assertEquals(String message, Object val1, Object val2) {
if(message != null) {
assert val1.equals(val2) : message;
}
else {
assert val1.equals(val2);
}
}
public static void assertEquals(Object val1, Object val2) {
assertEquals(null, val1, val2);
}
public static void assertNotNull(String message, Object val) {
if(message != null)
assert val != null : message;
else
assert val != null;
}
public static void assertNotNull(Object val) {
assertNotNull(null, val);
}
public static void assertNull(String message, Object val) {
if(message != null)
assert val == null : message;
else
assert val == null;
}
public static void assertNull(Object val) {
assertNotNull(null, val);
}
/**
* Verifies that val is <= max memory
* @param buf_name
* @param val
*/
public static void checkBufferSize(String buf_name, long val) {
// sanity check that max_credits doesn't exceed memory allocated to VM by -Xmx
long max_mem=Runtime.getRuntime().maxMemory();
if(val > max_mem) {
throw new IllegalArgumentException(buf_name + "(" + Util.printBytes(val) + ") exceeds max memory allocated to VM (" +
Util.printBytes(max_mem) + ")");
}
}
public static void close(InputStream inp) {
if(inp != null)
try {inp.close();} catch(IOException e) {}
}
public static void close(OutputStream out) {
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
public static void close(Socket s) {
if(s != null) {
try {s.close();} catch(Exception ex) {}
}
}
public static void close(ServerSocket s) {
if(s != null) {
try {s.close();} catch(Exception ex) {}
}
}
public static void close(DatagramSocket my_sock) {
if(my_sock != null) {
try {my_sock.close();} catch(Throwable t) {}
}
}
public static void close(Channel ch) {
if(ch != null) {
try {ch.close();} catch(Throwable t) {}
}
}
public static void close(Channel ... channels) {
if(channels != null) {
for(Channel ch: channels)
Util.close(ch);
}
}
public static void close(Connection conn) {
if(conn != null) {
try {conn.close();} catch(Throwable t) {}
}
}
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer);
return objectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer, offset, length);
Object retval=null;
InputStream in=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
byte b=(byte)in_stream.read();
try {
switch(b) {
case TYPE_NULL:
return null;
case TYPE_STREAMABLE:
in=new DataInputStream(in_stream);
retval=readGenericStreamable((DataInputStream)in);
break;
case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable
in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=((ContextObjectInputStream)in).readObject();
break;
case TYPE_BOOLEAN:
in=new DataInputStream(in_stream);
retval=Boolean.valueOf(((DataInputStream)in).readBoolean());
break;
case TYPE_BYTE:
in=new DataInputStream(in_stream);
retval=new Byte(((DataInputStream)in).readByte());
break;
case TYPE_CHAR:
in=new DataInputStream(in_stream);
retval=new Character(((DataInputStream)in).readChar());
break;
case TYPE_DOUBLE:
in=new DataInputStream(in_stream);
retval=new Double(((DataInputStream)in).readDouble());
break;
case TYPE_FLOAT:
in=new DataInputStream(in_stream);
retval=new Float(((DataInputStream)in).readFloat());
break;
case TYPE_INT:
in=new DataInputStream(in_stream);
retval=new Integer(((DataInputStream)in).readInt());
break;
case TYPE_LONG:
in=new DataInputStream(in_stream);
retval=new Long(((DataInputStream)in).readLong());
break;
case TYPE_SHORT:
in=new DataInputStream(in_stream);
retval=new Short(((DataInputStream)in).readShort());
break;
case TYPE_STRING:
in=new DataInputStream(in_stream);
if(((DataInputStream)in).readBoolean()) { // large string
ObjectInputStream ois=new ObjectInputStream(in);
try {
return ois.readObject();
}
finally {
ois.close();
}
}
else {
retval=((DataInputStream)in).readUTF();
}
break;
case TYPE_BYTEARRAY:
in=new DataInputStream(in_stream);
int len=((DataInputStream)in).readInt();
byte[] tmp=new byte[len];
in.read(tmp, 0, tmp.length);
retval=tmp;
break;
default:
throw new IllegalArgumentException("type " + b + " is invalid");
}
return retval;
}
finally {
Util.close(in);
}
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
if(JGROUPS_COMPAT)
return oldObjectToByteBuffer(obj);
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
if(obj == null) {
out_stream.write(TYPE_NULL);
out_stream.flush();
return out_stream.toByteArray();
}
OutputStream out=null;
Byte type;
try {
if(obj instanceof Streamable) { // use Streamable if we can
out_stream.write(TYPE_STREAMABLE);
out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, (DataOutputStream)out);
}
else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) {
out_stream.write(type.byteValue());
out=new DataOutputStream(out_stream);
switch(type.byteValue()) {
case TYPE_BOOLEAN:
((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue());
break;
case TYPE_BYTE:
((DataOutputStream)out).writeByte(((Byte)obj).byteValue());
break;
case TYPE_CHAR:
((DataOutputStream)out).writeChar(((Character)obj).charValue());
break;
case TYPE_DOUBLE:
((DataOutputStream)out).writeDouble(((Double)obj).doubleValue());
break;
case TYPE_FLOAT:
((DataOutputStream)out).writeFloat(((Float)obj).floatValue());
break;
case TYPE_INT:
((DataOutputStream)out).writeInt(((Integer)obj).intValue());
break;
case TYPE_LONG:
((DataOutputStream)out).writeLong(((Long)obj).longValue());
break;
case TYPE_SHORT:
((DataOutputStream)out).writeShort(((Short)obj).shortValue());
break;
case TYPE_STRING:
String str=(String)obj;
if(str.length() > Short.MAX_VALUE) {
((DataOutputStream)out).writeBoolean(true);
ObjectOutputStream oos=new ObjectOutputStream(out);
try {
oos.writeObject(str);
}
finally {
oos.close();
}
}
else {
((DataOutputStream)out).writeBoolean(false);
((DataOutputStream)out).writeUTF(str);
}
break;
case TYPE_BYTEARRAY:
byte[] buf=(byte[])obj;
((DataOutputStream)out).writeInt(buf.length);
out.write(buf, 0, buf.length);
break;
default:
throw new IllegalArgumentException("type " + type + " is invalid");
}
}
else { // will throw an exception if object is not serializable
out_stream.write(TYPE_SERIALIZABLE);
out=new ObjectOutputStream(out_stream);
((ObjectOutputStream)out).writeObject(obj);
}
}
finally {
Util.close(out);
}
result=out_stream.toByteArray();
return result;
}
public static void objectToStream(Object obj, DataOutputStream out) throws Exception {
if(obj == null) {
out.write(TYPE_NULL);
return;
}
Byte type;
try {
if(obj instanceof Streamable) { // use Streamable if we can
out.write(TYPE_STREAMABLE);
writeGenericStreamable((Streamable)obj, out);
}
else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) {
out.write(type.byteValue());
switch(type.byteValue()) {
case TYPE_BOOLEAN:
out.writeBoolean(((Boolean)obj).booleanValue());
break;
case TYPE_BYTE:
out.writeByte(((Byte)obj).byteValue());
break;
case TYPE_CHAR:
out.writeChar(((Character)obj).charValue());
break;
case TYPE_DOUBLE:
out.writeDouble(((Double)obj).doubleValue());
break;
case TYPE_FLOAT:
out.writeFloat(((Float)obj).floatValue());
break;
case TYPE_INT:
out.writeInt(((Integer)obj).intValue());
break;
case TYPE_LONG:
out.writeLong(((Long)obj).longValue());
break;
case TYPE_SHORT:
out.writeShort(((Short)obj).shortValue());
break;
case TYPE_STRING:
String str=(String)obj;
if(str.length() > Short.MAX_VALUE) {
out.writeBoolean(true);
ObjectOutputStream oos=new ObjectOutputStream(out);
try {
oos.writeObject(str);
}
finally {
oos.close();
}
}
else {
out.writeBoolean(false);
out.writeUTF(str);
}
break;
case TYPE_BYTEARRAY:
byte[] buf=(byte[])obj;
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
break;
default:
throw new IllegalArgumentException("type " + type + " is invalid");
}
}
else { // will throw an exception if object is not serializable
out.write(TYPE_SERIALIZABLE);
ObjectOutputStream tmp=new ObjectOutputStream(out);
tmp.writeObject(obj);
}
}
finally {
Util.close(out);
}
}
public static Object objectFromStream(DataInputStream in) throws Exception {
if(in == null) return null;
Object retval=null;
byte b=(byte)in.read();
switch(b) {
case TYPE_NULL:
return null;
case TYPE_STREAMABLE:
retval=readGenericStreamable(in);
break;
case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable
ContextObjectInputStream tmp=new ContextObjectInputStream(in);
retval=tmp.readObject();
break;
case TYPE_BOOLEAN:
retval=Boolean.valueOf(in.readBoolean());
break;
case TYPE_BYTE:
retval=new Byte(in.readByte());
break;
case TYPE_CHAR:
retval=new Character(in.readChar());
break;
case TYPE_DOUBLE:
retval=new Double(in.readDouble());
break;
case TYPE_FLOAT:
retval=new Float(in.readFloat());
break;
case TYPE_INT:
retval=new Integer(in.readInt());
break;
case TYPE_LONG:
retval=new Long(in.readLong());
break;
case TYPE_SHORT:
retval=new Short(in.readShort());
break;
case TYPE_STRING:
if(in.readBoolean()) { // large string
ObjectInputStream ois=new ObjectInputStream(in);
try {
retval=ois.readObject();
}
finally {
ois.close();
}
}
else {
retval=in.readUTF();
}
break;
case TYPE_BYTEARRAY:
int len=in.readInt();
byte[] tmpbuf=new byte[len];
in.read(tmpbuf, 0, tmpbuf.length);
retval=tmpbuf;
break;
default:
throw new IllegalArgumentException("type " + b + " is invalid");
}
return retval;
}
/** For backward compatibility in JBoss 4.0.2 */
public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
return oldObjectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Object retval=null;
try { // to read the object as an Externalizable
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=in.readObject();
in.close();
}
catch(StreamCorruptedException sce) {
try { // is it Streamable?
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream);
retval=readGenericStreamable(in);
in.close();
}
catch(Exception ee) {
IOException tmp=new IOException("unmarshalling failed");
tmp.initCause(ee);
throw tmp;
}
}
if(retval == null)
return null;
return retval;
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] oldObjectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
if(obj instanceof Streamable) { // use Streamable if we can
DataOutputStream out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, out);
out.close();
}
else {
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
out.close();
}
result=out_stream.toByteArray();
return result;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static byte[] streamableToByteBuffer(Streamable obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(out_stream);
obj.writeTo(out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(out_stream);
Util.writeAddresses(c, out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static int size(Address addr) {
int retval=Global.BYTE_SIZE; // presence byte
if(addr != null)
retval+=addr.size() + Global.BYTE_SIZE; // plus type of address
return retval;
}
public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{
Util.writeString(token.getName(), out);
token.writeTo(out);
}
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
try{
String type = Util.readString(in);
Object obj = Class.forName(type).newInstance();
AuthToken token = (AuthToken) obj;
token.readFrom(in);
return token;
}
catch(ClassNotFoundException cnfe){
return null;
}
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
if(addr == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if(addr instanceof IpAddress) {
// regular case, we don't need to include class information about the type of Address, e.g. JmsAddress
out.writeBoolean(true);
addr.writeTo(out);
}
else {
out.writeBoolean(false);
writeOtherAddress(addr, out);
}
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Address addr=null;
if(in.readBoolean() == false)
return null;
if(in.readBoolean()) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
int b=in.read();
short magic_number;
String classname;
Class cl=null;
Address addr;
if(b == 1) {
magic_number=in.readShort();
cl=ClassConfigurator.get(magic_number);
}
else {
classname=in.readUTF();
cl=ClassConfigurator.get(classname);
}
addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
short magic_number=ClassConfigurator.getMagicNumber(addr.getClass());
// write the class info
if(magic_number == -1) {
out.write(0);
out.writeUTF(addr.getClass().getName());
}
else {
out.write(1);
out.writeShort(magic_number);
}
// write the data itself
addr.writeTo(out);
}
/**
* Writes a Vector of Addresses. Can contain 65K addresses at most
* @param v A Collection<Address>
* @param out
* @throws IOException
*/
public static void writeAddresses(Collection<Address> v, DataOutputStream out) throws IOException {
if(v == null) {
out.writeShort(-1);
return;
}
out.writeShort(v.size());
for(Address addr: v) {
Util.writeAddress(addr, out);
}
}
public static Collection<Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException {
short length=in.readShort();
if(length < 0) return null;
Collection<Address> retval=(Collection<Address>)cl.newInstance();
Address addr;
for(int i=0; i < length; i++) {
addr=Util.readAddress(in);
retval.add(addr);
}
return retval;
}
/**
* Returns the marshalled size of a Collection of Addresses.
* <em>Assumes elements are of the same type !</em>
* @param addrs Collection<Address>
* @return long size
*/
public static long size(Collection<Address> addrs) {
int retval=Global.SHORT_SIZE; // number of elements
if(addrs != null && !addrs.isEmpty()) {
Address addr=addrs.iterator().next();
retval+=size(addr) * addrs.size();
}
return retval;
}
public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {
if(obj == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
obj.writeTo(out);
}
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Streamable retval=null;
if(in.readBoolean() == false)
return null;
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {
short magic_number;
String classname;
if(obj == null) {
out.write(0);
return;
}
out.write(1);
magic_number=ClassConfigurator.getMagicNumber(obj.getClass());
// write the magic number or the class name
if(magic_number == -1) {
out.writeBoolean(false);
classname=obj.getClass().getName();
out.writeUTF(classname);
}
else {
out.writeBoolean(true);
out.writeShort(magic_number);
}
// write the contents
obj.writeTo(out);
}
public static Streamable readGenericStreamable(DataInputStream in) throws IOException {
Streamable retval=null;
int b=in.read();
if(b == 0)
return null;
boolean use_magic_number=in.readBoolean();
String classname;
Class clazz;
try {
if(use_magic_number) {
short magic_number=in.readShort();
clazz=ClassConfigurator.get(magic_number);
if (clazz==null) {
throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found.");
}
}
else {
classname=in.readUTF();
clazz=ClassConfigurator.get(classname);
if (clazz==null) {
throw new ClassNotFoundException(classname);
}
}
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
catch(Exception ex) {
throw new IOException("failed reading object: " + ex.toString());
}
}
public static void writeObject(Object obj, DataOutputStream out) throws Exception {
if(obj == null || !(obj instanceof Streamable)) {
byte[] buf=objectToByteBuffer(obj);
out.writeShort(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.writeShort(-1);
writeGenericStreamable((Streamable)obj, out);
}
}
public static Object readObject(DataInputStream in) throws Exception {
short len=in.readShort();
Object retval=null;
if(len == -1) {
retval=readGenericStreamable(in);
}
else {
byte[] buf=new byte[len];
in.readFully(buf, 0, len);
retval=objectFromByteBuffer(buf);
}
return retval;
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
public static void writeAsciiString(String str, DataOutputStream out) throws IOException {
if(str == null) {
out.write(-1);
return;
}
int length=str.length();
if(length > Byte.MAX_VALUE)
throw new IllegalArgumentException("string is > " + Byte.MAX_VALUE);
out.write(length);
out.writeBytes(str);
}
public static String readAsciiString(DataInputStream in) throws IOException {
byte length=(byte)in.read();
if(length == -1)
return null;
byte[] tmp=new byte[length];
in.read(tmp, 0, tmp.length);
return new String(tmp, 0, tmp.length);
}
public static String parseString(DataInputStream in) {
return parseString(in, false);
}
public static String parseString(DataInputStream in, boolean break_on_newline) {
StringBuilder sb=new StringBuilder();
int ch;
// read white space
while(true) {
try {
ch=in.read();
if(ch == -1) {
return null; // eof
}
if(Character.isWhitespace(ch)) {
if(break_on_newline && ch == '\n')
return null;
}
else {
sb.append((char)ch);
break;
}
}
catch(IOException e) {
break;
}
}
while(true) {
try {
ch=in.read();
if(ch == -1)
break;
if(Character.isWhitespace(ch))
break;
else {
sb.append((char)ch);
}
}
catch(IOException e) {
break;
}
}
return sb.toString();
}
public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {
if(buf != null) {
out.write(1);
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.write(0);
}
}
public static byte[] readByteBuffer(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1) {
b=in.readInt();
byte[] buf=new byte[b];
in.read(buf, 0, buf.length);
return buf;
}
return null;
}
public static Buffer messageToByteBuffer(Message msg) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
out.writeBoolean(msg != null);
if(msg != null)
msg.writeTo(out);
out.flush();
Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception {
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
if(!in.readBoolean())
return null;
Message msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
return msg;
}
/**
* Marshalls a list of messages.
* @param xmit_list LinkedList<Message>
* @return Buffer
* @throws IOException
*/
public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
Buffer retval=null;
out.writeInt(xmit_list.size());
for(Message msg: xmit_list) {
msg.writeTo(out);
}
out.flush();
retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {
List<Message> retval=null;
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
int size=in.readInt();
if(size == 0)
return null;
Message msg;
retval=new LinkedList<Message>();
for(int i=0; i < size; i++) {
msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
retval.add(msg);
}
return retval;
}
public static boolean match(Object obj1, Object obj2) {
if(obj1 == null && obj2 == null)
return true;
if(obj1 != null)
return obj1.equals(obj2);
else
return obj2.equals(obj1);
}
public static boolean match(long[] a1, long[] a2) {
if(a1 == null && a2 == null)
return true;
if(a1 == null || a2 == null)
return false;
if(a1 == a2) // identity
return true;
// at this point, a1 != null and a2 != null
if(a1.length != a2.length)
return false;
for(int i=0; i < a1.length; i++) {
if(a1[i] != a2[i])
return false;
}
return true;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void sleep(long timeout, int nanos) {
try {
Thread.sleep(timeout,nanos);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
public static int keyPress(String msg) {
System.out.println(msg);
try {
return System.in.read();
}
catch(IOException e) {
return 0;
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * range) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
return r < cutoff;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
public static String dumpThreads() {
StringBuilder sb=new StringBuilder();
ThreadMXBean bean=ManagementFactory.getThreadMXBean();
long[] ids=bean.getAllThreadIds();
ThreadInfo[] threads=bean.getThreadInfo(ids, 20);
for(int i=0; i < threads.length; i++) {
ThreadInfo info=threads[i];
if(info == null)
continue;
sb.append(info.getThreadName()).append(":\n");
StackTraceElement[] stack_trace=info.getStackTrace();
for(int j=0; j < stack_trace.length; j++) {
StackTraceElement el=stack_trace[j];
sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName());
sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")");
sb.append("\n");
}
sb.append("\n\n");
}
return sb.toString();
}
public static boolean interruptAndWaitToDie(Thread t) {
return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME);
}
public static boolean interruptAndWaitToDie(Thread t, long timeout) {
if(t == null)
throw new IllegalArgumentException("Thread can not be null");
t.interrupt(); // interrupts the sleep()
try {
t.join(timeout);
}
catch(InterruptedException e){
Thread.currentThread().interrupt(); // set interrupt flag again
}
return t.isAlive();
}
/**
* Debugging method used to dump the content of a protocol queue in a
* condensed form. Useful to follow the evolution of the queue's content in
* time.
*/
public static String dumpQueue(Queue q) {
StringBuilder sb=new StringBuilder();
LinkedList values=q.values();
if(values.isEmpty()) {
sb.append("empty");
}
else {
for(Iterator it=values.iterator(); it.hasNext();) {
Object o=it.next();
String s=null;
if(o instanceof Event) {
Event event=(Event)o;
int type=event.getType();
s=Event.type2String(type);
if(type == Event.VIEW_CHANGE)
s+=" " + event.getArg();
if(type == Event.MSG)
s+=" " + event.getArg();
if(type == Event.MSG) {
s+="[";
Message m=(Message)event.getArg();
Map<String,Header> headers=new HashMap<String,Header>(m.getHeaders());
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
Object headerKey=i.next();
Object value=headers.get(headerKey);
String headerToString=null;
if(value instanceof FD.FdHeader) {
headerToString=value.toString();
}
else
if(value instanceof PingHeader) {
headerToString=headerKey + "-";
if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) {
headerToString+="GMREQ";
}
else
if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) {
headerToString+="GMRSP";
}
else {
headerToString+="UNKNOWN";
}
}
else {
headerToString=headerKey + "-" + (value == null ? "null" : value.toString());
}
s+=headerToString;
if(i.hasNext()) {
s+=",";
}
}
s+="]";
}
}
else {
s=o.toString();
}
sb.append(s).append("\n");
}
}
return sb.toString();
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static String mapToString(Map<? extends Object,? extends Object> map) {
if(map == null)
return "null";
StringBuilder sb=new StringBuilder();
for(Map.Entry<? extends Object,? extends Object> entry: map.entrySet()) {
Object key=entry.getKey();
Object val=entry.getValue();
sb.append(key).append("=");
if(val == null)
sb.append("null");
else
sb.append(val);
sb.append("\n");
}
return sb.toString();
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("
}
public static String activeThreads() {
StringBuilder sb=new StringBuilder();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("
for(int i=0; i < threads.length; i++) {
sb.append("#").append(i).append(": ").append(threads[i]).append('\n');
}
sb.append("
return sb.toString();
}
public static String printBytes(long bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
public static String printBytes(double bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
public static List<String> split(String input, int separator) {
List<String> retval=new ArrayList<String>();
if(input == null)
return retval;
int index=0, end;
while(true) {
index=input.indexOf(separator, index);
if(index == -1)
break;
index++;
end=input.indexOf(separator, index);
if(end == -1)
retval.add(input.substring(index));
else
retval.add(input.substring(index, end));
}
return retval;
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) {
byte[] retval[];
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < length) {
if(accumulated_size + frag_size <= length)
tmp_size=frag_size;
else
tmp_size=length - accumulated_size;
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
return fragmentBuffer(buf, frag_size, buf.length);
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static List<Range> computeFragOffsets(int offset, int length, int frag_size) {
List<Range> retval=new ArrayList<Range>();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static List<Range> computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) {
boolean first=true;
StringBuilder sb=new StringBuilder();
for(T el: list) {
if(first) {
first=false;
}
else {
sb.append(delimiter);
}
sb.append(el);
}
return sb.toString();
}
// /**
// Peeks for view on the channel until n views have been received or timeout has elapsed.
// Used to determine the view in which we want to start work. Usually, we start as only
// member in our own view (1st view) and the next view (2nd view) will be the full view
// of all members, or a timeout if we're the first member. If a non-view (a message or
// block) is received, the method returns immediately.
// @param channel The channel used to peek for views. Has to be operational.
// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,
// if there are other members, we start working with them included in our view.
// @param timeout Number of milliseconds to wait until view is forced to return. A value
// of <= 0 means wait forever.
// */
// public static View peekViews(Channel channel, int number_of_views, long timeout) {
// View retval=null;
// Object obj=null;
// int num=0;
// long start_time=System.currentTimeMillis();
// if(timeout <= 0) {
// while(true) {
// try {
// obj=channel.peek(0);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(0);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// else {
// while(timeout > 0) {
// try {
// obj=channel.peek(timeout);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(timeout);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// timeout=timeout - (System.currentTimeMillis() - start_time);
// return retval;
public static String array2String(long[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(short[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(Object[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
/** Returns true if all elements of c match obj */
public static boolean all(Collection c, Object obj) {
for(Iterator iterator=c.iterator(); iterator.hasNext();) {
Object o=iterator.next();
if(!o.equals(obj))
return false;
}
return true;
}
/**
* Returns a list of members which left from view one to two
* @param one
* @param two
* @return
*/
public static List<Address> leftMembers(View one, View two) {
if(one == null || two == null)
return null;
List<Address> retval=new ArrayList<Address>(one.getMembers());
retval.removeAll(two.getMembers());
return retval;
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector<Address> pickSubset(Vector<Address> members, double subset_percentage) {
Vector<Address> ret=new Vector<Address>(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector<Address>)members.clone();
for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
public static Object pickRandomElement(List list) {
if(list == null) return null;
int size=list.size();
int index=(int)((Math.random() * size * 10) % size);
return list.get(index);
}
public static Object pickRandomElement(Object[] array) {
if(array == null) return null;
int size=array.length;
int index=(int)((Math.random() * size * 10) % size);
return array[index];
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) {
Vector<Address> retval=new Vector<Address>();
Address mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printMembers(Vector v) {
StringBuilder sb=new StringBuilder("(");
boolean first=true;
Object el;
if(v != null) {
for(int i=0; i < v.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
el=v.elementAt(i);
sb.append(el);
}
}
sb.append(')');
return sb.toString();
}
public static String printPingRsps(List<PingRsp> rsps) {
StringBuilder sb=new StringBuilder();
if(rsps != null) {
int total=rsps.size();
int servers=0, clients=0, coords=0;
for(PingRsp rsp: rsps) {
if(rsp.isCoord())
coords++;
if(rsp.isServer())
servers++;
else
clients++;
}
sb.append(total + " total (" + servers + " servers (" + coords + " coord), " + clients + " clients)");
}
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception {
if(length > 1) {
out.write(buf, offset, 1);
out.write(buf, offset+1, length - 1);
}
else {
out.write(buf, offset, 0);
out.write(buf, offset, length);
}
}
/**
* if we were to register for OP_WRITE and send the remaining data on
* readyOps for this channel we have to either block the caller thread or
* queue the message buffers that may arrive while waiting for OP_WRITE.
* Instead of the above approach this method will continuously write to the
* channel until the buffer sent fully.
*/
public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException {
int written = 0;
int toWrite = buf.limit();
while (written < toWrite) {
written += out.write(buf);
}
}
// /* double writes are not required.*/
// public static void doubleWriteBuffer(
// ByteBuffer buf,
// WritableByteChannel out)
// throws Exception
// if (buf.limit() > 1)
// int actualLimit = buf.limit();
// buf.limit(1);
// writeFully(buf,out);
// buf.limit(actualLimit);
// writeFully(buf,out);
// else
// buf.limit(0);
// writeFully(buf,out);
// buf.limit(1);
// writeFully(buf,out);
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
inst=Util.loadClass(classname, null).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static int sizeOf(Streamable inst) {
byte[] data;
ByteArrayOutputStream output;
DataOutputStream out;
try {
output=new ByteArrayOutputStream();
out=new DataOutputStream(output);
inst.writeTo(out);
out.flush();
data=output.toByteArray();
return data.length;
}
catch(Exception ex) {
return -1;
}
}
/**
* Tries to load the class from the current thread's context class loader. If
* not successful, tries to load the class from the current instance.
* @param classname Desired class.
* @param clazz Class object used to obtain a class loader
* if no context class loader is available.
* @return Class, or null on failure.
*/
public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
throw new ClassNotFoundException(classname);
}
public static InputStream getResourceAsStream(String name, Class clazz) {
ClassLoader loader;
InputStream retval=null;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
return retval;
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
* Parses comma-delimited longs; e.g., 2000,4000,8000.
* Returns array of long, or null.
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector<Long> v=new Vector<Long>();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.isEmpty()) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=v.elementAt(i).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static List<String> parseCommaDelimitedStrings(String l) {
return parseStringList(l, ",");
}
/**
* Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of
* IpAddresses
*/
public static List<IpAddress> parseCommaDelimetedHosts(String hosts, int port_range) throws UnknownHostException {
StringTokenizer tok=new StringTokenizer(hosts, ",");
String t;
IpAddress addr;
Set<IpAddress> retval=new HashSet<IpAddress>();
while(tok.hasMoreTokens()) {
t=tok.nextToken().trim();
String host=t.substring(0, t.indexOf('['));
host=host.trim();
int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']')));
for(int i=port;i < port + port_range;i++) {
addr=new IpAddress(host, i);
retval.add(addr);
}
}
return Collections.unmodifiableList(new LinkedList<IpAddress>(retval));
}
public static List<String> parseStringList(String l, String separator) {
List<String> tmp=new LinkedList<String>();
StringTokenizer tok=new StringTokenizer(l, separator);
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t.trim());
}
return tmp;
}
public static String parseString(ByteBuffer buf) {
return parseString(buf, true);
}
public static String parseString(ByteBuffer buf, boolean discard_whitespace) {
StringBuilder sb=new StringBuilder();
char ch;
// read white space
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
buf.position(buf.position() -1);
break;
}
}
if(buf.remaining() == 0)
return null;
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
sb.append(ch);
}
else
break;
}
// read white space
if(discard_whitespace) {
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
buf.position(buf.position() -1);
break;
}
}
}
return sb.toString();
}
public static int readNewLine(ByteBuffer buf) {
char ch;
int num=0;
while(buf.remaining() > 0) {
ch=(char)buf.get();
num++;
if(ch == '\n')
break;
}
return num;
}
/**
* Reads and discards all characters from the input stream until a \r\n or EOF is encountered
* @param in
* @return
*/
public static int discardUntilNewLine(InputStream in) {
int ch;
int num=0;
while(true) {
try {
ch=in.read();
if(ch == -1)
break;
num++;
if(ch == '\n')
break;
}
catch(IOException e) {
break;
}
}
return num;
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
*
* @exception IOException If an I/O error occurs
*/
public static String readLine(InputStream in) throws IOException {
StringBuilder sb=new StringBuilder(35);
int ch;
while(true) {
ch=in.read();
if(ch == -1)
return null;
if(ch == '\r') {
;
}
else {
if(ch == '\n')
break;
else {
sb.append((char)ch);
}
}
}
return sb.toString();
}
public static void writeString(ByteBuffer buf, String s) {
for(int i=0; i < s.length(); i++)
buf.put((byte)s.charAt(i));
}
/**
*
* @param s
* @return List<NetworkInterface>
*/
public static List<NetworkInterface> parseInterfaceList(String s) throws Exception {
List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10);
if(s == null)
return null;
StringTokenizer tok=new StringTokenizer(s, ",");
String interface_name;
NetworkInterface intf;
while(tok.hasMoreTokens()) {
interface_name=tok.nextToken();
// try by name first (e.g. (eth0")
intf=NetworkInterface.getByName(interface_name);
// next try by IP address or symbolic name
if(intf == null)
intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name));
if(intf == null)
throw new Exception("interface " + interface_name + " not found");
if(!interfaces.contains(intf)) {
interfaces.add(intf);
}
}
return interfaces;
}
public static String print(List<NetworkInterface> interfaces) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(NetworkInterface intf: interfaces) {
if(first) {
first=false;
}
else {
sb.append(", ");
}
sb.append(intf.getName());
}
return sb.toString();
}
public static String shortName(String hostname) {
int index;
StringBuilder sb=new StringBuilder();
if(hostname == null) return null;
index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
sb.append(hostname.substring(0, index));
else
sb.append(hostname);
return sb.toString();
}
public static String shortName(InetAddress hostname) {
if(hostname == null) return null;
StringBuilder sb=new StringBuilder();
if(resolve_dns)
sb.append(hostname.getHostName());
else
sb.append(hostname.getHostAddress());
return sb.toString();
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static MulticastSocket createMulticastSocket(int port) throws IOException {
return createMulticastSocket(null, port, null);
}
public static MulticastSocket createMulticastSocket(InetAddress mcast_addr, int port, Log log) throws IOException {
if(mcast_addr != null && !mcast_addr.isMulticastAddress()) {
if(log != null && log.isWarnEnabled())
log.warn("mcast_addr (" + mcast_addr + ") is not a multicast address, will be ignored");
return new MulticastSocket(port);
}
SocketAddress saddr=new InetSocketAddress(mcast_addr, port);
MulticastSocket retval=null;
try {
retval=new MulticastSocket(saddr);
}
catch(IOException ex) {
if(log != null && log.isWarnEnabled()) {
StringBuilder sb=new StringBuilder();
String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a";
sb.append("could not bind to " + mcast_addr + " (" + type + " address)");
sb.append("; make sure your mcast_addr is of the same type as the IP stack (IPv4 or IPv6).");
sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " +
"(see http:
sb.append("\nException was: " + ex);
log.warn(sb);
}
}
if(retval == null)
retval=new MulticastSocket(port);
return retval;
}
/**
* Returns the address of the interface to use defined by bind_addr and bind_interface
* @param props
* @return
* @throws UnknownHostException
* @throws SocketException
*/
public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException {
boolean ignore_systemprops=Util.isBindAddressPropertyIgnored();
String bind_addr=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr",
ignore_systemprops, null);
String bind_interface=Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface",
ignore_systemprops, null);
InetAddress retval=null, bind_addr_host=null;
if(bind_addr != null) {
bind_addr_host=InetAddress.getByName(bind_addr);
}
if(bind_interface != null) {
NetworkInterface intf=NetworkInterface.getByName(bind_interface);
if(intf != null) {
for(Enumeration<InetAddress> addresses=intf.getInetAddresses(); addresses.hasMoreElements();) {
InetAddress addr=addresses.nextElement();
if(bind_addr == null) {
retval=addr;
break;
}
else {
if(bind_addr_host != null) {
if(bind_addr_host.equals(addr)) {
retval=addr;
break;
}
}
else if(addr.getHostAddress().trim().equalsIgnoreCase(bind_addr)) {
retval=addr;
break;
}
}
}
}
else {
throw new UnknownHostException("network interface " + bind_interface + " not found");
}
}
if(retval == null) {
retval=bind_addr != null? InetAddress.getByName(bind_addr) : InetAddress.getLocalHost();
}
//check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine
if(NetworkInterface.getByInetAddress(retval) == null) {
throw new UnknownHostException("Invalid bind address " + retval);
}
if(props != null) {
props.remove("bind_addr");
props.remove("bind_interface");
}
return retval;
}
public static boolean checkForLinux() {
return checkForPresence("os.name", "linux");
}
public static boolean checkForSolaris() {
return checkForPresence("os.name", "sun");
}
public static boolean checkForWindows() {
return checkForPresence("os.name", "win");
}
private static boolean checkForPresence(String key, String value) {
try {
String tmp=System.getProperty(key);
return tmp != null && tmp.trim().toLowerCase().startsWith(value);
}
catch(Throwable t) {
return false;
}
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static int getJavaVersion() {
String version=System.getProperty("java.version");
int retval=0;
if(version != null) {
if(version.startsWith("1.2"))
return 12;
if(version.startsWith("1.3"))
return 13;
if(version.startsWith("1.4"))
return 14;
if(version.startsWith("1.5"))
return 15;
if(version.startsWith("5"))
return 15;
if(version.startsWith("1.6"))
return 16;
if(version.startsWith("6"))
return 16;
}
return retval;
}
public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) {
if(v == null) return null;
return new UnmodifiableVector(v);
}
public static String memStats(boolean gc) {
StringBuilder sb=new StringBuilder();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
// public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
// Enumeration en=NetworkInterface.getNetworkInterfaces();
// while(en.hasMoreElements()) {
// NetworkInterface i=(NetworkInterface)en.nextElement();
// for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
// InetAddress addr=(InetAddress)en2.nextElement();
// if(!addr.isLoopbackAddress())
// return addr;
// return null;
public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
boolean preferIpv4=Boolean.getBoolean(Global.IPv4);
boolean preferIPv6=Boolean.getBoolean(Global.IPv6);
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
if(preferIPv6)
continue;
return addr;
}
if(addr instanceof Inet6Address) {
if(preferIpv4)
continue;
return addr;
}
}
}
}
return null;
}
public static boolean isIPv4Stack() {
return getIpStack()== 4;
}
public static boolean isIPv6Stack() {
return getIpStack() == 6;
}
public static short getIpStack() {
short retval=2;
if(Boolean.getBoolean(Global.IPv4)) {
retval=4;
}
if(Boolean.getBoolean(Global.IPv6)) {
retval=6;
}
return retval;
}
public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
continue;
}
if(addr instanceof Inet6Address) {
return addr;
}
}
}
}
return null;
}
public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10);
NetworkInterface intf;
for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
intf=(NetworkInterface)en.nextElement();
retval.add(intf);
}
return retval;
}
/**
* Returns a value associated wither with one or more system properties, or found in the props map
* @param system_props
* @param props List of properties read from the configuration file
* @param prop_name The name of the property, will be removed from props if found
* @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from
* props (not system_props)
* @param default_value Used to return a default value if the properties or system properties didn't have the value
* @return The value, or null if not found
*/
public static String getProperty(String[] system_props, Properties props, String prop_name,
boolean ignore_sysprops, String default_value) {
String retval=null;
if(props != null && prop_name != null) {
retval=props.getProperty(prop_name);
props.remove(prop_name);
}
if(!ignore_sysprops) {
String tmp, prop;
if(system_props != null) {
for(int i=0; i < system_props.length; i++) {
prop=system_props[i];
if(prop != null) {
try {
tmp=System.getProperty(prop);
if(tmp != null)
return tmp; // system properties override config file definitions
}
catch(SecurityException ex) {}
}
}
}
}
if(retval == null)
return default_value;
return retval;
}
public static boolean isBindAddressPropertyIgnored() {
try {
String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY);
if(tmp == null) {
tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD);
if(tmp == null)
return false;
}
tmp=tmp.trim().toLowerCase();
return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on"));
}
catch(SecurityException ex) {
return false;
}
}
public static MBeanServer getMBeanServer() {
ArrayList servers=MBeanServerFactory.findMBeanServer(null);
if(servers == null || servers.isEmpty())
return null;
// return 'jboss' server if available
for(int i=0; i < servers.size(); i++) {
MBeanServer srv=(MBeanServer)servers.get(i);
if("jboss".equalsIgnoreCase(srv.getDefaultDomain()))
return srv;
}
// return first available server
return (MBeanServer)servers.get(0);
}
public static void main(String args[]) throws Exception {
System.out.println("IPv4: " + isIPv4Stack());
System.out.println("IPv6: " + isIPv6Stack());
}
public static String generateList(Collection c, String separator) {
if(c == null) return null;
StringBuilder sb=new StringBuilder();
boolean first=true;
for(Iterator it=c.iterator(); it.hasNext();) {
if(first) {
first=false;
}
else {
sb.append(separator);
}
sb.append(it.next());
}
return sb.toString();
}
/**
* Go through the input string and replace any occurance of ${p} with the
* props.getProperty(p) value. If there is no such property p defined, then
* the ${p} reference will remain unchanged.
*
* If the property reference is of the form ${p:v} and there is no such
* property p, then the default value v will be returned.
*
* If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the
* primary and the secondary properties will be tried in turn, before
* returning either the unchanged input, or the default value.
*
* The property ${/} is replaced with System.getProperty("file.separator")
* value and the property ${:} is replaced with
* System.getProperty("path.separator").
*
* @param string -
* the string with possible ${} references
* @param props -
* the source for ${x} property ref values, null means use
* System.getProperty()
* @return the input string with all property references replaced if any. If
* there are no valid references the input string will be returned.
* @throws java.lang.AccessControlException
* when not authorised to retrieved system properties
*/
public static String replaceProperties(final String string, final Properties props) {
/** File separator value */
final String FILE_SEPARATOR=File.separator;
/** Path separator value */
final String PATH_SEPARATOR=File.pathSeparator;
/** File separator alias */
final String FILE_SEPARATOR_ALIAS="/";
/** Path separator alias */
final String PATH_SEPARATOR_ALIAS=":";
// States used in property parsing
final int NORMAL=0;
final int SEEN_DOLLAR=1;
final int IN_BRACKET=2;
final char[] chars=string.toCharArray();
StringBuffer buffer=new StringBuffer();
boolean properties=false;
int state=NORMAL;
int start=0;
for(int i=0;i < chars.length;++i) {
char c=chars[i];
// Dollar sign outside brackets
if(c == '$' && state != IN_BRACKET)
state=SEEN_DOLLAR;
// Open bracket immediatley after dollar
else if(c == '{' && state == SEEN_DOLLAR) {
buffer.append(string.substring(start, i - 1));
state=IN_BRACKET;
start=i - 1;
}
// No open bracket after dollar
else if(state == SEEN_DOLLAR)
state=NORMAL;
// Closed bracket after open bracket
else if(c == '}' && state == IN_BRACKET) {
// No content
if(start + 2 == i) {
buffer.append("${}"); // REVIEW: Correct?
}
else // Collect the system property
{
String value=null;
String key=string.substring(start + 2, i);
// check for alias
if(FILE_SEPARATOR_ALIAS.equals(key)) {
value=FILE_SEPARATOR;
}
else if(PATH_SEPARATOR_ALIAS.equals(key)) {
value=PATH_SEPARATOR;
}
else {
// check from the properties
if(props != null)
value=props.getProperty(key);
else
value=System.getProperty(key);
if(value == null) {
// Check for a default value ${key:default}
int colon=key.indexOf(':');
if(colon > 0) {
String realKey=key.substring(0, colon);
if(props != null)
value=props.getProperty(realKey);
else
value=System.getProperty(realKey);
if(value == null) {
// Check for a composite key, "key1,key2"
value=resolveCompositeKey(realKey, props);
// Not a composite key either, use the specified default
if(value == null)
value=key.substring(colon + 1);
}
}
else {
// No default, check for a composite key, "key1,key2"
value=resolveCompositeKey(key, props);
}
}
}
if(value != null) {
properties=true;
buffer.append(value);
}
}
start=i + 1;
state=NORMAL;
}
}
// No properties
if(properties == false)
return string;
// Collect the trailing characters
if(start != chars.length)
buffer.append(string.substring(start, chars.length));
// Done
return buffer.toString();
}
/**
* Try to resolve a "key" from the provided properties by checking if it is
* actually a "key1,key2", in which case try first "key1", then "key2". If
* all fails, return null.
*
* It also accepts "key1," and ",key2".
*
* @param key
* the key to resolve
* @param props
* the properties to use
* @return the resolved key or null
*/
private static String resolveCompositeKey(String key, Properties props) {
String value=null;
// Look for the comma
int comma=key.indexOf(',');
if(comma > -1) {
// If we have a first part, try resolve it
if(comma > 0) {
// Check the first part
String key1=key.substring(0, comma);
if(props != null)
value=props.getProperty(key1);
else
value=System.getProperty(key1);
}
// Check the second part, if there is one and first lookup failed
if(value == null && comma < key.length() - 1) {
String key2=key.substring(comma + 1);
if(props != null)
value=props.getProperty(key2);
else
value=System.getProperty(key2);
}
}
// Return whatever we've found or null
return value;
}
/**
* Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns
* the same string, otherwise a copy of the string with variables substituted
* @param val
* @return A string with vars replaced, or the same string if no vars found
*/
public static String substituteVariable(String val) {
if(val == null)
return val;
String retval=val, prev;
while(retval.contains("${")) { // handle multiple variables in val
prev=retval;
retval=_substituteVar(retval);
if(retval.equals(prev))
break;
}
return retval;
}
private static String _substituteVar(String val) {
int start_index, end_index;
start_index=val.indexOf("${");
if(start_index == -1)
return val;
end_index=val.indexOf("}", start_index+2);
if(end_index == -1)
throw new IllegalArgumentException("missing \"}\" in " + val);
String tmp=getProperty(val.substring(start_index +2, end_index));
if(tmp == null)
return val;
StringBuilder sb=new StringBuilder();
sb.append(val.substring(0, start_index));
sb.append(tmp);
sb.append(val.substring(end_index+1));
return sb.toString();
}
private static String getProperty(String s) {
String var, default_val, retval=null;
int index=s.indexOf(":");
if(index >= 0) {
var=s.substring(0, index);
default_val=s.substring(index+1);
retval=System.getProperty(var, default_val);
}
else {
var=s;
retval=System.getProperty(var);
}
return retval;
}
/**
* Used to convert a byte array in to a java.lang.String object
* @param bytes the bytes to be converted
* @return the String representation
*/
private static String getString(byte[] bytes) {
StringBuilder sb=new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
sb.append(0x00FF & b);
if (i + 1 < bytes.length) {
sb.append("-");
}
}
return sb.toString();
}
/**
* Converts a java.lang.String in to a MD5 hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String md5(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
return null;
}
}
/**
* Converts a java.lang.String in to a SHA hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String sha(String source) {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
package org.peg4d;
import org.peg4d.MemoMap.ObjectMemo;
public abstract class PExpression {
public final static int CyclicRule = 1;
public final static int HasNonTerminal = 1 << 1;
public final static int HasString = 1 << 2;
public final static int HasCharacter = 1 << 3;
public final static int HasAny = 1 << 4;
public final static int HasRepetition = 1 << 5;
public final static int HasOptional = 1 << 6;
public final static int HasChoice = 1 << 7;
public final static int HasAnd = 1 << 8;
public final static int HasNot = 1 << 9;
public final static int HasConstructor = 1 << 10;
public final static int HasConnector = 1 << 11;
public final static int HasTagging = 1 << 12;
public final static int HasMessage = 1 << 13;
public final static int HasContext = 1 << 14;
public final static int HasReserved = 1 << 15;
public final static int hasReserved2 = 1 << 16;
public final static int Mask = HasNonTerminal | HasString | HasCharacter | HasAny
| HasRepetition | HasOptional | HasChoice | HasAnd | HasNot
| HasConstructor | HasConnector | HasTagging | HasMessage
| HasReserved | hasReserved2 | HasContext;
public final static int HasLazyNonTerminal = Mask;
public final static int LeftObjectOperation = 1 << 17;
public final static int PossibleDifferentRight = 1 << 18;
public final static int NoMemo = 1 << 20;
public final static int Debug = 1 << 24;
Grammar base;
int flag = 0;
short uniqueId = 0;
short semanticId = 0;
protected PExpression(Grammar base, int flag) {
this.base = base;
this.flag = flag;
this.uniqueId = base.factory.issue(this);
this.semanticId = this.uniqueId;
}
protected abstract void visit(ParsingVisitor probe);
public PExpression getExpression() {
return this;
}
public abstract void vmMatch(ParsingContext context);
public abstract void simpleMatch(ParsingStream context);
boolean checkFirstByte(int ch) {
return true;
}
public final boolean is(int uflag) {
return ((this.flag & uflag) == uflag);
}
public void set(int uflag) {
this.flag = this.flag | uflag;
}
protected void derived(PExpression e) {
this.flag |= (e.flag & PExpression.Mask);
}
public String key() {
return "#" + this.uniqueId;
}
public int size() {
return 0;
}
public PExpression get(int index) {
return this; // to avoid NullPointerException
}
public PExpression get(int index, PExpression def) {
return def;
}
String nameAt(int index) {
return null;
}
private final static GrammarFormatter DefaultFormatter = new GrammarFormatter();
@Override public String toString() {
StringBuilder sb = new StringBuilder();
DefaultFormatter.format(this, sb);
return sb.toString();
}
public final String format(String name, GrammarFormatter fmt) {
StringBuilder sb = new StringBuilder();
fmt.formatRule(name, this, sb);
return sb.toString();
}
public final String format(String name) {
return this.format(name, new GrammarFormatter());
}
protected void warning(String msg) {
if(Main.VerbosePeg && Main.StatLevel == 0) {
Main._PrintLine("PEG warning: " + msg);
}
}
public final boolean hasObjectOperation() {
return this.is(PExpression.HasConstructor)
|| this.is(PExpression.HasConnector)
|| this.is(PExpression.HasTagging)
|| this.is(PExpression.HasMessage);
}
}
class PNonTerminal extends PExpression {
String symbol;
PExpression resolvedExpression = null;
PNonTerminal(Grammar base, int flag, String ruleName) {
super(base, flag | PExpression.HasNonTerminal | PExpression.NoMemo);
this.symbol = ruleName;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitNonTerminal(this);
}
@Override boolean checkFirstByte(int ch) {
if(this.resolvedExpression != null) {
return this.resolvedExpression.checkFirstByte(ch);
}
return true;
}
final PExpression getNext() {
if(this.resolvedExpression == null) {
return this.base.getExpression(this.symbol);
}
return this.resolvedExpression;
}
public boolean isForeignNonTerminal() {
return this.resolvedExpression.base != this.base;
}
@Override
public void vmMatch(ParsingContext context) {
this.resolvedExpression.vmMatch(context);
}
@Override
public void simpleMatch(ParsingStream context) {
this.resolvedExpression.simpleMatch(context);
//System.out.println("pos=" + context.pos + " called " + this.symbol + " isFailure: " + context.isFailure() + " " + this.resolvedExpression);
}
}
abstract class PTerminal extends PExpression {
PTerminal (Grammar base, int flag) {
super(base, flag);
}
@Override
public final int size() {
return 0;
}
@Override
public final PExpression get(int index) {
return this; // just avoid NullPointerException
}
}
class PString extends PTerminal {
String text;
byte[] utf8;
public PString(Grammar base, int flag, String text) {
super(base, PExpression.HasString | PExpression.NoMemo | flag);
this.text = text;
if(text != null) {
utf8 = ParsingCharset.toUtf8(text);
}
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitString(this);
}
@Override boolean checkFirstByte(int ch) {
if(this.text.length() == 0) {
return true;
}
return ParsingCharset.getFirstChar(this.utf8) == ch;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchText(this.utf8);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchText(this.utf8);
}
}
class PByteChar extends PString {
int byteChar;
PByteChar(Grammar base, int flag, String token) {
super(base, flag, token);
this.byteChar = this.utf8[0] & 0xff;
}
PByteChar(Grammar base, int flag, int ch, String text) {
super(base, flag, null);
this.utf8 = new byte[1];
this.utf8[0] = (byte)ch;
this.byteChar = ch & 0xff;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchByteChar(this.byteChar);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchByteChar(this.byteChar);
}
}
class PAny extends PTerminal {
PAny(Grammar base, int flag) {
super(base, PExpression.HasAny | PExpression.NoMemo | flag);
}
@Override boolean checkFirstByte(int ch) {
return true;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitAny(this);
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchAnyChar();
}
@Override
public void simpleMatch(ParsingStream context) {
if(context.hasUnconsumedCharacter()) {
context.consume(1);
return;
}
context.foundFailure(this);
}
}
class PCharacter extends PTerminal {
ParsingCharset charset;
PCharacter(Grammar base, int flag, ParsingCharset charset) {
super(base, PExpression.HasCharacter | PExpression.NoMemo | flag);
this.charset = charset;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitCharacter(this);
}
@Override boolean checkFirstByte(int ch) {
return this.charset.hasByte(ch);
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchCharset(this.charset);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchCharset(this.charset);
}
}
//class PNotAny extends PTerm {
// PNot not;
// PExpression exclude;
// PExpression orig;
// public PNotAny(Grammar base, int flag, PNot e, PExpression orig) {
// super(base, flag | PExpression.NoMemo);
// this.not = e;
// this.exclude = e.inner;
// this.orig = orig;
// @Override
// protected void visit(ParsingVisitor probe) {
// probe.visitNotAny(this);
// @Override boolean checkFirstByte(int ch) {
// return this.not.checkFirstByte(ch) && this.orig.checkFirstByte(ch);
// @Override
// public ParsingObject simpleMatch(ParsingObject left, ParsingContext2 context) {
// long pos = context.getPosition();
// ParsingObject right = this.exclude.simpleMatch(left, context);
// if(context.isFailure()) {
// assert(pos == context.getPosition());
// if(context.hasUnconsumedCharacter()) {
// context.consume(1);
// return left;
// else {
// context.rollback(pos);
// return context.foundFailure(this);
abstract class PUnary extends PExpression {
PExpression inner;
public PUnary(Grammar base, int flag, PExpression e) {
super(base, flag);
this.inner = e;
this.derived(e);
}
@Override
public final int size() {
return 1;
}
@Override
public final PExpression get(int index) {
return this.inner;
}
}
class POptional extends PUnary {
public POptional(Grammar base, int flag, PExpression e) {
super(base, flag | PExpression.HasOptional | PExpression.NoMemo, e);
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitOptional(this);
}
@Override boolean checkFirstByte(int ch) {
return true;
}
@Override
public void vmMatch(ParsingContext context) {
context.opRememberFailurePosition();
context.opStoreObject();
this.inner.vmMatch(context);
context.opRestoreObjectIfFailure();
context.opForgetFailurePosition();
}
@Override
public void simpleMatch(ParsingStream context) {
long f = context.rememberFailure();
ParsingObject left = context.left;
this.inner.simpleMatch(context);
if(context.isFailure()) {
context.forgetFailure(f);
context.left = left;
}
}
}
class POptionalString extends POptional {
byte[] utf8;
POptionalString(Grammar base, int flag, PString e) {
super(base, flag | PExpression.NoMemo, e);
this.utf8 = e.utf8;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchOptionalText(this.utf8);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchOptionalText(this.utf8);
}
}
class POptionalByteChar extends POptional {
int byteChar;
POptionalByteChar(Grammar base, int flag, PByteChar e) {
super(base, flag | PExpression.NoMemo, e);
this.byteChar = e.byteChar;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchOptionalByteChar(this.byteChar);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchOptionalByteChar(this.byteChar);
}
}
class POptionalCharacter extends POptional {
ParsingCharset charset;
POptionalCharacter(Grammar base, int flag, PCharacter e) {
super(base, flag | PExpression.NoMemo, e);
this.charset = e.charset;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchOptionalCharset(this.charset);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchOptionalCharset(this.charset);
}
}
class PRepetition extends PUnary {
public int atleast = 0;
protected PRepetition(Grammar base, int flag, PExpression e, int atLeast) {
super(base, flag | PExpression.HasRepetition, e);
this.atleast = atLeast;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitRepetition(this);
}
@Override boolean checkFirstByte(int ch) {
if(this.atleast > 0) {
return this.inner.checkFirstByte(ch);
}
return true;
}
@Override
public void vmMatch(ParsingContext context) {
context.opRememberFailurePosition();
context.opStoreObject();
while(true) {
context.opRefreshStoredObject();
this.inner.vmMatch(context);
if(context.isFailure()) {
context.opRestoreObject();
break;
}
}
context.opForgetFailurePosition();
}
@Override
public void simpleMatch(ParsingStream context) {
long ppos = -1;
long pos = context.getPosition();
long f = context.rememberFailure();
int count = 0;
while(ppos < pos) {
ParsingObject left = context.left;
this.inner.simpleMatch(context);
if(context.isFailure()) {
context.left = left;
break;
}
ppos = pos;
pos = context.getPosition();
count = count + 1;
}
if(count < this.atleast) {
context.foundFailure(this);
}
else {
context.forgetFailure(f);
}
}
}
//class POneMoreCharacter extends PRepetition {
// ParsingCharset charset;
// public POneMoreCharacter(Grammar base, int flag, PCharacter e) {
// super(base, flag, e, 1);
// charset = e.charset;
// @Override
// public ParsingObject simpleMatch(ParsingObject left, ParsingContext2 context) {
// long pos = context.getPosition();
// int consumed = this.charset.consume(context.source, pos);
// if(consumed == 0) {
// return context.foundFailure(this);
// pos += consumed;
// consumed = this.charset.consume(context.source, pos);
// pos += consumed;
// while(consumed > 0);
// context.setPosition(pos);
// return left;
class PZeroMoreCharacter extends PRepetition {
ParsingCharset charset;
public PZeroMoreCharacter(Grammar base, int flag, PCharacter e) {
super(base, flag, e, 0);
this.charset = e.charset;
}
@Override
public void simpleMatch(ParsingStream context) {
long pos = context.getPosition();
int consumed = 0;
do {
consumed = this.charset.consume(context.source, pos);
pos += consumed;
}
while(consumed > 0);
context.setPosition(pos);
}
}
class PAnd extends PUnary {
PAnd(Grammar base, int flag, PExpression e) {
super(base, flag | PExpression.HasAnd, e);
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitAnd(this);
}
@Override
boolean checkFirstByte(int ch) {
return this.inner.checkFirstByte(ch);
}
@Override
public void vmMatch(ParsingContext context) {
context.opRememberPosition();
this.inner.vmMatch(context);
context.opBacktrackPosition();
}
@Override
public void simpleMatch(ParsingStream context) {
long pos = context.getPosition();
this.inner.simpleMatch(context);
context.rollback(pos);
}
}
class PNot extends PUnary {
PNot(Grammar base, int flag, PExpression e) {
super(base, PExpression.HasNot | flag, e);
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitNot(this);
}
@Override
boolean checkFirstByte(int ch) {
return !this.inner.checkFirstByte(ch);
}
@Override
public void vmMatch(ParsingContext context) {
context.opRememberPosition();
context.opStoreObject();
context.opRememberFailurePosition();
this.inner.vmMatch(context);
context.opForgetFailurePosition();
context.opRestoreNegativeObject();
context.opBacktrackPosition();
}
@Override
public void simpleMatch(ParsingStream context) {
long pos = context.getPosition();
long f = context.rememberFailure();
ParsingObject left = context.left;
this.inner.simpleMatch(context);
if(context.isFailure()) {
context.forgetFailure(f);
context.left = left;
}
else {
context.foundFailure(this);
}
context.rollback(pos);
}
}
class PNotString extends PNot {
byte[] utf8;
PNotString(Grammar peg, int flag, PString e) {
super(peg, flag | PExpression.NoMemo, e);
this.utf8 = e.utf8;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchTextNot(utf8);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchTextNot(utf8);
}
}
class PNotByteChar extends PNotString {
int byteChar;
PNotByteChar(Grammar peg, int flag, PByteChar e) {
super(peg, flag, e);
this.byteChar = e.byteChar;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchByteCharNot(this.byteChar);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchByteCharNot(this.byteChar);
}
}
class PNotCharacter extends PNot {
ParsingCharset charset;
PNotCharacter(Grammar base, int flag, PCharacter e) {
super(base, flag | PExpression.NoMemo, e);
this.charset = e.charset;
}
@Override
public void vmMatch(ParsingContext context) {
context.opMatchCharsetNot(this.charset);
}
@Override
public void simpleMatch(ParsingStream context) {
context.opMatchCharsetNot(this.charset);
}
}
abstract class PList extends PExpression {
UList<PExpression> list;
int length = 0;
PList(Grammar base, int flag, UList<PExpression> list) {
super(base, flag);
this.list = list;
}
@Override
public final int size() {
return this.list.size();
}
@Override
public final PExpression get(int index) {
return this.list.ArrayValues[index];
}
public final void set(int index, PExpression e) {
this.list.ArrayValues[index] = e;
}
@Override
public final PExpression get(int index, PExpression def) {
if(index < this.size()) {
return this.list.ArrayValues[index];
}
return def;
}
@Override
public void vmMatch(ParsingContext context) {
context.opRememberSequencePosition();
for(int i = 0; i < this.size(); i++) {
this.get(i).vmMatch(context);
if(context.isFailure()) {
context.opBackTrackSequencePosition();
return;
}
}
context.opCommitSequencePosition();
}
private boolean isOptional(PExpression e) {
if(e instanceof POptional) {
return true;
}
if(e instanceof PRepetition && ((PRepetition) e).atleast == 0) {
return true;
}
return false;
}
private boolean isUnconsumed(PExpression e) {
if(e instanceof PNot && e instanceof PAnd) {
return true;
}
if(e instanceof PString && ((PString)e).utf8.length == 0) {
return true;
}
if(e instanceof PIndent) {
return true;
}
return false;
}
@Override
boolean checkFirstByte(int ch) {
for(int start = 0; start < this.size(); start++) {
PExpression e = this.get(start);
if(e instanceof PTagging || e instanceof PMessage) {
continue;
}
if(this.isOptional(e)) {
if(((PUnary)e).inner.checkFirstByte(ch)) {
return true;
}
continue; // unconsumed
}
if(this.isUnconsumed(e)) {
if(!e.checkFirstByte(ch)) {
return false;
}
continue;
}
return e.checkFirstByte(ch);
}
return true;
}
public final PExpression trim() {
int size = this.size();
boolean hasNull = true;
while(hasNull) {
hasNull = false;
for(int i = 0; i < size-1; i++) {
if(this.get(i) == null && this.get(i+1) != null) {
this.swap(i,i+1);
hasNull = true;
}
}
}
for(int i = 0; i < this.size(); i++) {
if(this.get(i) == null) {
size = i;
break;
}
}
if(size == 0) {
return null;
}
if(size == 1) {
return this.get(0);
}
this.list.clear(size);
return this;
}
public final void swap(int i, int j) {
PExpression e = this.list.ArrayValues[i];
this.list.ArrayValues[i] = this.list.ArrayValues[j];
this.list.ArrayValues[j] = e;
}
}
class PSequence extends PList {
PSequence(Grammar base, int flag, UList<PExpression> l) {
super(base, flag, l);
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitSequence(this);
}
@Override
public void simpleMatch(ParsingStream context) {
long pos = context.getPosition();
int mark = context.markObjectStack();
for(int i = 0; i < this.size(); i++) {
this.get(i).simpleMatch(context);
//System.out.println("Attmpt Sequence " + this.get(i) + " isFailure: " + context.isFailure());
if(context.isFailure()) {
context.abortLinkLog(mark);
context.rollback(pos);
break;
}
}
}
}
class PChoice extends PList {
PChoice(Grammar base, int flag, UList<PExpression> list) {
super(base, flag | PExpression.HasChoice, list);
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitChoice(this);
}
@Override
boolean checkFirstByte(int ch) {
for(int i = 0; i < this.size(); i++) {
if(this.get(i).checkFirstByte(ch)) {
return true;
}
}
return false;
}
@Override
public void vmMatch(ParsingContext context) {
context.opRememberFailurePosition();
context.opStoreObject();
for(int i = 0; i < this.size(); i++) {
this.get(i).vmMatch(context);
if(context.isFailure()) {
context.opRestoreObject();
context.opStoreObject();
}
else {
context.opDropStoredObject();
context.opForgetFailurePosition();
return;
}
}
context.opDropStoredObject();
context.opUpdateFailurePosition();
}
@Override
public void simpleMatch(ParsingStream context) {
long f = context.rememberFailure();
ParsingObject left = context.left;
for(int i = 0; i < this.size(); i++) {
context.left = left;
this.get(i).simpleMatch(context);
if(!context.isFailure()) {
context.forgetFailure(f);
return;
}
}
assert(context.isFailure());
}
}
class PMappedChoice extends PChoice {
PExpression[] caseOf = null;
PMappedChoice(Grammar base, int flag, UList<PExpression> list) {
super(base, flag, list);
}
@Override
public void simpleMatch(ParsingStream context) {
int ch = context.getByteChar();
if(this.caseOf == null) {
tryPrediction();
}
caseOf[ch].simpleMatch(context);
}
void tryPrediction() {
if(this.caseOf == null) {
this.caseOf = new PExpression[ParsingCharset.MAX];
PExpression failed = new PAlwaysFailure(this);
for(int ch = 0; ch < ParsingCharset.MAX; ch++) {
this.caseOf[ch] = selectC1(ch, failed);
}
this.base.PredictionOptimization += 1;
}
}
private PExpression selectC1(int ch, PExpression failed) {
PExpression e = null;
UList<PExpression> l = null; // new UList<Peg>(new Peg[2]);
for(int i = 0; i < this.size(); i++) {
if(this.get(i).checkFirstByte(ch)) {
if(e == null) {
e = this.get(i);
}
else {
if(l == null) {
l = new UList<PExpression>(new PExpression[2]);
l.add(e);
}
l.add(get(i));
}
}
}
if(l != null) {
e = new PChoice(e.base, 0, l);
e.base.UnpredicatedChoiceL1 += 1;
}
else {
if(e == null) {
e = failed;
}
e.base.PredicatedChoiceL1 +=1;
}
return e;
}
}
//class PegWordChoice extends PChoice {
// ParsingCharset charset = null;
// UList<byte[]> wordList = null;
// PegWordChoice(Grammar base, int flag, UList<PExpression> list) {
// super(base, flag | PExpression.HasChoice, list);
// this.wordList = new UList<byte[]>(new byte[list.size()][]);
// for(int i = 0; i < list.size(); i++) {
// PExpression se = list.ArrayValues[i];
// if(se instanceof PString1) {
// if(charset == null) {
// charset = new ParsingCharset("");
// charset.append(((PString1)se).symbol1);
// if(se instanceof PCharacter) {
// if(charset == null) {
// charset = new ParsingCharset("");
// charset.append(((PCharacter)se).charset);
// if(se instanceof PString) {
// wordList.add(((PString)se).utf8);
// @Override
// public ParsingObject simpleMatch(ParsingObject left, ParserContext context) {
// if(this.charset != null) {
// if(context.match(this.charset)) {
// return left;
// for(int i = 0; i < this.wordList.size(); i++) {
// if(context.match(this.wordList.ArrayValues[i])) {
// return left;
// return context.foundFailure(this);
class PAlwaysFailure extends PString {
public PAlwaysFailure(PExpression orig) {
super(orig.base, 0, "\0");
}
@Override
public void vmMatch(ParsingContext context) {
context.opFailure();
}
@Override
public void simpleMatch(ParsingStream context) {
context.foundFailure(this);
}
}
class PConnector extends PUnary {
public int index;
public PConnector(Grammar base, int flag, PExpression e, int index) {
super(base, flag | PExpression.HasConnector | PExpression.NoMemo, e);
this.index = index;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitConnector(this);
}
@Override
boolean checkFirstByte(int ch) {
return this.inner.checkFirstByte(ch);
}
@Override
public void vmMatch(ParsingContext context) {
context.opStoreObject();
this.inner.vmMatch(context);
context.opConnectObject(this.index);
}
@Override
public void simpleMatch(ParsingStream context) {
ParsingObject left = context.left;
assert(left != null);
long pos = left.getSourcePosition();
//System.out.println("== DEBUG connecting .. " + this.inner);
this.inner.simpleMatch(context);
//System.out.println("== DEBUG same? " + (context.left == left) + " by " + this.inner);
if(context.isFailure() || context.left == left) {
return;
}
if(context.canTransCapture()) {
context.logLink(left, this.index, context.left);
}
else {
left.setSourcePosition(pos);
}
context.left = left;
}
}
class PTagging extends PTerminal {
ParsingTag tag;
PTagging(Grammar base, int flag, ParsingTag tag) {
super(base, PExpression.HasTagging | PExpression.NoMemo | flag);
this.tag = tag;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitTagging(this);
}
@Override
public void vmMatch(ParsingContext context) {
context.opTagging(this.tag);
}
@Override
public void simpleMatch(ParsingStream context) {
if(!context.isRecognitionMode()) {
context.left.setTag(this.tag.tagging());
}
}
}
class PMessage extends PTerminal {
String symbol;
PMessage(Grammar base, int flag, String message) {
super(base, flag | PExpression.NoMemo | PExpression.HasMessage);
this.symbol = message;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitMessage(this);
}
@Override
public void vmMatch(ParsingContext context) {
context.opValue(this.symbol);
}
@Override
public void simpleMatch(ParsingStream context) {
if(!context.isRecognitionMode()) {
context.left.setMessage(this.symbol);
}
}
}
class PConstructor extends PList {
boolean leftJoin = false;
String tagName;
int prefetchIndex = 0;
PConstructor(Grammar base, int flag, boolean leftJoin, String tagName, UList<PExpression> list) {
super(base, flag | PExpression.HasConstructor, list);
this.leftJoin = leftJoin;
this.tagName = tagName == null ? "#new" : tagName;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitConstructor(this);
}
@Override
public void vmMatch(ParsingContext context) {
if(this.leftJoin) {
context.opLeftJoinObject(this);
}
else {
context.opNewObject(this);
}
super.vmMatch(context);
context.opCommitObject();
}
@Override
public void simpleMatch(ParsingStream context) {
long startIndex = context.getPosition();
ParsingObject left = context.left;
if(context.isRecognitionMode()) {
ParsingObject newone = context.newParsingObject(this.tagName, startIndex, this);
context.left = newone;
for(int i = 0; i < this.size(); i++) {
this.get(i).simpleMatch(context);
if(context.isFailure()) {
context.rollback(startIndex);
return;
}
}
context.left = newone;
return;
}
else {
for(int i = 0; i < this.prefetchIndex; i++) {
this.get(i).simpleMatch(context);
if(context.isFailure()) {
context.rollback(startIndex);
return;
}
}
int mark = context.markObjectStack();
ParsingObject newnode = context.newParsingObject(this.tagName, startIndex, this);
context.left = newnode;
if(this.leftJoin) {
context.logLink(newnode, -1, left);
}
for(int i = this.prefetchIndex; i < this.size(); i++) {
this.get(i).simpleMatch(context);
if(context.isFailure()) {
context.abortLinkLog(mark);
context.rollback(startIndex);
return;
}
}
context.commitLinkLog(newnode, startIndex, mark);
if(context.stat != null) {
context.stat.countObjectCreation();
}
context.left = newnode;
return;
}
}
// public void lazyMatch(ParsingObject newnode, ParsingStream context, long pos) {
// int mark = context.markObjectStack();
// for(int i = 0; i < this.size(); i++) {
// ParsingObject node = this.get(i).simpleMatch(context);
// if(context.isFailure()) {
// break; // this not happens
// context.commitLinkLog(newnode, pos, mark);
}
class PIndent extends PTerminal {
PIndent(Grammar base, int flag) {
super(base, flag | PExpression.HasContext);
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitIndent(this);
}
@Override
boolean checkFirstByte(int ch) {
return (ch == '\t' || ch == ' ');
}
@Override
public void vmMatch(ParsingContext context) {
context.opIndent();
}
@Override
public void simpleMatch(ParsingStream context) {
context.opIndent();
}
}
class PExport extends PUnary {
public PExport(Grammar base, int flag, PExpression e) {
super(base, flag | PExpression.NoMemo, e);
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitExport(this);
}
@Override
boolean checkFirstByte(int ch) {
return this.inner.checkFirstByte(ch);
}
@Override
public void vmMatch(ParsingContext context) {
}
@Override
public void simpleMatch(ParsingStream context) {
}
}
abstract class POperator extends PExpression {
PExpression inner;
protected POperator(PExpression inner) {
super(inner.base, inner.flag);
this.inner = inner;
}
@Override
protected void visit(ParsingVisitor probe) {
probe.visitOperation(this);
}
@Override
boolean checkFirstByte(int ch) {
return this.inner.checkFirstByte(ch);
}
@Override
public PExpression getExpression() {
return this.inner;
}
}
class PMemo extends POperator {
PExpression parent = null;
boolean enableMemo = true;
int memoHit = 0;
int memoMiss = 0;
protected PMemo(PExpression inner) {
super(inner);
this.semanticId = inner.semanticId;
}
@Override
public void vmMatch(ParsingContext context) {
this.inner.vmMatch(context);
}
@Override
public void simpleMatch(ParsingStream context) {
if(!this.enableMemo) {
this.inner.simpleMatch(context);
return;
}
long pos = context.getPosition();
ParsingObject left = context.left;
ObjectMemo m = context.memoMap.getMemo(this, pos);
if(m != null) {
this.memoHit += 1;
context.setPosition(pos + m.consumed);
if(m.generated == null) {
context.left = left;
return;
}
context.left = m.generated;
return;
}
this.inner.simpleMatch(context);
int length = (int)(context.getPosition() - pos);
// if(length > 0) {
if(context.left == left) {
context.memoMap.setMemo(pos, this, null, length);
}
else {
context.memoMap.setMemo(pos, this, context.left, length);
}
this.memoMiss += 1;
this.tryTracing();
}
private void tryTracing() {
if(Main.TracingMemo) {
if(this.memoMiss == 32) {
if(this.memoHit < 2) {
disabledMemo();
return;
}
}
if(this.memoMiss % 64 == 0) {
if(this.memoMiss / this.memoHit > 10) {
disabledMemo();
return;
}
}
}
}
private void disabledMemo() {
//this.show();
this.enableMemo = false;
this.base.DisabledMemo += 1;
int factor = this.base.EnabledMemo / 10;
if(factor != 0 && this.base.DisabledMemo % factor == 0) {
this.base.memoRemover.removeDisabled();
}
}
void show() {
if(Main.VerboseMode) {
double f = (double)this.memoHit / this.memoMiss;
System.out.println(this.inner.getClass().getSimpleName() + " #h/m=" + this.memoHit + "," + this.memoMiss + ", f=" + f + " " + this.inner);
}
}
// public ParsingObject simpleMatch1(ParsingObject left, ParsingStream context) {
// if(!this.enableMemo) {
// return this.inner.simpleMatch(context);
// long pos = context.getPosition();
// ObjectMemo m = context.memoMap.getMemo(this, pos);
// if(m != null) {
// this.memoHit += 1;
// assert(m.keypeg == this);
// if(m.generated == null) {
// return context.refoundFailure(this.inner, pos+m.consumed);
//// if(m.consumed > 0) {
//// //System.out.println("HIT : " + this.semanticId + ":" + pos + "," + m.consumed+ " :" + m.generated);
//// context.setPosition(pos + m.consumed);
//// return m.generated;
// return m.generated;
// ParsingObject result = this.inner.simpleMatch(context);
// if(context.isFailure()) {
// context.memoMap.setMemo(pos, this, null, /*(int)(result.getSourcePosition() - pos*/0);
// else {
// int length = (int)(context.getPosition() - pos);
//// if(length > 0) {
// context.memoMap.setMemo(pos, this, result, length);
// //System.out.println("MEMO: " + this.semanticId + ":" + pos + "," + length+ " :&" + result.id);
// this.memoMiss += 1;
// this.tryTracing();
// return result;
}
class PMatch extends POperator {
protected PMatch(PExpression inner) {
super(inner);
}
@Override
public void vmMatch(ParsingContext context) {
context.opDisableTransCapture();
this.inner.vmMatch(context);
context.opEnableTransCapture();
}
@Override
public void simpleMatch(ParsingStream context) {
boolean oldMode = context.setRecognitionMode(true);
ParsingObject left = context.left;
this.inner.simpleMatch(context);
context.setRecognitionMode(oldMode);
if(!context.isFailure()) {
context.left = left;
}
}
}
//class PCommit extends POperator {
// protected PCommit(PExpression inner) {
// super(inner);
// @Override
// public ParsingObject simpleMatch(ParsingObject left, ParsingContext2 context) {
// int mark = context.markObjectStack();
// left = this.inner.simpleMatch(left, context);
// if(left.isFailure()) {
// context.abortLinkLog(mark);
// return left;
|
package info.tregmine.gamemagic;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import org.bukkit.WorldCreator;
import org.bukkit.FireworkEffect;
import org.bukkit.Color;
import org.bukkit.World;
import org.bukkit.Chunk;
import org.bukkit.Server;
import org.bukkit.Material;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.inventory.Inventory;
import org.bukkit.block.Block;
import org.bukkit.Location;
import org.bukkit.ChatColor;
import org.bukkit.event.block.Action;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import info.tregmine.commands.ActionCommand;
import info.tregmine.database.ConnectionPool;
import info.tregmine.database.DBWalletDAO;
import info.tregmine.api.*;
public class GameMagic extends JavaPlugin implements Listener
{
private Map<Integer, String> portalLookup;
public final Logger log = Logger.getLogger("Minecraft");
public Tregmine tregmine = null;
public GameMagic()
{
portalLookup = new HashMap<Integer, String>();
}
@Override
public void onEnable()
{
PluginManager pluginMgm = getServer().getPluginManager();
pluginMgm.registerEvents(this, this);
WorldCreator alpha = new WorldCreator("alpha");
alpha.environment(World.Environment.NORMAL);
alpha.createWorld();
WorldCreator elva = new WorldCreator("elva");
elva.environment(World.Environment.NORMAL);
elva.createWorld();
WorldCreator treton = new WorldCreator("treton");
treton.environment(World.Environment.NORMAL);
treton.createWorld();
WorldCreator einhome = new WorldCreator("einhome");
einhome.environment(World.Environment.NORMAL);
einhome.createWorld();
WorldCreator citadel = new WorldCreator("citadel");
citadel.environment(World.Environment.NORMAL);
citadel.createWorld();
// Portal in tower of einhome
portalLookup.put(-1488547832, "world");
// Portal in elva
portalLookup.put(-1559526734, "world");
portalLookup.put(-1349166371, "treton");
portalLookup.put(1371197620, "citadel");
// portals in world
portalLookup.put(-973919203, "treton");
portalLookup.put(-777405698, "treton");
portalLookup.put(1259780606, "citadel");
portalLookup.put(690186900, "elva");
portalLookup.put(209068875, "einhome");
// portals in TRETON
portalLookup.put(45939467, "world");
portalLookup.put(-1408237330, "citadel");
portalLookup.put(559131756, "elva");
// portals in CITADEL
portalLookup.put(1609346891, "world");
portalLookup.put(-449465967, "treton");
portalLookup.put(1112623336, "elva");
// Shoot fireworks at spawn
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this,
new Runnable() {
public void run() {
World world = GameMagic.this.getServer().getWorld("world");
Location loc = world.getSpawnLocation();
FireworksFactory factory = new FireworksFactory();
factory.addColor(Color.BLUE);
factory.addColor(Color.YELLOW);
factory.addType(FireworkEffect.Type.STAR);
factory.shot(loc);
}
}, 100L, 200L);
//Check for tregmine plugin
Plugin test = this.getServer().getPluginManager().getPlugin("tregmine");
if(this.tregmine == null) {
if(test != null) {
this.tregmine = ((Tregmine)test);
} else {
log.info(this.getDescription().getName() + " " + this.getDescription().getVersion() + " - could not find Tregmine");
this.getServer().getPluginManager().disablePlugin(this);
}
}
getServer().getPluginManager().registerEvents(new Gates(this), this);
}
public static int locationChecksum(Location loc)
{
int checksum = (loc.getBlockX() + "," +
loc.getBlockZ() + "," +
loc.getBlockY() + "," +
loc.getWorld().getName()).hashCode();
return checksum;
}
private void gotoWorld(Player player, Location loc)
{
Inventory inventory = player.getInventory();
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) != null) {
player.sendMessage(ChatColor.RED + "You are carrying too much " +
"for the portal's magic to work.");
return;
}
}
World world = loc.getWorld();
Chunk chunk = world.getChunkAt(loc);
world.loadChunk(chunk);
if (world.isChunkLoaded(chunk)) {
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for traveling with " +
"TregPort!");
} else {
player.sendMessage(ChatColor.RED + "The portal needs some " +
"preparation. Please try again!");
}
}
@EventHandler
public void buttons(PlayerInteractEvent event)
{
if (event.getAction() == Action.LEFT_CLICK_AIR ||
event.getAction() == Action.RIGHT_CLICK_AIR) {
return;
}
Block block = event.getClickedBlock();
Player player = event.getPlayer();
int checksum = locationChecksum(block.getLocation());
if (!portalLookup.containsKey(checksum)) {
return;
}
String worldName = portalLookup.get(checksum);
Location loc = getServer().getWorld(worldName).getSpawnLocation();
gotoWorld(player, loc);
}
@EventHandler
public void onPlayerBucketFill(PlayerBucketFillEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{
if (event.getBucket() == Material.LAVA_BUCKET) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onCreatureSpawn(CreatureSpawnEvent event)
{
if (event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
event.setCancelled(true);
}
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onBlockBurn(BlockBurnEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onLeavesDecay(LeavesDecayEvent event)
{
Location l = event.getBlock().getLocation();
Block fence =
event.getBlock()
.getWorld()
.getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ());
if (fence.getType() == Material.FENCE) {
event.setCancelled(true);
}
}
@EventHandler
public void onBlockIgnite(BlockIgniteEvent event)
{
event.setCancelled(true);
Location l = event.getBlock().getLocation();
Block block =
event.getBlock()
.getWorld()
.getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ());
if (block.getType() == Material.OBSIDIAN) {
event.setCancelled(false);
}
}
}
|
package org.spine3.time;
import java.util.Calendar;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Calendar.DAY_OF_MONTH;
import static java.util.Calendar.HOUR;
import static java.util.Calendar.MILLISECOND;
import static java.util.Calendar.MINUTE;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.SECOND;
import static java.util.Calendar.YEAR;
import static org.spine3.time.Calendars.nowAt;
import static org.spine3.time.Calendars.toLocalDate;
import static org.spine3.time.Calendars.toLocalTime;
import static org.spine3.validate.Validate.checkPositive;
/**
* Routines for working with {@link OffsetDateTime}.
*
* @author Alexander Aleksandrov
*/
@SuppressWarnings("ClassWithTooManyMethods")
public class OffsetDateTimes {
private OffsetDateTimes() {
}
/**
* Obtains current OffsetDateTime instance using {@code ZoneOffset}.
*/
public static OffsetDateTime now(ZoneOffset zoneOffset) {
checkNotNull(zoneOffset);
final Calendar now = nowAt(zoneOffset);
final LocalTime localTime = toLocalTime(now);
final LocalDate localDate = toLocalDate(now);
final OffsetDateTime result = OffsetDateTime.newBuilder()
.setDate(localDate)
.setTime(localTime)
.setOffset(zoneOffset)
.build();
return result;
}
/**
* Obtains OffsetDateTime instance using {@code LocalDate}, {@code LocalTime} and {@code ZoneOffset}.
*/
public static OffsetDateTime of(LocalDate localDate, LocalTime localTime, ZoneOffset zoneOffset) {
final OffsetDateTime result = OffsetDateTime.newBuilder()
.setDate(localDate)
.setTime(localTime)
.setOffset(zoneOffset)
.build();
return result;
}
/**
* Obtains a copy of this offset date and time with the specified number of years added.
*/
public static OffsetDateTime plusYears(OffsetDateTime offsetDateTime, int yearsToAdd) {
checkNotNull(offsetDateTime);
checkPositive(yearsToAdd);
return changeYear(offsetDateTime, yearsToAdd);
}
/**
* Obtains a copy of this offset date and time with the specified number of months added.
*/
public static OffsetDateTime plusMonths(OffsetDateTime offsetDateTime, int monthsToAdd) {
checkNotNull(offsetDateTime);
checkPositive(monthsToAdd);
return changeMonth(offsetDateTime, monthsToAdd);
}
/**
* Obtains a copy of this offset date and time with the specified number of days added.
*/
public static OffsetDateTime plusDays(OffsetDateTime offsetDateTime, int daysToAdd) {
checkNotNull(offsetDateTime);
checkPositive(daysToAdd);
return changeDays(offsetDateTime, daysToAdd);
}
/**
* Obtains a copy of this offset date and time with the specified number of hours added.
*/
public static OffsetDateTime plusHours(OffsetDateTime offsetDateTime, int hoursToAdd) {
checkNotNull(offsetDateTime);
checkPositive(hoursToAdd);
return changeHours(offsetDateTime, hoursToAdd);
}
/**
* Obtains a copy of this offset date and time with the specified number of minutes added.
*/
public static OffsetDateTime plusMinutes(OffsetDateTime offsetDateTime, int minutesToAdd) {
checkNotNull(offsetDateTime);
checkPositive(minutesToAdd);
return changeMinutes(offsetDateTime, minutesToAdd);
}
/**
* Obtains a copy of this offset date and time with the specified number of seconds added.
*/
public static OffsetDateTime plusSeconds(OffsetDateTime offsetDateTime, int secondsToAdd) {
checkNotNull(offsetDateTime);
checkPositive(secondsToAdd);
return changeSeconds(offsetDateTime, secondsToAdd);
}
/**
* Obtains a copy of this offset date and time with the specified number of milliseconds added.
*/
public static OffsetDateTime plusMillis(OffsetDateTime offsetDateTime, int millisToAdd) {
checkNotNull(offsetDateTime);
checkPositive(millisToAdd);
return changeMillis(offsetDateTime, millisToAdd);
}
/**
* Obtains a copy of this offset date and time with the specified number of years subtracted.
*/
public static OffsetDateTime minusYears(OffsetDateTime offsetDateTime, int yearsToSubtract) {
checkNotNull(offsetDateTime);
checkPositive(yearsToSubtract);
return changeYear(offsetDateTime, -yearsToSubtract);
}
/**
* Obtains a copy of this offset date and time with the specified number of months subtracted.
*/
public static OffsetDateTime minusMonths(OffsetDateTime offsetDateTime, int monthsToSubtract) {
checkNotNull(offsetDateTime);
checkPositive(monthsToSubtract);
return changeMonth(offsetDateTime, -monthsToSubtract);
}
/**
* Obtains a copy of this offset date and time with the specified number of days subtracted.
*/
public static OffsetDateTime minusDays(OffsetDateTime offsetDateTime, int daysToSubtract) {
checkNotNull(offsetDateTime);
checkPositive(daysToSubtract);
return changeDays(offsetDateTime, -daysToSubtract);
}
/**
* Obtains a copy of this offset date and time with the specified number of hours subtracted.
*/
public static OffsetDateTime minusHours(OffsetDateTime offsetDateTime, int hoursToSubtract) {
checkNotNull(offsetDateTime);
checkPositive(hoursToSubtract);
return changeHours(offsetDateTime, -hoursToSubtract);
}
/**
* Obtains a copy of this offset date and time with the specified number of minutes subtracted.
*/
public static OffsetDateTime minusMinutes(OffsetDateTime offsetDateTime, int minutesToSubtract) {
checkNotNull(offsetDateTime);
checkPositive(minutesToSubtract);
return changeMinutes(offsetDateTime, -minutesToSubtract);
}
/**
* Obtains a copy of this offset date and time with the specified number of seconds subtracted.
*/
public static OffsetDateTime minusSeconds(OffsetDateTime offsetDateTime, int secondsToSubtract) {
checkNotNull(offsetDateTime);
checkPositive(secondsToSubtract);
return changeSeconds(offsetDateTime, -secondsToSubtract);
}
/**
* Obtains a copy of this offset date and time with the specified number of milliseconds subtracted.
*/
public static OffsetDateTime minusMillis(OffsetDateTime offsetDateTime, int millisToSubtract) {
checkNotNull(offsetDateTime);
checkPositive(millisToSubtract);
return changeMillis(offsetDateTime, -millisToSubtract);
}
/**
* Obtains offset date and time changed on specified amount of years.
*
* @param offsetDateTime offset date and time that will be changed
* @param yearsDelta a number of years that needs to be added or subtracted that can be either positive or negative
* @return copy of this offset date and time with new years value
*/
private static OffsetDateTime changeYear(OffsetDateTime offsetDateTime, int yearsDelta) {
return add(offsetDateTime, YEAR, yearsDelta);
}
/**
* Obtains offset date and time changed on specified amount of months.
*
* @param offsetDateTime offset date that will be changed
* @param monthDelta a number of months that needs to be added or subtracted that can be either positive or negative
* @return copy of this offset date and time with new months value
*/
private static OffsetDateTime changeMonth(OffsetDateTime offsetDateTime, int monthDelta) {
return add(offsetDateTime, MONTH, monthDelta);
}
/**
* Obtains offset date and time changed on specified amount of days.
*
* @param offsetDateTime offset date that will be changed
* @param daysDelta a number of days that needs to be added or subtracted that can be either positive or negative
* @return copy of this offset date and time with new days value
*/
private static OffsetDateTime changeDays(OffsetDateTime offsetDateTime, int daysDelta) {
return add(offsetDateTime, DAY_OF_MONTH, daysDelta);
}
/**
* Obtains offset date and time changed on specified amount of hours.
*
* @param offsetDateTime offset date and time that will be changed
* @param hoursDelta a number of hours that needs to be added or subtracted that can be either positive or negative
* @return copy of this offset date and time with new hours value
*/
private static OffsetDateTime changeHours(OffsetDateTime offsetDateTime, int hoursDelta) {
return add(offsetDateTime, HOUR, hoursDelta);
}
/**
* Obtains offset date and time changed on specified amount of minutes.
*
* @param offsetDateTime offset date and time that will be changed
* @param minutesDelta a number of minutes that needs to be added or subtracted that can be either positive or negative
* @return copy of this offset date and time with new minutes value
*/
private static OffsetDateTime changeMinutes(OffsetDateTime offsetDateTime, int minutesDelta) {
return add(offsetDateTime, MINUTE, minutesDelta);
}
/**
* Obtains offset date and time changed on specified amount of seconds.
*
* @param offsetDateTime offset date and time that will be changed
* @param secondsDelta a number of seconds that needs to be added or subtracted that can be either positive or negative
* @return copy of this offset date and time with new seconds value
*/
private static OffsetDateTime changeSeconds(OffsetDateTime offsetDateTime, int secondsDelta) {
return add(offsetDateTime, SECOND, secondsDelta);
}
/**
* Obtains offset date and time changed on specified amount of milliseconds.
*
* @param dateTime offset date and time that will be changed
* @param millisDelta a number of milliseconds that needs to be added or subtracted that can be either positive or negative
* @return copy of this offset date and time with new milliseconds value
*/
private static OffsetDateTime changeMillis(OffsetDateTime dateTime, int millisDelta) {
return add(dateTime, MILLISECOND, millisDelta);
}
/**
* Performs date and time calculation using parameters of {@link Calendar#add(int, int)}.
*/
private static OffsetDateTime add(OffsetDateTime dateTime, int calendarField, int delta) {
final Calendar calendar = Calendars.toCalendar(dateTime);
calendar.add(calendarField, delta);
final LocalDate localDate = toLocalDate(calendar);
final LocalTime localTime = toLocalTime(calendar);
final long nanos = dateTime.getTime()
.getNanos();
final LocalTime localTimeWithNanos = localTime.toBuilder()
.setNanos(nanos)
.build();
return withDateTime(dateTime, localDate, localTimeWithNanos);
}
/**
* Returns a new instance of offset date and time with changed local date or local time parameter.
*
* @param offsetDateTime offset date and time that will be changed
* @param date new local date for this offset date and time
* @param time new local time for this offset date and time
* @return new {@code OffsetDateTime} instance with changed parameter
*/
private static OffsetDateTime withDateTime(OffsetDateTime offsetDateTime, LocalDate date, LocalTime time) {
return offsetDateTime.toBuilder()
.setDate(date)
.setTime(time)
.build();
}
}
|
package VASSAL.build.module;
import VASSAL.tools.ProblemDialog;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URL;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.FontConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.preferences.Prefs;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.KeyStrokeSource;
import VASSAL.tools.ScrollPane;
/**
* The chat window component. Displays text messages and accepts input. Also
* acts as a {@link CommandEncoder}, encoding/decoding commands that display
* message in the text area
*/
public class Chatter extends JPanel implements CommandEncoder, Buildable {
private static final long serialVersionUID = 1L;
protected JTextPane conversationPane;
protected HTMLDocument doc;
protected HTMLEditorKit kit;
protected StyleSheet style;
protected JTextField input;
protected JScrollPane scroll = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
protected JScrollPane scroll2 = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
protected static final String MY_CHAT_COLOR = "HTMLChatColor"; //$NON-NLS-1$ // Different tags to "restart" w/ new default scheme
protected static final String OTHER_CHAT_COLOR = "HTMLotherChatColor"; //$NON-NLS-1$
protected static final String GAME_MSG1_COLOR = "HTMLgameMessage1Color"; //$NON-NLS-1$
protected static final String GAME_MSG2_COLOR = "HTMLgameMessage2Color"; //$NON-NLS-1$
protected static final String GAME_MSG3_COLOR = "HTMLgameMessage3Color"; //$NON-NLS-1$
protected static final String GAME_MSG4_COLOR = "HTMLgameMessage4Color"; //$NON-NLS-1$
protected static final String GAME_MSG5_COLOR = "HTMLgameMessage5Color"; //$NON-NLS-1$
protected static final String SYS_MSG_COLOR = "HTMLsystemMessageColor"; //$NON-NLS-1$
@Deprecated(since = "2020-08-06", forRemoval = true)
protected static final String GAME_MSG_COLOR = "gameMessageColor";
protected Font myFont;
protected Color gameMsg, gameMsg2, gameMsg3, gameMsg4, gameMsg5;
protected Color systemMsg, myChat, otherChat;
protected boolean needUpdate;
protected JTextArea conversation; // Backward compatibility for overridden classes. Needs something to suppress.
public static String getAnonymousUserName() {
return Resources.getString("Chat.anonymous"); //$NON-NLS-1$
}
public Chatter() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
conversation = new JTextArea(); // For backward override compatibility only.
//BR// Conversation is now a JTextPane w/ HTMLEditorKit to process HTML, which gives us HTML support "for free".
conversationPane = new JTextPane();
conversationPane.setContentType("text/html");
doc = (HTMLDocument) conversationPane.getDocument();
kit = (HTMLEditorKit) conversationPane.getEditorKit();
style = kit.getStyleSheet();
myFont = new Font("SansSerif", Font.PLAIN, 12); // Will be overridden by the font from Chat preferences
try {
for (int i = 0; i < 15; ++i) {
kit.insertHTML(doc, doc.getLength(), "<br>", 0, 0, null);
}
}
catch (BadLocationException | IOException ble) {
ErrorDialog.bug(ble);
}
conversationPane.setEditable(false);
conversationPane.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
scroll.getVerticalScrollBar().setValue(scroll.getVerticalScrollBar().getMaximum());
}
});
input = new JTextField(60);
input.setFocusTraversalKeysEnabled(false);
input.addActionListener(e -> {
send(formatChat(e.getActionCommand()));
input.setText(""); //$NON-NLS-1$
});
input.setMaximumSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height));
FontMetrics fm = getFontMetrics(myFont);
int fontHeight = fm.getHeight();
conversationPane.setPreferredSize(new Dimension(input.getMaximumSize().width, fontHeight * 10));
scroll.setViewportView(conversationPane);
scroll.getVerticalScrollBar().setUnitIncrement(input.getPreferredSize().height); //Scroll this faster
add(scroll);
add(input);
setPreferredSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height + conversationPane.getPreferredSize().height));
}
/**
* Because our Chatters make themselves visible in their constructor, providing a way for an overriding class to
* "turn this chatter off" is friendlier than What Went Before.
*
* @param vis - whether this chatter should be visible
*/
protected void setChatterVisible(boolean vis) {
conversationPane.setVisible(vis);
input.setVisible(vis);
scroll.setVisible(vis);
}
protected String formatChat(String text) {
final String id = GlobalOptions.getInstance().getPlayerId();
return String.format("<%s> - %s", id.isEmpty() ? "(" + getAnonymousUserName() + ")" : id, text); //HTML-friendly angle brackets //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public JTextField getInputField() {
return input;
}
/**
* Styles a chat message based on the player who sent it. Presently just distinguishes a chat message "from me" from a chat message "from anyone else".
*
* To make the player colors easy to override in a custom class
* (my modules have logic to assign individual player colors -- beyond the scope of the present effort but a perhaps a fun future addition)
* @param s - chat message from a player
* @return - an entry in our CSS style sheet to use for this chat message
*/
protected String getChatStyle(String s) {
return s.startsWith(formatChat("").trim()) ? "mychat" : "other";
}
/**
* A hook for inserting a console class that accepts commands
* @param s - chat message
* @param style - current style name (contains information that might be useful)
* @param html_allowed - flag if html_processing is enabled for this message (allows console to apply security considerations)
* @return true - if was accepted as a console command
*/
@SuppressWarnings("unused")
public boolean consoleHook(String s, String style, boolean html_allowed) {
return false;
}
/**
* Display a message in the text area. Ensures we execute in the EDT
*/
public void show(String s) {
if (SwingUtilities.isEventDispatchThread()) {
doShow(s);
}
else {
SwingUtilities.invokeLater(() -> doShow(s));
}
}
/**
* Display a message in the text area - use show() from outside the class - MUST run on EventDispatchThread
*/
private void doShow(String s) {
String style;
boolean html_allowed;
// Choose an appropriate style to display this message in
s = s.trim();
if (!s.isEmpty()) {
if (s.startsWith("*")) {
// Here we just extend the convention of looking at first characters, this time to the second character.
// | = msg1 (w/ HTML parsing explicitly opted in)
// ! = msg2
// ? = msg3
// ~ = msg4
// ` = msg5
// These characters can be pre-pended to Report messages to produce the color changes. The characters themselves are removed before display.
// Reports can also include <b></b> tags for bold and <i></i> for italic.
if (s.startsWith("* |") || s.startsWith("*|")) {
style = "msg";
s = s.replaceFirst("\\|", "");
html_allowed = true;
}
else if (s.startsWith("* !") || s.startsWith("*!")) {
style = "msg2";
s = s.replaceFirst("!", "");
html_allowed = true;
}
else if (s.startsWith("* ?") || s.startsWith("*?")) {
style = "msg3";
s = s.replaceFirst("\\?", "");
html_allowed = true;
}
else if (s.startsWith("* ~") || s.startsWith("*~")) {
style = "msg4";
s = s.replaceFirst("~", "");
html_allowed = true;
}
else if (s.startsWith("* `") || s.startsWith("*`")) {
style = "msg5";
s = s.replaceFirst("`", "");
html_allowed = true;
}
else {
style = "msg";
html_allowed = GlobalOptions.getInstance().chatterHTMLSupport(); // Generic report lines check compatibility flag (so old modules will not break on e.g. "<" in messages)
}
}
else if (s.startsWith("-")) {
style = "sys";
html_allowed = true;
}
else {
style = getChatStyle(s);
html_allowed = false;
}
}
else {
style = "msg";
html_allowed = false;
}
// Disable unwanted HTML tags in contexts where it shouldn't be allowed:
// (1) Anything received from chat channel, for security reasons
// (2) Legacy module "report" text when not explicitly opted in w/ first character or preference setting
if (!html_allowed) {
s = s.replaceAll("<", "<") // This prevents any unwanted tag from functioning
.replaceAll(">", ">"); // This makes sure > doesn't break any of our legit <div> tags
}
// Systematically search through for html image tags. When we find one, try
// to match it with an image from our DataArchive, and substitute the correct
// fully qualified URL into the tag.
URL url;
String keystring = "<img src=\"";
String file, tag, replace;
int base;
while (s.toLowerCase().contains(keystring)) { // Find next key (to-lower so we're not case sensitive)
base = s.toLowerCase().indexOf(keystring);
file = s.substring(base + keystring.length()).split("\"")[0]; // Pull the filename out from between the quotes
tag = s.substring(base, base + keystring.length()) + file + "\""; // Reconstruct the part of the tag we want to remove, leaving all attributes after the filename alone, and properly matching the upper/lowercase of the keystring
try {
url = GameModule.getGameModule().getDataArchive().getURL("images/" + file);
replace = "<img src=\"" + url.toString() + "\""; // Fully qualified URL if we are successful. The extra
// space between IMG and SRC in the processed
// version ensures we don't re-find THIS tag as we iterate
}
catch (IOException ex) {
replace = "<img src=\"" + file + "\""; // Or just leave in except alter just enough that we won't find this tag again
}
if (s.contains(tag)) {
s = s.replaceFirst(tag, replace); // Swap in our new URL-laden tag for the old one.
}
else {
break; // If something went wrong in matching up the tag, don't loop forever
}
}
// Now we have to fix up any legacy angle brackets around the word <observer>
keystring = Resources.getString("PlayerRoster.observer");
replace = keystring.replace("<", "<").replace(">", ">");
if (!replace.equals(keystring)) {
s = s.replace(keystring, replace);
}
// Insert a div of the correct style for our line of text. Module designer
// still free to insert <span> tags and <img> tags and the like in Report
// messages.
try {
kit.insertHTML(doc, doc.getLength(), "\n<div class=" + style + ">" + s + "</div>", 0, 0, null);
}
catch (BadLocationException | IOException ble) {
ErrorDialog.bug(ble);
}
conversationPane.repaint();
consoleHook(s, style, html_allowed);
}
/**
* Adds or updates a CSS stylesheet entry. Styles in the color, font type, and font size.
* @param s Style name
* @param f Font to use
* @param c Color for text
* @param font_weight Bold? Italic?
* @param size Font size
*/
protected void addStyle(String s, Font f, Color c, String font_weight, int size) {
if ((style == null) || (c == null)) return;
style.addRule(s +
" {color:" +
String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()) +
"; font-family:" +
f.getFamily() +
"; font-size:" +
(size > 0 ? size : f.getSize()) +
"; " +
((!font_weight.isBlank()) ? "font-weight:" + font_weight + "; " : "") +
"}");
}
/**
* Build ourselves a CSS stylesheet from our preference font/color settings.
* @param f - Font to use for this stylesheet
*/
protected void makeStyleSheet(Font f) {
if (style == null) {
return;
}
if (f == null) {
if (myFont == null) {
f = new Font("SansSerif", Font.PLAIN, 12);
myFont = f;
}
else {
f = myFont;
}
}
addStyle(".msg", f, gameMsg, "", 0);
addStyle(".msg2", f, gameMsg2, "", 0);
addStyle(".msg3", f, gameMsg3, "", 0);
addStyle(".msg4", f, gameMsg4, "", 0);
addStyle(".msg5", f, gameMsg5, "", 0);
addStyle(".mychat", f, myChat, "bold", 0);
addStyle(".other ", f, otherChat, "bold", 0);
addStyle(".sys", f, systemMsg, "", 0);
// A fun extension would be letting the module designer provide extra class styles.
}
/**
* Set the Font used by the text area
*/
@Override
public void setFont(Font f) {
myFont = f;
if (input != null) {
if (input.getText().isEmpty()) {
input.setText("XXX"); //$NON-NLS-1$
input.setFont(f);
input.setText(""); //$NON-NLS-1$
}
else {
input.setFont(f);
}
}
if (conversationPane != null) {
conversationPane.setFont(f);
}
makeStyleSheet(f); // When font changes, rebuild our stylesheet
}
@Override
public void build(org.w3c.dom.Element e) {
}
@Override
public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc) {
return doc.createElement(getClass().getName());
}
/**
* Expects to be added to a GameModule. Adds itself to the controls window and
* registers itself as a {@link CommandEncoder}
*/
@Override
public void addTo(Buildable b) {
GameModule mod = (GameModule) b;
mod.setChatter(this);
mod.addCommandEncoder(this);
mod.addKeyStrokeSource(new KeyStrokeSource(this, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
final FontConfigurer chatFont = new FontConfigurer("ChatFont",
Resources.getString("Chatter.chat_font_preference"));
chatFont.addPropertyChangeListener(evt -> setFont((Font) evt.getNewValue()));
mod.getPlayerWindow().addChatter(this);
chatFont.fireUpdate();
mod.getPrefs().addOption(Resources.getString("Chatter.chat_window"), chatFont); //$NON-NLS-1$
// Bug 10179 - Do not re-read Chat colors each time the Chat Window is
// repainted.
final Prefs globalPrefs = Prefs.getGlobalPrefs();
// game message color
final ColorConfigurer gameMsgColor = new ColorConfigurer(GAME_MSG1_COLOR,
Resources.getString("Chatter.game_messages_preference"), Color.black);
gameMsgColor.addPropertyChangeListener(e -> {
gameMsg = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsgColor);
gameMsg = (Color) globalPrefs.getValue(GAME_MSG1_COLOR);
// game message color #2 (messages starting with "!")
final ColorConfigurer gameMsg2Color = new ColorConfigurer(GAME_MSG2_COLOR,
Resources.getString("Chatter.game_messages_preference_2"), new Color(0, 153, 51));
gameMsg2Color.addPropertyChangeListener(e -> {
gameMsg2 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg2Color);
gameMsg2 = (Color) globalPrefs.getValue(GAME_MSG2_COLOR);
// game message color #3 (messages starting with "?")
final ColorConfigurer gameMsg3Color = new ColorConfigurer(GAME_MSG3_COLOR,
Resources.getString("Chatter.game_messages_preference_3"), new Color(255, 102, 102));
gameMsg3Color.addPropertyChangeListener(e -> {
gameMsg3 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg3Color);
gameMsg3 = (Color) globalPrefs.getValue(GAME_MSG3_COLOR);
// game message color #4 (messages starting with "~")
final ColorConfigurer gameMsg4Color = new ColorConfigurer(GAME_MSG4_COLOR,
Resources.getString("Chatter.game_messages_preference_4"), new Color(255, 0, 0));
gameMsg4Color.addPropertyChangeListener(e -> {
gameMsg4 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg4Color);
gameMsg4 = (Color) globalPrefs.getValue(GAME_MSG4_COLOR);
// game message color #5 (messages starting with "`")
final ColorConfigurer gameMsg5Color = new ColorConfigurer(GAME_MSG5_COLOR,
Resources.getString("Chatter.game_messages_preference_5"), new Color(153, 0, 153));
gameMsg5Color.addPropertyChangeListener(e -> {
gameMsg5 = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg5Color);
gameMsg5 = (Color) globalPrefs.getValue(GAME_MSG5_COLOR);
final ColorConfigurer systemMsgColor = new ColorConfigurer(SYS_MSG_COLOR,
Resources.getString("Chatter.system_message_preference"), new Color(160, 160, 160));
systemMsgColor.addPropertyChangeListener(e -> {
systemMsg = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), systemMsgColor);
systemMsg = (Color) globalPrefs.getValue(SYS_MSG_COLOR);
final ColorConfigurer myChatColor = new ColorConfigurer(
MY_CHAT_COLOR,
Resources.getString("Chatter.my_text_preference"),
new Color(9, 32, 229));
myChatColor.addPropertyChangeListener(e -> {
myChat = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), myChatColor);
myChat = (Color) globalPrefs.getValue(MY_CHAT_COLOR);
final ColorConfigurer otherChatColor = new ColorConfigurer(OTHER_CHAT_COLOR,
Resources.getString("Chatter.other_text_preference"), new Color (0, 153, 255));
otherChatColor.addPropertyChangeListener(e -> {
otherChat = (Color) e.getNewValue();
makeStyleSheet(null);
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), otherChatColor);
otherChat = (Color) globalPrefs.getValue(OTHER_CHAT_COLOR);
// Put up the HTML Enable/Disable checkbox if we're supposed to have it.
if (GlobalOptions.PROMPT.equals(GlobalOptions.getInstance().chatterHTMLSetting())) {
BooleanConfigurer config2 = new BooleanConfigurer(GlobalOptions.CHATTER_HTML_SUPPORT, Resources.getString("GlobalOptions.chatter_html_support")); //$NON-NLS-1$
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), config2);
}
makeStyleSheet(myFont);
}
@Override
public void add(Buildable b) {
}
@Override
public Command decode(String s) {
if (s.startsWith("CHAT")) { //$NON-NLS-1$
return new DisplayText(this, s.substring(4));
}
else {
return null;
}
}
@Override
public String encode(Command c) {
if (c instanceof DisplayText) {
return "CHAT" + ((VASSAL.build.module.Chatter.DisplayText) c).getMessage(); //$NON-NLS-1$
}
else {
return null;
}
}
/**
* Displays the message, Also logs and sends to the server a {@link Command}
* that displays this message.
*/
public void send(String msg) {
if (msg != null && !msg.isEmpty()) {
show(msg);
GameModule.getGameModule().sendAndLog(new DisplayText(this, msg));
}
}
/**
* Warning message method -- same as send, but accepts messages from static methods. For reporting soft-fail problems in modules.
*/
public static void warning(String msg) {
Chatter chatter = GameModule.getGameModule().getChatter();
chatter.send(msg);
}
/**
* Classes other than the Chatter itself may forward KeyEvents to the Chatter by
* using this method
*/
public void keyCommand(KeyStroke e) {
if ((e.getKeyCode() == 0 || e.getKeyCode() == KeyEvent.CHAR_UNDEFINED)
&& !Character.isISOControl(e.getKeyChar())) {
input.setText(input.getText() + e.getKeyChar());
}
else if (e.isOnKeyRelease()) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
if (!input.getText().isEmpty())
send(formatChat(input.getText()));
input.setText(""); //$NON-NLS-1$
break;
case KeyEvent.VK_BACK_SPACE:
case KeyEvent.VK_DELETE:
String s = input.getText();
if (!s.isEmpty())
input.setText(s.substring(0, s.length() - 1));
break;
}
}
}
/**
* This is a {@link Command} object that, when executed, displays
* a text message in the Chatter's text area */
public static class DisplayText extends Command {
private String msg;
private final Chatter c;
public DisplayText(Chatter c, String s) {
this.c = c;
msg = s;
if (msg.startsWith("<>")) {
msg = "<(" + Chatter.getAnonymousUserName() + ")>" + s.substring(2); // HTML-friendly
// angle brackets
}
else {
msg = s;
}
}
@Override
public void executeCommand() {
c.show(msg);
}
@Override
public Command myUndoCommand() {
return new DisplayText(c, Resources.getString("Chatter.undo_message", msg)); //$NON-NLS-1$
}
public String getMessage() {
return msg;
}
@Override
public String getDetails() {
return msg;
}
}
public static void main(String[] args) {
Chatter chat = new Chatter();
JFrame f = new JFrame();
f.add(chat);
f.pack();
f.setVisible(true);
}
/** @deprecated No Replacement */
@Deprecated(since = "2020-08-06", forRemoval = true)
public void setHandle(@SuppressWarnings("unused") String s) {
ProblemDialog.showDeprecated("2020-08-06");
}
/** @deprecated use {@link GlobalOptions#getPlayerId()} */
@Deprecated(since = "2020-08-06", forRemoval = true)
public String getHandle() {
ProblemDialog.showDeprecated("2020-08-06");
return GlobalOptions.getInstance().getPlayerId();
}
}
|
package VASSAL.build.module;
import VASSAL.Info;
import VASSAL.build.GameModule;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.command.Logger;
import VASSAL.tools.BugUtils;
import VASSAL.tools.SequenceEncoder;
import org.slf4j.LoggerFactory;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Expandable "Console" to allow entering commands into the Chatter.
*/
public class Console {
SequenceEncoder.Decoder decode;
String commandLine;
private static final org.slf4j.Logger log =
LoggerFactory.getLogger(Console.class);
private void show(String s) {
GameModule.getGameModule().warn(s);
}
private boolean matches(String s1, String s2) {
return matches(s1, s2, 2);
}
private boolean matches(String s1, String s2, int min) {
if (s2.isEmpty() || (s2.length() > s1.length()) || ((s2.length() < min) && (s1.length() > s2.length()))) {
return false;
}
if (s2.length() < min) {
return s1.toLowerCase().equals(s2.toLowerCase());
}
return s1.toLowerCase().substring(0, s2.length()).equals(s2.toLowerCase());
}
/**
* Opens the specified file (or folder) using the Desktop's default method
* @param file file or folder to open
*/
private void browseFileOrFolder(File file) {
final Desktop desktop = Desktop.getDesktop();
try {
desktop.open(file);
}
catch (IOException e) {
log.error("File Not Found", e); //NON-NLS
}
catch (IllegalArgumentException iae) {
log.error("Illegal argument", iae); //NON-NLS
}
}
private boolean doErrorLog() {
final String option = decode.nextToken("");
if (matches("show", option)) { //NON-NLS
final String errorLog = BugUtils.getErrorLog();
final String delims2 = "[\n]+";
final String[] lines = errorLog.split(delims2);
if (lines.length > 0) {
final int end = lines.length - 1;
final int linesToShow = decode.nextInt(0);
final int start = (linesToShow <= 0) ? 0 : Math.max(0, end - linesToShow + 1);
for (int line = start; line <= end; line++) {
show(lines[line]);
}
}
}
else if (matches("write", option)) { //NON-NLS
final int where = commandLine.toLowerCase().indexOf("write"); //NON-NLS
if ((where > 0) && commandLine.length() > where + 6) {
log.info(commandLine.substring(where + 6));
}
}
else if (matches("folder", option)) { //NON-NLS
browseFileOrFolder(Info.getConfDir());
}
else if (matches("noecho", option)) { //NON-NLS
GameModule.setErrorLogToChat(false);
show("Errorlog Echo: OFF"); //NON-NLS
}
else if (matches("echo", option)) { //NON-NLS
GameModule.setErrorLogToChat(true);
show("Errorlog Echo: ON"); //NON-NLS
}
else if (matches("open", option)) { //NON-NLS
browseFileOrFolder(Info.getErrorLogPath());
}
else if (matches("wipe", option)) { //NON-NLS
final File errorLog = Info.getErrorLogPath();
try {
new FileOutputStream(errorLog).close();
show("Wiped errorlog"); //NON-NLS
}
catch (IOException e) {
show("Failed to wipe errorlog"); //NON-NLS
}
}
else if (matches("?", option) || matches("help", option) || ("".equals(option))) { //NON-NLS
show("Usage:"); //NON-NLS
show(" /errorlog echo - Echoes new errorlog info in chat log"); //NON-NLS
show(" /errorlog folder - Opens folder containing errorlog"); //NON-NLS
show(" /errorlog noecho - Disables echoing of errorlog info in chat log"); //NON-NLS
show(" /errorlog open - Opens errorlog in OS"); //NON-NLS
show(" /errorlog show [n] - Show last n lines of errorlog"); //NON-NLS
show(" /errorlog wipe - Wipe the errorlog file"); //NON-NLS
show(" /errorlog write [text] - Write text into the errorlog file"); //NON-NLS
}
else {
show("Unknown command."); //NON-NLS
show("Use '/errorlog help' for usage info."); //NON-NLS
}
return true;
}
private boolean doProperty() {
final String option = decode.nextToken("");
final String property = decode.nextToken("");
if (matches("?", option) || matches("help", option)) { //NON-NLS
show("Usage:"); //NON-NLS
show(" /property show [property] - show global property value"); //NON-NLS
show(" /property set [property] [value] - set global property new value"); //NON-NLS
}
else if (matches("show", option)) { //NON-NLS
final MutableProperty.Impl propValue = (MutableProperty.Impl) GameModule.getGameModule().getMutableProperty(property);
if (propValue != null) {
show("[" + property + "]: " + propValue.getPropertyValue());
}
}
else if (matches("set", option)) { //NON-NLS
final MutableProperty.Impl propValue = (MutableProperty.Impl) GameModule.getGameModule().getMutableProperty(property);
if (propValue != null) {
propValue.setPropertyValue(decode.nextToken(""));
show("[" + property + "]: " + propValue.getPropertyValue());
}
}
return true;
}
public boolean consoleHook(String s, String commandLine, String cl, String command, SequenceEncoder.Decoder decode) {
// Hook for console subclasses, etc.
return false;
}
public boolean exec(String s, String style, boolean html_allowed) {
if (s.charAt(0) != '/') {
return false;
}
commandLine = s.substring(1);
// If this has EVER been a multiplayer game (has ever been connected to Server, or has ever had two player slots filled simultaneously), then
// it will not accept console commands.
final Logger log = GameModule.getGameModule().getLogger();
if (log instanceof BasicLogger) {
if (((BasicLogger)log).isMultiPlayer() || GameModule.getGameModule().getPlayerRoster().isMultiPlayer()) {
show("<b>Console commands not allowed in multiplayer games.</b>"); //NON-NLS
return false;
}
}
show(s);
// First get rid of any extra spaces between things
final String delims = "[ ]+";
final String[] tokens = commandLine.split(delims);
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (final String t : tokens) {
if (first) {
first = false;
}
else {
sb.append(" ");
}
sb.append(t);
}
final String cl = sb.toString(); // Our command line with things separated by no more than one space
decode = new SequenceEncoder.Decoder(cl, ' ');
final String command = decode.nextToken("");
if (matches("errorlog", command)) { //NON-NLS
return doErrorLog();
}
if (matches("property", command)) { //NON-NLS
return doProperty();
}
if (!consoleHook(s, commandLine, cl, command, decode)) {
show("Unknown command."); //NON-NLS
return false;
}
return true;
}
}
|
package net.bytebuddy.asm;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.method.ParameterList;
import net.bytebuddy.description.type.TypeDefinition;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeList;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.scaffold.FieldLocator;
import net.bytebuddy.implementation.bytecode.StackSize;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.utility.CompoundList;
import net.bytebuddy.utility.ExceptionTableSensitiveMethodVisitor;
import org.objectweb.asm.*;
import java.io.*;
import java.lang.annotation.*;
import java.util.*;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class Advice implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* A reference to the {@link OnMethodEnter#inline()} method.
*/
private static final MethodDescription.InDefinedShape INLINE_ENTER;
/**
* A reference to the {@link OnMethodEnter#suppress()} method.
*/
private static final MethodDescription.InDefinedShape SUPPRESS_ENTER;
/**
* A reference to the {@link OnMethodExit#inline()} method.
*/
private static final MethodDescription.InDefinedShape INLINE_EXIT;
/**
* A reference to the {@link OnMethodExit#suppress()} method.
*/
private static final MethodDescription.InDefinedShape SUPPRESS_EXIT;
/**
* A reference to the {@link OnMethodExit#onThrowable()} method.
*/
private static final MethodDescription.InDefinedShape ON_THROWABLE;
/*
* Extracts the annotation values for the enter and exit advice annotations.
*/
static {
MethodList<MethodDescription.InDefinedShape> enter = new TypeDescription.ForLoadedType(OnMethodEnter.class).getDeclaredMethods();
INLINE_ENTER = enter.filter(named("inline")).getOnly();
SUPPRESS_ENTER = enter.filter(named("suppress")).getOnly();
MethodList<MethodDescription.InDefinedShape> exit = new TypeDescription.ForLoadedType(OnMethodExit.class).getDeclaredMethods();
INLINE_EXIT = exit.filter(named("inline")).getOnly();
SUPPRESS_EXIT = exit.filter(named("suppress")).getOnly();
ON_THROWABLE = exit.filter(named("onThrowable")).getOnly();
}
/**
* The dispatcher for instrumenting the instrumented method upon entering.
*/
private final Dispatcher.Resolved.ForMethodEnter methodEnter;
/**
* The dispatcher for instrumenting the instrumented method upon exiting.
*/
private final Dispatcher.Resolved.ForMethodExit methodExit;
/**
* Creates a new advice.
*
* @param methodEnter The dispatcher for instrumenting the instrumented method upon entering.
* @param methodExit The dispatcher for instrumenting the instrumented method upon exiting.
*/
protected Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit) {
this.methodEnter = methodEnter;
this.methodExit = methodExit;
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param type The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> type) {
return to(type, ClassFileLocator.ForClassLoader.of(type.getClassLoader()));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param type The type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> type, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(type), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational
* class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set
* to {@code false} are resolvable by the returned instance.
*
* @param typeDescription The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription typeDescription) {
return to(typeDescription, ClassFileLocator.NoOp.INSTANCE);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param typeDescription A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription typeDescription, ClassFileLocator classFileLocator) {
return to(typeDescription, classFileLocator, Collections.<Dispatcher.OffsetMapping.Factory>emptyList());
}
/**
* Creates a new advice.
*
* @param typeDescription A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @param userFactories A list of custom factories for user generated offset mappings.
* @return A method visitor wrapper representing the supplied advice.
*/
protected static Advice to(TypeDescription typeDescription,
ClassFileLocator classFileLocator,
List<? extends Dispatcher.OffsetMapping.Factory> userFactories) {
try {
Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE;
for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods()) {
methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription);
methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription);
}
if (!methodEnter.isAlive() && !methodExit.isAlive()) {
throw new IllegalArgumentException("No advice defined by " + typeDescription);
}
ClassFileLocator.Resolution binaryRepresentation = methodEnter.isBinary() || methodExit.isBinary()
? classFileLocator.locate(typeDescription.getName())
: new ClassFileLocator.Resolution.Illegal(typeDescription.getName());
Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, binaryRepresentation);
return new Advice(resolved, methodExit.asMethodExitTo(userFactories, binaryRepresentation, resolved));
} catch (IOException exception) {
throw new IllegalStateException("Error reading class file of " + typeDescription, exception);
}
}
/**
* Locates a dispatcher for the method if available.
*
* @param type The annotation type that indicates a given form of advice that is currently resolved.
* @param property An annotation property that indicates if the advice method should be inlined.
* @param dispatcher Any previous dispatcher that was discovered or {@code null} if no such dispatcher was yet found.
* @param methodDescription The method description that is considered as an advice method.
* @return A resolved dispatcher or {@code null} if no dispatcher was resolved.
*/
private static Dispatcher.Unresolved locate(Class<? extends Annotation> type,
MethodDescription.InDefinedShape property,
Dispatcher.Unresolved dispatcher,
MethodDescription.InDefinedShape methodDescription) {
AnnotationDescription annotation = methodDescription.getDeclaredAnnotations().ofType(type);
if (annotation == null) {
return dispatcher;
} else if (dispatcher.isAlive()) {
throw new IllegalStateException("Duplicate advice for " + dispatcher + " and " + methodDescription);
} else if (!methodDescription.isStatic()) {
throw new IllegalStateException("Advice for " + methodDescription + " is not static");
} else {
return annotation.getValue(property, Boolean.class)
? new Dispatcher.Inlining(methodDescription)
: new Dispatcher.Delegating(methodDescription);
}
}
/**
* Allows for the configuration of custom annotations that are then bound to a dynamically computed, constant value.
*
* @return A builder for an {@link Advice} instrumentation with custom values.
* @see DynamicValue
*/
public static WithCustomMapping withCustomMapping() {
return new WithCustomMapping();
}
/**
* Returns an ASM visitor wrapper that matches the given matcher and applies this advice to the matched methods.
*
* @param matcher The matcher identifying methods to apply the advice to.
* @return A suitable ASM visitor wrapper with the <i>compute frames</i> option enabled.
*/
public AsmVisitorWrapper.ForDeclaredMethods on(ElementMatcher<? super MethodDescription.InDefinedShape> matcher) {
return new AsmVisitorWrapper.ForDeclaredMethods().method(matcher, this);
}
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape methodDescription,
MethodVisitor methodVisitor,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
if (methodDescription.isAbstract() || methodDescription.isNative()) {
throw new IllegalStateException("Cannot advice abstract or native method " + methodDescription);
} else if (!methodExit.isAlive()) {
return new AdviceVisitor.WithoutExitAdvice(methodVisitor,
methodDescription,
methodEnter,
writerFlags,
readerFlags);
} else if (methodExit.isSkipThrowable()) {
return new AdviceVisitor.WithExitAdvice.WithoutExceptionHandling(methodVisitor,
methodDescription,
methodEnter,
methodExit,
writerFlags,
readerFlags);
} else if (methodDescription.isConstructor()) {
throw new IllegalStateException("Cannot catch exception during constructor call for " + methodDescription);
} else {
return new AdviceVisitor.WithExitAdvice.WithExceptionHandling(methodVisitor,
methodDescription,
methodEnter,
methodExit,
writerFlags,
readerFlags);
}
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Advice advice = (Advice) other;
return methodEnter.equals(advice.methodEnter)
&& methodExit.equals(advice.methodExit);
}
@Override
public int hashCode() {
int result = methodEnter.hashCode();
result = 31 * result + methodExit.hashCode();
return result;
}
@Override
public String toString() {
return "Advice{" +
"methodEnter=" + methodEnter +
", methodExit=" + methodExit +
'}';
}
/**
* A meta data handler that is responsible for translating stack map frames and adjusting size requirements.
*/
protected interface MetaDataHandler {
/**
* Translates a frame.
*
* @param methodVisitor The method visitor to write the frame to.
* @param frameType The frame's type.
* @param localVariableLength The local variable length.
* @param localVariable An array containing the types of the current local variables.
* @param stackSize The size of the operand stack.
* @param stack An array containing the types of the current operand stack.
*/
void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack);
/**
* Injects a frame for a method's exception handler.
*
* @param methodVisitor The method visitor to write the frame to.
*/
void injectHandlerFrame(MethodVisitor methodVisitor);
/**
* Injects a frame after a method's completion.
*
* @param methodVisitor The method visitor to write the frame to.
* @param secondary {@code true} if the frame is written a second time.
*/
void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary);
/**
* A meta data handler for the instrumented method.
*/
interface ForInstrumentedMethod extends MetaDataHandler {
/**
* Indicates that a size is not computed but handled directly by ASM.
*/
int UNDEFINED_SIZE = Short.MAX_VALUE;
/**
* Binds this meta data handler for the entry advice.
*
* @param adviceMethod The entry advice method.
* @return An appropriate meta data handler for the enter method.
*/
ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod);
/**
* Binds this meta data handler for the exit advice.
*
* @param adviceMethod The exit advice method.
* @return An appropriate meta data handler for the enter method.
*/
ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod);
/**
* Computes a compound stack size for the advice and the translated instrumented method.
*
* @param stackSize The required stack size of the instrumented method before translation.
* @return The stack size required by the instrumented method and its advice methods.
*/
int compoundStackSize(int stackSize);
/**
* Computes a compound local variable array length for the advice and the translated instrumented method.
*
* @param localVariableLength The required local variable array length of the instrumented method before translation.
* @return The local variable length required by the instrumented method and its advice methods.
*/
int compoundLocalVariableLength(int localVariableLength);
/**
* Returns the reader hint to apply when parsing the advice method.
*
* @return The reader hint for parsing the advice method.
*/
int getReaderHint();
}
/**
* A meta data handler for an advice method.
*/
interface ForAdvice extends MetaDataHandler {
/**
* Records the maximum values for stack size and local variable array which are required by the advice method
* for its individual execution without translation.
*
* @param stackSize The minimum required stack size.
* @param localVariableLength The minimum required length of the local variable array.
*/
void recordMaxima(int stackSize, int localVariableLength);
/**
* Records a minimum padding additionally to the computed stack size that is required for implementing this advice method.
*
* @param padding The minimum required padding.
*/
void recordPadding(int padding);
}
/**
* A non-operational meta data handler that does not translate any frames and does not compute stack sizes.
*/
enum NoOp implements ForInstrumentedMethod, ForAdvice {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public void recordMaxima(int maxStack, int maxLocals) {
/* do nothing */
}
@Override
public void recordPadding(int padding) {
/* do nothing */
}
@Override
public int compoundStackSize(int stackSize) {
return UNDEFINED_SIZE;
}
@Override
public int compoundLocalVariableLength(int localVariableLength) {
return UNDEFINED_SIZE;
}
@Override
public ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public int getReaderHint() {
return ClassReader.SKIP_FRAMES;
}
@Override
public void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) {
/* do nothing */
}
@Override
public void injectHandlerFrame(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.MetaDataHandler.NoOp." + name();
}
}
/**
* A default implementation of a meta data handler for an instrumented method.
*/
abstract class Default implements ForInstrumentedMethod {
/**
* An empty array indicating an empty frame.
*/
private static final Object[] EMPTY = new Object[0];
/**
* The instrumented method.
*/
protected final MethodDescription.InDefinedShape instrumentedMethod;
/**
* A list of intermediate types to be considered as part of the instrumented method's steady signature.
*/
protected final TypeList requiredTypes;
/**
* The types that are expected to be added after the instrumented method returns.
*/
protected final TypeList yieldedTypes;
/**
* {@code true} if the meta data handler is expected to expand its frames.
*/
private final boolean expandFrames;
/**
* The current frame's size divergence from the original local variable array.
*/
private int currentFrameDivergence;
/**
* Creates a new default meta data handler.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes A list of intermediate types to be considered as part of the instrumented method's steady signature.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param expandFrames {@code true} if the meta data handler is expected to expand its frames.
*/
protected Default(MethodDescription.InDefinedShape instrumentedMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
boolean expandFrames) {
this.instrumentedMethod = instrumentedMethod;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
this.expandFrames = expandFrames;
}
/**
* Creates an appropriate meta data handler for an instrumented method based on the context of the method creation.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes The additional types that are added by the entry advice.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param writerFlags The ASM flags supplied to the {@link ClassWriter}.
* @param readerFlags The ASM flags supplied to the {@link ClassReader}.
* @return An appropriate meta data handler.
*/
protected static ForInstrumentedMethod of(MethodDescription.InDefinedShape instrumentedMethod,
List<? extends TypeDescription> requiredTypes,
List<? extends TypeDescription> yieldedTypes,
int writerFlags,
int readerFlags) {
if ((writerFlags & ClassWriter.COMPUTE_FRAMES) != 0) {
return NoOp.INSTANCE;
} else if ((writerFlags & ClassWriter.COMPUTE_MAXS) != 0) {
return new Default.WithoutStackSizeComputation(instrumentedMethod,
new TypeList.Explicit(requiredTypes),
new TypeList.Explicit(yieldedTypes),
(readerFlags & ClassReader.EXPAND_FRAMES) != 0);
} else {
return new Default.WithStackSizeComputation(instrumentedMethod,
new TypeList.Explicit(requiredTypes),
new TypeList.Explicit(yieldedTypes),
(readerFlags & ClassReader.EXPAND_FRAMES) != 0);
}
}
/**
* Translates a type into a representation of its form inside a stack map frame.
*
* @param typeDescription The type to translate.
* @return A stack entry representation of the supplied type.
*/
protected static Object toFrame(TypeDescription typeDescription) {
if (typeDescription.represents(boolean.class)
|| typeDescription.represents(byte.class)
|| typeDescription.represents(short.class)
|| typeDescription.represents(char.class)
|| typeDescription.represents(int.class)) {
return Opcodes.INTEGER;
} else if (typeDescription.represents(long.class)) {
return Opcodes.LONG;
} else if (typeDescription.represents(float.class)) {
return Opcodes.FLOAT;
} else if (typeDescription.represents(double.class)) {
return Opcodes.DOUBLE;
} else {
return typeDescription.getInternalName();
}
}
@Override
public ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
return bind(adviceMethod, new TypeList.Empty(), requiredTypes, TranslationMode.ENTRY);
}
@Override
public ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) {
return bind(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty(), TranslationMode.EXIT);
}
/**
* Binds the given advice method to an appropriate meta data handler.
*
* @param adviceMethod The advice method.
* @param requiredTypes The expected types that the advice method requires additionally to the instrumented method's parameters.
* @param yieldedTypes The types this advice method yields as additional parameters.
* @param translationMode The translation mode to apply for this advice.
* @return An appropriate meta data handler.
*/
protected abstract ForAdvice bind(MethodDescription.InDefinedShape adviceMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
TranslationMode translationMode);
@Override
public int getReaderHint() {
return expandFrames ? ClassReader.EXPAND_FRAMES : AsmVisitorWrapper.NO_FLAGS;
}
@Override
public void translateFrame(MethodVisitor methodVisitor,
int type,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
translateFrame(methodVisitor,
TranslationMode.COPY,
instrumentedMethod,
requiredTypes,
type,
localVariableLength,
localVariable,
stackSize,
stack);
}
/**
* Translates a frame.
*
* @param methodVisitor The method visitor to write the frame to.
* @param translationMode The translation mode to apply.
* @param methodDescription The method description for which the frame is written.
* @param additionalTypes The additional types to consider part of the instrumented method's parameters.
* @param frameType The frame's type.
* @param localVariableLength The local variable length.
* @param localVariable An array containing the types of the current local variables.
* @param stackSize The size of the operand stack.
* @param stack An array containing the types of the current operand stack.
*/
protected void translateFrame(MethodVisitor methodVisitor,
TranslationMode translationMode,
MethodDescription.InDefinedShape methodDescription,
TypeList additionalTypes,
int frameType,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
switch (frameType) {
case Opcodes.F_SAME:
case Opcodes.F_SAME1:
break;
case Opcodes.F_APPEND:
currentFrameDivergence += localVariableLength;
break;
case Opcodes.F_CHOP:
currentFrameDivergence -= localVariableLength;
break;
case Opcodes.F_FULL:
case Opcodes.F_NEW:
Object[] translated = new Object[localVariableLength
- methodDescription.getParameters().size()
- (methodDescription.isStatic() ? 0 : 1)
+ instrumentedMethod.getParameters().size()
+ (instrumentedMethod.isStatic() ? 0 : 1)
+ additionalTypes.size()];
int index = translationMode.copy(instrumentedMethod, methodDescription, localVariable, translated);
for (TypeDescription typeDescription : additionalTypes) {
translated[index++] = toFrame(typeDescription);
}
System.arraycopy(localVariable,
methodDescription.getParameters().size() + (methodDescription.isStatic() ? 0 : 1),
translated,
index,
translated.length - index);
localVariableLength = translated.length;
localVariable = translated;
currentFrameDivergence = translated.length - index;
break;
default:
throw new IllegalArgumentException("Unexpected frame frameType: " + frameType);
}
methodVisitor.visitFrame(frameType, localVariableLength, localVariable, stackSize, stack);
}
@Override
public void injectHandlerFrame(MethodVisitor methodVisitor) {
if (!expandFrames && currentFrameDivergence == 0) {
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)});
} else {
injectFullFrame(methodVisitor, requiredTypes, true);
}
}
@Override
public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) {
if (!expandFrames && currentFrameDivergence == 0 && (secondary || !instrumentedMethod.isConstructor())) {
if (secondary) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY);
} else {
Object[] local = new Object[yieldedTypes.size()];
int index = 0;
for (TypeDescription typeDescription : yieldedTypes) {
local[index++] = toFrame(typeDescription);
}
methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY);
}
} else {
injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), false);
}
}
/**
* Injects a full frame.
*
* @param methodVisitor The method visitor for which the frame should be written.
* @param additionalTypes The additional types that are considered to be part of the method's parameters.
* @param exceptionOnStack {@code true} if there is a {@link Throwable} on the operand stack.
*/
protected void injectFullFrame(MethodVisitor methodVisitor, List<? extends TypeDescription> additionalTypes, boolean exceptionOnStack) {
Object[] localVariable = new Object[instrumentedMethod.getParameters().size()
+ (instrumentedMethod.isStatic() ? 0 : 1)
+ additionalTypes.size()];
int index = 0;
if (!instrumentedMethod.isStatic()) {
localVariable[index++] = toFrame(instrumentedMethod.getDeclaringType());
}
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
localVariable[index++] = toFrame(typeDescription);
}
for (TypeDescription typeDescription : additionalTypes) {
localVariable[index++] = toFrame(typeDescription);
}
Object[] stackType = exceptionOnStack
? new Object[]{Type.getInternalName(Throwable.class)}
: EMPTY;
methodVisitor.visitFrame(expandFrames ? Opcodes.F_NEW : Opcodes.F_FULL, localVariable.length, localVariable, stackType.length, stackType);
currentFrameDivergence = 0;
}
/**
* A translation mode that determines how the fixed frames of the instrumented method are written.
*/
protected enum TranslationMode {
/**
* A translation mode that simply copies the original frames which are available when translating frames of the instrumented method.
*/
COPY {
@Override
protected int copy(MethodDescription.InDefinedShape instrumentedMethod,
MethodDescription.InDefinedShape methodDescription,
Object[] localVariable,
Object[] translated) {
int length = instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1);
System.arraycopy(localVariable, 0, translated, 0, length);
return length;
}
},
/**
* A translation mode for the entry advice that considers that the {@code this} reference might not be initialized for a constructor.
*/
ENTRY {
@Override
protected int copy(MethodDescription.InDefinedShape instrumentedMethod,
MethodDescription.InDefinedShape methodDescription,
Object[] localVariable,
Object[] translated) {
int index = 0;
if (!instrumentedMethod.isStatic()) {
translated[index++] = instrumentedMethod.isConstructor()
? Opcodes.UNINITIALIZED_THIS
: toFrame(instrumentedMethod.getDeclaringType());
}
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
translated[index++] = toFrame(typeDescription);
}
return index;
}
},
/**
* A translation mode for an exit advice where the {@code this} reference is always initialized.
*/
EXIT {
@Override
protected int copy(MethodDescription.InDefinedShape instrumentedMethod,
MethodDescription.InDefinedShape methodDescription,
Object[] localVariable,
Object[] translated) {
int index = 0;
if (!instrumentedMethod.isStatic()) {
translated[index++] = toFrame(instrumentedMethod.getDeclaringType());
}
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
translated[index++] = toFrame(typeDescription);
}
return index;
}
};
/**
* Copies the fixed parameters of the instrumented method onto the operand stack.
*
* @param instrumentedMethod The instrumented method.
* @param methodDescription The method for which a frame is created.
* @param localVariable The original local variable array.
* @param translated The array containing the translated frames.
* @return The amount of frames added to the translated frame array.
*/
protected abstract int copy(MethodDescription.InDefinedShape instrumentedMethod,
MethodDescription.InDefinedShape methodDescription,
Object[] localVariable,
Object[] translated);
}
/**
* A meta data handler that is bound to an advice method.
*/
protected abstract class ForAdvice implements MetaDataHandler.ForAdvice {
/**
* The method description for which frames are translated.
*/
protected final MethodDescription.InDefinedShape methodDescription;
/**
* A list of intermediate types to be considered as part of the instrumented method's steady signature.
*/
protected final TypeList requiredTypes;
/**
* The types that this method yields as a result.
*/
private final TypeList yieldedTypes;
/**
* The translation mode to apply for this advice method. Should be either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}.
*/
protected final TranslationMode translationMode;
/**
* Creates a new meta data handler for an advice method.
*
* @param methodDescription The method description for which frames are translated.
* @param requiredTypes A list of expected types to be considered as part of the instrumented method's steady signature.
* @param yieldedTypes The types that this method yields as a result.
* @param translationMode The translation mode to apply for this advice method. Should be
* either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}.
*/
protected ForAdvice(MethodDescription.InDefinedShape methodDescription,
TypeList requiredTypes,
TypeList yieldedTypes,
TranslationMode translationMode) {
this.methodDescription = methodDescription;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
this.translationMode = translationMode;
}
@Override
public void translateFrame(MethodVisitor methodVisitor,
int type,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
Default.this.translateFrame(methodVisitor,
translationMode,
methodDescription,
requiredTypes,
type,
localVariableLength,
localVariable,
stackSize,
stack);
}
@Override
public void injectHandlerFrame(MethodVisitor methodVisitor) {
if (!expandFrames && currentFrameDivergence == 0) {
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)});
} else {
injectFullFrame(methodVisitor, requiredTypes, true);
}
}
@Override
public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) {
if ((!expandFrames && currentFrameDivergence == 0 && yieldedTypes.size() < 4)) {
if (secondary || yieldedTypes.isEmpty()) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY);
} else {
Object[] local = new Object[yieldedTypes.size()];
int index = 0;
for (TypeDescription typeDescription : yieldedTypes) {
local[index++] = toFrame(typeDescription);
}
methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY);
}
} else {
injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), false);
}
}
}
/**
* A default meta data handler that recomputes the space requirements of an instrumented method.
*/
protected static class WithStackSizeComputation extends Default {
/**
* The maximum stack size required by a visited advice method.
*/
private int stackSize;
/**
* The maximum length of the local variable array required by a visited advice method.
*/
private int localVariableLength;
/**
* Creates a new default meta data handler that recomputes the space requirements of an instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes The types this meta data handler expects to be available additionally to the instrumented method's parameters.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param expandFrames {@code true} if this meta data handler is expected to expand its written frames.
*/
protected WithStackSizeComputation(MethodDescription.InDefinedShape instrumentedMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
boolean expandFrames) {
super(instrumentedMethod, requiredTypes, yieldedTypes, expandFrames);
stackSize = Math.max(instrumentedMethod.getReturnType().getStackSize().getSize(), StackSize.SINGLE.getSize());
}
@Override
public int compoundStackSize(int stackSize) {
return Math.max(this.stackSize, stackSize);
}
@Override
public int compoundLocalVariableLength(int localVariableLength) {
return Math.max(this.localVariableLength, localVariableLength
+ instrumentedMethod.getReturnType().getStackSize().getSize()
+ StackSize.SINGLE.getSize()
+ requiredTypes.getStackSize());
}
@Override
protected Default.ForAdvice bind(MethodDescription.InDefinedShape adviceMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
TranslationMode translationMode) {
if (translationMode == TranslationMode.ENTRY) {
stackSize = Math.max(adviceMethod.getReturnType().getStackSize().getSize(), stackSize);
}
return new ForAdvice(adviceMethod, requiredTypes, yieldedTypes, translationMode);
}
@Override
public String toString() {
return "Advice.MetaDataHandler.Default.WithStackSizeComputation{" +
"instrumentedMethod=" + instrumentedMethod +
", stackSize=" + stackSize +
", localVariableLength=" + localVariableLength +
"}";
}
/**
* A meta data handler for an advice method that records size requirements.
*/
protected class ForAdvice extends Default.ForAdvice {
/**
* The padding that this advice method requires additionally to its computed size.
*/
private int padding;
/**
* Creates a new meta data handler for an advice method.
*
* @param methodDescription The advice method.
* @param requiredTypes The types that this method expects to exist in addition to the method parameter types.
* @param yieldedTypes The types yielded by this advice method.
* @param translationMode The translation mode for this meta data handler.
*/
protected ForAdvice(MethodDescription.InDefinedShape methodDescription,
TypeList requiredTypes,
TypeList yieldedTypes,
TranslationMode translationMode) {
super(methodDescription, requiredTypes, yieldedTypes, translationMode);
}
@Override
public void recordMaxima(int stackSize, int localVariableLength) {
WithStackSizeComputation.this.stackSize = Math.max(WithStackSizeComputation.this.stackSize, stackSize) + padding;
WithStackSizeComputation.this.localVariableLength = Math.max(WithStackSizeComputation.this.localVariableLength, localVariableLength
- methodDescription.getStackSize()
+ instrumentedMethod.getStackSize()
+ requiredTypes.getStackSize());
}
@Override
public void recordPadding(int padding) {
this.padding = Math.max(this.padding, padding);
}
@Override
public String toString() {
return "Advice.MetaDataHandler.Default.WithStackSizeComputation.ForAdvice{" +
"instrumentedMethod=" + instrumentedMethod +
", methodDescription=" + methodDescription +
", padding=" + padding +
"}";
}
}
}
/**
* A default meta data handler that does not recompute the space requirements of an instrumented method.
*/
protected static class WithoutStackSizeComputation extends Default {
/**
* Creates a new default meta data handler that does not recompute the space requirements of an instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes The types this meta data handler expects to be available additionally to the instrumented method's parameters.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param expandFrames {@code true} if this meta data handler is expected to expand its written frames.
*/
protected WithoutStackSizeComputation(MethodDescription.InDefinedShape instrumentedMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
boolean expandFrames) {
super(instrumentedMethod, requiredTypes, yieldedTypes, expandFrames);
}
@Override
public int compoundStackSize(int stackSize) {
return UNDEFINED_SIZE;
}
@Override
public int compoundLocalVariableLength(int localVariableLength) {
return UNDEFINED_SIZE;
}
@Override
protected Default.ForAdvice bind(MethodDescription.InDefinedShape adviceMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
TranslationMode translationMode) {
return new ForAdvice(adviceMethod, requiredTypes, yieldedTypes, translationMode);
}
@Override
public String toString() {
return "Advice.MetaDataHandler.Default.WithoutStackSizeComputation{" +
"instrumentedMethod=" + instrumentedMethod +
"}";
}
/**
* A meta data handler for an advice method that does not record size requirements.
*/
protected class ForAdvice extends Default.ForAdvice {
/**
* Creates a new meta data handler for an advice method.
*
* @param methodDescription The advice method.
* @param requiredTypes The types that this method expects to exist in addition to the method parameter types.
* @param yieldedTypes The types yielded by this advice method.
* @param translationMode The translation mode for this meta data handler.
*/
protected ForAdvice(MethodDescription.InDefinedShape methodDescription,
TypeList requiredTypes,
TypeList yieldedTypes,
TranslationMode translationMode) {
super(methodDescription, requiredTypes, yieldedTypes, translationMode);
}
@Override
public void recordMaxima(int maxStack, int maxLocals) {
/* do nothing */
}
@Override
public void recordPadding(int padding) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.MetaDataHandler.Default.WithoutStackSizeComputation.ForAdvice{" +
"instrumentedMethod=" + instrumentedMethod +
", methodDescription=" + methodDescription +
"}";
}
}
}
}
}
/**
* A method visitor that weaves the advice methods' byte codes.
*/
protected abstract static class AdviceVisitor extends ExceptionTableSensitiveMethodVisitor {
/**
* Indicates a zero offset.
*/
private static final int NO_OFFSET = 0;
/**
* A description of the instrumented method.
*/
protected final MethodDescription.InDefinedShape instrumentedMethod;
/**
* The required padding before using local variables after the instrumented method's arguments.
*/
private final int padding;
/**
* The dispatcher to be used for method entry.
*/
private final Dispatcher.Bound methodEnter;
/**
* The dispatcher to be used for method exit.
*/
protected final Dispatcher.Bound methodExit;
/**
* A handler to use for translating meta embedded in the byte code.
*/
protected final MetaDataHandler.ForInstrumentedMethod metaDataHandler;
/**
* Creates a new advice visitor.
*
* @param methodVisitor The method visitor to which all instructions are written.
* @param instrumentedMethod The instrumented method.
* @param methodEnter The method enter advice.
* @param methodExit The method exit advice.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected AdviceVisitor(MethodVisitor methodVisitor,
MethodDescription.InDefinedShape instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
List<? extends TypeDescription> yieldedTypes,
int writerFlags,
int readerFlags) {
super(Opcodes.ASM5, methodVisitor);
this.instrumentedMethod = instrumentedMethod;
padding = methodEnter.getEnterType().getStackSize().getSize();
metaDataHandler = MetaDataHandler.Default.of(instrumentedMethod, methodEnter.getEnterType().represents(void.class)
? Collections.<TypeDescription>emptyList()
: Collections.singletonList(methodEnter.getEnterType()), yieldedTypes, writerFlags, readerFlags);
this.methodEnter = methodEnter.bind(instrumentedMethod, methodVisitor, metaDataHandler);
this.methodExit = methodExit.bind(instrumentedMethod, methodVisitor, metaDataHandler);
}
@Override
protected void onAfterExceptionTable() {
methodEnter.prepare();
onUserPrepare();
methodExit.prepare();
methodEnter.apply();
onUserStart();
}
/**
* Invoked when the user method's exception handler (if any) is supposed to be prepared.
*/
protected abstract void onUserPrepare();
/**
* Writes the advice for entering the instrumented method.
*/
protected abstract void onUserStart();
@Override
protected void onVisitVarInsn(int opcode, int offset) {
mv.visitVarInsn(opcode, offset < instrumentedMethod.getStackSize()
? offset
: padding + offset);
}
@Override
protected void onVisitIincInsn(int offset, int increment) {
mv.visitIincInsn(offset < instrumentedMethod.getStackSize()
? offset
: padding + offset, increment);
}
/**
* Access the first variable after the instrumented variables and return type are stored.
*
* @param opcode The opcode for accessing the variable.
*/
protected void variable(int opcode) {
variable(opcode, NO_OFFSET);
}
/**
* Access the first variable after the instrumented variables and return type are stored.
*
* @param opcode The opcode for accessing the variable.
* @param offset The additional offset of the variable.
*/
protected void variable(int opcode, int offset) {
mv.visitVarInsn(opcode, instrumentedMethod.getStackSize() + padding + offset);
}
@Override
public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) {
metaDataHandler.translateFrame(mv, frameType, localVariableLength, localVariable, stackSize, stack);
}
@Override
public void visitMaxs(int stackSize, int localVariableLength) {
onUserEnd();
mv.visitMaxs(metaDataHandler.compoundStackSize(stackSize), metaDataHandler.compoundLocalVariableLength(localVariableLength));
}
/**
* Writes the advice for completing the instrumented method.
*/
protected abstract void onUserEnd();
/**
* An advice visitor that does not apply exit advice.
*/
protected static class WithoutExitAdvice extends AdviceVisitor {
/**
* Creates an advice visitor that does not apply exit advice.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected WithoutExitAdvice(MethodVisitor methodVisitor,
MethodDescription.InDefinedShape instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
int writerFlags,
int readerFlags) {
super(methodVisitor,
instrumentedMethod,
methodEnter,
Dispatcher.Inactive.INSTANCE,
Collections.<TypeDescription>emptyList(),
writerFlags,
readerFlags);
}
@Override
protected void onUserPrepare() {
/* do nothing */
}
@Override
protected void onUserStart() {
/* do nothing */
}
@Override
protected void onUserEnd() {
/* do nothing */
}
@Override
public String toString() {
return "Advice.AdviceVisitor.WithoutExitAdvice{" +
", instrumentedMethod=" + instrumentedMethod +
"}";
}
}
/**
* An advice visitor that applies exit advice.
*/
protected abstract static class WithExitAdvice extends AdviceVisitor {
/**
* A label that indicates the end of the method.
*/
protected final Label endOfMethod;
/**
* Creates an advice visitor that applies exit advice.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param methodExit The dispatcher to be used for method exit.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected WithExitAdvice(MethodVisitor methodVisitor,
MethodDescription.InDefinedShape instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
List<? extends TypeDescription> yieldedTypes,
int writerFlags,
int readerFlags) {
super(methodVisitor, instrumentedMethod, methodEnter, methodExit, yieldedTypes, writerFlags, readerFlags);
endOfMethod = new Label();
}
@Override
protected void onVisitInsn(int opcode) {
switch (opcode) {
case Opcodes.RETURN:
break;
case Opcodes.IRETURN:
variable(Opcodes.ISTORE);
break;
case Opcodes.FRETURN:
variable(Opcodes.FSTORE);
break;
case Opcodes.DRETURN:
variable(Opcodes.DSTORE);
break;
case Opcodes.LRETURN:
variable(Opcodes.LSTORE);
break;
case Opcodes.ARETURN:
variable(Opcodes.ASTORE);
break;
default:
mv.visitInsn(opcode);
return;
}
onUserReturn();
mv.visitJumpInsn(Opcodes.GOTO, endOfMethod);
}
@Override
protected void onUserEnd() {
onUserExit();
mv.visitLabel(endOfMethod);
metaDataHandler.injectCompletionFrame(mv, false);
methodExit.apply();
onAdviceExit();
if (instrumentedMethod.getReturnType().represents(void.class)) {
mv.visitInsn(Opcodes.RETURN);
} else {
Type returnType = Type.getType(instrumentedMethod.getReturnType().asErasure().getDescriptor());
variable(returnType.getOpcode(Opcodes.ILOAD));
mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
}
onMethodExit();
}
/**
* Invoked when the user method issues a return statement before applying the exit handler.
*/
protected abstract void onUserReturn();
/**
* Invoked on completing to write the translated user code.
*/
protected abstract void onUserExit();
/**
* Invoked on completing the inlining of the exit advice.
*/
protected abstract void onAdviceExit();
/**
* Invoked on completing the method's code.
*/
protected abstract void onMethodExit();
/**
* An advice visitor that captures exceptions by weaving try-catch blocks around user code.
*/
protected static class WithExceptionHandling extends WithExitAdvice {
/**
* Indicates that any throwable should be captured.
*/
private static final String ANY_THROWABLE = null;
/**
* Indicates the start of the user method.
*/
private final Label userStart;
/**
* Indicates the end of the user method.
*/
private final Label userEnd;
/**
* Indicates the position of a handler for rethrowing an exception that was thrown by the user method.
*/
private final Label exceptionalReturn;
/**
* Creates a new advice visitor that captures exception by weaving try-catch blocks around user code.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param methodExit The dispatcher to be used for method exit.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected WithExceptionHandling(MethodVisitor methodVisitor,
MethodDescription.InDefinedShape instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
int writerFlags,
int readerFlags) {
super(methodVisitor,
instrumentedMethod,
methodEnter,
methodExit,
instrumentedMethod.getReturnType().represents(void.class)
? Collections.singletonList(TypeDescription.THROWABLE)
: Arrays.asList(instrumentedMethod.getReturnType().asErasure(), TypeDescription.THROWABLE),
writerFlags,
readerFlags);
userStart = new Label();
userEnd = new Label();
exceptionalReturn = new Label();
}
@Override
protected void onUserPrepare() {
mv.visitTryCatchBlock(userStart, userEnd, userEnd, ANY_THROWABLE);
}
@Override
protected void onUserStart() {
mv.visitLabel(userStart);
}
@Override
protected void onUserReturn() {
mv.visitInsn(Opcodes.ACONST_NULL);
variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize());
}
@Override
protected void onUserExit() {
mv.visitLabel(userEnd);
metaDataHandler.injectHandlerFrame(mv);
variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize());
storeDefaultReturn();
mv.visitJumpInsn(Opcodes.GOTO, endOfMethod);
}
@Override
protected void onAdviceExit() {
variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize());
mv.visitJumpInsn(Opcodes.IFNONNULL, exceptionalReturn);
}
@Override
protected void onMethodExit() {
mv.visitLabel(exceptionalReturn);
metaDataHandler.injectCompletionFrame(mv, true);
variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize());
mv.visitInsn(Opcodes.ATHROW);
}
/**
* Stores a default return value in the designated slot of the local variable array.
*/
private void storeDefaultReturn() {
if (instrumentedMethod.getReturnType().represents(boolean.class)
|| instrumentedMethod.getReturnType().represents(byte.class)
|| instrumentedMethod.getReturnType().represents(short.class)
|| instrumentedMethod.getReturnType().represents(char.class)
|| instrumentedMethod.getReturnType().represents(int.class)) {
mv.visitInsn(Opcodes.ICONST_0);
variable(Opcodes.ISTORE);
} else if (instrumentedMethod.getReturnType().represents(long.class)) {
mv.visitInsn(Opcodes.LCONST_0);
variable(Opcodes.LSTORE);
} else if (instrumentedMethod.getReturnType().represents(float.class)) {
mv.visitInsn(Opcodes.FCONST_0);
variable(Opcodes.FSTORE);
} else if (instrumentedMethod.getReturnType().represents(double.class)) {
mv.visitInsn(Opcodes.DCONST_0);
variable(Opcodes.DSTORE);
} else if (!instrumentedMethod.getReturnType().represents(void.class)) {
mv.visitInsn(Opcodes.ACONST_NULL);
variable(Opcodes.ASTORE);
}
}
@Override
public String toString() {
return "Advice.AdviceVisitor.WithExitAdvice.WithExceptionHandling{" +
"instrumentedMethod=" + instrumentedMethod +
"}";
}
}
/**
* An advice visitor that does not capture exceptions.
*/
protected static class WithoutExceptionHandling extends WithExitAdvice {
/**
* Creates a new advice visitor that does not capture exceptions.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param methodExit The dispatcher to be used for method exit.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected WithoutExceptionHandling(MethodVisitor methodVisitor,
MethodDescription.InDefinedShape instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
int writerFlags,
int readerFlags) {
super(methodVisitor,
instrumentedMethod,
methodEnter,
methodExit,
instrumentedMethod.getReturnType().represents(void.class)
? Collections.<TypeDescription>emptyList()
: Collections.singletonList(instrumentedMethod.getReturnType().asErasure()),
writerFlags,
readerFlags);
}
@Override
protected void onUserPrepare() {
/* empty */
}
@Override
protected void onUserStart() {
/* empty */
}
@Override
protected void onUserReturn() {
/* empty */
}
@Override
protected void onUserExit() {
/* empty */
}
@Override
protected void onAdviceExit() {
/* empty */
}
@Override
protected void onMethodExit() {
/* empty */
}
@Override
public String toString() {
return "Advice.AdviceVisitor.WithExitAdvice.WithoutExceptionHandling{" +
"instrumentedMethod=" + instrumentedMethod +
"}";
}
}
}
}
/**
* A dispatcher for implementing advice.
*/
protected interface Dispatcher {
/**
* Indicates that a method does not represent advice and does not need to be visited.
*/
MethodVisitor IGNORE_METHOD = null;
/**
* Expresses that an annotation should not be visited.
*/
AnnotationVisitor IGNORE_ANNOTATION = null;
/**
* Returns {@code true} if this dispatcher is alive.
*
* @return {@code true} if this dispatcher is alive.
*/
boolean isAlive();
/**
* A dispatcher that is not yet resolved.
*/
interface Unresolved extends Dispatcher {
/**
* Indicates that this dispatcher requires access to the class file declaring the advice method.
*
* @return {@code true} if this dispatcher requires access to the advice method's class file.
*/
boolean isBinary();
/**
* Resolves this dispatcher as a dispatcher for entering a method.
*
* @param userFactories A list of custom factories for binding parameters of an advice method.
* @param binaryRepresentation An unresolved binary representation of the type containing the advice method.
* @return This dispatcher as a dispatcher for entering a method.
*/
Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation);
/**
* Resolves this dispatcher as a dispatcher for exiting a method.
*
* @param userFactories A list of custom factories for binding parameters of an advice method.
* @param binaryRepresentation An unresolved binary representation of the type containing the advice method.
* @param dispatcher The dispatcher for entering a method.
* @return This dispatcher as a dispatcher for exiting a method.
*/
Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation,
Resolved.ForMethodEnter dispatcher);
}
/**
* Represents an offset mapping for an advice method to an alternative offset.
*/
interface OffsetMapping {
/**
* Resolves an offset mapping to a given target offset.
*
* @param instrumentedMethod The instrumented method for which the mapping is to be resolved.
* @param context The context in which the offset mapping is applied.
* @return A suitable target mapping.
*/
Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context);
/**
* A context for applying an {@link OffsetMapping}.
*/
interface Context {
/**
* Returns {@code true} if the advice is applied on a fully initialized instance, i.e. describes if the {@code this}
* instance is available or still uninitialized during calling the advice.
*
* @return {@code true} if the advice is applied onto a fully initialized method.
*/
boolean isInitialized();
/**
* Returns the padding before writing additional values that this context applies.
*
* @return The required padding for this context.
*/
int getPadding();
/**
* A context for an offset mapping describing a method entry.
*/
enum ForMethodEntry implements Context {
/**
* Describes a context for a method entry that is not a constructor.
*/
INITIALIZED(true),
/**
* Describes a context for a method entry that is a constructor.
*/
NON_INITIALIZED(false);
/**
* Resolves an appropriate method entry context for the supplied instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @return An appropriate context.
*/
protected static Context of(MethodDescription.InDefinedShape instrumentedMethod) {
return instrumentedMethod.isConstructor()
? NON_INITIALIZED
: INITIALIZED;
}
/**
* {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry.
*/
private final boolean initialized;
/**
* Creates a new context for a method entry.
*
* @param initialized {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry.
*/
ForMethodEntry(boolean initialized) {
this.initialized = initialized;
}
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public int getPadding() {
return StackSize.ZERO.getSize();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Context.ForMethodEntry." + name();
}
}
/**
* A context for an offset mapping describing a method exit.
*/
enum ForMethodExit implements Context {
/**
* A method exit with a zero sized padding.
*/
ZERO(StackSize.ZERO),
/**
* A method exit with a single slot padding.
*/
SINGLE(StackSize.SINGLE),
/**
* A method exit with a double slot padding.
*/
DOUBLE(StackSize.DOUBLE);
/**
* The padding implied by this method exit.
*/
private final StackSize stackSize;
/**
* Creates a new context for a method exit.
*
* @param stackSize The padding implied by this method exit.
*/
ForMethodExit(StackSize stackSize) {
this.stackSize = stackSize;
}
/**
* Resolves an appropriate method exit context for the supplied entry method type.
*
* @param typeDescription The type that is returned by the enter method.
* @return An appropriate context for the supplied entry method type.
*/
protected static Context of(TypeDescription typeDescription) {
switch (typeDescription.getStackSize()) {
case ZERO:
return ZERO;
case SINGLE:
return SINGLE;
case DOUBLE:
return DOUBLE;
default:
throw new IllegalStateException("Unknown stack size: " + typeDescription);
}
}
@Override
public boolean isInitialized() {
return true;
}
@Override
public int getPadding() {
return stackSize.getSize();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Context.ForMethodExit." + name();
}
}
}
/**
* A target offset of an offset mapping.
*/
interface Target {
/**
* Indicates that applying this target does not require any additional padding.
*/
int NO_PADDING = 0;
/**
* Applies this offset mapping for a {@link MethodVisitor#visitVarInsn(int, int)} instruction.
*
* @param methodVisitor The method visitor onto which this offset mapping is to be applied.
* @param opcode The opcode of the original instruction.
* @return The required padding to the advice's total stack size.
*/
int resolveAccess(MethodVisitor methodVisitor, int opcode);
/**
* Applies this offset mapping for a {@link MethodVisitor#visitIincInsn(int, int)} instruction.
*
* @param methodVisitor The method visitor onto which this offset mapping is to be applied.
* @param increment The value with which to increment the targeted value.
* @return The required padding to the advice's total stack size.
*/
int resolveIncrement(MethodVisitor methodVisitor, int increment);
/**
* Loads a default value onto the stack or pops the accessed value off it.
*/
enum ForDefaultValue implements Target {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ALOAD:
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
break;
case Opcodes.ILOAD:
methodVisitor.visitInsn(Opcodes.ICONST_0);
break;
case Opcodes.LLOAD:
methodVisitor.visitInsn(Opcodes.LCONST_0);
break;
case Opcodes.FLOAD:
methodVisitor.visitInsn(Opcodes.FCONST_0);
break;
case Opcodes.DLOAD:
methodVisitor.visitInsn(Opcodes.DCONST_0);
break;
case Opcodes.ISTORE:
case Opcodes.FSTORE:
case Opcodes.ASTORE:
methodVisitor.visitInsn(Opcodes.POP);
break;
case Opcodes.LSTORE:
case Opcodes.DSTORE:
methodVisitor.visitInsn(Opcodes.POP2);
break;
default:
throw new IllegalStateException("Unexpected opcode: " + opcode);
}
return NO_PADDING;
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
return NO_PADDING;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForDefaultValue." + name();
}
}
/**
* A read-write target mapping.
*/
class ForParameter implements Target {
/**
* The mapped offset.
*/
private final int offset;
/**
* Creates a new read-write target mapping.
*
* @param offset The mapped offset.
*/
protected ForParameter(int offset) {
this.offset = offset;
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
methodVisitor.visitVarInsn(opcode, offset);
return NO_PADDING;
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
methodVisitor.visitIincInsn(offset, increment);
return NO_PADDING;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForParameter forParameter = (ForParameter) object;
return offset == forParameter.offset;
}
@Override
public int hashCode() {
return offset;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForParameter{" +
"offset=" + offset +
'}';
}
}
/**
* A read-only target mapping.
*/
class ForReadOnlyParameter implements Target {
/**
* The mapped offset.
*/
private final int offset;
/**
* Creates a new read-only target mapping.
*
* @param offset The mapped offset.
*/
protected ForReadOnlyParameter(int offset) {
this.offset = offset;
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ISTORE:
case Opcodes.LSTORE:
case Opcodes.FSTORE:
case Opcodes.DSTORE:
case Opcodes.ASTORE:
throw new IllegalStateException("Cannot write to read-only parameter at offset " + offset);
case Opcodes.ILOAD:
case Opcodes.LLOAD:
case Opcodes.FLOAD:
case Opcodes.DLOAD:
case Opcodes.ALOAD:
methodVisitor.visitVarInsn(opcode, offset);
break;
default:
throw new IllegalArgumentException("Did not expect opcode: " + opcode);
}
return NO_PADDING;
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
throw new IllegalStateException("Cannot write to read-only parameter at offset " + offset);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForReadOnlyParameter forReadOnlyParameter = (ForReadOnlyParameter) object;
return offset == forReadOnlyParameter.offset;
}
@Override
public int hashCode() {
return offset;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForReadOnlyParameter{" +
"offset=" + offset +
'}';
}
}
/**
* An offset mapping for a field.
*/
class ForField implements Target {
/**
* The field being read.
*/
private final FieldDescription fieldDescription;
/**
* Creates a new offset mapping for a field.
*
* @param fieldDescription The field being read.
*/
protected ForField(FieldDescription fieldDescription) {
this.fieldDescription = fieldDescription;
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ISTORE:
case Opcodes.ASTORE:
case Opcodes.FSTORE:
if (!fieldDescription.isStatic()) {
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.DUP_X1);
methodVisitor.visitInsn(Opcodes.POP);
accessField(methodVisitor, Opcodes.PUTFIELD);
return 2;
}
case Opcodes.LSTORE:
case Opcodes.DSTORE:
if (!fieldDescription.isStatic()) {
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.DUP_X2);
methodVisitor.visitInsn(Opcodes.POP);
accessField(methodVisitor, Opcodes.PUTFIELD);
return 2;
}
accessField(methodVisitor, Opcodes.PUTSTATIC);
return NO_PADDING;
case Opcodes.ILOAD:
case Opcodes.FLOAD:
case Opcodes.ALOAD:
case Opcodes.LLOAD:
case Opcodes.DLOAD:
if (fieldDescription.isStatic()) {
accessField(methodVisitor, Opcodes.GETSTATIC);
} else {
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
accessField(methodVisitor, Opcodes.GETFIELD);
}
return NO_PADDING;
default:
throw new IllegalArgumentException("Did not expect opcode: " + opcode);
}
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
if (fieldDescription.isStatic()) {
accessField(methodVisitor, Opcodes.GETSTATIC);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.IADD);
accessField(methodVisitor, Opcodes.PUTSTATIC);
return NO_PADDING;
} else {
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.DUP);
accessField(methodVisitor, Opcodes.GETFIELD);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.IADD);
accessField(methodVisitor, Opcodes.PUTFIELD);
return 2;
}
}
/**
* Accesses a field.
*
* @param methodVisitor The method visitor for which to access the field.
* @param opcode The opcode for accessing the field.
*/
private void accessField(MethodVisitor methodVisitor, int opcode) {
methodVisitor.visitFieldInsn(opcode,
fieldDescription.getDeclaringType().asErasure().getInternalName(),
fieldDescription.getInternalName(),
fieldDescription.getDescriptor());
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForField forField = (ForField) object;
return fieldDescription.equals(forField.fieldDescription);
}
@Override
public int hashCode() {
return fieldDescription.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForField{" +
"fieldDescription=" + fieldDescription +
'}';
}
}
/**
* An offset mapping for a field.
*/
class ForReadOnlyField implements Target {
/**
* The field being read.
*/
private final FieldDescription fieldDescription;
/**
* Creates a new offset mapping for a field.
*
* @param fieldDescription The field being read.
*/
protected ForReadOnlyField(FieldDescription fieldDescription) {
this.fieldDescription = fieldDescription;
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ISTORE:
case Opcodes.ASTORE:
case Opcodes.FSTORE:
case Opcodes.LSTORE:
case Opcodes.DSTORE:
throw new IllegalStateException("Cannot write to field: " + fieldDescription);
case Opcodes.ILOAD:
case Opcodes.FLOAD:
case Opcodes.ALOAD:
case Opcodes.LLOAD:
case Opcodes.DLOAD:
int accessOpcode;
if (fieldDescription.isStatic()) {
accessOpcode = Opcodes.GETSTATIC;
} else {
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
accessOpcode = Opcodes.GETFIELD;
}
methodVisitor.visitFieldInsn(accessOpcode,
fieldDescription.getDeclaringType().asErasure().getInternalName(),
fieldDescription.getInternalName(),
fieldDescription.getDescriptor());
break;
default:
throw new IllegalArgumentException("Did not expect opcode: " + opcode);
}
return NO_PADDING;
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
throw new IllegalStateException("Cannot write to field: " + fieldDescription);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForReadOnlyField forReadOnlyField = (ForReadOnlyField) object;
return fieldDescription.equals(forReadOnlyField.fieldDescription);
}
@Override
public int hashCode() {
return fieldDescription.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForReadOnlyField{" +
"fieldDescription=" + fieldDescription +
'}';
}
}
/**
* An offset mapping for a constant pool value.
*/
class ForConstantPoolValue implements Target {
/**
* The constant pool value.
*/
private final Object value;
/**
* Creates a mapping for a constant pool value.
*
* @param value The constant pool value.
*/
protected ForConstantPoolValue(Object value) {
this.value = value;
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ISTORE:
case Opcodes.ASTORE:
case Opcodes.FSTORE:
case Opcodes.LSTORE:
case Opcodes.DSTORE:
throw new IllegalStateException("Cannot write to fixed value: " + value);
case Opcodes.ILOAD:
case Opcodes.FLOAD:
case Opcodes.ALOAD:
case Opcodes.LLOAD:
case Opcodes.DLOAD:
methodVisitor.visitLdcInsn(value);
return NO_PADDING;
default:
throw new IllegalArgumentException("Did not expect opcode: " + opcode);
}
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
throw new IllegalStateException("Cannot write to fixed value: " + value);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForConstantPoolValue that = (ForConstantPoolValue) object;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForConstantPoolValue{" +
"value=" + value +
'}';
}
}
/**
* A target for an offset mapping that boxes a primitive parameter value.
*/
class ForBoxedParameter implements Target {
/**
* The parameters offset.
*/
private final int offset;
/**
* A dispatcher for boxing the primitive value.
*/
private final BoxingDispatcher boxingDispatcher;
/**
* Creates a new offset mapping for boxing a primitive parameter value.
*
* @param offset The parameters offset.
* @param boxingDispatcher A dispatcher for boxing the primitive value.
*/
protected ForBoxedParameter(int offset, BoxingDispatcher boxingDispatcher) {
this.offset = offset;
this.boxingDispatcher = boxingDispatcher;
}
/**
* Resolves a target representing an assignment of a boxed, primitive parameter value.
*
* @param offset The parameter's offset.
* @param type The primitive type of the parameter being boxed.
* @return An appropriate target.
*/
protected static Target of(int offset, TypeDefinition type) {
return new ForBoxedParameter(offset, BoxingDispatcher.of(type));
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ALOAD:
boxingDispatcher.loadBoxed(methodVisitor, offset);
return boxingDispatcher.getStackSize().getSize() - 1;
default:
throw new IllegalStateException("Unexpected opcode: " + opcode);
}
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
throw new IllegalStateException("Cannot increment a boxed parameter");
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForBoxedParameter that = (ForBoxedParameter) object;
return offset == that.offset && boxingDispatcher == that.boxingDispatcher;
}
@Override
public int hashCode() {
int result = offset;
result = 31 * result + boxingDispatcher.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForBoxedParameter{" +
"offset=" + offset +
", boxingDispatcher=" + boxingDispatcher +
'}';
}
/**
* A dispatcher for boxing a primitive value.
*/
protected enum BoxingDispatcher {
/**
* A boxing dispatcher for the {@code boolean} type.
*/
BOOLEAN(Opcodes.ILOAD, Boolean.class, boolean.class),
/**
* A boxing dispatcher for the {@code byte} type.
*/
BYTE(Opcodes.ILOAD, Byte.class, byte.class),
/**
* A boxing dispatcher for the {@code short} type.
*/
SHORT(Opcodes.ILOAD, Short.class, short.class),
/**
* A boxing dispatcher for the {@code char} type.
*/
CHARACTER(Opcodes.ILOAD, Character.class, char.class),
/**
* A boxing dispatcher for the {@code int} type.
*/
INTEGER(Opcodes.ILOAD, Integer.class, int.class),
/**
* A boxing dispatcher for the {@code long} type.
*/
LONG(Opcodes.LLOAD, Long.class, long.class),
/**
* A boxing dispatcher for the {@code float} type.
*/
FLOAT(Opcodes.FLOAD, Float.class, float.class),
/**
* A boxing dispatcher for the {@code double} type.
*/
DOUBLE(Opcodes.DLOAD, Double.class, double.class);
/**
* The name of the boxing method of a wrapper type.
*/
private static final String VALUE_OF = "valueOf";
/**
* The opcode to use for loading a value of this type.
*/
private final int opcode;
/**
* The name of the wrapper type.
*/
private final String owner;
/**
* The descriptor of the boxing method.
*/
private final String descriptor;
/**
* The required stack size of the unboxed value.
*/
private final StackSize stackSize;
/**
* Creates a new boxing dispatcher.
*
* @param opcode The opcode to use for loading a value of this type.
* @param wrapperType The represented wrapper type.
* @param primitiveType The represented primitive type.
*/
BoxingDispatcher(int opcode, Class<?> wrapperType, Class<?> primitiveType) {
this.opcode = opcode;
owner = Type.getInternalName(wrapperType);
descriptor = Type.getMethodDescriptor(Type.getType(wrapperType), Type.getType(primitiveType));
stackSize = StackSize.of(primitiveType);
}
/**
* Resolves a boxing dispatcher for the supplied primitive type.
*
* @param typeDefinition A description of a primitive type.
* @return An appropriate boxing dispatcher.
*/
protected static BoxingDispatcher of(TypeDefinition typeDefinition) {
if (typeDefinition.represents(boolean.class)) {
return BOOLEAN;
} else if (typeDefinition.represents(byte.class)) {
return BYTE;
} else if (typeDefinition.represents(short.class)) {
return SHORT;
} else if (typeDefinition.represents(char.class)) {
return CHARACTER;
} else if (typeDefinition.represents(int.class)) {
return INTEGER;
} else if (typeDefinition.represents(long.class)) {
return LONG;
} else if (typeDefinition.represents(float.class)) {
return FLOAT;
} else if (typeDefinition.represents(double.class)) {
return DOUBLE;
} else {
throw new IllegalArgumentException("Cannot box: " + typeDefinition);
}
}
/**
* Loads the value as a boxed version onto the stack.
*
* @param methodVisitor the method visitor for which to load the value.
* @param offset The offset of the primitive value.
*/
protected void loadBoxed(MethodVisitor methodVisitor, int offset) {
methodVisitor.visitVarInsn(opcode, offset);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, owner, VALUE_OF, descriptor, false);
}
/**
* Returns the stack size of the primitive value.
*
* @return The stack size of the primitive value.
*/
protected StackSize getStackSize() {
return stackSize;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForBoxedParameter.BoxingDispatcher." + name();
}
}
}
/**
* A target for an offset mapping of an array containing all (boxed) arguments of the instrumented method.
*/
class ForBoxedArguments implements Target {
/**
* The parameters of the instrumented method.
*/
private final List<ParameterDescription.InDefinedShape> parameters;
/**
* Creates a mapping for a boxed array containing all arguments of the instrumented method.
*
* @param parameters The parameters of the instrumented method.
*/
protected ForBoxedArguments(List<ParameterDescription.InDefinedShape> parameters) {
this.parameters = parameters;
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ALOAD:
loadInteger(methodVisitor, parameters.size());
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, TypeDescription.OBJECT.getInternalName());
StackSize stackSize = StackSize.ZERO;
for (ParameterDescription parameter : parameters) {
methodVisitor.visitInsn(Opcodes.DUP);
loadInteger(methodVisitor, parameter.getIndex());
if (parameter.getType().isPrimitive()) {
ForBoxedParameter.BoxingDispatcher.of(parameter.getType()).loadBoxed(methodVisitor, parameter.getOffset());
} else {
methodVisitor.visitVarInsn(Opcodes.ALOAD, parameter.getOffset());
}
methodVisitor.visitInsn(Opcodes.AASTORE);
stackSize = stackSize.maximum(parameter.getType().getStackSize());
}
return stackSize.getSize() + 2;
default:
throw new IllegalStateException("Unexpected opcode: " + opcode);
}
}
/**
* Loads an integer onto the operand stack.
*
* @param methodVisitor The method visitor for which the integer is loaded.
* @param value The integer value to load onto the stack.
*/
private static void loadInteger(MethodVisitor methodVisitor, int value) {
switch (value) {
case 0:
methodVisitor.visitInsn(Opcodes.ICONST_0);
break;
case 1:
methodVisitor.visitInsn(Opcodes.ICONST_1);
break;
case 2:
methodVisitor.visitInsn(Opcodes.ICONST_2);
break;
case 3:
methodVisitor.visitInsn(Opcodes.ICONST_3);
break;
case 4:
methodVisitor.visitInsn(Opcodes.ICONST_4);
break;
case 5:
methodVisitor.visitInsn(Opcodes.ICONST_5);
break;
default:
if (value < Byte.MAX_VALUE) {
methodVisitor.visitIntInsn(Opcodes.BIPUSH, value);
} else if (value < Short.MAX_VALUE) {
methodVisitor.visitIntInsn(Opcodes.SIPUSH, value);
} else {
methodVisitor.visitLdcInsn(value);
}
}
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
throw new IllegalStateException("Cannot increment a boxed argument");
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForBoxedArguments that = (ForBoxedArguments) object;
return parameters.equals(that.parameters);
}
@Override
public int hashCode() {
return parameters.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForBoxedArguments{" +
"parameters=" + parameters +
'}';
}
}
/**
* Binds a null constant to the target parameter.
*/
enum ForNullConstant implements Target {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ALOAD:
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
return NO_PADDING;
default:
throw new IllegalStateException("Unexpected opcode: " + opcode);
}
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
throw new IllegalStateException("Cannot increment a null constant");
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForNullConstant." + name();
}
}
/**
* Creates a target that represents a value in form of a serialized field.
*/
class ForSerializedObject implements Target {
/**
* A charset that does not change the supplied byte array upon encoding or decoding.
*/
private static final String CHARSET = "ISO-8859-1";
/**
* The target type.
*/
private final TypeDescription target;
/**
* The serialized form of the supplied form encoded as a string to be stored in the constant pool.
*/
private final String serialized;
/**
* Creates a target for an offset mapping that references a serialized value.
*
* @param target The target type.
* @param serialized The serialized form of the supplied form encoded as a string to be stored in the constant pool.
*/
protected ForSerializedObject(TypeDescription target, String serialized) {
this.target = target;
this.serialized = serialized;
}
/**
* Resolves a serializable value to a target that reads a value from reconstructing a serializable string representation.
*
* @param target The target type of the serializable value.
* @param value The value that the mapped field should represent.
* @return A target for deserializing the supplied value on access.
*/
protected static Target of(TypeDescription target, Serializable value) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
try {
objectOutputStream.writeObject(value);
} finally {
objectOutputStream.close();
}
return new ForSerializedObject(target, byteArrayOutputStream.toString(CHARSET));
} catch (IOException exception) {
throw new IllegalStateException("Cannot serialize " + value, exception);
}
}
@Override
public int resolveAccess(MethodVisitor methodVisitor, int opcode) {
switch (opcode) {
case Opcodes.ALOAD:
methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ObjectInputStream.class));
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ByteArrayInputStream.class));
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitLdcInsn(serialized);
methodVisitor.visitLdcInsn(CHARSET);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
Type.getInternalName(String.class),
"getBytes",
Type.getMethodType(Type.getType(byte[].class), Type.getType(String.class)).toString(),
false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
Type.getInternalName(ByteArrayInputStream.class),
MethodDescription.CONSTRUCTOR_INTERNAL_NAME,
Type.getMethodType(Type.VOID_TYPE, Type.getType(byte[].class)).toString(),
false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
Type.getInternalName(ObjectInputStream.class),
MethodDescription.CONSTRUCTOR_INTERNAL_NAME,
Type.getMethodType(Type.VOID_TYPE, Type.getType(InputStream.class)).toString(),
false);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
Type.getInternalName(ObjectInputStream.class),
"readObject",
Type.getMethodType(Type.getType(Object.class)).toString(),
false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, target.getInternalName());
return 5;
default:
throw new IllegalStateException("Unexpected opcode: " + opcode);
}
}
@Override
public int resolveIncrement(MethodVisitor methodVisitor, int increment) {
throw new IllegalStateException("Cannot increment serialized object");
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForSerializedObject that = (ForSerializedObject) object;
return target.equals(that.target) && serialized.equals(that.serialized);
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + serialized.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForSerializedObject{" +
"target=" + target +
", serialized='" + serialized + '\'' +
'}';
}
}
}
/**
* Represents a factory for creating a {@link OffsetMapping} for a given parameter.
*/
interface Factory {
/**
* Indicates that an offset mapping is undefined.
*/
OffsetMapping UNDEFINED = null;
/**
* Creates a new offset mapping for the supplied parameter if possible.
*
* @param parameterDescription The parameter description for which to resolve an offset mapping.
* @return A resolved offset mapping or {@code null} if no mapping can be resolved for this parameter.
*/
OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription);
}
/**
* An offset mapping for a given parameter of the instrumented method.
*/
class ForParameter implements OffsetMapping {
/**
* The index of the parameter.
*/
private final int index;
/**
* Determines if the parameter is to be treated as read-only.
*/
private final boolean readOnly;
/**
* The type expected by the advice method.
*/
private final TypeDescription targetType;
/**
* Creates a new offset mapping for a parameter.
*
* @param argument The annotation for which the mapping is to be created.
* @param targetType Determines if the parameter is to be treated as read-only.
*/
protected ForParameter(Argument argument, TypeDescription targetType) {
this(argument.value(), argument.readOnly(), targetType);
}
/**
* Creates a new offset mapping for a parameter of the instrumented method.
*
* @param index The index of the parameter.
* @param readOnly Determines if the parameter is to be treated as read-only.
* @param targetType The type expected by the advice method.
*/
protected ForParameter(int index, boolean readOnly, TypeDescription targetType) {
this.index = index;
this.readOnly = readOnly;
this.targetType = targetType;
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
ParameterList<?> parameters = instrumentedMethod.getParameters();
if (parameters.size() <= index) {
throw new IllegalStateException(instrumentedMethod + " does not define an index " + index);
} else if (!readOnly && !parameters.get(index).getType().asErasure().equals(targetType)) {
throw new IllegalStateException("read-only " + targetType + " is not equal to type of " + parameters.get(index));
} else if (readOnly && !parameters.get(index).getType().asErasure().isAssignableTo(targetType)) {
throw new IllegalStateException(targetType + " is not assignable to " + parameters.get(index));
}
return readOnly
? new Target.ForReadOnlyParameter(parameters.get(index).getOffset())
: new Target.ForParameter(parameters.get(index).getOffset());
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForParameter that = (ForParameter) object;
return index == that.index
&& readOnly == that.readOnly
&& targetType.equals(that.targetType);
}
@Override
public int hashCode() {
int result = index;
result = 31 * result + (readOnly ? 1 : 0);
result = 31 * result + targetType.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForParameter{" +
"index=" + index +
", readOnly=" + readOnly +
", targetType=" + targetType +
'}';
}
/**
* A factory for creating a {@link ForParameter} offset mapping.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Argument> annotation = parameterDescription.getDeclaredAnnotations().ofType(Argument.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot define writable field access for " + parameterDescription);
} else {
return new ForParameter(annotation.loadSilent(), parameterDescription.getType().asErasure());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForParameter.Factory." + name();
}
}
}
/**
* An offset mapping that provides access to the {@code this} reference of the instrumented method.
*/
class ForThisReference implements OffsetMapping {
/**
* The offset of the this reference in a Java method.
*/
private static final int THIS_REFERENCE = 0;
/**
* Determines if the parameter is to be treated as read-only.
*/
private final boolean readOnly;
/**
* The type that the advice method expects for the {@code this} reference.
*/
private final TypeDescription targetType;
/**
* Creates a new offset mapping for a {@code this} reference.
*
* @param readOnly Determines if the parameter is to be treated as read-only.
* @param targetType The type that the advice method expects for the {@code this} reference.
*/
protected ForThisReference(boolean readOnly, TypeDescription targetType) {
this.readOnly = readOnly;
this.targetType = targetType;
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
if (instrumentedMethod.isStatic()) {
throw new IllegalStateException("Cannot map this reference for static method " + instrumentedMethod);
} else if (!readOnly && !instrumentedMethod.getDeclaringType().equals(targetType)) {
throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not equal to read-only " + targetType);
} else if (readOnly && !instrumentedMethod.getDeclaringType().isAssignableTo(targetType)) {
throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not assignable to " + targetType);
} else if (!context.isInitialized()) {
throw new IllegalStateException("Cannot access this reference before calling constructor: " + instrumentedMethod);
}
return readOnly
? new Target.ForReadOnlyParameter(THIS_REFERENCE)
: new Target.ForParameter(THIS_REFERENCE);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForThisReference that = (ForThisReference) object;
return readOnly == that.readOnly
&& targetType.equals(that.targetType);
}
@Override
public int hashCode() {
int result = (readOnly ? 1 : 0);
result = 31 * result + targetType.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThisReference{" +
"readOnly=" + readOnly +
", targetType=" + targetType +
'}';
}
/**
* A factory for creating a {@link ForThisReference} offset mapping.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<This> annotation = parameterDescription.getDeclaredAnnotations().ofType(This.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot write to this reference for " + parameterDescription + " in read-only context");
} else {
return new ForThisReference(annotation.loadSilent().readOnly(), parameterDescription.getType().asErasure());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThisReference.Factory." + name();
}
}
}
/**
* Maps the declaring type of the instrumented method.
*/
enum ForInstrumentedType implements OffsetMapping {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
return new Target.ForConstantPoolValue(Type.getType(instrumentedMethod.getDeclaringType().getDescriptor()));
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForInstrumentedType." + name();
}
}
/**
* An offset mapping for a field.
*/
abstract class ForField implements OffsetMapping {
/**
* The {@link FieldValue#value()} method.
*/
private static final MethodDescription.InDefinedShape VALUE;
/**
* The {@link FieldValue#declaringType()}} method.
*/
private static final MethodDescription.InDefinedShape DECLARING_TYPE;
/**
* The {@link FieldValue#readOnly()}} method.
*/
private static final MethodDescription.InDefinedShape READ_ONLY;
static {
MethodList<MethodDescription.InDefinedShape> methods = new TypeDescription.ForLoadedType(FieldValue.class).getDeclaredMethods();
VALUE = methods.filter(named("value")).getOnly();
DECLARING_TYPE = methods.filter(named("declaringType")).getOnly();
READ_ONLY = methods.filter(named("readOnly")).getOnly();
}
/**
* The name of the field.
*/
protected final String name;
/**
* The expected type that the field can be assigned to.
*/
protected final TypeDescription targetType;
/**
* {@code true} if this mapping is read-only.
*/
protected final boolean readOnly;
/**
* Creates an offset mapping for a field.
*
* @param name The name of the field.
* @param targetType The expected type that the field can be assigned to.
* @param readOnly {@code true} if this mapping is read-only.
*/
protected ForField(String name, TypeDescription targetType, boolean readOnly) {
this.name = name;
this.targetType = targetType;
this.readOnly = readOnly;
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
FieldLocator.Resolution resolution = fieldLocator(instrumentedMethod.getDeclaringType()).locate(name);
if (!resolution.isResolved()) {
throw new IllegalStateException("Cannot locate field named " + name + " for " + instrumentedMethod);
} else if (readOnly && !resolution.getField().getType().asErasure().isAssignableTo(targetType)) {
throw new IllegalStateException("Cannot assign type of read-only field " + resolution.getField() + " to " + targetType);
} else if (!readOnly && !resolution.getField().getType().asErasure().equals(targetType)) {
throw new IllegalStateException("Type of field " + resolution.getField() + " is not equal to " + targetType);
} else if (!resolution.getField().isStatic() && instrumentedMethod.isStatic()) {
throw new IllegalStateException("Cannot read non-static field " + resolution.getField() + " from static method " + instrumentedMethod);
} else if (!context.isInitialized() && !resolution.getField().isStatic()) {
throw new IllegalStateException("Cannot access non-static field before calling constructor: " + instrumentedMethod);
}
return readOnly
? new Target.ForReadOnlyField(resolution.getField())
: new Target.ForField(resolution.getField());
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForField forField = (ForField) object;
return name.equals(forField.name) && targetType.equals(forField.targetType) && readOnly == forField.readOnly;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + targetType.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
return result;
}
/**
* Returns a field locator for this instance.
*
* @param instrumentedType The instrumented type.
* @return An appropriate field locator.
*/
protected abstract FieldLocator fieldLocator(TypeDescription instrumentedType);
/**
* An offset mapping for a field with an implicit declaring type.
*/
protected static class WithImplicitType extends ForField {
/**
* Creates an offset mapping for a field with an implicit declaring type.
*
* @param name The name of the field.
* @param targetType The expected type that the field can be assigned to.
* @param readOnly {@code true} if the field is read-only.
*/
protected WithImplicitType(String name, TypeDescription targetType, boolean readOnly) {
super(name, targetType, readOnly);
}
@Override
protected FieldLocator fieldLocator(TypeDescription instrumentedType) {
return new FieldLocator.ForClassHierarchy(instrumentedType);
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForField.WithImplicitType{" +
"name=" + name +
", targetType=" + targetType +
'}';
}
}
/**
* An offset mapping for a field with an explicit declaring type.
*/
protected static class WithExplicitType extends ForField {
/**
* The type declaring the field.
*/
private final TypeDescription explicitType;
/**
* Creates an offset mapping for a field with an explicit declaring type.
*
* @param name The name of the field.
* @param targetType The expected type that the field can be assigned to.
* @param locatedType The type declaring the field.
* @param readOnly {@code true} if the field is read-only.
*/
protected WithExplicitType(String name, TypeDescription targetType, TypeDescription locatedType, boolean readOnly) {
super(name, targetType, readOnly);
this.explicitType = locatedType;
}
@Override
protected FieldLocator fieldLocator(TypeDescription instrumentedType) {
if (!instrumentedType.isAssignableTo(explicitType)) {
throw new IllegalStateException(explicitType + " is no super type of " + instrumentedType);
}
return new FieldLocator.ForExactType(explicitType);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
if (!super.equals(object)) return false;
WithExplicitType that = (WithExplicitType) object;
return explicitType.equals(that.explicitType);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + explicitType.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForField.WithExplicitType{" +
"name=" + name +
", targetType=" + targetType +
", explicitType=" + explicitType +
'}';
}
}
/**
* A factory for a {@link ForField} offset mapping.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription annotation = parameterDescription.getDeclaredAnnotations().ofType(FieldValue.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.getValue(ForField.READ_ONLY, Boolean.class)) {
throw new IllegalStateException("Cannot write to field for " + parameterDescription + " in read-only context");
} else {
TypeDescription declaringType = annotation.getValue(DECLARING_TYPE, TypeDescription.class);
String name = annotation.getValue(VALUE, String.class);
TypeDescription targetType = parameterDescription.getType().asErasure();
return declaringType.represents(void.class)
? new WithImplicitType(name, targetType, annotation.getValue(ForField.READ_ONLY, Boolean.class))
: new WithExplicitType(name, targetType, declaringType, annotation.getValue(ForField.READ_ONLY, Boolean.class));
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForField.Factory." + name();
}
}
}
/**
* An offset mapping for the {@link Advice.Origin} annotation.
*/
class ForOrigin implements OffsetMapping {
/**
* The delimiter character.
*/
private static final char DELIMITER = '
/**
* The escape character.
*/
private static final char ESCAPE = '\\';
/**
* The renderers to apply.
*/
private final List<Renderer> renderers;
/**
* Creates a new offset mapping for an origin value.
*
* @param renderers The renderers to apply.
*/
protected ForOrigin(List<Renderer> renderers) {
this.renderers = renderers;
}
/**
* Parses a pattern of an origin annotation.
*
* @param pattern The supplied pattern.
* @return An appropriate offset mapping.
*/
protected static OffsetMapping parse(String pattern) {
if (pattern.equals(Origin.DEFAULT)) {
return new ForOrigin(Collections.<Renderer>singletonList(Renderer.ForStringRepresentation.INSTANCE));
} else {
List<Renderer> renderers = new ArrayList<Renderer>(pattern.length());
int from = 0;
for (int to = pattern.indexOf(DELIMITER); to != -1; to = pattern.indexOf(DELIMITER, from)) {
if (to != 0 && pattern.charAt(to - 1) == ESCAPE && (to == 1 || pattern.charAt(to - 2) != ESCAPE)) {
renderers.add(new Renderer.ForConstantValue(pattern.substring(from, Math.max(0, to - 1)) + DELIMITER));
from = to + 1;
continue;
} else if (pattern.length() == to + 1) {
throw new IllegalStateException("Missing sort descriptor for " + pattern + " at index " + to);
}
renderers.add(new Renderer.ForConstantValue(pattern.substring(from, to).replace("" + ESCAPE + ESCAPE, "" + ESCAPE)));
switch (pattern.charAt(to + 1)) {
case Renderer.ForMethodName.SYMBOL:
renderers.add(Renderer.ForMethodName.INSTANCE);
break;
case Renderer.ForTypeName.SYMBOL:
renderers.add(Renderer.ForTypeName.INSTANCE);
break;
case Renderer.ForDescriptor.SYMBOL:
renderers.add(Renderer.ForDescriptor.INSTANCE);
break;
case Renderer.ForReturnTypeName.SYMBOL:
renderers.add(Renderer.ForReturnTypeName.INSTANCE);
break;
case Renderer.ForJavaSignature.SYMBOL:
renderers.add(Renderer.ForJavaSignature.INSTANCE);
break;
default:
throw new IllegalStateException("Illegal sort descriptor " + pattern.charAt(to + 1) + " for " + pattern);
}
from = to + 2;
}
renderers.add(new Renderer.ForConstantValue(pattern.substring(from)));
return new ForOrigin(renderers);
}
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
StringBuilder stringBuilder = new StringBuilder();
for (Renderer renderer : renderers) {
stringBuilder.append(renderer.apply(instrumentedMethod));
}
return new Target.ForConstantPoolValue(stringBuilder.toString());
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForOrigin forOrigin = (ForOrigin) object;
return renderers.equals(forOrigin.renderers);
}
@Override
public int hashCode() {
return renderers.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin{" +
"renderers=" + renderers +
'}';
}
/**
* A renderer for an origin pattern element.
*/
protected interface Renderer {
/**
* Returns a string representation for this renderer.
*
* @param instrumentedMethod The method being rendered.
* @return The string representation.
*/
String apply(MethodDescription.InDefinedShape instrumentedMethod);
/**
* A renderer for a method's internal name.
*/
enum ForMethodName implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The method name symbol.
*/
public static final char SYMBOL = 'm';
@Override
public String apply(MethodDescription.InDefinedShape instrumentedMethod) {
return instrumentedMethod.getInternalName();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForMethodName." + name();
}
}
/**
* A renderer for a method declaring type's binary name.
*/
enum ForTypeName implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The type name symbol.
*/
public static final char SYMBOL = 't';
@Override
public String apply(MethodDescription.InDefinedShape instrumentedMethod) {
return instrumentedMethod.getDeclaringType().getName();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForTypeName." + name();
}
}
/**
* A renderer for a method descriptor.
*/
enum ForDescriptor implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The descriptor symbol.
*/
public static final char SYMBOL = 'd';
@Override
public String apply(MethodDescription.InDefinedShape instrumentedMethod) {
return instrumentedMethod.getDescriptor();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForDescriptor." + name();
}
}
/**
* A renderer for a method's Java signature in binary form.
*/
enum ForJavaSignature implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The signature symbol.
*/
public static final char SYMBOL = 's';
@Override
public String apply(MethodDescription.InDefinedShape instrumentedMethod) {
StringBuilder stringBuilder = new StringBuilder("(");
boolean comma = false;
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
if (comma) {
stringBuilder.append(',');
} else {
comma = true;
}
stringBuilder.append(typeDescription.getName());
}
return stringBuilder.append(')').toString();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForJavaSignature." + name();
}
}
/**
* A renderer for a method's return type in binary form.
*/
enum ForReturnTypeName implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The return type symbol.
*/
public static final char SYMBOL = 'r';
@Override
public String apply(MethodDescription.InDefinedShape instrumentedMethod) {
return instrumentedMethod.getReturnType().asErasure().getName();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForReturnTypeName." + name();
}
}
/**
* A renderer for a method's {@link Object#toString()} representation.
*/
enum ForStringRepresentation implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public String apply(MethodDescription.InDefinedShape instrumentedMethod) {
return instrumentedMethod.toString();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForStringRepresentation." + name();
}
}
/**
* A renderer for a constant value.
*/
class ForConstantValue implements Renderer {
/**
* The constant value.
*/
private final String value;
/**
* Creates a new renderer for a constant value.
*
* @param value The constant value.
*/
protected ForConstantValue(String value) {
this.value = value;
}
@Override
public String apply(MethodDescription.InDefinedShape instrumentedMethod) {
return value;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForConstantValue that = (ForConstantValue) object;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForConstantValue{" +
"value='" + value + '\'' +
'}';
}
}
}
/**
* A factory for a method origin.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Origin> origin = parameterDescription.getDeclaredAnnotations().ofType(Origin.class);
if (origin == null) {
return UNDEFINED;
} else if (parameterDescription.getType().asErasure().represents(Class.class)) {
return OffsetMapping.ForInstrumentedType.INSTANCE;
} else if (parameterDescription.getType().asErasure().isAssignableFrom(String.class)) {
return ForOrigin.parse(origin.loadSilent().value());
} else {
throw new IllegalStateException("Non-String type " + parameterDescription + " for origin annotation");
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Factory." + name();
}
}
}
/**
* An offset mapping for a parameter where assignments are fully ignored and that always return the parameter type's default value.
*/
enum ForIgnored implements OffsetMapping, Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
return Target.ForDefaultValue.INSTANCE;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
return parameterDescription.getDeclaredAnnotations().isAnnotationPresent(Ignored.class)
? this
: UNDEFINED;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForIgnored." + name();
}
}
/**
* An offset mapping that provides access to the value that is returned by the enter advice.
*/
enum ForEnterValue implements OffsetMapping {
/**
* Enables writing to the mapped offset.
*/
WRITABLE(false),
/**
* Only allows for reading the mapped offset.
*/
READ_ONLY(true);
/**
* Determines if the parameter is to be treated as read-only.
*/
private final boolean readOnly;
/**
* Creates a new offset mapping for an enter value.
*
* @param readOnly Determines if the parameter is to be treated as read-only.
*/
ForEnterValue(boolean readOnly) {
this.readOnly = readOnly;
}
/**
* Resolves an offset mapping for an enter value.
*
* @param readOnly {@code true} if the value is to be treated as read-only.
* @return An appropriate offset mapping.
*/
public static OffsetMapping of(boolean readOnly) {
return readOnly
? READ_ONLY
: WRITABLE;
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
return readOnly
? new Target.ForReadOnlyParameter(instrumentedMethod.getStackSize())
: new Target.ForParameter(instrumentedMethod.getStackSize());
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForEnterValue." + name();
}
/**
* A factory for creating a {@link ForEnterValue} offset mapping.
*/
protected static class Factory implements OffsetMapping.Factory {
/**
* The supplied type of the enter method.
*/
private final TypeDescription enterType;
/**
* Indicates that the mapped parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory for creating a {@link ForEnterValue} offset mapping.
*
* @param enterType The supplied type of the enter method.
* @param readOnly Indicates that the mapped parameter is read-only.
*/
protected Factory(TypeDescription enterType, boolean readOnly) {
this.enterType = enterType;
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Enter> annotation = parameterDescription.getDeclaredAnnotations().ofType(Enter.class);
if (annotation != null) {
boolean readOnly = annotation.loadSilent().readOnly();
if (!readOnly && !enterType.equals(parameterDescription.getType().asErasure())) {
throw new IllegalStateException("read-only type of " + parameterDescription + " does not equal " + enterType);
} else if (readOnly && !enterType.isAssignableTo(parameterDescription.getType().asErasure())) {
throw new IllegalStateException("Cannot assign the type of " + parameterDescription + " to supplied type " + enterType);
} else if (this.readOnly && !readOnly) {
throw new IllegalStateException("Cannot write to enter value field for " + parameterDescription + " in read only context");
}
return ForEnterValue.of(readOnly);
} else {
return UNDEFINED;
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Factory factory = (Factory) object;
if (readOnly != factory.readOnly) return false;
return enterType.equals(factory.enterType);
}
@Override
public int hashCode() {
int result = enterType.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForEnterValue.Factory{" +
"enterType=" + enterType +
"m readOnly=" + readOnly +
'}';
}
}
}
/**
* An offset mapping that provides access to the value that is returned by the instrumented method.
*/
class ForReturnValue implements OffsetMapping {
/**
* Determines if the parameter is to be treated as read-only.
*/
private final boolean readOnly;
/**
* The type that the advice method expects for the {@code this} reference.
*/
private final TypeDescription targetType;
/**
* Creates an offset mapping for accessing the return type of the instrumented method.
*
* @param readOnly Determines if the parameter is to be treated as read-only.
* @param targetType The expected target type of the return type.
*/
protected ForReturnValue(boolean readOnly, TypeDescription targetType) {
this.readOnly = readOnly;
this.targetType = targetType;
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
if (!readOnly && !instrumentedMethod.getReturnType().asErasure().equals(targetType)) {
throw new IllegalStateException("read-only return type of " + instrumentedMethod + " is not equal to " + targetType);
} else if (readOnly && !instrumentedMethod.getReturnType().asErasure().isAssignableTo(targetType)) {
throw new IllegalStateException("Cannot assign return type of " + instrumentedMethod + " to " + targetType);
}
return readOnly
? new Target.ForReadOnlyParameter(instrumentedMethod.getStackSize() + context.getPadding())
: new Target.ForParameter(instrumentedMethod.getStackSize() + context.getPadding());
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ForReturnValue that = (ForReturnValue) other;
return readOnly == that.readOnly && targetType.equals(that.targetType);
}
@Override
public int hashCode() {
return (readOnly ? 1 : 0) + 31 * targetType.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForReturnValue{" +
"readOnly=" + readOnly +
", targetType=" + targetType +
'}';
}
/**
* A factory for creating a {@link ForReturnValue} offset mapping.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Return> annotation = parameterDescription.getDeclaredAnnotations().ofType(Return.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot write return value for " + parameterDescription + " in read-only context");
} else {
return new ForReturnValue(annotation.loadSilent().readOnly(), parameterDescription.getType().asErasure());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForReturnValue.Factory." + name();
}
}
}
/**
* An offset mapping for the method's (boxed) return value.
*/
enum ForBoxedReturnValue implements OffsetMapping, Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
if (instrumentedMethod.getReturnType().represents(void.class)) {
return Target.ForNullConstant.INSTANCE;
} else if (instrumentedMethod.getReturnType().isPrimitive()) {
return Target.ForBoxedParameter.of(instrumentedMethod.getStackSize() + context.getPadding(), instrumentedMethod.getReturnType());
} else {
return new Target.ForReadOnlyParameter(instrumentedMethod.getStackSize() + context.getPadding());
}
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
if (!parameterDescription.getDeclaredAnnotations().isAnnotationPresent(BoxedReturn.class)) {
return UNDEFINED;
} else if (parameterDescription.getType().represents(Object.class)) {
return this;
} else {
throw new IllegalStateException("Can only assign a boxed return value to an Object type");
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForBoxedReturnValue." + name();
}
}
/**
* An offset mapping for an array containing the (boxed) method arguments.
*/
enum ForBoxedArguments implements OffsetMapping, Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
return new Target.ForBoxedArguments(instrumentedMethod.getParameters());
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
if (!parameterDescription.getDeclaredAnnotations().isAnnotationPresent(BoxedArguments.class)) {
return UNDEFINED;
} else if (parameterDescription.getType().represents(Object[].class)) {
return this;
} else {
throw new IllegalStateException("Can only assign an array of boxed arguments to an Object[] array");
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForBoxedArguments." + name();
}
}
/**
* An offset mapping for accessing a {@link Throwable} of the instrumented method.
*/
enum ForThrowable implements OffsetMapping {
/**
* A mapping that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A mapping that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new offset mapping.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
ForThrowable(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
int offset = instrumentedMethod.getStackSize() + context.getPadding() + instrumentedMethod.getReturnType().getStackSize().getSize();
return readOnly
? new Target.ForReadOnlyParameter(offset)
: new Target.ForParameter(offset);
}
/**
* A factory for accessing an exception that was thrown by the instrumented method.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Thrown> annotation = parameterDescription.getDeclaredAnnotations().ofType(Thrown.class);
if (annotation == null) {
return UNDEFINED;
} else if (!parameterDescription.getType().represents(Throwable.class)) {
throw new IllegalStateException("Parameter must be of type Throwable for " + parameterDescription);
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot write exception value for " + parameterDescription + " in read-only context");
} else {
return annotation.loadSilent().readOnly()
? ForThrowable.READ_ONLY
: ForThrowable.READ_WRITE;
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThrowable.Factory." + name();
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThrowable." + name();
}
}
/**
* Represents an offset mapping for a user-defined value.
*
* @param <T> The mapped annotation type.
*/
class ForUserValue<T extends Annotation> implements OffsetMapping {
/**
* The target parameter that is bound.
*/
private final ParameterDescription.InDefinedShape target;
/**
* The annotation value that triggered the binding.
*/
private final AnnotationDescription.Loadable<T> annotation;
/**
* The dynamic value that is bound.
*/
private final DynamicValue<T> dynamicValue;
/**
* Creates a new offset mapping for a user-defined value.
*
* @param target The target parameter that is bound.
* @param annotation The annotation value that triggered the binding.
* @param dynamicValue The dynamic value that is bound.
*/
protected ForUserValue(ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<T> annotation,
DynamicValue<T> dynamicValue) {
this.target = target;
this.annotation = annotation;
this.dynamicValue = dynamicValue;
}
@Override
public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) {
Object value = dynamicValue.resolve(instrumentedMethod, target, annotation, context.isInitialized());
if (value == null) {
if (target.getType().isPrimitive()) {
throw new IllegalStateException("Cannot map null to primitive type of " + target);
}
return Target.ForNullConstant.INSTANCE;
} else if ((target.getType().asErasure().isAssignableFrom(String.class) && value instanceof String)
|| (target.getType().isPrimitive() && target.getType().asErasure().isInstanceOrWrapper(value))) {
if (value instanceof Boolean) {
value = (Boolean) value ? 1 : 0;
} else if (value instanceof Byte) {
value = ((Byte) value).intValue();
} else if (value instanceof Short) {
value = ((Short) value).intValue();
} else if (value instanceof Character) {
value = (int) ((Character) value).charValue();
}
return new Target.ForConstantPoolValue(value);
} else if (target.getType().asErasure().isAssignableFrom(Class.class) && value instanceof Class) {
return new Target.ForConstantPoolValue(Type.getType((Class<?>) value));
} else if (target.getType().asErasure().isAssignableFrom(Class.class) && value instanceof TypeDescription) {
return new Target.ForConstantPoolValue(Type.getType(((TypeDescription) value).getDescriptor()));
} else if (!target.getType().isPrimitive() && !target.getType().isArray() && value instanceof Serializable && target.getType().asErasure().isInstance(value)) {
return Target.ForSerializedObject.of(target.getType().asErasure(), (Serializable) value);
} else {
throw new IllegalStateException("Cannot map " + value + " as constant value of " + target.getType());
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForUserValue that = (ForUserValue) object;
return target.equals(that.target)
&& annotation.equals(that.annotation)
&& dynamicValue.equals(that.dynamicValue);
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + annotation.hashCode();
result = 31 * result + dynamicValue.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForUserValue{" +
"target=" + target +
", annotation=" + annotation +
", dynamicValue=" + dynamicValue +
'}';
}
/**
* A factory for mapping a user-defined dynamic value.
*
* @param <S> The mapped annotation type.
*/
protected static class Factory<S extends Annotation> implements OffsetMapping.Factory {
/**
* The mapped annotation type.
*/
private final Class<S> type;
/**
* The dynamic value instance used for resolving a binding.
*/
private final DynamicValue<S> dynamicValue;
/**
* Creates a new factory for a user-defined dynamic value.
*
* @param type The mapped annotation type.
* @param dynamicValue The dynamic value instance used for resolving a binding.
*/
protected Factory(Class<S> type, DynamicValue<S> dynamicValue) {
this.type = type;
this.dynamicValue = dynamicValue;
}
/**
* Creates a new factory for mapping a user value.
*
* @param type The mapped annotation type.
* @param dynamicValue The dynamic value instance used for resolving a binding.
* @return An appropriate factory for such a offset mapping.
*/
@SuppressWarnings("unchecked")
protected static OffsetMapping.Factory of(Class<? extends Annotation> type, DynamicValue<?> dynamicValue) {
return new Factory(type, dynamicValue);
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<S> annotation = parameterDescription.getDeclaredAnnotations().ofType(type);
return annotation == null
? UNDEFINED
: new ForUserValue<S>(parameterDescription, annotation, dynamicValue);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Factory factory = (Factory) object;
return type.equals(factory.type) && dynamicValue.equals(factory.dynamicValue);
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + dynamicValue.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForUserValue.Factory{" +
"type=" + type +
", dynamicValue=" + dynamicValue +
'}';
}
}
}
class Illegal implements Factory {
private final List<? extends Class<? extends Annotation>> annotations;
//@SafeVarargs
protected Illegal(Class<? extends Annotation>... annotation) {
this(Arrays.asList(annotation));
}
protected Illegal(List<? extends Class<? extends Annotation>> annotations) {
this.annotations = annotations;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
for (Class<? extends Annotation> annotation : annotations) {
if (parameterDescription.getDeclaredAnnotations().isAnnotationPresent(annotation)) {
throw new IllegalStateException("Illegal annotation " + annotation + " for " + parameterDescription);
}
}
return UNDEFINED;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Illegal illegal = (Illegal) other;
return annotations.equals(illegal.annotations);
}
@Override
public int hashCode() {
return annotations.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Illegal{" +
"annotations=" + annotations +
'}';
}
}
}
/**
* A suppression handler for optionally suppressing exceptions.
*/
interface SuppressionHandler {
/**
* Binds the suppression handler for instrumenting a specific method.
*
* @return A bound version of the suppression handler.
*/
Bound bind();
/**
* A producer for a default return value if this is applicable.
*/
interface ReturnValueProducer {
/**
* Stores a default return value for the advised method.
*
* @param methodVisitor The instrumented method's method visitor.
*/
void storeDefaultValue(MethodVisitor methodVisitor);
}
/**
* A bound version of a suppression handler that must not be reused.
*/
interface Bound {
/**
* Invoked to prepare the suppression handler, i.e. to write an exception handler entry if appropriate.
*
* @param methodVisitor The method visitor to apply the preparation to.
*/
void onPrepare(MethodVisitor methodVisitor);
/**
* Invoked at the start of a method.
*
* @param methodVisitor The method visitor of the instrumented method.
* @param metaDataHandler The meta data handler to use for translating meta data.
*/
void onStart(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler);
/**
* Invoked at the end of a method.
*
* @param methodVisitor The method visitor of the instrumented method.
* @param metaDataHandler The meta data handler to use for translating meta data.
* @param returnValueProducer A producer for defining a default return value of the advised method.
*/
void onEnd(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer);
/**
* Invoked at the end of a method. Additionally indicates that the handler block should be surrounding by a skipping instruction.
*
* @param methodVisitor The method visitor of the instrumented method.
* @param metaDataHandler The meta data handler to use for translating meta data.
* @param returnValueProducer A producer for defining a default return value of the advised method.
*/
void onEndSkipped(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer);
}
/**
* A non-operational suppression handler that does not suppress any method.
*/
enum NoOp implements SuppressionHandler, Bound {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Bound bind() {
return this;
}
@Override
public void onPrepare(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public void onStart(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler) {
/* do nothing */
}
@Override
public void onEnd(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer) {
/* do nothing */
}
@Override
public void onEndSkipped(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer) {
metaDataHandler.injectCompletionFrame(methodVisitor, false);
}
@Override
public String toString() {
return "Advice.Dispatcher.SuppressionHandler.NoOp." + name();
}
}
/**
* A suppression handler that suppresses a given throwable type.
*/
class Suppressing implements SuppressionHandler {
/**
* The suppressed throwable type.
*/
private final TypeDescription throwableType;
/**
* Creates a new suppressing suppression handler.
*
* @param throwableType The suppressed throwable type.
*/
protected Suppressing(TypeDescription throwableType) {
this.throwableType = throwableType;
}
@Override
public SuppressionHandler.Bound bind() {
return new Bound(throwableType);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Suppressing that = (Suppressing) object;
return throwableType.equals(that.throwableType);
}
@Override
public int hashCode() {
return throwableType.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.SuppressionHandler.Suppressing{" +
"throwableType=" + throwableType +
'}';
}
/**
* An active, bound suppression handler.
*/
protected static class Bound implements SuppressionHandler.Bound {
/**
* The suppressed throwable type.
*/
private final TypeDescription throwableType;
/**
* A label indicating the start of the method.
*/
private final Label startOfMethod;
/**
* A label indicating the end of the method.
*/
private final Label endOfMethod;
/**
* Creates a new active, bound suppression handler.
*
* @param throwableType The suppressed throwable type.
*/
protected Bound(TypeDescription throwableType) {
this.throwableType = throwableType;
startOfMethod = new Label();
endOfMethod = new Label();
}
@Override
public void onPrepare(MethodVisitor methodVisitor) {
methodVisitor.visitTryCatchBlock(startOfMethod, endOfMethod, endOfMethod, throwableType.getInternalName());
}
@Override
public void onStart(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler) {
methodVisitor.visitLabel(startOfMethod);
}
@Override
public void onEnd(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer) {
writeHandler(methodVisitor, metaDataHandler, returnValueProducer);
}
@Override
public void onEndSkipped(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer) {
Label endOfHandler = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfHandler);
writeHandler(methodVisitor, metaDataHandler, returnValueProducer);
methodVisitor.visitLabel(endOfHandler);
metaDataHandler.injectCompletionFrame(methodVisitor, false);
}
/**
* Invoked for writing the ending segment of this suppression handler.
*
* @param methodVisitor The method visitor to which to write the suppression handler to.
* @param metaDataHandler The meta data handler to apply.
* @param returnValueProducer The return value producer to use.
*/
private void writeHandler(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer) {
methodVisitor.visitLabel(endOfMethod);
metaDataHandler.injectHandlerFrame(methodVisitor);
methodVisitor.visitInsn(Opcodes.POP);
returnValueProducer.storeDefaultValue(methodVisitor);
}
@Override
public String toString() {
return "Advice.Dispatcher.SuppressionHandler.Suppressing.Bound{" +
"throwableType=" + throwableType +
", startOfMethod=" + startOfMethod +
", endOfMethod=" + endOfMethod +
'}';
}
}
}
}
/**
* Represents a resolved dispatcher.
*/
interface Resolved extends Dispatcher {
/**
* Binds this dispatcher for resolution to a specific method.
*
* @param instrumentedMethod The instrumented method.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param metaDataHandler A meta data handler for writing to the instrumented method.
* @return A dispatcher that is bound to the instrumented method.
*/
Bound bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MetaDataHandler.ForInstrumentedMethod metaDataHandler);
/**
* Represents a resolved dispatcher for entering a method.
*/
interface ForMethodEnter extends Resolved {
/**
* Returns the type that this dispatcher supplies as a result of its advice or a description of {@code void} if
* no type is supplied as a result of the enter advice.
*
* @return The type that this dispatcher supplies as a result of its advice or a description of {@code void}.
*/
TypeDescription getEnterType();
}
/**
* Represents a resolved dispatcher for exiting a method.
*/
interface ForMethodExit extends Resolved {
/**
* Indicates if this advice requires to be called when the instrumented method terminates exceptionally.
*
* @return {@code true} if this advice requires to be called when the instrumented method terminates exceptionally.
*/
boolean isSkipThrowable();
}
}
/**
* A bound resolution of an advice method.
*/
interface Bound {
/**
* Prepares the advice method's exception handlers.
*/
void prepare();
/**
* Writes the advice method's code.
*/
void apply();
}
/**
* An implementation for inactive devise that does not write any byte code.
*/
enum Inactive implements Dispatcher.Unresolved, Resolved.ForMethodEnter, Resolved.ForMethodExit, Bound {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public boolean isAlive() {
return false;
}
@Override
public boolean isBinary() {
return false;
}
@Override
public boolean isSkipThrowable() {
return true;
}
@Override
public TypeDescription getEnterType() {
return TypeDescription.VOID;
}
@Override
public Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation) {
return this;
}
@Override
public Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation,
ForMethodEnter dispatcher) {
return this;
}
@Override
public void prepare() {
/* do nothing */
}
@Override
public void apply() {
/* do nothing */
}
@Override
public Bound bind(MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler) {
return this;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inactive." + name();
}
}
/**
* A dispatcher for an advice method that is being inlined into the instrumented method.
*/
class Inlining implements Unresolved {
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* Creates a dispatcher for inlined advice method.
*
* @param adviceMethod The advice method.
*/
protected Inlining(MethodDescription.InDefinedShape adviceMethod) {
this.adviceMethod = adviceMethod;
}
@Override
public boolean isAlive() {
return true;
}
@Override
public boolean isBinary() {
return true;
}
@Override
public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation) {
return new Resolved.ForMethodEnter(adviceMethod, userFactories, binaryRepresentation.resolve());
}
@Override
public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation,
Dispatcher.Resolved.ForMethodEnter dispatcher) {
return Resolved.ForMethodExit.of(adviceMethod, userFactories, binaryRepresentation.resolve(), dispatcher.getEnterType());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass()) && adviceMethod.equals(((Inlining) other).adviceMethod);
}
@Override
public int hashCode() {
return adviceMethod.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining{" +
"adviceMethod=" + adviceMethod +
'}';
}
/**
* A resolved version of a dispatcher.
*/
protected abstract static class Resolved implements Dispatcher.Resolved {
/**
* Indicates a read-only mapping for an offset.
*/
private static final boolean READ_ONLY = true;
/**
* The represented advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* The binary representation of the advice method.
*/
private final byte[] binaryRepresentation;
/**
* An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter.
*/
protected final Map<Integer, OffsetMapping> offsetMappings;
/**
* The suppression handler to use.
*/
protected final SuppressionHandler suppressionHandler;
/**
* Creates a new resolved version of a dispatcher.
*
* @param adviceMethod The represented advice method.
* @param factories A list of factories to resolve for the parameters of the advice method.
* @param binaryRepresentation The binary representation of the advice method.
* @param throwableType The type to handle by a suppression handler or {@link NoSuppression} to not handle any exceptions.
*/
protected Resolved(MethodDescription.InDefinedShape adviceMethod,
List<OffsetMapping.Factory> factories,
byte[] binaryRepresentation,
TypeDescription throwableType) {
this.adviceMethod = adviceMethod;
offsetMappings = new HashMap<Integer, OffsetMapping>();
for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) {
OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED;
for (OffsetMapping.Factory factory : factories) {
OffsetMapping possible = factory.make(parameterDescription);
if (possible != null) {
if (offsetMapping == null) {
offsetMapping = possible;
} else {
throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping);
}
}
}
offsetMappings.put(parameterDescription.getOffset(), offsetMapping == null
? new OffsetMapping.ForParameter(parameterDescription.getIndex(), READ_ONLY, parameterDescription.getType().asErasure())
: offsetMapping);
}
this.binaryRepresentation = binaryRepresentation;
suppressionHandler = throwableType.represents(NoSuppression.class)
? SuppressionHandler.NoOp.INSTANCE
: new SuppressionHandler.Suppressing(throwableType);
}
@Override
public boolean isAlive() {
return true;
}
@Override
public Bound bind(MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler) {
return new AdviceMethodInliner(instrumentedMethod,
methodVisitor,
metaDataHandler,
suppressionHandler.bind(),
new ClassReader(binaryRepresentation));
}
/**
* Applies a resolution for a given instrumented method.
*
* @param methodVisitor A method visitor for writing byte code to the instrumented method.
* @param metaDataHandler A handler for translating meta data that is embedded into the instrumented method's byte code.
* @param instrumentedMethod A description of the instrumented method.
* @param suppressionHandler The bound suppression handler that is used for suppressing exceptions of this advice method.
* @return A method visitor for visiting the advice method's byte code.
*/
protected abstract MethodVisitor apply(MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler,
MethodDescription.InDefinedShape instrumentedMethod,
SuppressionHandler.Bound suppressionHandler);
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Inlining.Resolved resolved = (Inlining.Resolved) other;
return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings);
}
@Override
public int hashCode() {
int result = adviceMethod.hashCode();
result = 31 * result + offsetMappings.hashCode();
return result;
}
/**
* A bound advice method that copies the code by first extracting the exception table and later appending the
* code of the method without copying any meta data.
*/
protected class AdviceMethodInliner extends ClassVisitor implements Bound {
/**
* The instrumented method.
*/
private final MethodDescription.InDefinedShape instrumentedMethod;
/**
* The method visitor for writing the instrumented method.
*/
private final MethodVisitor methodVisitor;
/**
* A meta data handler for writing to the instrumented method.
*/
private final MetaDataHandler.ForInstrumentedMethod metaDataHandler;
/**
* A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
private final SuppressionHandler.Bound suppressionHandler;
/**
* A class reader for parsing the class file containing the represented advice method.
*/
private final ClassReader classReader;
/**
* The labels that were found during parsing the method's exception handler in the order of their discovery.
*/
private List<Label> labels;
/**
* Creates a new code copier.
*
* @param instrumentedMethod The instrumented method.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param metaDataHandler A meta data handler for writing to the instrumented method.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
* @param classReader A class reader for parsing the class file containing the represented advice method.
*/
protected AdviceMethodInliner(MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler,
SuppressionHandler.Bound suppressionHandler,
ClassReader classReader) {
super(Opcodes.ASM5);
this.instrumentedMethod = instrumentedMethod;
this.methodVisitor = methodVisitor;
this.metaDataHandler = metaDataHandler;
this.suppressionHandler = suppressionHandler;
this.classReader = classReader;
labels = new ArrayList<Label>();
}
@Override
public void prepare() {
classReader.accept(new ExceptionTableExtractor(), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
suppressionHandler.onPrepare(methodVisitor);
}
@Override
public void apply() {
classReader.accept(this, ClassReader.SKIP_DEBUG | metaDataHandler.getReaderHint());
}
@Override
public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) {
return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor)
? new ExceptionTableSubstitutor(Inlining.Resolved.this.apply(methodVisitor, metaDataHandler, instrumentedMethod, suppressionHandler))
: IGNORE_METHOD;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner{" +
"instrumentedMethod=" + instrumentedMethod +
", methodVisitor=" + methodVisitor +
", metaDataHandler=" + metaDataHandler +
", suppressionHandler=" + suppressionHandler +
", classReader=" + classReader +
", labels=" + labels +
'}';
}
/**
* A class visitor that extracts the exception tables of the advice method.
*/
protected class ExceptionTableExtractor extends ClassVisitor {
/**
* Creates a new exception table extractor.
*/
protected ExceptionTableExtractor() {
super(Opcodes.ASM5);
}
@Override
public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) {
return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor)
? new ExceptionTableCollector(methodVisitor)
: IGNORE_METHOD;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableExtractor{" +
"methodVisitor=" + methodVisitor +
'}';
}
}
/**
* A visitor that only writes try-catch-finally blocks to the supplied method visitor. All labels of these tables are collected
* for substitution when revisiting the reminder of the method.
*/
protected class ExceptionTableCollector extends MethodVisitor {
/**
* The method visitor for which the try-catch-finally blocks should be written.
*/
private final MethodVisitor methodVisitor;
/**
* Creates a new exception table collector.
*
* @param methodVisitor The method visitor for which the try-catch-finally blocks should be written.
*/
protected ExceptionTableCollector(MethodVisitor methodVisitor) {
super(Opcodes.ASM5);
this.methodVisitor = methodVisitor;
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
methodVisitor.visitTryCatchBlock(start, end, handler, type);
labels.addAll(Arrays.asList(start, end, handler));
}
@Override
public AnnotationVisitor visitTryCatchAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) {
return methodVisitor.visitTryCatchAnnotation(typeReference, typePath, descriptor, visible);
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableCollector{" +
"methodVisitor=" + methodVisitor +
'}';
}
}
/**
* A label substitutor allows to visit an advice method a second time after the exception handlers were already written.
* Doing so, this visitor substitutes all labels that were already created during the first visit to keep the mapping
* consistent.
*/
protected class ExceptionTableSubstitutor extends MethodVisitor {
/**
* A map containing resolved substitutions.
*/
private final Map<Label, Label> substitutions;
/**
* The current index of the visited labels that are used for try-catch-finally blocks.
*/
private int index;
/**
* Creates a label substitor.
*
* @param methodVisitor The method visitor for which to substitute labels.
*/
protected ExceptionTableSubstitutor(MethodVisitor methodVisitor) {
super(Opcodes.ASM5, methodVisitor);
substitutions = new IdentityHashMap<Label, Label>();
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
substitutions.put(start, labels.get(index++));
substitutions.put(end, labels.get(index++));
substitutions.put(handler, labels.get(index++));
}
@Override
public AnnotationVisitor visitTryCatchAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public void visitLabel(Label label) {
super.visitLabel(resolve(label));
}
@Override
public void visitJumpInsn(int opcode, Label label) {
super.visitJumpInsn(opcode, resolve(label));
}
@Override
public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) {
super.visitTableSwitchInsn(min, max, dflt, resolve(labels));
}
@Override
public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
super.visitLookupSwitchInsn(resolve(dflt), keys, resolve(labels));
}
/**
* Resolves an array of labels.
*
* @param label The labels to resolved.
* @return An array containing the resolved arrays.
*/
private Label[] resolve(Label[] label) {
Label[] resolved = new Label[label.length];
int index = 0;
for (Label aLabel : label) {
resolved[index++] = resolve(aLabel);
}
return resolved;
}
/**
* Resolves a single label if mapped or returns the original label.
*
* @param label The label to resolve.
* @return The resolved label.
*/
private Label resolve(Label label) {
Label substitution = substitutions.get(label);
return substitution == null
? label
: substitution;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableSubstitutor{" +
"methodVisitor=" + methodVisitor +
", substitutions=" + substitutions +
", index=" + index +
'}';
}
}
}
/**
* A resolved dispatcher for implementing method enter advice.
*/
protected static class ForMethodEnter extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodEnter {
/**
* Creates a new resolved dispatcher for implementing method enter advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param binaryRepresentation The binary representation of the advice method.
*/
@SuppressWarnings("all") // In absence of @SafeVarargs for Java 6
protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
byte[] binaryRepresentation) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForParameter.Factory.READ_WRITE,
OffsetMapping.ForBoxedArguments.INSTANCE,
OffsetMapping.ForThisReference.Factory.READ_WRITE,
OffsetMapping.ForField.Factory.READ_WRITE,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForIgnored.INSTANCE,
new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class, BoxedReturn.class)), userFactories),
binaryRepresentation,
adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER, TypeDescription.class));
}
@Override
public TypeDescription getEnterType() {
return adviceMethod.getReturnType().asErasure();
}
@Override
protected MethodVisitor apply(MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler,
MethodDescription.InDefinedShape instrumentedMethod,
SuppressionHandler.Bound suppressionHandler) {
Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>();
for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) {
offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod)));
}
return new CodeTranslationVisitor.ForMethodEnter(methodVisitor,
metaDataHandler.bindEntry(adviceMethod),
instrumentedMethod,
adviceMethod,
offsetMappings,
suppressionHandler);
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodEnter{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
/**
* A resolved dispatcher for implementing method exit advice.
*/
protected abstract static class ForMethodExit extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodExit {
/**
* The additional stack size to consider when accessing the local variable array.
*/
private final TypeDescription enterType;
/**
* Creates a new resolved dispatcher for implementing method exit advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param binaryRepresentation The binary representation of the advice method.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
@SuppressWarnings("all") // In absence of @SafeVarargs for Java 6
protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
byte[] binaryRepresentation,
TypeDescription enterType) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForParameter.Factory.READ_WRITE,
OffsetMapping.ForBoxedArguments.INSTANCE,
OffsetMapping.ForThisReference.Factory.READ_WRITE,
OffsetMapping.ForField.Factory.READ_WRITE,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForIgnored.INSTANCE,
new OffsetMapping.ForEnterValue.Factory(enterType, false),
OffsetMapping.ForReturnValue.Factory.READ_WRITE,
OffsetMapping.ForBoxedReturnValue.INSTANCE,
adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(ON_THROWABLE, Boolean.class)
? OffsetMapping.ForThrowable.Factory.READ_WRITE
: new OffsetMapping.Illegal(Thrown.class)), userFactories),
binaryRepresentation,
adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT, TypeDescription.class));
this.enterType = enterType;
}
/**
* Resolves exit advice that handles exceptions depending on the specification of the exit advice.
*
* @param adviceMethod The advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param binaryRepresentation The binary representation of the advice method.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
* @return An appropriate exit handler.
*/
protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
byte[] binaryRepresentation,
TypeDescription enterType) {
return adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).loadSilent().onThrowable()
? new WithExceptionHandler(adviceMethod, userFactories, binaryRepresentation, enterType)
: new WithoutExceptionHandler(adviceMethod, userFactories, binaryRepresentation, enterType);
}
@Override
protected MethodVisitor apply(MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler,
MethodDescription.InDefinedShape instrumentedMethod,
SuppressionHandler.Bound suppressionHandler) {
Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>();
for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) {
offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, OffsetMapping.Context.ForMethodExit.of(enterType)));
}
return new CodeTranslationVisitor.ForMethodExit(methodVisitor,
metaDataHandler.bindExit(adviceMethod),
instrumentedMethod,
adviceMethod,
offsetMappings,
suppressionHandler,
enterType.getStackSize().getSize() + getPadding().getSize());
}
/**
* Returns the additional padding this exit advice implies.
*
* @return The additional padding this exit advice implies.
*/
protected abstract StackSize getPadding();
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& super.equals(other)
&& enterType == ((Inlining.Resolved.ForMethodExit) other).enterType;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + enterType.hashCode();
return result;
}
/**
* Implementation of exit advice that handles exceptions.
*/
protected static class WithExceptionHandler extends Inlining.Resolved.ForMethodExit {
/**
* Creates a new resolved dispatcher for implementing method exit advice that handles exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param binaryRepresentation The binary representation of the advice method.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
byte[] binaryRepresentation,
TypeDescription enterType) {
super(adviceMethod, userFactories, binaryRepresentation, enterType);
}
@Override
protected StackSize getPadding() {
return StackSize.SINGLE;
}
@Override
public boolean isSkipThrowable() {
return false;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.WithExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
/**
* Implementation of exit advice that ignores exceptions.
*/
protected static class WithoutExceptionHandler extends Inlining.Resolved.ForMethodExit {
/**
* Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param binaryRepresentation The binary representation of the advice method.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
byte[] binaryRepresentation,
TypeDescription enterType) {
super(adviceMethod, userFactories, binaryRepresentation, enterType);
}
@Override
protected StackSize getPadding() {
return StackSize.ZERO;
}
@Override
public boolean isSkipThrowable() {
return true;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.WithoutExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
}
}
/**
* A visitor for translating an advice method's byte code for inlining into the instrumented method.
*/
protected abstract static class CodeTranslationVisitor extends MethodVisitor implements SuppressionHandler.ReturnValueProducer {
/**
* A handler for translating meta data found in the byte code.
*/
protected final MetaDataHandler.ForAdvice metaDataHandler;
/**
* The instrumented method.
*/
protected final MethodDescription.InDefinedShape instrumentedMethod;
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* A mapping of offsets to resolved target offsets in the instrumented method.
*/
private final Map<Integer, Resolved.OffsetMapping.Target> offsetMappings;
/**
* A handler for optionally suppressing exceptions.
*/
private final SuppressionHandler.Bound suppressionHandler;
/**
* A label indicating the end of the advice byte code.
*/
protected final Label endOfMethod;
/**
* Creates a new code translation visitor.
*
* @param methodVisitor A method visitor for writing the instrumented method's byte code.
* @param metaDataHandler A handler for translating meta data found in the byte code.
* @param instrumentedMethod The instrumented method.
* @param adviceMethod The advice method.
* @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method.
* @param suppressionHandler The suppression handler to use.
*/
protected CodeTranslationVisitor(MethodVisitor methodVisitor,
MetaDataHandler.ForAdvice metaDataHandler,
MethodDescription.InDefinedShape instrumentedMethod,
MethodDescription.InDefinedShape adviceMethod,
Map<Integer, Resolved.OffsetMapping.Target> offsetMappings,
SuppressionHandler.Bound suppressionHandler) {
super(Opcodes.ASM5, methodVisitor);
this.metaDataHandler = metaDataHandler;
this.instrumentedMethod = instrumentedMethod;
this.adviceMethod = adviceMethod;
this.offsetMappings = offsetMappings;
this.suppressionHandler = suppressionHandler;
endOfMethod = new Label();
}
@Override
public void visitParameter(String name, int modifiers) {
/* do nothing */
}
@Override
public AnnotationVisitor visitAnnotationDefault() {
return IGNORE_ANNOTATION;
}
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public AnnotationVisitor visitTypeAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public AnnotationVisitor visitParameterAnnotation(int index, String descriptor, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public void visitAttribute(Attribute attribute) {
/* do nothing */
}
@Override
public void visitCode() {
suppressionHandler.onStart(mv, metaDataHandler);
}
@Override
public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) {
metaDataHandler.translateFrame(mv, frameType, localVariableLength, localVariable, stackSize, stack);
}
@Override
public void visitEnd() {
suppressionHandler.onEnd(mv, metaDataHandler, this);
mv.visitLabel(endOfMethod);
metaDataHandler.injectCompletionFrame(mv, false);
}
@Override
public void visitMaxs(int stackSize, int localVariableLength) {
metaDataHandler.recordMaxima(stackSize, localVariableLength);
}
@Override
public void visitVarInsn(int opcode, int offset) {
Resolved.OffsetMapping.Target target = offsetMappings.get(offset);
if (target != null) {
metaDataHandler.recordPadding(target.resolveAccess(mv, opcode));
} else {
mv.visitVarInsn(opcode, adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize()));
}
}
@Override
public void visitIincInsn(int offset, int increment) {
Resolved.OffsetMapping.Target target = offsetMappings.get(offset);
if (target != null) {
metaDataHandler.recordPadding(target.resolveIncrement(mv, increment));
} else {
mv.visitIincInsn(adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize()), increment);
}
}
/**
* Adjusts the offset of a variable instruction within the advice method such that no arguments to
* the instrumented method are overridden.
*
* @param offset The original offset.
* @return The adjusted offset.
*/
protected abstract int adjust(int offset);
@Override
public abstract void visitInsn(int opcode);
/**
* A code translation visitor that retains the return value of the represented advice method.
*/
protected static class ForMethodEnter extends CodeTranslationVisitor {
/**
* Creates a code translation visitor for translating exit advice.
*
* @param methodVisitor A method visitor for writing the instrumented method's byte code.
* @param metaDataHandler A handler for translating meta data found in the byte code.
* @param instrumentedMethod The instrumented method.
* @param adviceMethod The advice method.
* @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method.
* @param suppressionHandler The suppression handler to use.
*/
protected ForMethodEnter(MethodVisitor methodVisitor,
MetaDataHandler.ForAdvice metaDataHandler,
MethodDescription.InDefinedShape instrumentedMethod,
MethodDescription.InDefinedShape adviceMethod,
Map<Integer, Resolved.OffsetMapping.Target> offsetMappings,
SuppressionHandler.Bound suppressionHandler) {
super(methodVisitor, metaDataHandler, instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler);
}
@Override
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.RETURN:
break;
case Opcodes.IRETURN:
mv.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize());
break;
case Opcodes.LRETURN:
mv.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize());
break;
case Opcodes.ARETURN:
mv.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize());
break;
case Opcodes.FRETURN:
mv.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize());
break;
case Opcodes.DRETURN:
mv.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize());
break;
default:
mv.visitInsn(opcode);
return;
}
mv.visitJumpInsn(Opcodes.GOTO, endOfMethod);
}
@Override
protected int adjust(int offset) {
return offset;
}
@Override
public void storeDefaultValue(MethodVisitor methodVisitor) {
if (adviceMethod.getReturnType().represents(boolean.class)
|| adviceMethod.getReturnType().represents(byte.class)
|| adviceMethod.getReturnType().represents(short.class)
|| adviceMethod.getReturnType().represents(char.class)
|| adviceMethod.getReturnType().represents(int.class)) {
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(long.class)) {
methodVisitor.visitInsn(Opcodes.LCONST_0);
methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(float.class)) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(double.class)) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize());
} else if (!adviceMethod.getReturnType().represents(void.class)) {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.CodeTranslationVisitor.ForMethodEnter{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
'}';
}
}
/**
* A code translation visitor that discards the return value of the represented advice method.
*/
protected static class ForMethodExit extends CodeTranslationVisitor {
/**
* The padding after the instrumented method's arguments in the local variable array.
*/
private final int padding;
/**
* Creates a code translation visitor for translating exit advice.
*
* @param methodVisitor A method visitor for writing the instrumented method's byte code.
* @param metaDataHandler A handler for translating meta data found in the byte code.
* @param instrumentedMethod The instrumented method.
* @param adviceMethod The advice method.
* @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method.
* @param suppressionHandler The suppression handler to use.
* @param padding The padding after the instrumented method's arguments in the local variable array.
*/
protected ForMethodExit(MethodVisitor methodVisitor,
MetaDataHandler.ForAdvice metaDataHandler,
MethodDescription.InDefinedShape instrumentedMethod,
MethodDescription.InDefinedShape adviceMethod,
Map<Integer, Resolved.OffsetMapping.Target> offsetMappings,
SuppressionHandler.Bound suppressionHandler,
int padding) {
super(methodVisitor,
metaDataHandler,
instrumentedMethod,
adviceMethod,
offsetMappings,
suppressionHandler);
this.padding = padding;
}
@Override
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.RETURN:
break;
case Opcodes.IRETURN:
case Opcodes.ARETURN:
case Opcodes.FRETURN:
mv.visitInsn(Opcodes.POP);
break;
case Opcodes.LRETURN:
case Opcodes.DRETURN:
mv.visitInsn(Opcodes.POP2);
break;
default:
mv.visitInsn(opcode);
return;
}
mv.visitJumpInsn(Opcodes.GOTO, endOfMethod);
}
@Override
protected int adjust(int offset) {
return instrumentedMethod.getReturnType().getStackSize().getSize() + padding + offset;
}
@Override
public void storeDefaultValue(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.CodeTranslationVisitor.ForMethodExit{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
", padding=" + padding +
'}';
}
}
}
}
/**
* A dispatcher for an advice method that is being invoked from the instrumented method.
*/
class Delegating implements Unresolved {
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* Creates a new delegating advice dispatcher.
*
* @param adviceMethod The advice method.
*/
protected Delegating(MethodDescription.InDefinedShape adviceMethod) {
this.adviceMethod = adviceMethod;
}
@Override
public boolean isAlive() {
return true;
}
@Override
public boolean isBinary() {
return false;
}
@Override
public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation) {
return new Resolved.ForMethodEnter(adviceMethod, userFactories);
}
@Override
public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassFileLocator.Resolution binaryRepresentation,
Dispatcher.Resolved.ForMethodEnter dispatcher) {
return Resolved.ForMethodExit.of(adviceMethod, userFactories, dispatcher.getEnterType());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass()) && adviceMethod.equals(((Delegating) other).adviceMethod);
}
@Override
public int hashCode() {
return adviceMethod.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating{" +
"adviceMethod=" + adviceMethod +
'}';
}
/**
* A resolved version of a dispatcher.
*/
protected abstract static class Resolved implements Dispatcher.Resolved {
/**
* Indicates a read-only mapping for an offset.
*/
private static final boolean READ_ONLY = true;
/**
* The represented advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter.
*/
protected final List<OffsetMapping> offsetMappings;
/**
* The suppression handler to use.
*/
protected final SuppressionHandler suppressionHandler;
/**
* Creates a new resolved version of a dispatcher.
*
* @param adviceMethod The represented advice method.
* @param factories A list of factories to resolve for the parameters of the advice method.
* @param throwableType The type to handle by a suppression handler or {@link NoSuppression} to not handle any exceptions.
*/
protected Resolved(MethodDescription.InDefinedShape adviceMethod, List<OffsetMapping.Factory> factories, TypeDescription throwableType) {
this.adviceMethod = adviceMethod;
offsetMappings = new ArrayList<OffsetMapping>(adviceMethod.getParameters().size());
for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) {
OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED;
for (OffsetMapping.Factory factory : factories) {
OffsetMapping possible = factory.make(parameterDescription);
if (possible != null) {
if (offsetMapping == null) {
offsetMapping = possible;
} else {
throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping);
}
}
}
offsetMappings.add(offsetMapping == null
? new OffsetMapping.ForParameter(parameterDescription.getIndex(), READ_ONLY, parameterDescription.getType().asErasure())
: offsetMapping);
}
suppressionHandler = throwableType.represents(NoSuppression.class)
? SuppressionHandler.NoOp.INSTANCE
: new SuppressionHandler.Suppressing(throwableType);
}
@Override
public boolean isAlive() {
return true;
}
@Override
public Bound bind(MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler) {
if (!adviceMethod.isVisibleTo(instrumentedMethod.getDeclaringType())) {
throw new IllegalStateException(adviceMethod + " is not visible to " + instrumentedMethod.getDeclaringType());
}
return resolve(instrumentedMethod, methodVisitor, metaDataHandler);
}
/**
* Binds this dispatcher for resolution to a specific method.
*
* @param instrumentedMethod The instrumented method that is being bound.
* @param methodVisitor The method visitor for writing to the instrumented method.
* @param metaDataHandler The meta data handler to apply.
* @return An appropriate bound advice dispatcher.
*/
protected abstract Bound resolve(MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler);
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Delegating.Resolved resolved = (Delegating.Resolved) other;
return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings);
}
@Override
public int hashCode() {
int result = adviceMethod.hashCode();
result = 31 * result + offsetMappings.hashCode();
return result;
}
/**
* A bound advice method that copies the code by first extracting the exception table and later appending the
* code of the method without copying any meta data.
*/
protected abstract static class AdviceMethodWriter implements Bound, SuppressionHandler.ReturnValueProducer {
/**
* Indicates an empty local variable array which is not required for calling a method.
*/
private static final int EMPTY = 0;
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* The instrumented method.
*/
protected final MethodDescription.InDefinedShape instrumentedMethod;
/**
* The offset mappings available to this advice.
*/
private final List<OffsetMapping.Target> offsetMappings;
/**
* The method visitor for writing the instrumented method.
*/
protected final MethodVisitor methodVisitor;
/**
* A meta data handler for writing to the instrumented method.
*/
private final MetaDataHandler.ForAdvice metaDataHandler;
/**
* A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
private final SuppressionHandler.Bound suppressionHandler;
/**
* Creates a new advice method writer.
*
* @param adviceMethod The advice method.
* @param instrumentedMethod The instrumented method.
* @param offsetMappings The offset mappings available to this advice.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param metaDataHandler A meta data handler for writing to the instrumented method.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
protected AdviceMethodWriter(MethodDescription.InDefinedShape adviceMethod,
MethodDescription.InDefinedShape instrumentedMethod,
List<OffsetMapping.Target> offsetMappings,
MethodVisitor methodVisitor,
MetaDataHandler.ForAdvice metaDataHandler,
SuppressionHandler.Bound suppressionHandler) {
this.adviceMethod = adviceMethod;
this.instrumentedMethod = instrumentedMethod;
this.offsetMappings = offsetMappings;
this.methodVisitor = methodVisitor;
this.metaDataHandler = metaDataHandler;
this.suppressionHandler = suppressionHandler;
}
@Override
public void prepare() {
suppressionHandler.onPrepare(methodVisitor);
}
@Override
public void apply() {
suppressionHandler.onStart(methodVisitor, metaDataHandler);
int index = 0, currentStackSize = 0, maximumStackSize = 0;
for (OffsetMapping.Target offsetMapping : offsetMappings) {
Type type = Type.getType(adviceMethod.getParameters().get(index++).getType().asErasure().getDescriptor());
currentStackSize += type.getSize();
maximumStackSize = Math.max(maximumStackSize, currentStackSize + offsetMapping.resolveAccess(methodVisitor, type.getOpcode(Opcodes.ILOAD)));
}
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC,
adviceMethod.getDeclaringType().getInternalName(),
adviceMethod.getInternalName(),
adviceMethod.getDescriptor(),
false);
onAfterCall();
suppressionHandler.onEndSkipped(methodVisitor, metaDataHandler, this);
metaDataHandler.recordMaxima(Math.max(maximumStackSize, adviceMethod.getReturnType().getStackSize().getSize()), EMPTY);
}
/**
* Invoked after the advise method was invoked.
*/
protected abstract void onAfterCall();
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter{" +
"instrumentedMethod=" + instrumentedMethod +
", methodVisitor=" + methodVisitor +
", metaDataHandler=" + metaDataHandler +
", suppressionHandler=" + suppressionHandler +
'}';
}
/**
* An advice method writer for a method entry.
*/
protected static class ForMethodEnter extends AdviceMethodWriter {
/**
* Creates a new advice method writer.
*
* @param adviceMethod The advice method.
* @param instrumentedMethod The instrumented method.
* @param offsetMappings The offset mappings available to this advice.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param metaDataHandler A meta data handler for writing to the instrumented method.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod,
MethodDescription.InDefinedShape instrumentedMethod,
List<OffsetMapping.Target> offsetMappings,
MethodVisitor methodVisitor,
MetaDataHandler.ForAdvice metaDataHandler,
SuppressionHandler.Bound suppressionHandler) {
super(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, metaDataHandler, suppressionHandler);
}
@Override
protected void onAfterCall() {
if (adviceMethod.getReturnType().represents(boolean.class)
|| adviceMethod.getReturnType().represents(byte.class)
|| adviceMethod.getReturnType().represents(short.class)
|| adviceMethod.getReturnType().represents(char.class)
|| adviceMethod.getReturnType().represents(int.class)) {
methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(long.class)) {
methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(float.class)) {
methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(double.class)) {
methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize());
} else if (!adviceMethod.getReturnType().represents(void.class)) {
methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize());
}
}
@Override
public void storeDefaultValue(MethodVisitor methodVisitor) {
if (adviceMethod.getReturnType().represents(boolean.class)
|| adviceMethod.getReturnType().represents(byte.class)
|| adviceMethod.getReturnType().represents(short.class)
|| adviceMethod.getReturnType().represents(char.class)
|| adviceMethod.getReturnType().represents(int.class)) {
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(long.class)) {
methodVisitor.visitInsn(Opcodes.LCONST_0);
methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(float.class)) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(double.class)) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize());
} else if (!adviceMethod.getReturnType().represents(void.class)) {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter.ForMethodEnter{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
"}";
}
}
/**
* An advice method writer for a method exit.
*/
protected static class ForMethodExit extends AdviceMethodWriter {
/**
* Creates a new advice method writer.
*
* @param adviceMethod The advice method.
* @param instrumentedMethod The instrumented method.
* @param offsetMappings The offset mappings available to this advice.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param metaDataHandler A meta data handler for writing to the instrumented method.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod,
MethodDescription.InDefinedShape instrumentedMethod,
List<OffsetMapping.Target> offsetMappings,
MethodVisitor methodVisitor,
MetaDataHandler.ForAdvice metaDataHandler,
SuppressionHandler.Bound suppressionHandler) {
super(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, metaDataHandler, suppressionHandler);
}
@Override
protected void onAfterCall() {
switch (adviceMethod.getReturnType().getStackSize()) {
case ZERO:
return;
case SINGLE:
methodVisitor.visitInsn(Opcodes.POP);
return;
case DOUBLE:
methodVisitor.visitInsn(Opcodes.POP2);
return;
default:
throw new IllegalStateException("Unexpected size: " + adviceMethod.getReturnType().getStackSize());
}
}
@Override
public void storeDefaultValue(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter.ForMethodExit{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
"}";
}
}
}
/**
* A resolved dispatcher for implementing method enter advice.
*/
protected static class ForMethodEnter extends Delegating.Resolved implements Dispatcher.Resolved.ForMethodEnter {
/**
* Creates a new resolved dispatcher for implementing method enter advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
*/
@SuppressWarnings("all") // In absence of @SafeVarargs for Java 6
protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForParameter.Factory.READ_ONLY,
OffsetMapping.ForBoxedArguments.INSTANCE,
OffsetMapping.ForThisReference.Factory.READ_ONLY,
OffsetMapping.ForField.Factory.READ_ONLY,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForIgnored.INSTANCE,
new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class, BoxedReturn.class)), userFactories),
adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER, TypeDescription.class));
}
@Override
public TypeDescription getEnterType() {
return adviceMethod.getReturnType().asErasure();
}
@Override
protected Bound resolve(MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler) {
List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size());
for (OffsetMapping offsetMapping : this.offsetMappings) {
offsetMappings.add(offsetMapping.resolve(instrumentedMethod, OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod)));
}
return new AdviceMethodWriter.ForMethodEnter(adviceMethod,
instrumentedMethod,
offsetMappings,
methodVisitor,
metaDataHandler.bindEntry(adviceMethod),
suppressionHandler.bind());
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.ForMethodEnter{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
/**
* A resolved dispatcher for implementing method exit advice.
*/
protected abstract static class ForMethodExit extends Delegating.Resolved implements Dispatcher.Resolved.ForMethodExit {
/**
* The additional stack size to consider when accessing the local variable array.
*/
private final TypeDescription enterType;
/**
* Creates a new resolved dispatcher for implementing method exit advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
@SuppressWarnings("all") // In absence of @SafeVarargs for Java 6
protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDescription enterType) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForParameter.Factory.READ_ONLY,
OffsetMapping.ForBoxedArguments.INSTANCE,
OffsetMapping.ForThisReference.Factory.READ_ONLY,
OffsetMapping.ForField.Factory.READ_ONLY,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForIgnored.INSTANCE,
new OffsetMapping.ForEnterValue.Factory(enterType, true),
OffsetMapping.ForReturnValue.Factory.READ_ONLY,
OffsetMapping.ForBoxedReturnValue.INSTANCE,
adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(ON_THROWABLE, Boolean.class)
? OffsetMapping.ForThrowable.Factory.READ_ONLY
: new OffsetMapping.Illegal(Thrown.class)), userFactories),
adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT, TypeDescription.class));
this.enterType = enterType;
}
/**
* Resolves exit advice that handles exceptions depending on the specification of the exit advice.
*
* @param adviceMethod The advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
* @return An appropriate exit handler.
*/
protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDescription enterType) {
return adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).loadSilent().onThrowable()
? new WithExceptionHandler(adviceMethod, userFactories, enterType)
: new WithoutExceptionHandler(adviceMethod, userFactories, enterType);
}
@Override
protected Bound resolve(MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
MetaDataHandler.ForInstrumentedMethod metaDataHandler) {
List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size());
for (OffsetMapping offsetMapping : this.offsetMappings) {
offsetMappings.add(offsetMapping.resolve(instrumentedMethod, OffsetMapping.Context.ForMethodExit.of(enterType)));
}
return new AdviceMethodWriter.ForMethodExit(adviceMethod,
instrumentedMethod,
offsetMappings,
methodVisitor,
metaDataHandler.bindExit(adviceMethod),
suppressionHandler.bind());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& super.equals(other)
&& enterType == ((Delegating.Resolved.ForMethodExit) other).enterType;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + enterType.hashCode();
return result;
}
/**
* Implementation of exit advice that handles exceptions.
*/
protected static class WithExceptionHandler extends Delegating.Resolved.ForMethodExit {
/**
* Creates a new resolved dispatcher for implementing method exit advice that handles exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDescription enterType) {
super(adviceMethod, userFactories, enterType);
}
@Override
public boolean isSkipThrowable() {
return false;
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.ForMethodExit.WithExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
/**
* Implementation of exit advice that ignores exceptions.
*/
protected static class WithoutExceptionHandler extends Delegating.Resolved.ForMethodExit {
/**
* Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDescription enterType) {
super(adviceMethod, userFactories, enterType);
}
@Override
public boolean isSkipThrowable() {
return true;
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.ForMethodExit.WithoutExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
}
}
}
}
/**
* <p>
* Indicates that this method should be inlined before the matched method is invoked. Any class must declare
* at most one method with this annotation. The annotated method must be static. When instrumenting constructors,
* the {@code this} values can only be accessed for writing fields but not for reading fields or invoking methods.
* </p>
* <p>
* The annotated method can return a value that is made accessible to another method annotated by {@link OnMethodExit}.
* </p>
*
* @see Advice
* @see Argument
* @see This
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnMethodEnter {
/**
* Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method
* is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code
* with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods.
* When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to
* set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into
* the instrumented method.
*
* @return {@code true} if the annotated method should be inlined into the instrumented method.
*/
boolean inline() default true;
/**
* Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution.
*
* @return The type of {@link Throwable} to suppress.
*/
Class<? extends Throwable> suppress() default NoSuppression.class;
}
/**
* <p>
* Indicates that this method should be executed before calling the instrumented method. Any class must declare
* at most one method with this annotation. The annotated method must be static.
* </p>
* <p>
* The annotated method can imply to not be invoked when the instrumented method terminates exceptionally by
* setting the {@link OnMethodExit#onThrowable()} property.
* </p>
*
* @see Advice
* @see Argument
* @see This
* @see Enter
* @see Return
* @see Thrown
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnMethodExit {
/**
* Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method
* is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code
* with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods.
* When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to
* set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into
* the instrumented method.
*
* @return {@code true} if the annotated method should be inlined into the instrumented method.
*/
boolean inline() default true;
/**
* Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution.
*
* @return The type of {@link Throwable} to suppress.
*/
Class<? extends Throwable> suppress() default NoSuppression.class;
/**
* Indicates that the advice method should also be called when a method terminates exceptionally. This property must
* not be set to {@code true} when defining advice for a constructor.
*
* @return {@code true} if the advice method should be invoked when a method terminates exceptionally.
*/
boolean onThrowable() default true;
}
/**
* Indicates that the annotated parameter should be mapped to the parameter with index {@link Argument#value()} of
* the instrumented method.
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Argument {
/**
* Returns the index of the mapped parameter.
*
* @return The index of the mapped parameter.
*/
int value();
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the
* annotated parameter can be any super type of the instrumented methods parameter.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to the {@code this} reference of the instrumented method.
* </p>
* <p>
* <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with
* {@link OnMethodEnter} where the {@code this} reference is not available.
* </p>
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface This {
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the type declaring the instrumented method. If this property is set to {@code true}, the
* annotated parameter can be any super type of the instrumented method's declaring type.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to a field in the scope of the instrumented method.
* </p>
* <p>
* <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with
* {@link OnMethodEnter} and a non-static field where the {@code this} reference is not available.
* </p>
* <p>
* <b>Note</b>: As the mapping is virtual, Byte Buddy might be required to reserve more space on the operand stack than the
* optimal value when accessing this parameter. This does not normally matter as the additional space requirement is minimal.
* However, if the runtime performance of class creation is secondary, one can require ASM to recompute the optimal frames by
* setting {@link ClassWriter#COMPUTE_MAXS}. This is however only relevant when writing to a non-static field.
* </p>
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface FieldValue {
/**
* Returns the name of the field.
*
* @return The name of the field.
*/
String value();
/**
* Returns the type that declares the field that should be mapped to the annotated parameter. If this property
* is set to {@code void}, the field is looked up implicitly within the instrumented class's class hierarchy.
*
* @return The type that declares the field or {@code void} if this type should be determined implicitly.
*/
Class<?> declaringType() default void.class;
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the mapped field type. If this property is set to {@code true}, the annotated parameter
* can be any super type of the field type.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
}
/**
* Indicates that the annotated parameter should be mapped to a string representation of the instrumented method or
* to a constant representing the {@link Class} declaring the method.
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Origin {
/**
* Indicates that the origin string should be indicated by the {@link Object#toString()} representation of the instrumented method.
*/
String DEFAULT = "";
/**
* Returns the pattern the annotated parameter should be assigned. By default, the {@link Origin#toString()} representation
* of the method is assigned. Alternatively, a pattern can be assigned where:
* <ul>
* <li>{@code #t} inserts the method's declaring type.</li>
* <li>{@code #m} inserts the name of the method ({@code <init>} for constructors and {@code <clinit>} for static initializers).</li>
* <li>{@code #d} for the method's descriptor.</li>
* <li>{@code #s} for the method's signature.</li>
* <li>{@code #r} for the method's return type.</li>
* </ul>
* Any other {@code #} character must be escaped by {@code \} which can be escaped by itself. This property is ignored if the annotated
* parameter is of type {@link Class}.
*
* @return The pattern the annotated parameter should be assigned.
*/
String value() default DEFAULT;
}
/**
* Indicates that the annotated parameter should always return a default value (i.e. {@code 0} for numeric values, {@code false}
* for {@code boolean} types and {@code null} for reference types).
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Ignored {
/* empty */
}
/**
* Indicates that the annotated parameter should be mapped to the value that is returned by the advice method that is annotated
* by {@link OnMethodEnter}.
*
* @see Advice
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Enter {
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the
* annotated parameter can be any super type of the instrumented methods parameter.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
}
/**
* Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented
* method terminates exceptionally, the type's default value is assigned to the parameter, i.e. {@code 0} for numeric types
* and {@code null} for reference types.
*
* @see Advice
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Return {
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the
* annotated parameter can be any super type of the instrumented methods parameter.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface BoxedReturn {
/* boxed */
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface BoxedArguments {
/* boxed */
}
/**
* Indicates that the annotated parameter should be mapped to the return value of the instrumented method. For this to be valid,
* the parameter must be of type {@link Throwable}. If the instrumented method terminates regularly, {@code null} is assigned to
* the annotated parameter.
*
* @see Advice
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Thrown {
boolean readOnly() default true;
}
/**
* <p>
* A dynamic value allows to bind parameters of an {@link Advice} method to a custom, constant value.
* </p>
* <p>The mapped value must be a constant value that can be embedded into a Java class file. This holds for all primitive types,
* instances of {@link String} and for {@link Class} instances as well as their unloaded {@link TypeDescription} representations.
* </p>
*
* @param <T> The type of the annotation this dynamic value requires to provide a mapping.
* @see WithCustomMapping
*/
public interface DynamicValue<T extends Annotation> {
/**
* Resolves a constant value that is mapped to a parameter that is annotated with a custom bound annotation.
*
* @param instrumentedMethod The instrumented method onto which this advice is applied.
* @param target The target parameter that is bound.
* @param annotation The annotation that triggered this binding.
* @param initialized {@code true} if the method is initialized when the value is bound, i.e. that the value is not
* supplied to a constructor before the super constructor was invoked.
* @return The constant pool value that is bound to the supplied parameter or {@code null} to assign this value.
*/
Object resolve(MethodDescription.InDefinedShape instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<T> annotation,
boolean initialized);
/**
* <p>
* A {@link DynamicValue} implementation that always binds a fixed value.
* </p>
* <p>
* The mapped value must be a constant value that can be embedded into a Java class file. This holds for all primitive types,
* instances of {@link String} and for {@link Class} instances as well as their unloaded {@link TypeDescription} representations.
* </p>
*/
class ForFixedValue implements DynamicValue<Annotation> {
/**
* The fixed value to bind to the corresponding annotation.
*/
private final Object value;
/**
* Creates a dynamic value for a fixed value.
*
* @param value The fixed value to bind to the corresponding annotation.
*/
public ForFixedValue(Object value) {
this.value = value;
}
@Override
public Object resolve(MethodDescription.InDefinedShape instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
boolean initialized) {
return value;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForFixedValue that = (ForFixedValue) object;
return value != null ? value.equals(that.value) : that.value == null;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
@Override
public String toString() {
return "Advice.DynamicValue.ForFixedValue{" +
"value=" + value +
'}';
}
}
}
/**
* A builder step for creating an {@link Advice} that uses custom mappings of annotations to constant pool values.
*/
public static class WithCustomMapping {
/**
* A map containing dynamically computed constant pool values that are mapped by their triggering annotation type.
*/
private final Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues;
/**
* Creates a new custom mapping builder step without including any custom mappings.
*/
protected WithCustomMapping() {
this(Collections.<Class<? extends Annotation>, DynamicValue<?>>emptyMap());
}
/**
* Creates a new custom mapping builder step with the given custom mappings.
*
* @param dynamicValues A map containing dynamically computed constant pool values that are mapped by their triggering annotation type.
*/
protected WithCustomMapping(Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues) {
this.dynamicValues = dynamicValues;
}
/**
* Binds an annotation type to dynamically computed value. Whenever the {@link Advice} component discovers the given annotation on
* a parameter of an advice method, the dynamic value is asked to provide a value that is then assigned to the parameter in question.
*
* @param type The annotation type that triggers the mapping.
* @param dynamicValue The dynamic value that is computed for binding the parameter to a value.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, DynamicValue<T> dynamicValue) {
Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues = new HashMap<Class<? extends Annotation>, Advice.DynamicValue<?>>(this.dynamicValues);
if (!type.isAnnotation()) {
throw new IllegalArgumentException("Not an annotation type: " + type);
} else if (dynamicValues.put(type, dynamicValue) != null) {
throw new IllegalArgumentException("Annotation-type already mapped: " + type);
}
return new WithCustomMapping(dynamicValues);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param type The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(Class<?> type) {
return to(type, ClassFileLocator.ForClassLoader.of(type.getClassLoader()));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param type The type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(Class<?> type, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(type), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param typeDescription A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(TypeDescription typeDescription, ClassFileLocator classFileLocator) {
List<Dispatcher.OffsetMapping.Factory> userFactories = new ArrayList<Dispatcher.OffsetMapping.Factory>(dynamicValues.size());
for (Map.Entry<Class<? extends Annotation>, DynamicValue<?>> entry : dynamicValues.entrySet()) {
userFactories.add(Dispatcher.OffsetMapping.ForUserValue.Factory.of(entry.getKey(), entry.getValue()));
}
return Advice.to(typeDescription, classFileLocator, userFactories);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
WithCustomMapping that = (WithCustomMapping) object;
return dynamicValues.equals(that.dynamicValues);
}
@Override
public int hashCode() {
return dynamicValues.hashCode();
}
@Override
public String toString() {
return "Advice.WithCustomMapping{" +
"dynamicValues=" + dynamicValues +
'}';
}
}
/**
* A marker class that indicates that an advice method does not suppress any {@link Throwable}.
*/
private static class NoSuppression extends Throwable {
/**
* A private constructor as this class is not supposed to be invoked.
*/
private NoSuppression() {
throw new UnsupportedOperationException("This marker class is not supposed to be instantiated");
}
}
}
|
package com.annimon.ownlang.parser.ast;
import com.annimon.ownlang.exceptions.OperationIsNotSupportedException;
import com.annimon.ownlang.lib.NumberValue;
import com.annimon.ownlang.lib.Types;
import com.annimon.ownlang.lib.Value;
/**
*
* @author aNNiMON
*/
public final class ConditionalExpression implements Expression {
public static enum Operator {
EQUALS("=="),
NOT_EQUALS("!="),
LT("<"),
LTEQ("<="),
GT(">"),
GTEQ(">="),
AND("&&"),
OR("||");
private final String name;
private Operator(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public final Expression expr1, expr2;
public final Operator operation;
public ConditionalExpression(Operator operation, Expression expr1, Expression expr2) {
this.operation = operation;
this.expr1 = expr1;
this.expr2 = expr2;
}
@Override
public Value eval() {
final Value value1 = expr1.eval();
switch (operation) {
case AND: return NumberValue.fromBoolean(
(value1.asInt() != 0) && (expr2.eval().asInt() != 0) );
case OR: return NumberValue.fromBoolean(
(value1.asInt() != 0) || (expr2.eval().asInt() != 0) );
}
final Value value2 = expr2.eval();
double number1, number2;
if (value1.type() == Types.NUMBER) {
number1 = value1.asNumber();
number2 = value2.asNumber();
} else {
number1 = value1.compareTo(value2);
number2 = 0;
}
boolean result;
switch (operation) {
case EQUALS: result = number1 == number2; break;
case NOT_EQUALS: result = number1 != number2; break;
case LT: result = number1 < number2; break;
case LTEQ: result = number1 <= number2; break;
case GT: result = number1 > number2; break;
case GTEQ: result = number1 >= number2; break;
default:
throw new OperationIsNotSupportedException(operation);
}
return NumberValue.fromBoolean(result);
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public String toString() {
return String.format("%s %s %s", expr1, operation.getName(), expr2);
}
}
|
package com.splicemachine.job;
import com.google.common.base.Throwables;
import com.splicemachine.derby.stats.TaskStats;
import com.splicemachine.derby.utils.Exceptions;
import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;
import org.apache.hadoop.hbase.client.Row;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
public class TaskStatus implements Externalizable{
private static final long serialVersionUID = 6l;
private AtomicReference<Status> status;
private final Set<StatusListener> listeners;
private volatile TaskStats stats;
private volatile String txnId;
private volatile boolean shouldRetry;
private volatile String errorCode;
private volatile String errorMessage;
public static TaskStatus failed(String s) {
return new TaskStatus(Status.FAILED,new IOException(s));
}
public String getTransactionId() {
return txnId;
}
public String getErrorCode() {
return errorCode;
}
public static interface StatusListener{
void statusChanged(Status oldStatus,Status newStatus,TaskStatus taskStatus);
}
public TaskStatus(){
this.listeners = Collections.newSetFromMap(new ConcurrentHashMap<StatusListener, Boolean>());
}
public TaskStatus(Status status, Throwable error) {
this();
this.status = new AtomicReference<Status>(status);
if(error!=null){
error = Exceptions.getRootCause(error);
this.shouldRetry = Exceptions.shouldRetry(error);
this.errorMessage = error.getMessage();
}
}
public void setTxnId(String txnId){
this.txnId = txnId;
}
public String getErrorMessage(){
return errorMessage;
}
public boolean shouldRetry(){
return shouldRetry;
}
public Status getStatus(){
return status.get();
}
/**
* @return stats if the task has then, or {@code null}. Usually, stats are only
* present when the state is COMPLETED.
*/
public TaskStats getStats(){
return this.stats;
}
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos= new ByteArrayOutputStream();
ObjectOutput oo = new ObjectOutputStream(baos);
oo.writeObject(this);
oo.flush();
return baos.toByteArray();
}
public void fromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInput ii = new ObjectInputStream(bais);
readExternal(ii);
}
public static TaskStatus cancelled(){
return new TaskStatus(Status.CANCELLED,null);
}
/**
* @param status the new status to set
* @return the old status
*/
public void setStatus(Status status) {
Status oldStatus = this.status.getAndSet(status);
for(StatusListener listener:listeners){
listener.statusChanged(oldStatus,status,this);
}
}
public void setError(Throwable error) {
error = Exceptions.getRootCause(error);
this.errorMessage = error.getMessage();
this.errorCode = Exceptions.getErrorCode(error);
this.shouldRetry = Exceptions.shouldRetry(error);
}
public void setStats(TaskStats stats){
this.stats = stats;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
Status statusInfo = status.get();
out.writeUTF(statusInfo.name());
if(statusInfo==Status.FAILED){
out.writeBoolean(shouldRetry);
out.writeUTF(errorCode);
out.writeUTF((errorMessage != null ? errorMessage : "NULL"));
}
out.writeBoolean(stats!=null);
if(stats!=null)
out.writeObject(stats);
out.writeBoolean(txnId !=null);
if(txnId !=null)
out.writeUTF(txnId);
}
private void writeError(ObjectOutput out, Throwable error) throws IOException {
Throwable e = Throwables.getRootCause(error);
if(e instanceof RetriesExhaustedWithDetailsException){
RetriesExhaustedWithDetailsException rewde = (RetriesExhaustedWithDetailsException)e;
List<String>hostnameAndPorts = Collections.emptyList();
RetriesExhaustedWithDetailsException copy = new RetriesExhaustedWithDetailsException(rewde.getCauses(),
Collections.<Row>emptyList(),hostnameAndPorts);
e = copy;
out.writeObject(e);
}else{
out.writeObject(error);
}
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
status = new AtomicReference<Status>(Status.valueOf(in.readUTF()));
if(status.get()==Status.FAILED){
shouldRetry = in.readBoolean();
errorCode = in.readUTF();
errorMessage = in.readUTF();
}
if(in.readBoolean()){
stats = (TaskStats)in.readObject();
}
if(in.readBoolean())
txnId = in.readUTF();
}
public void attachListener(StatusListener listener) {
this.listeners.add(listener);
}
public void detachListener(StatusListener listener){
this.listeners.remove(listener);
}
}
|
package th.ac.kmitl.ce.ooad;
public class Plan {
public String cloudProv, vmIP;
public String cpu, mem, network;
public String storage;
public float monthlyRate;
}
|
package com.wizzardo.tools.collections.flow;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class FlowTest {
@Test
public void test_grouping_1() {
List<List<Integer>> result = Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer it) {
return it % 2 == 0;
}
})
.flatMap(new Mapper<FlowGroup<Boolean, Integer>, List<Integer>>() {
@Override
public List<Integer> map(FlowGroup<Boolean, Integer> group) {
return group.toList();
}
})
.toSortedList(new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.size() < o2.size() ? -1 : (o1.size() == o2.size() ? 0 : 1);
}
});
Assert.assertEquals(2, result.size());
Assert.assertEquals(1, result.get(0).size());
Assert.assertEquals(Integer.valueOf(2), result.get(0).get(0));
Assert.assertEquals(2, result.get(1).size());
Assert.assertEquals(Integer.valueOf(1), result.get(1).get(0));
Assert.assertEquals(Integer.valueOf(3), result.get(1).get(1));
}
@Test
public void test_grouping_2() {
List<List<Integer>> result = Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer it) {
return it % 2 == 0;
}
})
.filter(new Filter<FlowGroup<Boolean, Integer>>() {
@Override
public boolean allow(FlowGroup<Boolean, Integer> group) {
return group.getKey();
}
})
.flatMap(new Mapper<FlowGroup<Boolean, Integer>, List<Integer>>() {
int counter = 0;
@Override
public List<Integer> map(FlowGroup<Boolean, Integer> group) {
Assert.assertEquals("should be executed only once", 1, ++counter);
return group.toList();
}
})
.toSortedList(new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.size() < o2.size() ? -1 : (o1.size() == o2.size() ? 0 : 1);
}
});
Assert.assertEquals(1, result.size());
Assert.assertEquals(1, result.get(0).size());
Assert.assertEquals(Integer.valueOf(2), result.get(0).get(0));
}
@Test
public void test_grouping_3() {
List<Integer> result = Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer it) {
return it % 2 == 0;
}
})
.flatMap(new Mapper<FlowGroup<Boolean, Integer>, Integer>() {
@Override
public Integer map(FlowGroup<Boolean, Integer> group) {
return group.first();
}
})
.toSortedList();
Assert.assertEquals(2, result.size());
Assert.assertEquals(Integer.valueOf(1), result.get(0));
Assert.assertEquals(Integer.valueOf(2), result.get(1));
}
@Test
public void test_grouping_4() {
final AtomicInteger counter = new AtomicInteger();
Integer result = Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer it) {
counter.incrementAndGet();
return it % 2 == 0;
}
})
.flatMap(new Mapper<FlowGroup<Boolean, Integer>, Integer>() {
@Override
public Integer map(FlowGroup<Boolean, Integer> group) {
return group.first();
}
})
.first();
Assert.assertEquals(Integer.valueOf(1), result);
Assert.assertEquals(1, counter.get());
}
static class Person {
final String name;
final int age;
final long salary;
Person(String name, int age, long salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
}
@Test
public void test_grouping_5() {
Map<Integer, Map<Long, List<Person>>> result = Flow.of(
new Person("Paul", 24, 20000),
new Person("Mark", 24, 30000),
new Person("Will", 28, 28000),
new Person("William", 28, 28000)
)
.groupBy(new Mapper<Person, Integer>() {
@Override
public Integer map(Person person) {
return person.age;
}
})
.toMap(new Mapper<FlowGroup<Integer, Person>, Map<Long, List<Person>>>() {
@Override
public Map<Long, List<Person>> map(FlowGroup<Integer, Person> ageGroup) {
return ageGroup
.groupBy(new Mapper<Person, Long>() {
@Override
public Long map(Person person) {
return person.salary;
}
})
.toMap(new Mapper<FlowGroup<Long, Person>, List<Person>>() {
@Override
public List<Person> map(FlowGroup<Long, Person> salaryGroup) {
return salaryGroup.toList();
}
});
}
});
Assert.assertEquals(2, result.size());
Assert.assertEquals(2, result.get(24).size());
Assert.assertEquals(1, result.get(24).get(20000l).size());
Assert.assertEquals("Paul", result.get(24).get(20000l).get(0).name);
Assert.assertEquals(2, result.get(24).size());
Assert.assertEquals(1, result.get(24).get(30000l).size());
Assert.assertEquals("Mark", result.get(24).get(30000l).get(0).name);
Assert.assertEquals(1, result.get(28).size());
Assert.assertEquals(2, result.get(28).get(28000l).size());
Assert.assertEquals("Will", result.get(28).get(28000l).get(0).name);
Assert.assertEquals("William", result.get(28).get(28000l).get(1).name);
}
@Test
public void test_grouping_6() {
List<List<Map<String, List<Person>>>> result = Flow.of(
new Person("Paul", 24, 20000),
new Person("Mark", 24, 30000),
new Person("Will", 28, 28000),
new Person("William", 28, 28000)
)
.groupBy(new Mapper<Person, Integer>() {
@Override
public Integer map(Person person) {
return person.age;
}
})
.flatMap(new Mapper<FlowGroup<Integer, Person>, List<Map<String, List<Person>>>>() {
@Override
public List<Map<String, List<Person>>> map(FlowGroup<Integer, Person> integerPersonFlowGroup) {
return integerPersonFlowGroup.groupBy(new Mapper<Person, Long>() {
@Override
public Long map(Person person) {
return person.salary;
}
}).flatMap(new Mapper<FlowGroup<Long, Person>, Map<String, List<Person>>>() {
@Override
public Map<String, List<Person>> map(FlowGroup<Long, Person> longPersonFlowGroup) {
return longPersonFlowGroup.groupBy(new Mapper<Person, String>() {
@Override
public String map(Person person) {
return person.name;
}
}).toMap();
}
}).toList();
}
})
.toList();
Assert.assertEquals(2, result.size());
Assert.assertEquals(2, result.get(0).size());
Assert.assertEquals(1, result.get(0).get(0).size());
Assert.assertEquals(1, result.get(0).get(0).get("Paul").size());
Assert.assertEquals("Paul", result.get(0).get(0).get("Paul").get(0).name);
Assert.assertEquals(1, result.get(0).get(1).size());
Assert.assertEquals(1, result.get(0).get(1).get("Mark").size());
Assert.assertEquals("Mark", result.get(0).get(1).get("Mark").get(0).name);
Assert.assertEquals(1, result.get(1).size());
Assert.assertEquals(2, result.get(1).get(0).size());
Assert.assertEquals(1, result.get(1).get(0).get("Will").size());
Assert.assertEquals("Will", result.get(1).get(0).get("Will").get(0).name);
Assert.assertEquals(1, result.get(1).get(0).get("William").size());
Assert.assertEquals("William", result.get(1).get(0).get("William").get(0).name);
}
@Test
public void test_sorted_list() {
List<Integer> result = Flow.of(3, 2, 1).toSortedList();
Assert.assertEquals(3, result.size());
Assert.assertEquals(Integer.valueOf(1), result.get(0));
Assert.assertEquals(Integer.valueOf(2), result.get(1));
Assert.assertEquals(Integer.valueOf(3), result.get(2));
}
@Test
public void test_each() {
final AtomicInteger counter = new AtomicInteger();
Flow.of(1, 2, 3).each(new Consumer<Integer>() {
@Override
public void consume(Integer integer) {
counter.incrementAndGet();
}
}).execute();
Assert.assertEquals(3, counter.get());
}
@Test
public void test_each_2() {
final AtomicInteger counter = new AtomicInteger();
Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
})
.each(new Consumer<FlowGroup<Boolean, Integer>>() {
@Override
public void consume(FlowGroup<Boolean, Integer> group) {
counter.incrementAndGet();
}
}).execute();
Assert.assertEquals(2, counter.get());
}
@Test
public void test_each_3() {
final AtomicInteger counter = new AtomicInteger();
Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
})
.each(new Consumer<FlowGroup<Boolean, Integer>>() {
@Override
public void consume(FlowGroup<Boolean, Integer> group) {
counter.incrementAndGet();
}
})
.first()
.execute()
.get();
Assert.assertEquals(1, counter.get());
}
@Test
public void test_first() {
Assert.assertEquals(Integer.valueOf(1), Flow.of(1, 2, 3).first());
}
@Test
public void test_stop_after_first() {
final AtomicInteger counter = new AtomicInteger();
Assert.assertEquals(Integer.valueOf(1), Flow.of(1, 2, 3).each(new Consumer<Integer>() {
@Override
public void consume(Integer integer) {
counter.incrementAndGet();
}
}).first());
Assert.assertEquals(1, counter.get());
}
@Test
public void test_last() {
Assert.assertEquals(Integer.valueOf(3), Flow.of(1, 2, 3).last());
}
@Test
public void test_min() {
Assert.assertEquals(Integer.valueOf(1), Flow.of(1, 2, 3).min());
Assert.assertEquals(Integer.valueOf(1), Flow.of(3, 2, 1).min());
}
@Test
public void test_min_2() {
Comparator<Number> comparator = new Comparator<Number>() {
@Override
public int compare(Number o1, Number o2) {
return Integer.valueOf(o1.intValue()).compareTo(o2.intValue());
}
};
Assert.assertEquals(Integer.valueOf(1), Flow.of(1, 2, 3).min(comparator));
Assert.assertEquals(Integer.valueOf(1), Flow.of(3, 2, 1).min(comparator));
}
@Test
public void test_max() {
Assert.assertEquals(Integer.valueOf(3), Flow.of(1, 2, 3).max());
Assert.assertEquals(Integer.valueOf(3), Flow.of(3, 2, 1).max());
}
@Test
public void test_max_2() {
Comparator<Number> comparator = new Comparator<Number>() {
@Override
public int compare(Number o1, Number o2) {
return Integer.valueOf(o1.intValue()).compareTo(o2.intValue());
}
};
Assert.assertEquals(Integer.valueOf(3), Flow.of(1, 2, 3).max(comparator));
Assert.assertEquals(Integer.valueOf(3), Flow.of(3, 2, 1).max(comparator));
}
@Test
public void test_max_3() {
Assert.assertEquals(Integer.valueOf(6), Flow.of(1, 2, 3)
.maxFlow()
.map(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer * 2;
}
}).first()
);
Assert.assertEquals(Integer.valueOf(6), Flow.of(3, 2, 1)
.maxFlow()
.map(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer * 2;
}
}).first());
}
@Test
public void test_reduce() {
Assert.assertEquals(Integer.valueOf(3), Flow.of(1, 2, 3).reduce(new Reducer<Integer>() {
@Override
public Integer reduce(Integer a, Integer b) {
return a > b ? a : b;
}
}));
Assert.assertEquals(Integer.valueOf(3), Flow.of(3, 2, 1).reduce(new Reducer<Integer>() {
@Override
public Integer reduce(Integer a, Integer b) {
return a > b ? a : b;
}
}));
}
@Test
public void test_reduce2() {
Assert.assertEquals(Integer.valueOf(6), Flow.of(1, 2, 3).reduceFlow(new Reducer<Integer>() {
@Override
public Integer reduce(Integer a, Integer b) {
return a > b ? a : b;
}
}).map(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer * 2;
}
}).first());
Assert.assertEquals(Integer.valueOf(6), Flow.of(3, 2, 1).reduceFlow(new Reducer<Integer>() {
@Override
public Integer reduce(Integer a, Integer b) {
return a > b ? a : b;
}
}).map(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer * 2;
}
}).first());
}
@Test
public void test_collect() {
List<Integer> list = new ArrayList<Integer>();
List<Integer> result = Flow.of(1, 2, 3)
.collect(list, new BiConsumer<List<Integer>, Integer>() {
@Override
public void consume(List<Integer> integers, Integer integer) {
integers.add(integer * 2);
}
})
.execute()
.get();
Assert.assertSame(list, result);
Assert.assertEquals(3, result.size());
Assert.assertEquals(Integer.valueOf(2), result.get(0));
Assert.assertEquals(Integer.valueOf(4), result.get(1));
Assert.assertEquals(Integer.valueOf(6), result.get(2));
}
@Test
public void test_merge() {
List<Integer> result = Flow.of(1, 2, 3, 4, 5, 6)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
})
.merge()
.toList();
Assert.assertEquals(6, result.size());
Assert.assertEquals(Integer.valueOf(1), result.get(0));
Assert.assertEquals(Integer.valueOf(2), result.get(1));
Assert.assertEquals(Integer.valueOf(3), result.get(2));
Assert.assertEquals(Integer.valueOf(4), result.get(3));
Assert.assertEquals(Integer.valueOf(5), result.get(4));
Assert.assertEquals(Integer.valueOf(6), result.get(5));
}
@Test
public void test_merge_2() {
List<Integer> result = Flow.of(1, 2, 3, 4, 5, 6)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
})
.filter(new Filter<FlowGroup<Boolean, Integer>>() {
@Override
public boolean allow(FlowGroup<Boolean, Integer> group) {
return group.getKey();
}
})
.merge()
.toList();
Assert.assertEquals(3, result.size());
Assert.assertEquals(Integer.valueOf(2), result.get(0));
Assert.assertEquals(Integer.valueOf(4), result.get(1));
Assert.assertEquals(Integer.valueOf(6), result.get(2));
}
@Test
public void test_merge_3() {
List<Integer> result = Flow.of(new int[]{1, 2}, new int[]{3, 4}, new int[]{5, 6})
.merge(new Mapper<int[], Flow<Integer>>() {
@Override
public Flow<Integer> map(int[] ints) {
return Flow.of(ints);
}
})
.toList();
Assert.assertEquals(6, result.size());
Assert.assertEquals(Integer.valueOf(1), result.get(0));
Assert.assertEquals(Integer.valueOf(2), result.get(1));
Assert.assertEquals(Integer.valueOf(3), result.get(2));
Assert.assertEquals(Integer.valueOf(4), result.get(3));
Assert.assertEquals(Integer.valueOf(5), result.get(4));
Assert.assertEquals(Integer.valueOf(6), result.get(5));
}
@Test
public void test_merge_4() {
List<Integer> result = Flow.of(1, 2, 3, 4, 5, 6)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
})
.filter(new Filter<FlowGroup<Boolean, Integer>>() {
@Override
public boolean allow(FlowGroup<Boolean, Integer> group) {
return group.getKey();
}
})
.merge(new Mapper<FlowGroup<Boolean, Integer>, Flow<Integer>>() {
@Override
public Flow<Integer> map(FlowGroup<Boolean, Integer> group) {
return group.map(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer / 2;
}
});
}
})
.toList();
Assert.assertEquals(3, result.size());
Assert.assertEquals(Integer.valueOf(1), result.get(0));
Assert.assertEquals(Integer.valueOf(2), result.get(1));
Assert.assertEquals(Integer.valueOf(3), result.get(2));
}
@Test
public void test_count() {
int result = Flow.of(1, 2, 3, 4, 5, 6).count();
Assert.assertEquals(6, result);
}
@Test
public void test_map() {
List<String> result = Flow.of(1, 2, 3)
.map(new Mapper<Integer, String>() {
@Override
public String map(Integer integer) {
return integer.toString();
}
}).toList();
Assert.assertEquals(3, result.size());
Assert.assertEquals("1", result.get(0));
Assert.assertEquals("2", result.get(1));
Assert.assertEquals("3", result.get(2));
}
@Test
public void test_filter() {
List<Integer> result = Flow.of(1, 2, 3, 4)
.filter(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 == 0;
}
}).toList();
Assert.assertEquals(2, result.size());
Assert.assertEquals(Integer.valueOf(2), result.get(0));
Assert.assertEquals(Integer.valueOf(4), result.get(1));
}
@Test
public void test_of_iterable() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
int result = Flow.of(list).count();
Assert.assertEquals(3, result);
}
@Test
public void test_of_iterable_2() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
int result = Flow.of(list).first();
Assert.assertEquals(1, result);
}
@Test
public void test_of_iterator() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
int result = Flow.of(list.iterator()).first();
Assert.assertEquals(1, result);
}
@Test
public void test_do_nothing() {
Flow.of(new Iterator() {
@Override
public boolean hasNext() {
throw new IllegalStateException("should not be called");
}
@Override
public Object next() {
throw new IllegalStateException("should not be called");
}
@Override
public void remove() {
throw new IllegalStateException("should not be called");
}
}).start();
}
@Test
public void test_toMap() {
Map<Boolean, List<Integer>> map = Flow.of(1, 2, 3)
.toMap(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
}, Flow.<Boolean, Integer>flowGroupListMapper());
Assert.assertEquals(2, map.size());
Assert.assertEquals(1, map.get(true).size());
Assert.assertEquals(Integer.valueOf(2), map.get(true).get(0));
Assert.assertEquals(2, map.get(false).size());
Assert.assertEquals(Integer.valueOf(1), map.get(false).get(0));
Assert.assertEquals(Integer.valueOf(3), map.get(false).get(1));
}
@Test
public void test_toMap_2() {
Map<Boolean, List<Integer>> map = Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
})
.toMap();
Assert.assertEquals(2, map.size());
Assert.assertEquals(1, map.get(true).size());
Assert.assertEquals(Integer.valueOf(2), map.get(true).get(0));
Assert.assertEquals(2, map.get(false).size());
Assert.assertEquals(Integer.valueOf(1), map.get(false).get(0));
Assert.assertEquals(Integer.valueOf(3), map.get(false).get(1));
}
@Test
public void test_toMap_3() {
Map<Boolean, List<Integer>> map = Flow.of(1, 2, 3)
.groupBy(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
})
.filter(new Filter<FlowGroup<Boolean, Integer>>() {
@Override
public boolean allow(FlowGroup<Boolean, Integer> group) {
return group.getKey();
}
})
.toMap();
Assert.assertEquals(1, map.size());
Assert.assertEquals(1, map.get(true).size());
Assert.assertEquals(Integer.valueOf(2), map.get(true).get(0));
}
@Test
public void test_toMap_4() {
Map<Boolean, List<String>> map = Flow.of(1, 2, 3)
.toMap(new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
}, new Mapper<FlowGroup<Boolean, Integer>, List<String>>() {
@Override
public List<String> map(FlowGroup<Boolean, Integer> group) {
return group.map(new Mapper<Integer, String>() {
@Override
public String map(Integer integer) {
return integer.toString();
}
}).toList();
}
});
Assert.assertEquals(2, map.size());
Assert.assertEquals(1, map.get(true).size());
Assert.assertEquals("2", map.get(true).get(0));
Assert.assertEquals(2, map.get(false).size());
Assert.assertEquals("1", map.get(false).get(0));
Assert.assertEquals("3", map.get(false).get(1));
}
@Test
public void test_toMap_6() {
Map<Boolean, List<Integer>> map = Flow.of(1, 2, 3)
.toMap(new Supplier<Map<Boolean, FlowGroup<Boolean, Integer>>>() {
@Override
public Map<Boolean, FlowGroup<Boolean, Integer>> supply() {
return new TreeMap<Boolean, FlowGroup<Boolean, Integer>>();
}
}, new Mapper<Integer, Boolean>() {
@Override
public Boolean map(Integer integer) {
return integer % 2 == 0;
}
});
Assert.assertEquals(2, map.size());
Assert.assertEquals(1, map.get(true).size());
Assert.assertEquals(Integer.valueOf(2), map.get(true).get(0));
Assert.assertEquals(2, map.get(false).size());
Assert.assertEquals(Integer.valueOf(1), map.get(false).get(0));
Assert.assertEquals(Integer.valueOf(3), map.get(false).get(1));
}
@Test
public void test_join() {
Assert.assertEquals("1,2,3", Flow.of(1, 2, 3).join(","));
}
@Test
public void improveCoverage() {
Assert.assertEquals(null, new Flow().get());
}
@Test
public void test_of_ints() {
Assert.assertEquals("1,2,3", Flow.of(new int[]{1, 2, 3}).join(","));
IllegalState flow = Flow.of(new int[]{1, 2, 3}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
@Test
public void test_of_longs() {
Assert.assertEquals("1,2,3", Flow.of(new long[]{1, 2, 3}).join(","));
IllegalState flow = Flow.of(new long[]{1, 2, 3}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
@Test
public void test_of_shorts() {
Assert.assertEquals("1,2,3", Flow.of(new short[]{1, 2, 3}).join(","));
IllegalState flow = Flow.of(new short[]{1, 2, 3}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
@Test
public void test_of_bytes() {
Assert.assertEquals("1,2,3", Flow.of(new byte[]{1, 2, 3}).join(","));
IllegalState flow = Flow.of(new byte[]{1, 2, 3}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
@Test
public void test_of_floats() {
Assert.assertEquals("1.0,2.0,3.0", Flow.of(new float[]{1, 2, 3}).join(","));
IllegalState flow = Flow.of(new float[]{1, 2, 3}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
@Test
public void test_of_doubles() {
Assert.assertEquals("1.0,2.0,3.0", Flow.of(new double[]{1, 2, 3}).join(","));
IllegalState flow = Flow.of(new double[]{1, 2, 3}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
@Test
public void test_of_booleans() {
Assert.assertEquals("true,false", Flow.of(new boolean[]{true, false}).join(","));
IllegalState flow = Flow.of(new boolean[]{true, false}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
@Test
public void test_of_chars() {
Assert.assertEquals("a,b,c", Flow.of(new char[]{'a', 'b', 'c'}).join(","));
IllegalState flow = Flow.of(new char[]{'a', 'b', 'c'}).then(new IllegalState());
flow.stop();
flow.execute();
Assert.assertEquals(null, flow.get());
}
static class IllegalState extends FlowProcessor {
@Override
public void process(Object o) {
throw new IllegalStateException();
}
}
@Test
public void test_of_map() {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "1");
map.put(2, "2");
map.put(3, "3");
String result = Flow.of(map).map(new Mapper<Map.Entry<Integer, String>, Integer>() {
@Override
public Integer map(Map.Entry<Integer, String> entry) {
return entry.getKey();
}
}).join(", ");
Assert.assertEquals("1, 2, 3", result);
}
@Test
public void test_each_with_index() {
final StringBuilder sb = new StringBuilder();
Flow.of(2, 4, 6).each(new ConsumerWithInt<Integer>() {
@Override
public void consume(int i, Integer integer) {
if (sb.length() != 0)
sb.append(", ");
sb.append(i);
}
}).execute();
Assert.assertEquals("0, 1, 2", sb.toString());
}
@Test
public void test_each_with_index_2() {
final StringBuilder sb = new StringBuilder();
Flow.of(2, 4, 6)
.groupBy(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer;
}
})
.each(new ConsumerWithInt<FlowGroup<Integer, Integer>>() {
@Override
public void consume(int i, FlowGroup<Integer, Integer> integerIntegerFlowGroup) {
if (sb.length() != 0)
sb.append(", ");
sb.append(i);
}
})
.execute();
Assert.assertEquals("0, 1, 2", sb.toString());
}
@Test
public void test_each_with_index_3() {
final StringBuilder sb = new StringBuilder();
Flow.of(2, 4, 6)
.each(new ConsumerWithInt<Integer>() {
@Override
public void consume(int i, Integer integer) {
if (sb.length() != 0)
sb.append(", ");
sb.append(i);
}
})
.first();
Assert.assertEquals("0", sb.toString());
}
@Test
public void test_each_with_index_4() {
final StringBuilder sb = new StringBuilder();
Flow.of(2, 4, 6)
.groupBy(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer;
}
})
.each(new ConsumerWithInt<FlowGroup<Integer, Integer>>() {
@Override
public void consume(int i, FlowGroup<Integer, Integer> integerIntegerFlowGroup) {
if (sb.length() != 0)
sb.append(", ");
sb.append(i);
}
})
.first();
Assert.assertEquals("0", sb.toString());
}
@Test
public void test_any() {
Assert.assertTrue(Flow.of(1, 2, 3).any(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 == 0;
}
}));
Assert.assertFalse(Flow.of(1, 3, 5).any(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 == 0;
}
}));
}
@Test
public void test_all() {
Assert.assertTrue(Flow.of(1, 3, 5).all(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 != 0;
}
}));
Assert.assertFalse(Flow.of(1, 2, 3).all(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 != 0;
}
}));
}
@Test
public void test_none() {
Assert.assertTrue(Flow.of(1, 3, 5).none(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 == 0;
}
}));
Assert.assertFalse(Flow.of(1, 2, 3).none(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 != 0;
}
}));
}
@Test
public void test_none_and() {
Assert.assertEquals("yes", Flow.of(1, 3, 5)
.noneFlow(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 == 0;
}
})
.map(new Mapper<Boolean, String>() {
@Override
public String map(Boolean aBoolean) {
return aBoolean ? "yes" : "no";
}
})
.first()
);
Assert.assertEquals("no", Flow.of(1, 2, 3)
.noneFlow(new Filter<Integer>() {
@Override
public boolean allow(Integer integer) {
return integer % 2 != 0;
}
})
.map(new Mapper<Boolean, String>() {
@Override
public String map(Boolean aBoolean) {
return aBoolean ? "yes" : "no";
}
})
.first()
);
}
@Test
public void test_skip() {
Assert.assertEquals("3,4,5", Flow.of(1, 2, 3, 4, 5).skip(2).join(","));
}
@Test
public void test_skip_2() {
Assert.assertEquals("3,4,5", Flow.of(1, 2, 3, 4, 5)
.groupBy(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer;
}
})
.skip(2)
.map(new Mapper<FlowGroup<Integer, Integer>, Integer>() {
@Override
public Integer map(FlowGroup<Integer, Integer> group) {
return group.key;
}
}).join(","));
}
@Test
public void test_limit() {
Assert.assertEquals("1,2,3", Flow.of(1, 2, 3, 4, 5).limit(3).join(","));
}
@Test
public void test_limit_2() {
Assert.assertEquals("1,2,3", Flow.of(1, 2, 3, 4, 5)
.groupBy(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer;
}
})
.limit(3)
.map(new Mapper<FlowGroup<Integer, Integer>, Integer>() {
@Override
public Integer map(FlowGroup<Integer, Integer> group) {
return group.key;
}
})
.join(","));
}
@Test
public void test_limit_3() {
Assert.assertEquals("{1=[1], 2=[2], 3=[3]}", Flow.of(1, 2, 3, 4, 5)
.groupBy(new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer integer) {
return integer;
}
})
.limit(3)
.toMap()
.toString()
);
}
@Test
public void test_limit_4() {
final AtomicInteger i = new AtomicInteger();
Assert.assertEquals("0,1,2", Flow.of(new Supplier<Integer>() {
@Override
public Integer supply() {
Assert.assertTrue(i.get() < 5);
return i.get() < 5 ? i.getAndIncrement() : null;
}
}).limit(3).join(","));
}
@Test
public void test_supplier() {
final int[] ints = new int[]{1, 2, 3};
final AtomicInteger i = new AtomicInteger();
Assert.assertEquals("1,2,3", Flow.of(new Supplier<Integer>() {
@Override
public Integer supply() {
return i.get() < ints.length ? ints[i.getAndIncrement()] : null;
}
}).join(","));
}
@Test
public void test_async() {
List<String> result = Flow.of("a", "b", "c").async(new Mapper<String, Flow<String>>() {
@Override
public Flow<String> map(String s) {
return Flow.of(s.toUpperCase());
}
}).toList();
Assert.assertEquals(3, result.size());
Assert.assertTrue(result.containsAll(Arrays.asList("A", "B", "C")));
}
@Test
public void test_async_non_blocking() {
final AtomicInteger counter = new AtomicInteger();
Flow.of("a", "b", "c")
.async(new Mapper<String, Flow<String>>() {
@Override
public Flow<String> map(String s) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter.incrementAndGet();
return Flow.of(s);
}
}).execute();
Assert.assertEquals(0, counter.get());
try {
Thread.sleep(350);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertEquals(3, counter.get());
}
@Test
public void test_async_executor_service() {
long time = System.currentTimeMillis();
List<String> result = Flow.of("a", "b", "c")
.async(Executors.newFixedThreadPool(1), 1, new Mapper<String, Flow<String>>() {
@Override
public Flow<String> map(String s) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Flow.of(s.toUpperCase());
}
}).toList();
time = System.currentTimeMillis() - time;
Assert.assertTrue(time > 60);
Assert.assertEquals(3, result.size());
Assert.assertTrue(result.containsAll(Arrays.asList("A", "B", "C")));
}
@Test
public void test_async_executor_service_2() {
long time = System.currentTimeMillis();
List<String> result = Flow.of("a", "b", "c")
.async(Executors.newFixedThreadPool(2), 1, new Mapper<String, Flow<String>>() {
@Override
public Flow<String> map(String s) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Flow.of(s.toUpperCase());
}
}).toList();
time = System.currentTimeMillis() - time;
Assert.assertTrue(time > 40);
Assert.assertEquals(3, result.size());
Assert.assertTrue(result.containsAll(Arrays.asList("A", "B", "C")));
}
@Test
public void test_async_queue_limit() {
final AtomicInteger before = new AtomicInteger();
long time = System.currentTimeMillis();
String result = Flow.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.each(new Consumer<Integer>() {
@Override
public void consume(Integer integer) {
before.incrementAndGet();
}
})
.async(Executors.newFixedThreadPool(1), 5, new Mapper<Integer, Flow<String>>() {
@Override
public Flow<String> map(Integer i) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Flow.of(String.valueOf(i));
}
})
.first();
time = System.currentTimeMillis() - time;
Assert.assertTrue(time > 20);
Assert.assertEquals(7, before.get()); // 1 processed + 5 in queue + 1 waiting to be added
Assert.assertEquals("1", result);
}
@Test
public void test_async_process_only_first_after() {
final AtomicInteger after = new AtomicInteger();
String result = Flow.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.async(Executors.newFixedThreadPool(1), 5, new Mapper<Integer, Flow<String>>() {
@Override
public Flow<String> map(Integer i) {
return Flow.of(String.valueOf(i));
}
})
.each(new Consumer<String>() {
@Override
public void consume(String s) {
after.incrementAndGet();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})
.first();
Assert.assertEquals(1, after.get());
Assert.assertEquals("1", result);
}
}
|
package com.esotericsoftware.kryo.serializers;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.reflectasm.MethodAccess;
import static com.esotericsoftware.minlog.Log.*;
/** Serializes Java beans using bean accessor methods. Only bean properties with both a getter and setter are serialized. This
* class is not as fast as {@link FieldSerializer} but is much faster and more efficient than Java serialization. Bytecode
* generation is used to invoke the bean propert methods, if possible.
* <p>
* BeanSerializer does not write header data, only the object data is stored. If the type of a bean property is not final (note
* primitives are final) then an extra byte is written for that property.
* @see Serializer
* @see Kryo#register(Class, Serializer)
* @author Nathan Sweet <misc@n4te.com> */
public class BeanSerializer<T> extends Serializer<T> {
static final Object[] noArgs = {};
private final Kryo kryo;
private CachedProperty[] properties;
Object access;
public BeanSerializer (Kryo kryo, Class type) {
this.kryo = kryo;
BeanInfo info;
try {
info = Introspector.getBeanInfo(type);
} catch (IntrospectionException ex) {
throw new KryoException("Error getting bean info.", ex);
}
// Methods are sorted by alpha so the order of the data is known.
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
Arrays.sort(descriptors, new Comparator<PropertyDescriptor>() {
public int compare (PropertyDescriptor o1, PropertyDescriptor o2) {
return o1.getName().compareTo(o2.getName());
}
});
ArrayList<CachedProperty> cachedProperties = new ArrayList(descriptors.length);
for (int i = 0, n = descriptors.length; i < n; i++) {
PropertyDescriptor property = descriptors[i];
String name = property.getName();
if (name.equals("class")) continue;
Method getMethod = property.getReadMethod();
Method setMethod = property.getWriteMethod();
if (getMethod == null || setMethod == null) continue; // Require both a getter and setter.
// Always use the same serializer for this property if the properties' class is final.
Serializer serializer = null;
Class returnType = getMethod.getReturnType();
if (kryo.isFinal(returnType)) serializer = kryo.getRegistration(returnType).getSerializer();
CachedProperty cachedProperty = new CachedProperty();
cachedProperty.name = name;
cachedProperty.getMethod = getMethod;
cachedProperty.setMethod = setMethod;
cachedProperty.serializer = serializer;
cachedProperty.setMethodType = setMethod.getParameterTypes()[0];
cachedProperties.add(cachedProperty);
}
properties = cachedProperties.toArray(new CachedProperty[cachedProperties.size()]);
try {
access = MethodAccess.get(type);
for (int i = 0, n = properties.length; i < n; i++) {
CachedProperty property = properties[i];
property.getterAccessIndex = ((MethodAccess)access).getIndex(property.getMethod.getName(),
property.getMethod.getParameterTypes());
property.setterAccessIndex = ((MethodAccess)access).getIndex(property.setMethod.getName(),
property.setMethod.getParameterTypes());
}
} catch (Throwable ignored) {
// ReflectASM is not available on Android.
}
}
public void write (Kryo kryo, Output output, T object) {
Class type = object.getClass();
for (int i = 0, n = properties.length; i < n; i++) {
CachedProperty property = properties[i];
try {
if (TRACE) trace("kryo", "Write property: " + property + " (" + type.getName() + ")");
Object value = property.get(object);
Serializer serializer = property.serializer;
if (serializer != null)
kryo.writeObjectOrNull(output, value, serializer);
else
kryo.writeClassAndObject(output, value);
} catch (IllegalAccessException ex) {
throw new KryoException("Error accessing getter method: " + property + " (" + type.getName() + ")", ex);
} catch (InvocationTargetException ex) {
throw new KryoException("Error invoking getter method: " + property + " (" + type.getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(property + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(property + " (" + type.getName() + ")");
throw ex;
}
}
}
public T read (Kryo kryo, Input input, Class<T> type) {
T object = kryo.newInstance(type);
kryo.reference(object);
for (int i = 0, n = properties.length; i < n; i++) {
CachedProperty property = properties[i];
try {
if (TRACE) trace("kryo", "Read property: " + property + " (" + object.getClass() + ")");
Object value;
Serializer serializer = property.serializer;
if (serializer != null)
value = kryo.readObjectOrNull(input, property.setMethodType, serializer);
else
value = kryo.readClassAndObject(input);
property.set(object, value);
} catch (IllegalAccessException ex) {
throw new KryoException("Error accessing setter method: " + property + " (" + object.getClass().getName() + ")", ex);
} catch (InvocationTargetException ex) {
throw new KryoException("Error invoking setter method: " + property + " (" + object.getClass().getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(property + " (" + object.getClass().getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(property + " (" + object.getClass().getName() + ")");
throw ex;
}
}
return object;
}
public T copy (Kryo kryo, T original) {
T copy = (T)kryo.newInstance(original.getClass());
for (int i = 0, n = properties.length; i < n; i++) {
CachedProperty property = properties[i];
try {
Object value = property.get(original);
property.set(copy, value);
} catch (KryoException ex) {
ex.addTrace(property + " (" + copy.getClass().getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(property + " (" + copy.getClass().getName() + ")");
throw ex;
} catch (Exception ex) {
throw new KryoException("Error copying bean property: " + property + " (" + copy.getClass().getName() + ")", ex);
}
}
return copy;
}
class CachedProperty<X> {
String name;
Method getMethod, setMethod;
Class setMethodType;
Serializer serializer;
int getterAccessIndex, setterAccessIndex;
public String toString () {
return name;
}
Object get (Object object) throws IllegalAccessException, InvocationTargetException {
if (access != null) return ((MethodAccess)access).invoke(object, getterAccessIndex);
return getMethod.invoke(object, noArgs);
}
void set (Object object, Object value) throws IllegalAccessException, InvocationTargetException {
if (access != null) {
((MethodAccess)access).invoke(object, setterAccessIndex, value);
return;
}
setMethod.invoke(object, new Object[] {value});
}
}
}
|
package ch.unibas.cs.dbis.cineast.core.util;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import boofcv.abst.distort.FDistort;
import boofcv.alg.filter.binary.BinaryImageOps;
import boofcv.alg.filter.binary.Contour;
import boofcv.alg.filter.binary.ThresholdImageOps;
import boofcv.alg.filter.blur.GBlurImageOps;
import boofcv.alg.misc.PixelMath;
import boofcv.factory.filter.kernel.FactoryKernelGaussian;
import boofcv.gui.image.ShowImages;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.ConnectRule;
import boofcv.struct.ImageRectangle;
import boofcv.struct.convolve.Kernel1D_I32;
import boofcv.struct.image.GrayU8;
import ch.unibas.cs.dbis.cineast.core.data.Frame;
import ch.unibas.cs.dbis.cineast.core.data.Pair;
import ch.unibas.cs.dbis.cineast.core.descriptor.PathList;
import georegression.struct.point.Point2D_F32;
import georegression.struct.point.Point2D_I32;
import org.ddogleg.nn.FactoryNearestNeighbor;
import org.ddogleg.nn.NearestNeighbor;
import org.ddogleg.nn.NnData;
import org.ddogleg.struct.FastQueue;
public class MaskGenerator {
private MaskGenerator(){}
public static ArrayList<Pair<Long,ArrayList<Float>>> getNormalizedBbox(List<Frame> frames,
List<Pair<Integer, LinkedList<Point2D_F32>>> foregroundPaths,
List<Pair<Integer, LinkedList<Point2D_F32>>> backgroundPaths){
if (frames == null || frames.isEmpty() || foregroundPaths == null) {
return null;
}
ArrayList<Pair<Long,ArrayList<Float>>> bboxWithIdx = new ArrayList<Pair<Long,ArrayList<Float>>>();
ArrayList<ImageRectangle> rects = MaskGenerator.getFgBoundingBox(frames, foregroundPaths, backgroundPaths);
int width = frames.get(0).getImage().getWidth();
int height = frames.get(0).getImage().getHeight();
long frameIdx = 0;
for(ImageRectangle rect : rects){
ArrayList<Float> bbox = normalize(rect, width, height);
bboxWithIdx.add(new Pair<Long,ArrayList<Float>>(frameIdx, bbox));
frameIdx += PathList.frameInterval;
}
return bboxWithIdx;
}
public static ArrayList<Float> normalize(ImageRectangle rect, int width, int height){
ArrayList<Float> norm = new ArrayList<Float>();
norm.add((float)rect.getX0() / (float)width);
norm.add((float)rect.getY0() / (float)height);
norm.add((float)rect.getWidth() / (float)width);
norm.add((float)rect.getHeight() / (float)height);
return norm;
}
public static ArrayList<ImageRectangle> getFgBoundingBox(List<Frame> frames,
List<Pair<Integer, LinkedList<Point2D_F32>>> foregroundPaths,
List<Pair<Integer, LinkedList<Point2D_F32>>> backgroundPaths){
if (frames == null || frames.isEmpty() || foregroundPaths == null) {
return null;
}
ArrayList<ImageRectangle> rects = new ArrayList<ImageRectangle>();
ArrayList<GrayU8> masks = getFgMasksByNN(frames, foregroundPaths, backgroundPaths);
for(GrayU8 mask : masks){
ImageRectangle rect = getLargestBoundingBox(mask);
rects.add(rect);
}
return rects;
}
public static ImageRectangle getLargestBoundingBox(GrayU8 mask){
List<ImageRectangle> rects = getBoundingBox(mask);
ImageRectangle largest = new ImageRectangle(0,0,0,0);
for(ImageRectangle rect : rects){
if(rect.getWidth() * rect.getHeight() > largest.getWidth() * largest.getHeight()){
largest = rect;
}
}
return largest;
}
public static List<ImageRectangle> getBoundingBox(GrayU8 mask){
List<Contour> contours = BinaryImageOps.contour(mask,ConnectRule.FOUR,null);
List<ImageRectangle> rects = new ArrayList<ImageRectangle>();
for(Contour contour : contours){
ImageRectangle rect = new ImageRectangle(mask.width,mask.height,0,0);
for (Point2D_I32 p : contour.external){
if (p.x < rect.x0) rect.x0 = p.x;
if (p.y < rect.y0) rect.y0 = p.y;
if (p.x > rect.x1) rect.x1 = p.x;
if (p.y > rect.y1) rect.y1 = p.y;
}
rects.add(rect);
}
return rects;
}
public static ArrayList<GrayU8> getFgMasksByFilter(List<Frame> frames,
List<Pair<Integer, LinkedList<Point2D_F32>>> foregroundPaths,
List<Pair<Integer, LinkedList<Point2D_F32>>> backgroundPaths) {
if (frames == null || frames.isEmpty() || foregroundPaths == null) {
return null;
}
ArrayList<GrayU8> masksScaled = generateScaledMasksFromPath(frames, foregroundPaths);
ArrayList<GrayU8> masksScaledSmoothed1 = createNewMasks(masksScaled);
smoothMasks(masksScaled, masksScaledSmoothed1, 4, 2, 64, 26);
ArrayList<GrayU8> masks = scaleUpMasks(masksScaledSmoothed1, frames.get(0).getImage().getBufferedImage().getWidth(), frames.get(0).getImage().getBufferedImage().getHeight());
ArrayList<GrayU8> masksSmoothed1 = createNewMasks(masks);
smoothMasks(masks, masksSmoothed1, 5, 2, 64, 10);
ArrayList<GrayU8> masksSmoothed2 = createNewMasks(masks);
smoothMasks(masksSmoothed1, masksSmoothed2, 5, 2, 64, 10);
//multiply3D(masksSmoothed2,masksSmoothed2,255);
return masksSmoothed2;
}
public static ArrayList<GrayU8> getFgMasksByNN(List<Frame> frames,
List<Pair<Integer, LinkedList<Point2D_F32>>> foregroundPaths,
List<Pair<Integer, LinkedList<Point2D_F32>>> backgroundPaths) {
if (frames == null || frames.isEmpty() || foregroundPaths == null) {
return null;
}
ArrayList<GrayU8> masks = generateMasksFromPath(frames, foregroundPaths, backgroundPaths);
ArrayList<GrayU8> masksSmoothed1 = createNewMasks(masks);
smoothMasks(masks, masksSmoothed1, 21, 2, 64, 26);
ArrayList<GrayU8> masksSmoothed2 = createNewMasks(masks);
smoothMasks(masksSmoothed1, masksSmoothed2, 11, 2, 64, 26);
//multiply3D(masksSmoothed2,masksSmoothed2,255);
return masksSmoothed2;
}
public static ArrayList<GrayU8> generateMasksFromPath(List<Frame> frames,
List<Pair<Integer, LinkedList<Point2D_F32>>> foregroundPaths,
List<Pair<Integer, LinkedList<Point2D_F32>>> backgroundPaths){
if (frames == null || frames.isEmpty() || foregroundPaths == null) {
return null;
}
ArrayList<GrayU8> masks = new ArrayList<GrayU8>();
int width = frames.get(0).getImage().getBufferedImage().getWidth();
int height = frames.get(0).getImage().getBufferedImage().getHeight();
ListIterator<Pair<Integer, LinkedList<Point2D_F32>>> fgPathItor = foregroundPaths.listIterator();
ListIterator<Pair<Integer, LinkedList<Point2D_F32>>> bgPathItor = backgroundPaths.listIterator();
int cnt = 0;
for (int frameIdx = 0; frameIdx < frames.size(); ++frameIdx) {
if (cnt >= PathList.frameInterval) {
cnt = 0;
continue;
}
cnt += 1;
GrayU8 mask = new GrayU8(width, height);
NearestNeighbor<Integer> nn = FactoryNearestNeighbor.kdtree();
LinkedList<double[]> nnPoints = new LinkedList<double[]>();
LinkedList<Integer> nnData = new LinkedList<Integer>();
while (fgPathItor.hasNext()) {
Pair<Integer, LinkedList<Point2D_F32>> pair = fgPathItor.next();
if (pair.first > frameIdx)
break;
Point2D_F32 p = pair.second.getFirst();
double[] point = {p.x * width, p.y * height};
nnPoints.add(point);
nnData.add(1);
}
while (bgPathItor.hasNext()) {
Pair<Integer, LinkedList<Point2D_F32>> pair = bgPathItor.next();
if (pair.first > frameIdx)
break;
Point2D_F32 p = pair.second.getFirst();
double[] point = {p.x * width, p.y * height};
nnPoints.add(point);
nnData.add(0);
}
nn.init(2);
nn.setPoints(nnPoints, nnData);
for(int x = 0; x < width; ++x){
for(int y = 0; y < height; ++y){
double[] point = {x, y};
FastQueue<NnData<Integer>> results = new FastQueue(5,NnData.class,true);
nn.findNearest(point, -1, 5, results);
int sum = 0;
for(NnData<Integer> r : results.toList()){
sum += r.data.intValue();
}
int value = sum > results.size()/2 ? 1 : 0;
mask.set(x, y, value);
}
}
//showBineryImage(mask);
masks.add(mask);
}
return masks;
}
public static ArrayList<GrayU8> generateScaledMasksFromPath(List<Frame> frames,
List<Pair<Integer, LinkedList<Point2D_F32>>> foregroundPaths) {
if (frames == null || frames.isEmpty() || foregroundPaths == null) {
return null;
}
ArrayList<GrayU8> masks = new ArrayList<GrayU8>();
int width = frames.get(0).getImage().getBufferedImage().getWidth();
int height = frames.get(0).getImage().getBufferedImage().getHeight();
ListIterator<Pair<Integer, LinkedList<Point2D_F32>>> fgPathItor = foregroundPaths.listIterator();
int cnt = 0;
for (int frameIdx = 0; frameIdx < frames.size(); ++frameIdx) {
if (cnt >= PathList.frameInterval) {
cnt = 0;
continue;
}
cnt += 1;
GrayU8 mask = new GrayU8(width / PathList.samplingInterval, height / PathList.samplingInterval);
while (fgPathItor.hasNext()) {
Pair<Integer, LinkedList<Point2D_F32>> pair = fgPathItor.next();
if (pair.first > frameIdx)
break;
Point2D_F32 p1 = pair.second.getFirst();
int x = (int) (p1.x * width / PathList.samplingInterval);
int y = (int) (p1.y * height / PathList.samplingInterval);
if (mask.isInBounds(x, y)) {
mask.set(x, y, 1);
}
}
//showBineryImage(mask);
masks.add(mask);
}
return masks;
}
public static ArrayList<GrayU8> smoothMasks(ArrayList<GrayU8> input, ArrayList<GrayU8> output,
int spatialRadius, int temporalRadius, double multipyFactor, int threshold){
if(input == null || input.isEmpty()){
return input;
}
if(output == null){
output = createNewMasks(input);
}
if(output.size() != input.size()){
throw new IllegalArgumentException("size of input and output do not match. input: "+input.size()+" output: "+output.size());
}
multiply3D(input, input, multipyFactor);
gaussianFilter3D(input, output, spatialRadius, temporalRadius);
threshold3D(output,output,threshold);
return output;
}
public static ArrayList<GrayU8> gaussianFilter3D(ArrayList<GrayU8> input, ArrayList<GrayU8> output,
int spatialRadius, int temporalRadius) {
ArrayList<GrayU8> spatialResult = createNewMasks(input);
gaussianFilterSpatial(input, spatialResult, spatialRadius);
gaussianFilterTemporal(spatialResult, output, temporalRadius);
return output;
}
public static ArrayList<GrayU8> gaussianFilterSpatial(ArrayList<GrayU8> input, ArrayList<GrayU8> output, int spatialRadius){
for (int i = 0; i < input.size(); ++i){
GBlurImageOps.gaussian(input.get(i), output.get(i), -1, spatialRadius, null);
}
return output;
}
public static ArrayList<GrayU8> gaussianFilterTemporal(ArrayList<GrayU8> input, ArrayList<GrayU8> output, int spatialRadius){
int width = input.get(0).getWidth();
int height = input.get(0).getHeight();
int len = input.size();
Kernel1D_I32 kernel = FactoryKernelGaussian.gaussian(Kernel1D_I32.class,-1,spatialRadius);
int divisor = kernel.computeSum();
int data1D[] = new int[len + 2*kernel.offset];
for (int x = 0; x < width; ++x){
for (int y = 0; y < height; ++y){
for(int i = 0; i < len; ++i){
data1D[i + kernel.offset] = input.get(i).get(x, y);
}
for(int i = 0; i < len; ++i){
int total = 0;
for (int k = 0; k < kernel.width; ++k){
total += (data1D[i+k] & 0xFF) * kernel.data[k];
}
output.get(i).set(x, y, total/divisor);
}
}
}
return output;
}
public static ArrayList<GrayU8> multiply3D(ArrayList<GrayU8> input, ArrayList<GrayU8> output, double value){
for (int i = 0; i < input.size(); ++i){
PixelMath.multiply(input.get(i), value, output.get(i));
}
return output;
}
public static ArrayList<GrayU8> threshold3D(ArrayList<GrayU8> input, ArrayList<GrayU8> output, int threshold){
for (int i = 0; i < input.size(); ++i){
ThresholdImageOps.threshold(input.get(i), output.get(i), threshold, false);
}
return output;
}
public static ArrayList<GrayU8> createNewMasks(ArrayList<GrayU8> input){
ArrayList<GrayU8> output = new ArrayList<GrayU8>();
for (int i = 0; i < input.size(); ++i){
output.add(input.get(i).createSameShape());
}
return output;
}
public static ArrayList<GrayU8> scaleUpMasks(ArrayList<GrayU8> input, int width, int height){
ArrayList<GrayU8> output = new ArrayList<GrayU8>();
for (int i = 0; i < input.size(); ++i){
GrayU8 in = input.get(i);
GrayU8 out = new GrayU8(width, height);
new FDistort(in, out).scaleExt().apply();
output.add(out);
}
return output;
}
public static void showBineryImage(GrayU8 image){
PixelMath.multiply(image,255,image);
BufferedImage out = ConvertBufferedImage.convertTo(image,null);
ShowImages.showWindow(out,"Output");
}
}
|
package de.zalando.aruha.nakadi.domain;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.zalando.aruha.nakadi.config.JsonConfig;
import org.junit.Test;
import static de.zalando.aruha.nakadi.utils.TestUtils.resourceAsString;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
public class EventTypeTest {
private final ObjectMapper objectMapper;
public EventTypeTest() {
objectMapper = new JsonConfig().jacksonObjectMapper();
}
@Test
public void canDeserializeWithoutOrderingKeyFields() throws Exception {
final String json = resourceAsString("event-type.without.ordering-key-fields.json", this.getClass());
final EventType eventType = objectMapper.readValue(json, EventType.class);
assertThat(eventType, notNullValue());
}
@Test
public void canDeserializeWithOrderingKeyFields() throws Exception {
final String json = resourceAsString("event-type.with.ordering-key-fields.json", this.getClass());
final EventType eventType = objectMapper.readValue(json, EventType.class);
assertThat(eventType, notNullValue());
}
}
|
package controls.sunburst;
import javafx.geometry.Pos;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.List;
public class SunburstLegend extends VBox {
private SunburstView<?> sunburstView;
private List<LegendItem> legendItems = new ArrayList<>();
private int legendItemMax = 20;
public SunburstLegend(SunburstView sunburstView) {
this.sunburstView = sunburstView;
this.setAlignment(Pos.CENTER);
sunburstView.selectedItemProperty().addListener(x -> updateLegend());
sunburstView.rootItemProperty().addListener(x -> updateLegend());
sunburstView.legendVisibility().addListener(x -> updateLegend());
}
public int getLegendItemMax() {
return legendItemMax;
}
public void setLegendItemMax(int legendItemMax) {
this.legendItemMax = legendItemMax;
}
/**
* Clears the content of the legend.
*/
public void clearLegend() {
this.getChildren().clear();
}
/**
* Updates the legend by setting the color and text values of the inner most units.
* There will be generated as many LegendItems as needed.
* This method is called by the updateSelectedItem method.
*/
private void updateLegend() {
if (!sunburstView.getLegendVisibility()) {
clearLegend();
} else {
clearLegend();
WeightedTreeItem<?> currentRoot = sunburstView.getSelectedItem();
int count = 0;
for (WeightedTreeItem innerChild : currentRoot.getChildrenWeighted()) {
if (count < legendItemMax) {
String value = (String) innerChild.getValue();
Color color = sunburstView.getItemColor(innerChild);
System.out.println(color);
if (count < legendItems.size()) {
LegendItem item = legendItems.get(count);
item.setLabelText(value);
item.setRectColor(color);
this.getChildren().add(item);
} else {
LegendItem item = new LegendItem(color, value);
legendItems.add(item);
this.getChildren().add(item);
}
count++;
}
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.labyrinth;
import com.kitfox.svg.*;
import com.kitfox.svg.SVGUniverse;
import java.awt.Shape;
import java.awt.geom.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.media.opengl.*;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.glu.GLUquadric;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import net.sf.jaer.Description;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.*;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.Matrix;
/**
* Loads SVG file describing a board and displays it in the annotate method.
*
* @author Tobi
*/
@Description("Handles SVG maps of Labyrinth game")
public class LabyrinthMap extends EventFilter2D implements FrameAnnotater, Observer {
// svg stuff
public static final String DEFAULT_MAP = "labyrinth-hardest.svg"; // in source tree
ArrayList<Ellipse2D.Float> holesSVG = new ArrayList();
ArrayList<Line2D.Float> linesSVG = new ArrayList();
ArrayList<ArrayList<Point2D.Float>> pathsSVG = new ArrayList();
ArrayList<Point2D.Float> ballPathSVG = new ArrayList();
Rectangle2D.Float outlineSVG = null;
Rectangle2D boundsSVG = null;
// chip space stuff, in retina coordinates
private LinkedList<PathPoint> ballPath = new LinkedList();
private ArrayList<Point2D.Float> holes = new ArrayList();
private ArrayList<Float> holeRadii = new ArrayList();
private ArrayList<ArrayList<Point2D.Float>> walls = new ArrayList();
private ArrayList<Point2D.Float> outline = new ArrayList();
private ClosestPointLookupTable closestPointComputer = new ClosestPointLookupTable();
private Rectangle2D.Float boundingBox=new Rectangle2D.Float();
/**
* @return the boundingBox
*/
public Rectangle2D.Float getBoundingBox() {
return boundingBox;
}
enum TrackPointType {
Normal, Start, End
};
public class PathPoint extends Point2D.Float {
public int index = -1;
public TrackPointType type = TrackPointType.Normal;
public float fractionToNext=0;
public PathPoint(float x, float y, int index) {
super(x, y);
this.index = index;
}
public PathPoint(Point2D.Float p, int index) {
this(p.x, p.y, index);
}
public PathPoint next() {
if (index == getNumPathVertices() - 1) {
return loopEnabled ? ballPath.getFirst() : ballPath.getLast();
} else {
return ballPath.get(index + 1);
}
}
/** Computes a new Point2D some fraction of the way to the next point
*
* @param fraction 0 to give this point, 1 to give next point
* @return new point in between.
*/
public Point2D.Float getPointFractionToNext(float fraction){
PathPoint next=next();
float b=1-fraction;
Point2D.Float ret=new Point2D.Float(b*x+fraction*next.x,b*y+fraction*next.y);
return ret;
}
@Override
public String toString() {
return super.toString() + " index=" + index + " type=" + type.toString();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PathPoint) {
PathPoint p2d = (PathPoint) obj;
return p2d.index == this.index;
}
return super.equals(obj);
}
}
// properties
private boolean displayMap = getBoolean("displayMap", true);
private float rotationDegCCW = getFloat("rotationDegCCW", 0);
private float scale = getFloat("scale", 1);
private float transXPixels = getFloat("transXPixels", 0);
private float transYPixels = getFloat("transYPixels", 0);
private boolean loopEnabled = getBoolean("loopEnabled", true);
private boolean recomputeDisplayList = true; // to flag annotation to recompute its display list
public LabyrinthMap(AEChip chip) {
super(chip);
setPropertyTooltip("loadMap", "opens file dialog to select SVG file of map");
setPropertyTooltip("clearMap", "clears map data");
File f = getLastFilePrefs();
try {
loadMapFromFile(f);
} catch (Exception ex) {
log.warning("couldn't load map information from file " + f + ", caught " + ex + "; you are missing the SVG file describing the Labyrinth maze or it is corrupted");
}
setPropertyTooltip("displayMap", "Enables map display"); // TODO
setPropertyTooltip("rotationDegCCW", "rotates the map CCW in degrees");
setPropertyTooltip("scale", "scales the map");
setPropertyTooltip("transXPixels", "translates the map; positive to move it up");
setPropertyTooltip("transYPixels", "translates the map; positive to move to right");
setPropertyTooltip("loopEnabled", "loops path instead of just finishing");
chip.addObserver(this);// to get informed about changes to chip size
}
@Override
public EventPacket<?> filterPacket(EventPacket<?> in) {
return in;
}
@Override
synchronized public void resetFilter() {
invalidateDisplayList();
}
@Override
public void initFilter() {
}
private void addGeneralPath(GeneralPath path) {
PathIterator itr = path.getPathIterator(null, 0.1);
ArrayList<Point2D.Float> pathList = new ArrayList();
Point2D.Float pathStart = null, lastPoint = null;
boolean closed = false;
while (!itr.isDone()) {
float[] coords = new float[6];
int segtype = itr.currentSegment(coords);
switch (segtype) {
case PathIterator.SEG_MOVETO:
pathStart = new Point2D.Float(coords[0], coords[1]); // save start point
case PathIterator.SEG_LINETO:
case PathIterator.SEG_QUADTO:
case PathIterator.SEG_CUBICTO:
pathList.add((lastPoint = new Point2D.Float(coords[0], coords[1]))); // TODO store quads/cubes as well as linesSVG
break;
case PathIterator.SEG_CLOSE:
closed = true;
// if (pathStart != null) {
// pathList.add(pathStart);
break;
default:
log.info("found other element " + segtype);
}
itr.next();
}
if (closed && lastPoint != null) {
pathList.remove(lastPoint);
}
if (pathList.size() > longestPath) {
ballPathSVG = pathList;
longestPath = ballPathSVG.size();
}
pathsSVG.add(pathList);
}
// transforms all coordinates from SVG to retina space. Doesnt' change base SVG data.
synchronized private void computeTransformsToRetinaCoordinates() {
if (boundsSVG == null) {
log.warning("can't compute transforms - no SVG map data");
return;
}
float s = getScale() * (float) (chip.getSizeX() / boundsSVG.getWidth()); // we'll scale up to pixels, and flip y while we're at it since drawing starts in UL
float tx = -(float) boundsSVG.getMinX(), ty = -(float) boundsSVG.getMaxY(); // this is LL corner of bounding box in Java2d space
float cos = (float) Math.cos(getRotationDegCCW() * Math.PI / 180);
float sin = (float) Math.sin(getRotationDegCCW() * Math.PI / 180);
float[][] trm1 = {
{1, 0, tx},
{0, 1, ty},
{0, 0, 1}
};
// affine transform from SVG coords to pixel coords
float[][] scm = {
{s, 0, 0},
{0, -s, 0},
{0, 0, 1}
};
// now transform according to desired rotation and translation
float[][] rotm = {
{cos, -sin, 0},
{sin, cos, 0},
{0, 0, 1}
};
float[][] trm2 = {
{1, 0, getTransXPixels()},
{0, 1, getTransYPixels()},
{0, 0, 1}
};
// now compute t*r*x so that we first transform to pixel space, then rotate, then translate
float[][] m1 = Matrix.multMatrix(scm, trm1);
float[][] m2 = Matrix.multMatrix(rotm, m1);
float[][] tsrt = Matrix.multMatrix(trm2, m2);
// now transform all Point2D coordinates
if (ballPathSVG != null) {
ballPath.clear();
int idx = 0;
for (Point2D.Float v : ballPathSVG) {
PathPoint p = new PathPoint(transform(tsrt, v), idx);
if (idx == 0) {
p.type = TrackPointType.Start;
} else if (idx == ballPathSVG.size() - 1) {
p.type = TrackPointType.End;
} else {
p.type = TrackPointType.Normal;
}
ballPath.add(p);
idx++;
}
}
holes.clear();
holeRadii.clear();
for (Ellipse2D.Float e : holesSVG) {
Point2D.Float center = new Point2D.Float(e.x + e.width / 2, e.y + e.height / 2);
holes.add(transform(tsrt, center));
holeRadii.add(e.height * s / 2);
}
walls.clear();
for (ArrayList<Point2D.Float> path : pathsSVG) {
if (path == ballPathSVG) {
continue;
}
ArrayList<Point2D.Float> wall = new ArrayList();
for (Point2D.Float v : path) {
wall.add(transform(tsrt, v));
}
walls.add(wall);
}
// outline
outline.clear();
Point2D.Float p1 = transform(tsrt, new Point2D.Float((float) outlineSVG.getMinX(), (float) outlineSVG.getMinY()));
Point2D.Float p2 = transform(tsrt, new Point2D.Float((float) outlineSVG.getMaxX(), (float) outlineSVG.getMaxY()));
outline.add(transform(tsrt, outlineSVG.x, outlineSVG.y));
outline.add(transform(tsrt, outlineSVG.x + outlineSVG.width, outlineSVG.y));
outline.add(transform(tsrt, outlineSVG.x + outlineSVG.width, outlineSVG.y + outlineSVG.height));
outline.add(transform(tsrt, outlineSVG.x, outlineSVG.y + outlineSVG.height));
outline.add(transform(tsrt, outlineSVG.x, outlineSVG.y));
float minx=Float.POSITIVE_INFINITY, miny=Float.POSITIVE_INFINITY, maxx=Float.NEGATIVE_INFINITY, maxy=Float.NEGATIVE_INFINITY;
for(Point2D.Float p:outline){
if(p.x>maxx) maxx=p.x; else if(p.x<minx) minx=p.x;
if(p.y>maxy) maxy=p.y; else if(p.y<miny) miny=p.y;
}
getBoundingBox().setFrame(minx, miny, maxx-minx, maxy-miny);
invalidateDisplayList();
closestPointComputer.init();
}
private Point2D.Float transform(float[][] m, Point2D.Float p) {
float[] v = {p.x, p.y, 1};
float[] pt = Matrix.multMatrix(m, v);
return new Point2D.Float(pt[0], pt[1]);
}
private Point2D.Float transform(float[][] m, float x, float y) {
float[] v = {x, y, 1};
float[] pt = Matrix.multMatrix(m, v);
return new Point2D.Float(pt[0], pt[1]);
}
public void doLoadMap() {
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(getLastFilePrefs()); // defaults to startup runtime folder
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory()
|| f.getName().toLowerCase().endsWith(".svg");
}
@Override
public String getDescription() {
return "SVG files (scalable vector graphics)";
}
});
final int[] state = new int[1];
state[0] = Integer.MIN_VALUE;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setSelectedFile(new File(getString("lastFile", System.getProperty("user.dir"))));
state[0] = fc.showOpenDialog(chip.getAeViewer() != null && chip.getAeViewer().getFilterFrame() != null ? chip.getAeViewer().getFilterFrame() : null);
if (state[0] == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
putLastFilePrefs(file);
try {
loadMapFromFile(file);
} catch (Exception e) {
log.warning(e.toString());
JOptionPane.showMessageDialog(fc, "Couldn't load map from file " + file + ", caught exception " + e, "Map file error", JOptionPane.WARNING_MESSAGE);
}
} else {
log.info("Cancelled saving!");
}
}
});
}
synchronized public void doClearMap() {
// use to clear any map for pure mouse control on a blank area
holesSVG.clear();
pathsSVG.clear();
ballPathSVG.clear();
ballPath.clear();
walls.clear();
outline.clear();
holes.clear();
holeRadii.clear();
closestPointComputer.init();
longestPath = Integer.MIN_VALUE;
invalidateDisplayList();
}
synchronized private void loadMapFromFile(File file) throws MalformedURLException {
log.info("loading map file " + file);
doClearMap();
SVGUniverse svgUniverse = new SVGUniverse();
SVGDiagram svgDiagram = null;
svgUniverse.setVerbose(true);
URI svgURI = svgUniverse.loadSVG(file.toURI().toURL());
svgDiagram = svgUniverse.getDiagram(svgURI);
SVGRoot root = svgDiagram.getRoot();
loadChildren(root.getChildren(null));
String s = String.format("map has %d holes, %d lines, %d paths, ball path has %d vertices", holesSVG.size(), linesSVG.size(), pathsSVG.size(), ballPathSVG != null ? ballPathSVG.size() : 0);
log.info(s);
computeTransformsToRetinaCoordinates();
}
int longestPath = Integer.MIN_VALUE;
private void loadChildren(List children) {
StringBuilder sb = new StringBuilder("Shapes found:");
for (Object o : children) {
if (o instanceof Circle) {
Circle c = (Circle) o;
holesSVG.add((Ellipse2D.Float) c.getShape());
sb.append("\n Circle ").append(c);
} else if (o instanceof Line) {
Line l = (Line) o;
ArrayList<Point2D.Float> pathList = new ArrayList();
Line2D.Float line = (Line2D.Float) l.getShape();
pathList.add(new Point2D.Float(line.x1, line.y1));
pathList.add(new Point2D.Float(line.x2, line.y2));
pathsSVG.add(pathList);
sb.append("\n Line ").append(l);
} else if (o instanceof Polyline) {
Polyline l = (Polyline) o;
Shape s = l.getShape();
if (s instanceof GeneralPath) {
GeneralPath path = (GeneralPath) s;
addGeneralPath(path);
}
sb.append("\n PolyLine ").append(l);
} else if (o instanceof Rect) { // assumes only 1 rect which is outline of map
Rect r = (Rect) o;
outlineSVG = (Rectangle2D.Float) r.getShape(); // this returned rect has x,y relative to UL of viewBox in SVG increasing down and to right (in Java2D coordinates)
boundsSVG = outlineSVG.getBounds2D();
sb.append("\n Rect ").append(r);
} else if (o instanceof Path) {
// only the actual path of the ball should be a path, it should be a connected path
Path r = (Path) o;
GeneralPath path = (GeneralPath) r.getShape();
addGeneralPath(path);
sb.append("\n Path ").append(r);
} else if (o instanceof Polygon) {
// only the actual path of the ball should be a path, it should be a connected path
Polygon r = (Polygon) o;
GeneralPath path = (GeneralPath) r.getShape();
addGeneralPath(path);
sb.append("\n Polygon ").append(r);
} else if (o instanceof List) {
sb.append("\n List ").append(o);
loadChildren((List) o);
} else if (o instanceof Group) {
Group g = (Group) o;
sb.append("\n Group ").append(g);
List l = g.getChildren(null);
loadChildren(l);
}
}
log.info(sb.toString());
}
private File getLastFilePrefs() {
String pack = this.getClass().getPackage().getName();
String path = "src" + File.separator + pack.replace(".", File.separator) + File.separator + DEFAULT_MAP;
return new File(getString("lastFile", path));
}
private void putLastFilePrefs(File file) {
putString("lastFile", file.toString());
}
private GLU glu = new GLU();
private GLUquadric holeQuad = glu.gluNewQuadric();
int listnum = 0;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
if (!isDisplayMap()) {
return;
}
GL gl = drawable.getGL();
if (recomputeDisplayList) {
if (listnum > 0) {
gl.glDeleteLists(listnum, 1);
}
listnum = gl.glGenLists(1);
if (listnum == 0) {
log.warning("cannot create display list to show the map, glGenLists returned 0");
return;
}
gl.glNewList(listnum, GL.GL_COMPILE_AND_EXECUTE);
{
gl.glColor4f(0, 0, .2f, 0.3f);
gl.glLineWidth(1);
{
// draw outline
gl.glBegin(GL.GL_LINE_STRIP);
for (Point2D.Float p : outline) {
gl.glVertex2f(p.x, p.y);
}
gl.glEnd();
// draw maze walls
for (ArrayList<Point2D.Float> p : walls) {
gl.glBegin(GL.GL_LINE_STRIP);
for (Point2D.Float v : p) {
gl.glVertex2f(v.x, v.y);
}
gl.glEnd();
}
}
// draw holes
{
glu.gluQuadricDrawStyle(holeQuad, GLU.GLU_LINE);
gl.glColor4f(.1f, .1f, .1f, .3f);
Iterator<Float> it = holeRadii.iterator();
for (Point2D.Float e : holes) { // ellipse has UL corner as x,y location (here LL corner)
gl.glPushMatrix();
gl.glTranslatef(e.x, e.y, 0);
glu.gluDisk(holeQuad, 0, it.next(), 16, 1);
gl.glPopMatrix();
}
}
// draw path
{
// render ball path using retina coordinates
gl.glColor4f(.1f, .4f, .1f, .3f);
gl.glLineWidth(3);
gl.glBegin(GL.GL_LINE_STRIP);
for (Point2D.Float l : ballPath) {
gl.glVertex2f(l.x, l.y);
}
gl.glEnd();
gl.glPointSize(9);
gl.glBegin(GL.GL_POINTS);
for (Point2D.Float l : ballPath) {
gl.glVertex2f(l.x, l.y);
}
gl.glEnd();
}
}
gl.glEndList();
chip.getCanvas().checkGLError(gl, glu, "after making list for map");
recomputeDisplayList = false;
} else {
gl.glCallList(listnum);
}
}
@Override
public void update(Observable o, Object arg) {
if (o instanceof AEChip) {
if (arg instanceof String) {
String s = (String) arg;
if (s.equals(AEChip.EVENT_SIZEY) || s.equals(AEChip.EVENT_SIZEX)) {
if (chip.getNumPixels() > 0) {
computeTransformsToRetinaCoordinates(); // can only compute transform once the chip sizes are set
}
}
}
}
}
/**
* @return the displayMap
*/
public boolean isDisplayMap() {
return displayMap;
}
/**
* @param displayMap the displayMap to set
*/
synchronized public void setDisplayMap(boolean displayMap) {
this.displayMap = displayMap;
putBoolean("displayMap", displayMap);
}
/**
* @return the rotationDegCCW
*/
public float getRotationDegCCW() {
return rotationDegCCW;
}
/**
* @param rotationDegCCW the rotationDegCCW to set
*/
synchronized public void setRotationDegCCW(float rotationDegCCW) {
this.rotationDegCCW = rotationDegCCW;
putFloat("rotationDegCCW", rotationDegCCW);
computeTransformsToRetinaCoordinates();
}
/**
* @return the scale
*/
public float getScale() {
return scale;
}
/**
* @param scale the scale to set
*/
synchronized public void setScale(float scale) {
this.scale = scale;
putFloat("scale", scale);
computeTransformsToRetinaCoordinates();
}
/**
* @return the transXPixels
*/
public float getTransXPixels() {
return transXPixels;
}
/**
* @param transXPixels the transXPixels to set
*/
synchronized public void setTransXPixels(float transXPixels) {
this.transXPixels = transXPixels;
putFloat("transXPixels", transXPixels);
computeTransformsToRetinaCoordinates();
}
/**
* @return the transYPixels
*/
public float getTransYPixels() {
return transYPixels;
}
/**
* @param transYPixels the transYPixels to set
*/
synchronized public void setTransYPixels(float transYPixels) {
this.transYPixels = transYPixels;
putFloat("transYPixels", transYPixels);
computeTransformsToRetinaCoordinates();
}
private void invalidateDisplayList() {
recomputeDisplayList = true;
}
/** Computes nearest path point using lookup from table */
class ClosestPointLookupTable {
private int size = 64;
private int[] map = new int[size * size];
int sx, sy;
float xPixPerUnit, yPixPerUnit = 1;
Rectangle2D.Float bounds = new Rectangle2D.Float(); // overall bounds of entire labyrinth map
private boolean displayClosestPointMap = false;
public ClosestPointLookupTable() {
init();
}
final void init() {
// if(ballPath==null || ballPath.isEmpty())
computeBounds();
xPixPerUnit = (float) bounds.getWidth() / size;
yPixPerUnit = (float) bounds.getHeight() / size;
Arrays.fill(map, -1);
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
// for each grid entry, locate point at center of grid point, then find nearest path vertex and put in map
Point2D.Float pos = new Point2D.Float(x * xPixPerUnit + xPixPerUnit / 2 + (float) bounds.getX(), y * yPixPerUnit + yPixPerUnit / 2 + (float) bounds.getY());
int idx = findClosestIndex(pos, Float.POSITIVE_INFINITY, false); // TODO make tolerance larger
setMapEntry(idx, x, y);
}
}
// if (displayClosestPointMap) {
// if (closestPointFrame == null) {
// closestPointFrame = new JFrame("Closest Point Map");
// closestPointFrame.setPreferredSize(new Dimension(200, 200));
// closestPointImage = ImageDisplay.createOpenGLCanvas();
// closestPointImage.setFontSize(10);
// closestPointImage.setSize(size, size);
// closestPointImage.setxLabel("x");
// closestPointImage.setyLabel("y");
// closestPointImage.addGLEventListener(new GLEventListener() {
// @Override
// public void init(GLAutoDrawable drawable) {
// @Override
// public void display(GLAutoDrawable drawable) {
// closestPointImage.checkPixmapAllocation();
// for (int x = 0; x < size; x++) {
// for (int y = 0; y < size; y++) {
// int point = getMapEntry(x, y);
// if (point == -1) {
// closestPointImage.setPixmapGray(x, y, 0);
// } else {
// Color c = Color.getHSBColor((float) point / getNumPoints(), .5f, .5f);
// float[] rgb = c.getColorComponents(null);
// closestPointImage.setPixmapRGB(x, y, rgb);
// closestPointImage.drawCenteredString(x, y, Integer.toString(point));
//// GL gl=drawable.getGL();
//// gl.glPushMatrix();
//// gl.glLineWidth(.5f);
//// gl.glColor3f(0,0,1);
//// gl.glBegin(GL.GL_LINE_LOOP);
//// for(Point2D.Float p:trackPoints){
//// gl.glVertex2f(p.x, p.y);
//// gl.glEnd();
//// gl.glBegin
//// gl.glPopMatrix(); // TODO needs coordinate transform to ImageDisplay pixels to draw track
// @Override
// public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
// @Override
// public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
// closestPointFrame.getContentPane().add(closestPointImage, BorderLayout.CENTER);
// closestPointFrame.setVisible(true);
// closestPointImage.repaint();
}
int getMapEntry(int x, int y) {
final int idx = x + size * y;
if (idx < 0 || idx >= map.length) {
return -1;
}
return map[idx];
}
void setMapEntry(int val, int x, int y) {
final int idx = x + size * y;
if (idx < 0 || idx > map.length) {
return;
}
map[x + size * y] = val;
}
int findPoint(Point2D.Float pos) {
int x = (int) (size * (pos.x - bounds.getX() /*- xPixPerUnit / 2*/) / bounds.getWidth());
int y = (int) (size * (pos.y - bounds.getY() /*- yPixPerUnit / 2*/) / bounds.getHeight());
return getMapEntry(x, y);
}
int findPoint(double x, double y) {
int xx = (int) (size * (x - bounds.getX() /*- xPixPerUnit / 2*/) / bounds.getWidth());
int yy = (int) (size * (y - bounds.getY() /*- yPixPerUnit / 2*/) / bounds.getHeight());
return getMapEntry(xx, yy);
}
private void computeBounds() {
// bounds are computed from outline polygon
final float extraFraction = .25f;
if (outline == null) {
log.warning("no outline, can't compute bounds of ClosestPointLookupTable");
return;
}
float minx = Float.MAX_VALUE, miny = Float.MAX_VALUE, maxx = Float.MIN_VALUE, maxy = Float.MIN_VALUE;
for (Point2D.Float p : outline) {
if (p.x < minx) {
minx = p.x;
}
if (p.y < miny) {
miny = p.y;
}
if (p.x > maxx) {
maxx = p.x;
}
if (p.y > maxy) {
maxy = p.y;
}
}
final float w = maxx - minx, h = maxy - miny;
bounds.setRect(minx - w * extraFraction, miny - h * extraFraction, w * (1 + 2 * extraFraction), h * (1 + 2 * extraFraction));
}
/**
* @return the displayClosestPointMap
*/
public boolean isDisplayClosestPointMap() {
return displayClosestPointMap;
}
/**
* @param displayClosestPointMap the displayClosestPointMap to set
*/
public void setDisplayClosestPointMap(boolean displayClosestPointMap) {
this.displayClosestPointMap = displayClosestPointMap;
}
}
private int lastFindIdx = -1;
/** Find the closest point on the path with option for local minimum distance or global minimum distance search.
* @param pos Point in x,y Cartesian space for which to search closest path point.
* @param maxDist the maximum allowed distance.
* @param fastLocalSearchEnabled if true, the search uses the ClosestPointLookupTable lookup and maxDist is ignored.
* @return Index of closest point on path or -1 if no path point is <= maxDist from pos or is not found in the ClosestPointLookupTable.
*/
synchronized public int findClosestIndex(Point2D pos, float maxDist, boolean fastLocalSearchEnabled) {
if (pos == null) {
return -1;
}
int n = ballPath.size();
if (n == 0) {
return -1;
}
if (fastLocalSearchEnabled) {
lastFindIdx = closestPointComputer.findPoint(pos.getX(), pos.getY());
return lastFindIdx;
} else {
int idx = 0, closestIdx = -1;
float closestDist = Float.MAX_VALUE;
for (Point2D.Float p : ballPath) {
float d = (float) p.distance(pos);
if (d <= maxDist) {
if (d < closestDist) {
closestDist = d;
closestIdx = idx;
}
}
idx++;
}
return closestIdx;
}
}
// public Point2D.Float find
/** returns the path index, or -1 if there is no ball or is too far away from the path.
*
* @return
*/
public int findNearestPathIndex(Point2D point) {
return findClosestIndex(point, 15, true);
}
public int getNumPathVertices() {
return getBallPath().size();
}
public PathPoint findNearestPathPoint(Point2D point) {
if (point == null) {
return null;
}
int ind = findNearestPathIndex(point);
if (ind == -1) {
return null;
}
return getBallPath().get(ind);
}
public PathPoint findNextPathPoint(Point2D point) {
if (point == null) {
return null;
}
int ind = findNearestPathIndex(point);
if (ind == -1) {
return null;
}
if (!isLoopEnabled()) {
if (ind == getNumPathVertices() - 1) {
return getBallPath().get(ind);
}
} else {
if (ind == getNumPathVertices() - 1) {
return getBallPath().get(0);
}
}
return getBallPath().get(ind + 1);
}
/**
* @return the ballPath, a list of Point2D starting at the start point and ending at the end point.
*/
public LinkedList<PathPoint> getBallPath() {
return ballPath;
}
/**
* @return the holes
*/
public ArrayList<Point2D.Float> getHoles() {
return holes;
}
/**
* @return the holeRadii for the holes
*/
public ArrayList<Float> getHoleRadii() {
return holeRadii;
}
/**
* @return the walls
*/
public ArrayList<ArrayList<Point2D.Float>> getWalls() {
return walls;
}
/**
* @return the outline of the entire map.
*/
public ArrayList<Point2D.Float> getOutline() {
return outline;
}
/**
* @return the loopEnabled
*/
public boolean isLoopEnabled() {
return loopEnabled;
}
/**
* @param loopEnabled the loopEnabled to set
*/
public void setLoopEnabled(boolean loopEnabled) {
this.loopEnabled = loopEnabled;
putBoolean("loopEnabled", loopEnabled);
}
}
|
package cli;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import persistance.dao.DaoCompany;
import persistance.dao.DaoComputer;
import model.Company;
import model.Computer;
import model.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import services.CompanyService;
import services.ComputerService;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
import java.util.Scanner;
public class Cli {
private static DaoComputer daoC;
private static DaoCompany daoComp;
private static Logger logger = LoggerFactory.getLogger("dao.Cli");
private static Boolean running = true;
private static ComputerService compService;
private static CompanyService companyService;
private static Scanner scanner = new Scanner(System.in);
private static Page<Computer> pageComputer = new Page<Computer>(20, 0);
private static Page<Company> pageCompany = new Page<Company>(20, 0);
private static final String APIURL = "http://localhost:8080/api";
private static final Client CLIENT = ClientBuilder.newClient();
private static final String USERNAME = "test";
private static final String PASSWORD = "test";
private static final String AUTHSTRING = USERNAME + ":" + PASSWORD;
private static final String AUTHHEADER = "Authorization";
private static final String AUTHHEADERVAL = "Basic " + java.util.Base64.getEncoder().encodeToString(AUTHSTRING.getBytes());
/**
* main of Cli.
*
* @param args arguments
*/
public static void main(String[] args) {
Computer c = CLIENT
.target(APIURL)
.path("computer/{id}")
.resolveTemplate("id", 1)
.request(MediaType.APPLICATION_JSON).header(AUTHHEADER, AUTHHEADERVAL) // The basic authentication header goes here
.get(Computer.class);
System.out.println(c);
System.out.println("Welcome to ComputerDataBase CLI");
logger.debug("CLI start");
while (running) {
String command = waitCommand();
System.out.println(execCommand(command));
}
}
/**
* display available commands & wait input.
*
* @return user input command
*/
public static String waitCommand() {
System.out.println("Available commands (not case sensitive) : getComputerbyId, getAllComputer, getAllCompany, createComputer, getallcomputerp, deleteCompany, quit");
System.out.println("Enter your command : ");
String command = scanner.nextLine();
return command;
}
/**
* get input.
*
* @return input
*/
public static String getInput() {
String input = scanner.nextLine();
return input;
}
/**
* convert input to Long.
*
* @param input input
* @return Long input
*/
public static Long getLongInput(String input) {
long longInput = -1;
try {
longInput = Long.parseLong(input);
} catch (NumberFormatException ex) {
System.out.println("Wrong input, please enter a positive integrer number");
}
if (longInput < 0) {
longInput = getLongInput(getInput());
}
return longInput;
}
/**
* controller switch to execute commands.
*
* @param command command
* @return result of command
*/
public static String execCommand(String command) {
command = command.toLowerCase();
String result = "";
String[] splited = new String[0];
if (command.contains(" ")) {
splited = command.split("\\s+");
command = splited[0];
}
switch (command) {
case "getallcomputer":
if (splited.length > 1) {
result = displayAllComputers(splited[1], splited[2]);
} else {
result = displayAllComputers("1", "1000");
}
break;
case "getallcompany":
if (splited.length > 1) {
result = displayAllCompanies(splited[1], splited[2]);
} else {
result = displayAllCompanies("1", "1000");
}
break;
case "getcomputerbyid":
if (splited.length > 0) {
result = displayComputerbyId(getLongInput(splited[1]));
} else {
System.out.println("Enter the computer ID to retrieve");
Long id = getLongInput(getInput());
result = displayComputerbyId(id);
}
break;
case "createcomputer":
if (splited.length > 0) {
result = createComputer(createComputerObjectfromArray(splited));
} else {
System.out.println("Enter the computer to create under format : 'companyId name intro disco' the intro and disco dates can be 0");
result = createComputer(createComputerObject(getInput()));
}
break;
case "getallcomputerp":
if (splited.length > 2) {
result = displayAllComputerPaged(splited[1], splited[2]);
} else if (splited.length == 2) {
result = displayAllComputerPaged(splited[1], "20");
} else {
result = displayAllComputerPaged("0", "20");
}
break;
case "deletecompany":
if (splited.length > 0) {
result = deleteCompany(getLongInput(splited[1]));
} else {
System.out.println("Enter the company ID to delete");
Long id = getLongInput(getInput());
result = deleteCompany(id);
}
break;
case "quit":
running = false;
break;
default:
result = "Invalid Command";
break;
}
return result;
}
/**
* display all companies.
*
* @param start starting index
* @param end nb of entries
* @return command status
*/
public static String displayAllCompanies(String start, String end) {
System.out.println("Displaying all companies stored in DB : ");
try {
ArrayList<Company> cList = companyService.getAll(Long.parseLong(start), Long.parseLong(end));
for (Company c : cList) {
System.out.println(c.toString());
}
} catch (Exception ex) {
return "Command error " + ex.getMessage();
}
return "Command success";
}
/**
* display computer with pagination.
*
* @param pageN page number
* @param nb entries per page
* @return command success status string
*/
public static String displayAllComputerPaged(String pageN, String nb) {
System.out.println("Displaying all computers stored in DB : ");
try {
/*pageComputer.setNbEntries(Integer.parseInt(nb));
pageComputer.setCurrentPage(Integer.parseInt(pageN));
compService.getPaginated(pageComputer);*/
Response response = CLIENT
.target(APIURL)
.path("computer/list")
.queryParam("pageN", pageN)
.queryParam("perPage", nb)
.request(MediaType.APPLICATION_JSON).header(AUTHHEADER, AUTHHEADERVAL) // The basic authentication header goes here
.get();
String json = response.readEntity(String.class);
response.close();
byte[] jsonData = json.getBytes();
ObjectMapper objectMapper = new ObjectMapper();
//read JSON like DOM Parser
// read/print as json because difficulties both for page generic, and for computer dates
JsonNode rootNode = objectMapper.readTree(jsonData);
JsonNode listNode = rootNode.path("list");
Iterator<JsonNode> elements = listNode.elements();
while (elements.hasNext()) {
System.out.println(elements.next().toString());
//Computer c = objectMapper.readValue(elements.next().toString(), Computer.class);
//System.out.println(c.toString());
}
} catch (Exception ex) {
return "Command error " + ex.getMessage();
}
return "Command success";
}
/**
* display all computer.
*
* @param start offset
* @param end nb to return
* @return command success status string
*/
public static String displayAllComputers(String start, String end) {
System.out.println("Displaying all computers stored in DB : ");
try {
ArrayList<Computer> cList = compService.getAll(Long.parseLong(start), Long.parseLong(end));
for (Computer c : cList) {
System.out.println(c.toString());
}
} catch (Exception ex) {
return "Command error " + ex.getMessage();
}
return "Command success";
}
/**
* display computer by id.
*
* @param id id
* @return command success status string
*/
public static String displayComputerbyId(Long id) {
System.out.println("Retrieving computer of ID " + id + ": ");
try {
Computer c = CLIENT
.target(APIURL)
.path("computer/{id}")
.resolveTemplate("id", id)
.request(MediaType.APPLICATION_JSON).header(AUTHHEADER, AUTHHEADERVAL) // The basic authentication header goes here
.get(Computer.class);
//Computer computer = compService.getById(id);
System.out.println(c.toString());
} catch (Exception ex) {
return "Command error " + ex.getMessage();
}
return "Command success";
}
/**
* create a computer obj from input string.
*
* @param input input
* @return computer obj
*/
public static Computer createComputerObject(String input) {
Computer c = null;
String[] splited = new String[0];
if (input.contains(" ")) {
splited = input.split("\\s+");
}
if (splited.length == 0 || splited.length > 5) {
System.out.println("Wrong arg number");
return c;
}
c = createComputerObjectfromArray(splited);
return c;
}
/**
* create computer obj for an array of strings.
*
* @param input input
* @return Computer obj
*/
public static Computer createComputerObjectfromArray(String[] input) {
Computer c = null;
int startIndex = 0;
if (input.length > 4) {
startIndex = 1;
}
try {
Long companyId = Long.parseLong(input[startIndex]);
String name = input[startIndex + 1];
LocalDateTime intro = null;
LocalDateTime disco = null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
if (!Objects.equals(input[startIndex + 2], "0")) {
intro = LocalDate.parse(input[startIndex + 2], formatter).atStartOfDay();
}
if (!Objects.equals(input[startIndex + 3], "0")) {
disco = LocalDate.parse(input[startIndex + 3], formatter).atStartOfDay();
}
c = new Computer(companyId, name, intro, disco);
System.out.println(c.toString());
} catch (DateTimeException ex) {
System.out.println("Command error, check dates " + ex.getMessage());
} catch (Exception ex) {
System.out.println("Command error " + ex.getMessage());
}
return c;
}
/**
* create computer in db.
*
* @param c computer obj
* @return command success status string
*/
public static String createComputer(Computer c) {
if (c == null) {
return "Command error : error creating computer object, check args";
}
long generatedKey = 0;
try {
Form form = new Form();
form.param("name", c.getName());
form.param("companyId", c.getCompanyId() != null ? c.getCompanyId().toString() : "");
form.param("introduced", c.getIntroducedTimestamp() != null ? c.getIntroducedTimestamp().toString() : "");
form.param("discontinued", c.getDiscontinuedTimestamp() != null ? c.getDiscontinuedTimestamp().toString() : "");
c = CLIENT
.target(APIURL)
.path("computer/add")
.request(MediaType.APPLICATION_JSON).header(AUTHHEADER, AUTHHEADERVAL) // The basic authentication header goes here
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE),
Computer.class);
generatedKey = c.getId();
System.out.println(c.toString());
} catch (Exception ex) {
return "Command error " + ex.getMessage();
}
return "Command success, generated ID : " + generatedKey;
}
/**
* delete a company and all computers of that company.
* @param id company id to delete
* @return command return status string
*/
public static String deleteCompany(long id) {
int deletedRows = 0;
try {
deletedRows = companyService.delete(id);
} catch (Exception ex) {
return "Command error " + ex.getMessage();
}
return "Command success, deleted rows : " + deletedRows;
}
}
|
package org.smoothbuild.acceptance.lang;
import static com.google.common.truth.Truth.assertThat;
import static org.smoothbuild.testing.BooleanCreators.falseByteString;
import static org.smoothbuild.testing.BooleanCreators.trueByteString;
import static org.smoothbuild.util.Lists.list;
import java.io.IOException;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.smoothbuild.acceptance.AcceptanceTestCase;
public class ArrayTest extends AcceptanceTestCase {
@Nested
class empty_array_of {
@Test
public void blobs() throws Exception {
createUserModule(
" [Blob] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void bools() throws Exception {
createUserModule(
" [Bool] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void nothings() throws Exception {
createUserModule(
" result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void strings() throws Exception {
createUserModule(
" [String] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void files() throws Exception {
createUserModule(
" [File] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Nested
class arrays_of {
@Test
public void nothings() throws Exception {
createUserModule(
" [[Nothing]] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void bools() throws Exception {
createUserModule(
" [[Bool]] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void strings() throws Exception {
createUserModule(
" [[String]] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void blobs() throws Exception {
createUserModule(
" [[Blob]] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void files() throws Exception {
createUserModule(
" [[File]] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
@Test
public void arrays_of_nothings() throws Exception {
createUserModule(
" [[[Nothing]]] result = []; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list());
}
}
}
@Nested
class array_of {
@Test
public void blobs() throws Exception {
createUserModule(
" result = [ toBlob('abc'), toBlob('def') ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list("abc", "def"));
}
@Test
public void bools() throws Exception {
createUserModule(
" result = [ true(), false() ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(artifactAsByteStrings("result"))
.isEqualTo(list(trueByteString(), falseByteString()));
}
@Test
public void strings() throws Exception {
createUserModule(
" result = [ 'abc', 'def' ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list("abc", "def"));
}
@Test
public void files() throws Exception {
createUserModule(
" result = [ file(toBlob('abc'), 'file1.txt'), file(toBlob('def'), 'file2.txt') ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(artifactTreeContentAsStrings("result"))
.containsExactly("file1.txt", "abc", "file2.txt", "def");
}
@Nested
class arrays_of {
@Test
public void nothings_with_one_element() throws Exception {
createUserModule(
" [[Nothing]] result = [ [] ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list(list()));
}
@Test
public void nothings_with_two_elements() throws Exception {
createUserModule(
" [[Nothing]] result = [ [], [] ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list(list(), list()));
}
@Test
public void strings() throws Exception {
createUserModule(
" [[String]] result = [ [], [ 'abc' ], [ 'def', 'ghi' ] ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list(list(), list("abc"), list("def", "ghi")));
}
@Test
public void arrays_of_strings() throws Exception {
createUserModule(
" [[[String]]] result = [ [ [] ], [ [ 'abc' ], [ 'def', 'ghi' ] ] ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list(list(list()), list(list("abc"), list("def", "ghi"))));
}
}
}
@Test
public void empty_array_with_comma_causes_error() throws Exception {
createUserModule(
" result = [,]; ");
runSmoothBuild("result");
assertFinishedWithError();
}
@Test
public void array_with_one_element() throws Exception {
createUserModule(
" result = [ 'abc' ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list("abc"));
}
@Test
public void array_with_trailing_comma() throws Exception {
createUserModule(
" result = [ 'abc', ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list("abc"));
}
@Test
public void array_with_two_trailing_commas_causes_error() throws Exception {
createUserModule(
" result = [ 'abc', , ]; ");
runSmoothBuild("result");
assertFinishedWithError();
}
@Test
public void array_with_leading_comma_causes_error() throws Exception {
createUserModule(
" result = [ , 'abc' ]; ");
runSmoothBuild("result");
assertFinishedWithError();
}
@Test
public void array_with_elements_of_the_same_type() throws Exception {
createUserModule(
" result = [ 'abc', 'def' ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list("abc", "def"));
}
@Test
public void array_with_elements_of_compatible_types() throws Exception {
createUserModule(
" myFile = file(toBlob('abc'), 'file.txt'); ",
" result = [ myFile, toBlob('def') ]; ");
runSmoothBuild("result");
assertFinishedWithSuccess();
assertThat(stringifiedArtifact("result"))
.isEqualTo(list("abc", "def"));
}
@Test
public void array_with_elements_of_incompatible_types() throws Exception {
createUserModule(
" result = [ 'abc', toBlob('abc') ]; ");
runSmoothBuild("result");
assertFinishedWithError();
assertSysOutContainsParseError(1,
"Array cannot contain elements of incompatible types.",
"First element has type 'String' while element at index 1 has type 'Blob'.");
}
@Test
public void first_element_expression_error_doesnt_suppress_second_element_expression_error()
throws IOException {
createUserModule(
" function1 = 'abc'; ",
" result = [ function1(unknown1=''), function1(unknown2='') ]; ");
runSmoothBuild("result");
assertFinishedWithError();
assertSysOutContains("In call to `function1`: Unknown parameter 'unknown1'.");
assertSysOutContains("In call to `function1`: Unknown parameter 'unknown2'.");
}
}
|
package com.namelessmc.NamelessAPI.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.namelessmc.NamelessAPI.NamelessException;
public class NamelessRequestUtil {
/**
* @param url Full URL with / at the end
* @param postString
* @param https
* @return
*/
public static Request sendPostRequest(URL baseUrl, String action, String postString) {
if (baseUrl == null) {
throw new IllegalArgumentException("URL must not be null");
}
if (postString == null) {
postString = "";
}
String baseUrlString = appendCharacter(baseUrl.toString(), '/');
URL url;
try {
url = new URL(baseUrlString + action);
} catch (MalformedURLException e1) {
throw new IllegalArgumentException("URL or action is malformed (" + e1.getMessage() + ")");
}
if(url.toString().startsWith("https")){
return httpsRequest(url, postString);
}else {
return httpRequest(url, postString);
}
}
private static Request httpsRequest(URL url, String postString) {
Exception exception;
JsonObject response;
try {
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", Integer.toString(postString.length()));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
// Initialize output stream
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// Write request
outputStream.writeBytes(postString);
// Initialize input stream
InputStream inputStream = connection.getInputStream();
// Handle response
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseBuilder = new StringBuilder();
String responseString;
while ((responseString = streamReader.readLine()) != null)
responseBuilder.append(responseString);
JsonParser parser = new JsonParser();
response = parser.parse(responseBuilder.toString()).getAsJsonObject();
if (response.has("error")) {
// Error with request
String errorMessage = response.get("message").getAsString();
exception = new NamelessException(errorMessage);
}
// Close output/input stream
outputStream.flush();
outputStream.close();
inputStream.close();
// Disconnect
connection.disconnect();
exception = null;
} catch (Exception e) {
exception = e;
response = null;
}
return new Request(exception, response);
}
private static Request httpRequest(URL url, String postString) {
Exception exception;
JsonObject response;
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", Integer.toString(postString.length()));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
// Initialize output stream
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// Write request
outputStream.writeBytes(postString);
// Initialize input stream
InputStream inputStream = connection.getInputStream();
// Handle response
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseBuilder = new StringBuilder();
String responseString;
while ((responseString = streamReader.readLine()) != null)
responseBuilder.append(responseString);
JsonParser parser = new JsonParser();
response = parser.parse(responseBuilder.toString()).getAsJsonObject();
if (response.has("error")) {
// Error with request
String errorMessage = response.get("message").getAsString();
exception = new NamelessException(errorMessage);
}
// Close output/input stream
outputStream.flush();
outputStream.close();
inputStream.close();
// Disconnect
connection.disconnect();
exception = null;
} catch (Exception e) {
exception = e;
response = null;
}
return new Request(exception, response);
}
private static String appendCharacter(String string, char c) {
if (string.endsWith(c + "")) {
return string;
} else {
return string + c;
}
}
public static class Request {
private Exception exception;
private JsonObject response;
public Request(Exception exception, JsonObject response) {
this.exception = exception;
}
public Exception getException() {
return exception;
}
public boolean hasSucceeded() {
return exception == null;
}
public JsonObject getResponse() {
return response;
}
}
}
|
package com.peterverzijl.softwaresystems.qwirkle.tui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.peterverzijl.softwaresystems.qwirkle.networking.Client;
public class MainTUI {
static class ServerSettings {
public InetAddress address;
public int port;
}
private static boolean mRunning = false;
// private static Thread mServerThread;
private static ServerTUI mServerTUI;
private static ServerSettings server;
private static Client mClient;
// private static Thread mClientThread;
public static final ReentrantLock lock = new ReentrantLock(true);
private static boolean mInGame = false;
private static BufferedReader br;
public static void main(String[] args) {
System.out.println("Welcome to the Qwirkle TUI!");
System.out.println("You can now start typing commands.");
// Do the input wait loop
mRunning = true;
br = new BufferedReader(new InputStreamReader(System.in));
do {
lock.lock();
handleCommand(readInput());
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
} while (mRunning);
}
public static String readInput() {
String result = "";
try {
result = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Handles the execution of the give command.
*
* @param input
* The command to execute.
*/
private static void handleCommand(String input) {
if (input.trim().length() == 0 || input.equals(System.lineSeparator())) {
return;
}
if (input.contains("help")) {
System.out.println("Perhaps you need HELP.");
return;
}
input = input.toUpperCase();
// Show the help
if (input.contains("HELP")) {
showHelp();
} else if (input.contains("CHAT")) {
openChat();
} else if (input.contains("SERVER CREATE")) {
input = input.replace("SERVER CREATE ", "");
createServer(input);
} else if (input.contains("SERVER CONNECT")) {
input = input.replace("SERVER CONNECT ", "");
connectServer(input);
} else if (input.contains("SERVER MESSAGES")) {
if (mServerTUI != null) {
mServerTUI.displayMessages();
} else {
System.out.println("No.");
}
} else if (input.contains("SERVER COMMAND")) {
if (mClient != null) {
input = input.replace("SERVER COMMAND ", "");
mClient.sendCommand(input);
}
} else if (input.contains("GAME JOIN")) {
if (mClient != null) {
if (!mInGame) {
tryJoinGame(input);
} else {
System.out.println("You are already in a game!");
}
} else {
System.out.println("Go play with yourself somewhere else!");
}
} else if (input.contains("GAME STONE AMOUNT")) {
if (mInGame && mClient != null) {
mClient.getNumStones();
} else {
System.out.println("Deez nuts are in Da sack.");
}
} else if (input.contains("GAME HAND")) {
if (mInGame && mClient != null) {
System.out.println(mClient.getPlayerHand());
} else {
System.out.println("Put your hand in my pants and I bet you feel nutz!");
}
} else if (input.contains("GAME TRADE")) {
input = input.replace("GAME TRADE ", "");
if (mInGame && mClient != null) {
String[] blocks = input.split(" ");
List<Integer> indexList = new ArrayList<Integer>();
for (int i = 0; i < blocks.length; i++) {
indexList.add(Integer.parseInt(blocks[i]));
}
mClient.tradeBlocks(indexList);
} else {
System.out.println("You have nothing of value to me.");
}
} else if (input.contains("WHOAMI")) {
if (mClient != null && mClient.getName() != null) {
System.out.println(mClient.getName());
} else {
System.out.println("How am I supposed to know?!");
}
} else if (input.contains("EXIT")) {
System.out.println("Initiating RAGEQUIT...\nExiting Qwirkle.");
mRunning = false;
System.exit(0);
} else {
System.out.println("I don't speak retard. Command " + input + " does not exist.");
}
}
private static void tryJoinGame(String input) {
// Remove the command
input = input.replaceAll("GAME JOIN ", "");
String[] param = input.split(" ");
// Try to get the number
if (param.length != 1) {
// Stupid
System.out.println("");
return;
}
try {
int numPlayers = Integer.parseInt(param[0]);
mClient.joinGame(numPlayers);
} catch (NumberFormatException e) {
System.out.println("Do you even know what a number is?!");
return;
}
mInGame = true;
}
/**
* Gets the settings from a string file.
*
* @param input
* The server settings in string.
* @return Either the previous server settings or the created server
* settings.
*/
private static ServerSettings getSettings(String input) {
if (server == null) {
server = new ServerSettings();
String[] param = input.split(" ");
// Check if the correct amount of parameters is supplied
if (param.length != 2) {
System.out.println("RTFM!");
return null;
}
// Check if the correct parameters are given.
try {
server.address = InetAddress.getByName(param[0]);
} catch (UnknownHostException e) {
System.out.println("Apparently typing in correct IP adresses is hard.");
return null;
}
try {
server.port = Integer.parseInt(param[1]);
} catch (NumberFormatException e) {
System.out.println("Do you even know what a number is?!");
return null;
}
}
return server;
}
/**
* Shows the help information
*/
private static void showHelp() {
System.out.println("Commands:");
System.out.println("CHAT \t opens chat");
System.out.println("SERVER CONNECT <address> <port> \t connects to a server.");
System.out.println("SERVER CREATE <address> <port> \t creates server.");
System.out.println("SERVER MESSAGES \t shows all server messages.");
System.out.println("GAME JOIN <number of opponents> \t tries to join a game with x opponents.");
System.out.println("GAME STONE AMOUNT \t asks the game how many stones are left in the game bag.");
System.out.println("GAME HAND \t asks the game to display the stones in the hand.");
System.out.println("WHOAMI \t shows the name of the user.");
System.out.println("EXIT \t exits the application.");
}
/**
* Fills out the server settings.
*
* @param input
* The input string with the settings.
*/
private static void connectServer(String input) {
server = getSettings(input);
if (mClient == null && server != null) {
try {
mClient = createClient();
// Now fetch the name of the user
System.out.println("Connecting to server...");
// Ask the player for his name.
askName();
} catch (IOException e) {
System.out.println("Failed to create a client. Due to: " + e.getMessage());
}
}
}
public static void askName() {
while (lock.isLocked() && !lock.isHeldByCurrentThread()) {
// Do nothing.
}
lock.lock();
try {
String name = "";
do {
System.out.println("Enter your name: ");
name = readInput();
name = name.trim();
if (name.length() < 2) {
System.out.println("Enter a longer name!");
}
if (name.equals("dave")) {
System.out.println("I am sorry dave, but I can't let you do that.");
}
} while (name.length() < 2);
mClient.setPlayerName(name);
} finally {
lock.unlock();
}
}
/**
* Tries to create a client;
*/
private static Client createClient() throws IOException {
Client client = null;
client = new Client(server.address, server.port, new ClientViewer());
(new Thread(client)).start();
return client;
}
/**
* Creates a server from the given input. [syntax] <serverAddress> <port>
*
* @param input
* A string containing the name and the port of the server.
*/
private static void createServer(String input) {
server = getSettings(input);
if (server != null) {
try {
mServerTUI = new ServerTUI(server.address, server.port);
connectServer(input);
} catch (IOException e) {
lock.unlock();
System.out.println("Oeps, it seems you did something wrong. " + e.getMessage());
}
} else {
System.out.println("Forgot to enter the rest of the command?");
}
}
/**
* Opens the chat TUI
*/
private static void openChat() {
// Are we even connected to a server?
if (server == null || mClient == null) {
System.out.println("Hey idiot, nobody is going to talk to someone who forgets to connect to a server!");
return;
}
try {
System.out.println("Opening chat client...");
ChatTUI chat = new ChatTUI(mClient);
chat.run();
} catch (IOException e1) {
System.out.println("Error: could not connect to server at address " + server.address.toString() + ":"
+ server.port + ". Due to " + e1.getMessage());
System.out.println("Are you stupid?! You can't start a chat at a server that doesn't exist!");
}
}
}
|
package org.apache.hadoop.hbase.hbql;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.hadoop.hbase.hbql.client.HBqlException;
import org.apache.hadoop.hbase.hbql.query.object.client.ObjectQuery;
import org.apache.hadoop.hbase.hbql.query.object.client.ObjectQueryListenerAdapter;
import org.apache.hadoop.hbase.hbql.query.object.client.ObjectQueryManager;
import org.apache.hadoop.hbase.hbql.query.object.client.ObjectQueryPredicate;
import org.apache.hadoop.hbase.hbql.query.object.client.ObjectResults;
import org.apache.hadoop.hbase.hbql.util.Counter;
import org.apache.hadoop.hbase.hbql.util.ObjectTests;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class ObjectEvalsTest extends ObjectTests<ObjectEvalsTest.SimpleObject> {
public class SimpleObject {
final int intval1, intval2;
final String strval;
final Date dateval;
public SimpleObject(final int val) {
this.intval1 = val;
this.intval2 = this.intval1 * 2;
this.strval = "Test Value: " + val;
this.dateval = new Date(System.currentTimeMillis());
}
public String toString() {
return "intval1: " + intval1 + " intval2: " + intval2 + " strval: " + strval;
}
}
@Test
public void objectExpressions() throws HBqlException {
final List<SimpleObject> objList = Lists.newArrayList();
for (int i = 0; i < 10; i++)
objList.add(new SimpleObject(i));
assertResultCount(objList, "intval1 = 2", 1);
assertResultCount(objList, "intval1 >= 5", 5);
assertResultCount(objList, "2*intval1 = intval2", 10);
assertResultCount(objList, "intval2 = 2*intval1", 10);
assertResultCount(objList, "intval1 between 1 and 4", 4);
assertResultCount(objList, "intval1 in (1, 2+1, 2+1+1, 4+3)", 4);
assertResultCount(objList, "strval like 'T[est]+ Value: [1-5]'", 5);
assertResultCount(objList, "NOW() between NOW()-DAY(1) AND NOW()+DAY(1)", 10);
assertResultCount(objList, "dateval between NOW()-MINUTE(1) AND NOW()+MINUTE(1)", 10);
assertResultCount(objList, "dateval between DATE('09/09/2009', 'mm/dd/yyyy')-MINUTE(1) AND NOW()+MINUTE(1)", 10);
// Using Listeners with CollectionQuery Object
String qstr = "strval like 'T[est]+ Value: [1-3]'";
final Counter cnt1 = new Counter();
ObjectQuery<SimpleObject> query = ObjectQueryManager.newObjectQuery(qstr);
query.addListener(
new ObjectQueryListenerAdapter<SimpleObject>() {
public void onEachObject(final SimpleObject val) throws HBqlException {
cnt1.increment();
}
}
);
query.getResults(objList);
assertTrue(cnt1.getCount() == 3);
query = ObjectQueryManager.newObjectQuery(qstr);
List<SimpleObject> r1 = query.getResultList(objList);
assertTrue(r1.size() == 3);
ObjectQuery<SimpleObject> query1 = ObjectQueryManager.newObjectQuery("strval like :str1");
query1.setParameter("str1", "T[est]+ Value: [1-3]");
r1 = query1.getResultList(objList);
assertTrue(r1.size() == 3);
// Using Iterator
int cnt2 = 0;
ObjectQuery<SimpleObject> query2 = ObjectQueryManager.newObjectQuery("strval like 'T[est]+ Value: [1-3]'");
final ObjectResults<SimpleObject> results = query2.getResults(objList);
for (final SimpleObject obj : results)
cnt2++;
assertTrue(cnt2 == 3);
// Using Google collections
qstr = "intval1 in (1, 2+1, 2+1+1, 4+3)";
List<SimpleObject> list = Lists.newArrayList(Iterables.filter(objList, new ObjectQueryPredicate<SimpleObject>(qstr)));
assertTrue(list.size() == 4);
ObjectQueryPredicate pred = new ObjectQueryPredicate<SimpleObject>("intval1 in (:vals)");
List<Integer> intList = Lists.newArrayList();
intList.add(1);
intList.add(3);
intList.add(4);
intList.add(7);
pred.setParameter("vals", intList);
list = Lists.newArrayList(Iterables.filter(objList, pred));
assertTrue(list.size() == 4);
}
}
|
package dyvil.tools.compiler.ast.expression;
import dyvil.reflect.Opcodes;
import dyvil.tools.compiler.ast.annotation.IAnnotation;
import dyvil.tools.compiler.ast.context.IContext;
import dyvil.tools.compiler.ast.generic.ITypeContext;
import dyvil.tools.compiler.ast.parameter.ArgumentList;
import dyvil.tools.compiler.ast.structure.IClassCompilableList;
import dyvil.tools.compiler.ast.type.IType;
import dyvil.tools.compiler.ast.type.Mutability;
import dyvil.tools.compiler.ast.type.builtin.Types;
import dyvil.tools.compiler.ast.type.compound.MapType;
import dyvil.tools.compiler.backend.MethodWriter;
import dyvil.tools.compiler.backend.exception.BytecodeException;
import dyvil.tools.compiler.config.Formatting;
import dyvil.tools.compiler.transform.TypeChecker;
import dyvil.tools.parsing.marker.MarkerList;
import dyvil.tools.parsing.position.ICodePosition;
public class MapExpr implements IValue
{
private static final TypeChecker.MarkerSupplier KEY_MARKER_SUPPLIER = TypeChecker.markerSupplier(
"map.key.type.incompatible", "map.key.type.expected", "map.key.type.actual");
private static final TypeChecker.MarkerSupplier VALUE_MARKER_SUPPLIER = TypeChecker.markerSupplier(
"map.value.type.incompatible", "map.value.type.expected", "map.value.type.actual");
protected ICodePosition position;
protected IValue[] keys;
protected IValue[] values;
protected int count;
// Metadata
private IType type;
private IType keyType;
private IType valueType;
public MapExpr(ICodePosition position)
{
this.position = position;
}
public MapExpr(ICodePosition position, IValue[] keys, IValue[] values, int count)
{
this.position = position;
this.keys = keys;
this.values = values;
this.count = count;
}
@Override
public int valueTag()
{
return MAP;
}
@Override
public void setPosition(ICodePosition position)
{
this.position = position;
}
@Override
public ICodePosition getPosition()
{
return this.position;
}
public IType getKeyType()
{
if (this.keyType != null)
{
return this.keyType;
}
return this.keyType = ArrayExpr.getCommonType(this.keys, this.count);
}
public IType getValueType()
{
if (this.valueType != null)
{
return this.valueType;
}
return this.valueType = ArrayExpr.getCommonType(this.values, this.count);
}
@Override
public boolean isResolved()
{
if (this.type != null)
{
return this.type.isResolved();
}
if (this.keyType != null && this.valueType != null)
{
return this.keyType.isResolved() && this.valueType.isResolved();
}
for (int i = 0; i < this.count; i++)
{
if (!this.keys[i].isResolved())
{
return false;
}
if (!this.values[i].isResolved())
{
return false;
}
}
return true;
}
@Override
public IType getType()
{
if (this.type == null)
{
return this.type = new MapType(this.getKeyType(), this.getValueType(), Mutability.IMMUTABLE,
MapType.MapTypes.IMMUTABLE_MAP_CLASS);
}
return this.type;
}
@Override
public void setType(IType type)
{
this.type = type;
}
@Override
public IValue withType(IType mapType, ITypeContext typeContext, MarkerList markers, IContext context)
{
if (!MapType.MapTypes.MAP_CLASS.isSubClassOf(mapType))
{
IAnnotation annotation = mapType.getTheClass().getAnnotation(MapType.MapTypes.MAP_CONVERTIBLE_CLASS);
if (annotation != null)
{
ArgumentList arguments = new ArgumentList(new IValue[] { new ArrayExpr(this.keys, this.count),
new ArrayExpr(this.values, this.count) }, 2);
return new LiteralConversion(this, annotation, arguments)
.withType(mapType, typeContext, markers, context);
}
return null;
}
final IType keyType = this.keyType = Types.resolveTypeSafely(mapType, MapType.MapTypes.KEY_VARIABLE);
final IType valueType = this.valueType = Types.resolveTypeSafely(mapType, MapType.MapTypes.VALUE_VARIABLE);
for (int i = 0; i < this.count; i++)
{
this.keys[i] = TypeChecker
.convertValue(this.keys[i], keyType, typeContext, markers, context, KEY_MARKER_SUPPLIER);
this.values[i] = TypeChecker.convertValue(this.values[i], valueType, typeContext, markers, context,
VALUE_MARKER_SUPPLIER);
}
return this;
}
@Override
public boolean isType(IType type)
{
if (!MapType.MapTypes.MAP_CLASS.isSubClassOf(type))
{
return this.isConvertibleFrom(type);
}
IType keyType = Types.resolveTypeSafely(type, MapType.MapTypes.KEY_VARIABLE);
IType valueType = Types.resolveTypeSafely(type, MapType.MapTypes.VALUE_VARIABLE);
for (int i = 0; i < this.count; i++)
{
if (!this.keys[i].isType(keyType))
{
return false;
}
if (!this.values[i].isType(valueType))
{
return false;
}
}
return true;
}
private boolean isConvertibleFrom(IType type)
{
return type.getAnnotation(MapType.MapTypes.MAP_CONVERTIBLE_CLASS) != null;
}
@Override
public int getTypeMatch(IType type)
{
if (!MapType.MapTypes.MAP_CLASS.isSubClassOf(type))
{
return this.isConvertibleFrom(type) ? CONVERSION_MATCH : 0;
}
if (this.count == 0)
{
return EXACT_MATCH;
}
final IType keyType = Types.resolveTypeSafely(type, MapType.MapTypes.KEY_VARIABLE);
final IType valueType = Types.resolveTypeSafely(type, MapType.MapTypes.VALUE_VARIABLE);
int min = Integer.MAX_VALUE;
for (int i = 0; i < this.count; i++)
{
int match = this.keys[i].getTypeMatch(keyType);
if (match == MISMATCH)
{
return MISMATCH;
}
if (match < min)
{
min = match;
}
match = this.values[i].getTypeMatch(valueType);
if (match == MISMATCH)
{
return 0;
}
if (match < min)
{
min = match;
}
}
return min;
}
@Override
public void resolveTypes(MarkerList markers, IContext context)
{
for (int i = 0; i < this.count; i++)
{
this.keys[i].resolveTypes(markers, context);
this.values[i].resolveTypes(markers, context);
}
}
@Override
public IValue resolve(MarkerList markers, IContext context)
{
for (int i = 0; i < this.count; i++)
{
this.keys[i] = this.keys[i].resolve(markers, context);
this.values[i] = this.values[i].resolve(markers, context);
}
return this;
}
@Override
public void checkTypes(MarkerList markers, IContext context)
{
for (int i = 0; i < this.count; i++)
{
this.keys[i].checkTypes(markers, context);
this.values[i].checkTypes(markers, context);
}
}
@Override
public void check(MarkerList markers, IContext context)
{
for (int i = 0; i < this.count; i++)
{
this.keys[i].check(markers, context);
this.values[i].check(markers, context);
}
}
@Override
public IValue foldConstants()
{
for (int i = 0; i < this.count; i++)
{
this.keys[i] = this.keys[i].foldConstants();
this.values[i] = this.values[i].foldConstants();
}
return this;
}
@Override
public IValue cleanup(IContext context, IClassCompilableList compilableList)
{
for (int i = 0; i < this.count; i++)
{
this.keys[i] = this.keys[i].cleanup(context, compilableList);
this.values[i] = this.values[i].cleanup(context, compilableList);
}
return this;
}
@Override
public void writeExpression(MethodWriter writer, IType type) throws BytecodeException
{
if (this.count == 0)
{
writer.visitFieldInsn(Opcodes.GETSTATIC, "dyvil/collection/immutable/EmptyMap", "instance",
"Ldyvil/collection/immutable/EmptyMap;");
return;
}
final IType keyObject = this.keyType.getObjectType();
final IType valueObject = this.valueType.getObjectType();
final int varIndex = writer.localCount();
writer.visitLdcInsn(this.count);
writer.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
writer.visitVarInsn(Opcodes.ASTORE, varIndex);
writer.visitLdcInsn(this.count);
writer.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
writer.visitVarInsn(Opcodes.ASTORE, varIndex + 1);
for (int i = 0; i < this.count; i++)
{
writer.visitVarInsn(Opcodes.ALOAD, varIndex);
writer.visitLdcInsn(i);
this.keys[i].writeExpression(writer, keyObject);
writer.visitInsn(Opcodes.AASTORE);
writer.visitVarInsn(Opcodes.ALOAD, varIndex + 1);
writer.visitLdcInsn(i);
this.values[i].writeExpression(writer, valueObject);
writer.visitInsn(Opcodes.AASTORE);
}
writer.visitVarInsn(Opcodes.ALOAD, varIndex);
writer.visitVarInsn(Opcodes.ALOAD, varIndex + 1);
writer.visitMethodInsn(Opcodes.INVOKESTATIC, "dyvil/collection/ImmutableMap", "apply",
"([Ljava/lang/Object;[Ljava/lang/Object;)Ldyvil/collection/ImmutableMap;", true);
if (type != null)
{
this.getType().writeCast(writer, type, this.getLineNumber());
}
}
@Override
public void toString(String prefix, StringBuilder buffer)
{
if (this.count <= 0)
{
if (Formatting.getBoolean("map.empty.space_between"))
{
buffer.append("[ ]");
}
else
{
buffer.append("[]");
}
return;
}
String mapPrefix = Formatting.getIndent("map.entry_separator.indent", prefix);
buffer.append('[');
if (Formatting.getBoolean("map.open_paren.space_after"))
{
buffer.append(' ');
}
this.keys[0].toString(mapPrefix, buffer);
Formatting.appendSeparator(buffer, "map.key_value_separator", ':');
this.values[0].toString(mapPrefix, buffer);
for (int i = 1; i < this.count; i++)
{
Formatting.appendSeparator(buffer, "map.entry_separator", ',');
this.keys[i].toString(mapPrefix, buffer);
Formatting.appendSeparator(buffer, "map.key_value_separator", ':');
this.values[i].toString(mapPrefix, buffer);
}
if (Formatting.getBoolean("map.close_paren.space_before"))
{
buffer.append(' ');
}
buffer.append(']');
}
}
|
package VASSAL.configure;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* A Configurer that returns a String from among a list of possible values
*/
public class StringEnumConfigurer extends Configurer {
private String[] validValues;
private JComboBox<String> box;
private Box panel;
public StringEnumConfigurer(String key, String name, String[] validValues) {
super(key, name);
this.validValues = validValues;
}
@Override
public Component getControls() {
if (panel == null) {
panel = Box.createHorizontalBox();
panel.add(new JLabel(name));
box = new JComboBox<>(validValues);
box.setMaximumSize(new Dimension(box.getMaximumSize().width, box.getPreferredSize().height));
if (isValidValue(getValue())) {
box.setSelectedItem(getValue());
}
else if (validValues.length > 0) {
box.setSelectedIndex(0);
}
box.addActionListener(e -> {
noUpdate = true;
setValue(box.getSelectedItem());
noUpdate = false;
});
panel.add(box);
}
return panel;
}
public void setEnabled(boolean enabled) {
box.setEnabled(enabled);
}
public void setEditable(boolean enabled) {
box.setEditable(enabled);
}
public boolean isValidValue(Object o) {
for (String validValue : validValues) {
if (validValue.equals(o)) {
return true;
}
}
return false;
}
public String[] getValidValues() {
return validValues;
}
public void setValidValues(String[] s) {
validValues = s;
if (box == null) {
getControls();
}
box.setModel(new DefaultComboBoxModel<>(validValues));
}
@Override
public void setValue(Object o) {
if (validValues == null
|| isValidValue(o)) {
super.setValue(o);
if (!noUpdate && box != null) {
box.setSelectedItem(o);
}
}
}
@Override
public String getValueString() {
return box != null ? (String) box.getSelectedItem() : validValues[0];
}
@Override
public void setValue(String s) {
setValue((Object) s);
}
// TODO move test code to a manual unit test annotated with @Ignore
public static void main(String[] args) {
JFrame f = new JFrame();
StringEnumConfigurer c = new StringEnumConfigurer(null, "Pick one: ", new String[]{"one", "two", "three"}); // NON-NLS
c.addPropertyChangeListener(evt -> System.err.println(evt.getPropertyName() + " = " + evt.getNewValue()));
f.add(c.getControls());
f.pack();
f.setVisible(true);
}
}
|
package io.strimzi.systemtest.log;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.Pod;
import io.strimzi.api.kafka.model.JvmOptions;
import io.strimzi.api.kafka.model.KafkaBridgeResources;
import io.strimzi.api.kafka.model.KafkaConnectResources;
import io.strimzi.api.kafka.model.KafkaConnectS2IResources;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2Resources;
import io.strimzi.api.kafka.model.KafkaMirrorMakerResources;
import io.strimzi.api.kafka.model.KafkaResources;
import io.strimzi.systemtest.AbstractST;
import io.strimzi.systemtest.annotations.OpenShiftOnly;
import io.strimzi.systemtest.resources.ResourceManager;
import io.strimzi.systemtest.resources.crd.KafkaBridgeResource;
import io.strimzi.systemtest.resources.crd.KafkaClientsResource;
import io.strimzi.systemtest.resources.crd.KafkaConnectResource;
import io.strimzi.systemtest.resources.crd.KafkaConnectS2IResource;
import io.strimzi.systemtest.resources.crd.KafkaMirrorMaker2Resource;
import io.strimzi.systemtest.resources.crd.KafkaMirrorMakerResource;
import io.strimzi.systemtest.resources.crd.KafkaResource;
import io.strimzi.systemtest.resources.crd.KafkaTopicResource;
import io.strimzi.systemtest.resources.crd.KafkaUserResource;
import io.strimzi.systemtest.utils.kubeUtils.controllers.DeploymentConfigUtils;
import io.strimzi.systemtest.utils.kubeUtils.controllers.DeploymentUtils;
import io.strimzi.systemtest.utils.kubeUtils.controllers.StatefulSetUtils;
import io.strimzi.test.timemeasuring.Operation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static io.strimzi.systemtest.Constants.BRIDGE;
import static io.strimzi.systemtest.Constants.CONNECT;
import static io.strimzi.systemtest.Constants.CONNECT_COMPONENTS;
import static io.strimzi.systemtest.Constants.MIRROR_MAKER;
import static io.strimzi.systemtest.Constants.MIRROR_MAKER2;
import static io.strimzi.systemtest.Constants.REGRESSION;
import static io.strimzi.test.k8s.KubeClusterResource.cmdKubeClient;
import static io.strimzi.test.k8s.KubeClusterResource.kubeClient;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
@Tag(REGRESSION)
@Tag(CONNECT)
@Tag(MIRROR_MAKER)
@Tag(MIRROR_MAKER2)
@Tag(BRIDGE)
@Tag(CONNECT_COMPONENTS)
@TestMethodOrder(OrderAnnotation.class)
class LogSettingST extends AbstractST {
static final String NAMESPACE = "log-setting-cluster-test";
private static final Logger LOGGER = LogManager.getLogger(LogSettingST.class);
private static final String INFO = "INFO";
private static final String ERROR = "ERROR";
private static final String WARN = "WARN";
private static final String TRACE = "TRACE";
private static final String DEBUG = "DEBUG";
private static final String FATAL = "FATAL";
private static final String OFF = "OFF";
private static final String GC_LOGGING_SET_NAME = "gc-set-logging";
private static final String BRIDGE_NAME = "my-bridge";
private static final String MM_NAME = "my-mirror-maker";
private static final String MM2_NAME = "my-mirror-maker-2";
private static final String CONNECT_NAME = "my-connect";
private static final String CONNECTS2I_NAME = "my-connect-s2i";
private static final String KAFKA_MAP = KafkaResources.kafkaMetricsAndLogConfigMapName(CLUSTER_NAME);
private static final String ZOOKEEPER_MAP = KafkaResources.zookeeperMetricsAndLogConfigMapName(CLUSTER_NAME);
private static final String TO_MAP = String.format("%s-%s", CLUSTER_NAME, "entity-topic-operator-config");
private static final String UO_MAP = String.format("%s-%s", CLUSTER_NAME, "entity-user-operator-config");
private static final String CONNECT_MAP = KafkaConnectResources.metricsAndLogConfigMapName(CONNECT_NAME);
private static final String CONNECTS2I_MAP = KafkaConnectS2IResources.metricsAndLogConfigMapName(CONNECTS2I_NAME);
private static final String MM_MAP = KafkaMirrorMakerResources.metricsAndLogConfigMapName(MM_NAME);
private static final String MM2_MAP = KafkaMirrorMaker2Resources.metricsAndLogConfigMapName(MM2_NAME);
private static final String BRIDGE_MAP = KafkaBridgeResources.metricsAndLogConfigMapName(BRIDGE_NAME);
private static final Map<String, String> KAFKA_LOGGERS = new HashMap<String, String>() {
{
put("kafka.root.logger.level", INFO);
put("test.kafka.logger.level", INFO);
put("log4j.logger.org.I0Itec.zkclient.ZkClient", ERROR);
put("log4j.logger.org.apache.zookeeper", WARN);
put("log4j.logger.kafka", TRACE);
put("log4j.logger.org.apache.kafka", DEBUG);
put("log4j.logger.kafka.request.logger", FATAL);
put("log4j.logger.kafka.network.Processor", OFF);
put("log4j.logger.kafka.server.KafkaApis", INFO);
put("log4j.logger.kafka.network.RequestChannel$", ERROR);
put("log4j.logger.kafka.controller", WARN);
put("log4j.logger.kafka.log.LogCleaner", TRACE);
put("log4j.logger.state.change.logger", DEBUG);
put("log4j.logger.kafka.authorizer.logger", FATAL);
}
};
private static final Map<String, String> ZOOKEEPER_LOGGERS = new HashMap<String, String>() {
{
put("zookeeper.root.logger", OFF);
put("test.zookeeper.logger.level", DEBUG);
}
};
private static final Map<String, String> CONNECT_LOGGERS = new HashMap<String, String>() {
{
put("connect.root.logger.level", INFO);
put("test.connect.logger.level", DEBUG);
put("log4j.logger.org.I0Itec.zkclient", ERROR);
put("log4j.logger.org.reflections", WARN);
}
};
private static final Map<String, String> OPERATORS_LOGGERS = new HashMap<String, String>() {
{
put("rootLogger.level", DEBUG);
put("test.operator.logger.level", DEBUG);
}
};
private static final Map<String, String> MIRROR_MAKER_LOGGERS = new HashMap<String, String>() {
{
put("mirrormaker.root.logger", TRACE);
put("test.mirrormaker.logger.level", TRACE);
}
};
private static final Map<String, String> BRIDGE_LOGGERS = new HashMap<String, String>() {
{
put("logger.createConsumer.name", "http.openapi.operation.createConsumer");
put("logger.createConsumer.level", INFO);
put("logger.deleteConsumer.name", "http.openapi.operation.deleteConsumer");
put("logger.deleteConsumer.level", DEBUG);
put("logger.subscribe.name", "http.openapi.operation.subscribe");
put("logger.subscribe.level", TRACE);
put("logger.unsubscribe.name", "http.openapi.operation.unsubscribe");
put("logger.unsubscribe.level", DEBUG);
put("logger.poll.name", "http.openapi.operation.poll");
put("logger.poll.level", INFO);
put("logger.assign.name", "http.openapi.operation.assign");
put("logger.assign.level", TRACE);
put("logger.commit.name", "http.openapi.operation.commit");
put("logger.commit.level", DEBUG);
put("logger.send.name", "http.openapi.operation.send");
put("logger.send.level", ERROR);
put("logger.sendToPartition.name", "http.openapi.operation.sendToPartition");
put("logger.sendToPartition.level", TRACE);
put("logger.seekToBeginning.name", "http.openapi.operation.seekToBeginning");
put("logger.seekToBeginning.level", DEBUG);
put("logger.seekToEnd.name", "http.openapi.operation.seekToEnd");
put("logger.seekToEnd.level", WARN);
put("logger.seek.name", "http.openapi.operation.seek");
put("logger.seek.level", INFO);
put("logger.healthy.name", "http.openapi.operation.healthy");
put("logger.healthy.level", ERROR);
put("logger.ready.name", "http.openapi.operation.ready");
put("logger.ready.level", WARN);
put("logger.openapi.name", "http.openapi.operation.openapi");
put("logger.openapi.level", TRACE);
put("test.logger.bridge.level", ERROR);
}
};
@Test
@Order(1)
void testLoggersKafka() {
assertThat("Kafka's log level is set properly", checkLoggersLevel(KAFKA_LOGGERS, KAFKA_MAP), is(true));
}
@Test
@Order(2)
void testLoggersZookeeper() {
assertThat("Zookeeper's log level is set properly", checkLoggersLevel(ZOOKEEPER_LOGGERS, ZOOKEEPER_MAP), is(true));
}
@Test
@Order(3)
void testLoggersTO() {
assertThat("Topic operator's log level is set properly", checkLoggersLevel(OPERATORS_LOGGERS, TO_MAP), is(true));
}
@Test
@Order(4)
void testLoggersUO() {
assertThat("User operator's log level is set properly", checkLoggersLevel(OPERATORS_LOGGERS, UO_MAP), is(true));
}
@Test
@Order(5)
void testLoggersKafkaConnect() {
assertThat("Kafka connect's log level is set properly", checkLoggersLevel(CONNECT_LOGGERS, CONNECT_MAP), is(true));
}
@Test
@Order(6)
void testLoggersMirrorMaker() {
assertThat("KafkaMirrorMaker's log level is set properly", checkLoggersLevel(MIRROR_MAKER_LOGGERS, MM_MAP), is(true));
}
@Test
@Order(7)
void testLoggersMirrorMaker2() {
assertThat("KafkaMirrorMaker2's log level is set properly", checkLoggersLevel(MIRROR_MAKER_LOGGERS, MM2_MAP), is(true));
}
@Test
@Order(8)
void testLoggersBridge() {
assertThat("Bridge's log level is set properly", checkLoggersLevel(BRIDGE_LOGGERS, BRIDGE_MAP), is(true));
}
@Test
@OpenShiftOnly
@Order(9)
void testLoggersConnectS2I() {
assertThat("KafkaConnectS2I's log level is set properly", checkLoggersLevel(CONNECT_LOGGERS, CONNECTS2I_MAP), is(true));
}
@Test
@Order(10)
void testGcLoggingNonSetDisabled() {
assertThat("Kafka GC logging is enabled", checkGcLoggingStatefulSets(KafkaResources.kafkaStatefulSetName(GC_LOGGING_SET_NAME)), is(false));
assertThat("Zookeeper GC logging is enabled", checkGcLoggingStatefulSets(KafkaResources.zookeeperStatefulSetName(GC_LOGGING_SET_NAME)), is(false));
assertThat("TO GC logging is enabled", checkGcLoggingDeployments(KafkaResources.entityOperatorDeploymentName(GC_LOGGING_SET_NAME), "topic-operator"), is(false));
assertThat("UO GC logging is enabled", checkGcLoggingDeployments(KafkaResources.entityOperatorDeploymentName(GC_LOGGING_SET_NAME), "user-operator"), is(false));
}
@Test
@Order(11)
void testGcLoggingSetEnabled() {
assertThat("Kafka GC logging is enabled", checkGcLoggingStatefulSets(KafkaResources.kafkaStatefulSetName(CLUSTER_NAME)), is(true));
assertThat("Zookeeper GC logging is enabled", checkGcLoggingStatefulSets(KafkaResources.zookeeperStatefulSetName(CLUSTER_NAME)), is(true));
assertThat("TO GC logging is enabled", checkGcLoggingDeployments(KafkaResources.entityOperatorDeploymentName(CLUSTER_NAME), "topic-operator"), is(true));
assertThat("UO GC logging is enabled", checkGcLoggingDeployments(KafkaResources.entityOperatorDeploymentName(CLUSTER_NAME), "user-operator"), is(true));
assertThat("Connect GC logging is enabled", checkGcLoggingDeployments(KafkaConnectResources.deploymentName(CONNECT_NAME)), is(true));
assertThat("Mirror-maker GC logging is enabled", checkGcLoggingDeployments(KafkaMirrorMakerResources.deploymentName(MM_NAME)), is(true));
assertThat("Mirror-maker-2 GC logging is enabled", checkGcLoggingDeployments(KafkaMirrorMaker2Resources.deploymentName(MM2_NAME)), is(true));
if (cluster.isNotKubernetes()) {
assertThat("ConnectS2I GC logging is enabled", checkGcLoggingDeploymentConfig(KafkaConnectS2IResources.deploymentName(CONNECTS2I_NAME)), is(true));
}
}
@Test
@Order(12)
void testGcLoggingSetDisabled() {
String connectName = KafkaConnectResources.deploymentName(CONNECT_NAME);
String connectS2IName = KafkaConnectS2IResources.deploymentName(CONNECTS2I_NAME);
String mmName = KafkaMirrorMakerResources.deploymentName(MM_NAME);
String mm2Name = KafkaMirrorMaker2Resources.deploymentName(MM2_NAME);
String eoName = KafkaResources.entityOperatorDeploymentName(CLUSTER_NAME);
String kafkaName = KafkaResources.kafkaStatefulSetName(CLUSTER_NAME);
String zkName = KafkaResources.zookeeperStatefulSetName(CLUSTER_NAME);
Map<String, String> connectPods = DeploymentUtils.depSnapshot(connectName);
Map<String, String> mmPods = DeploymentUtils.depSnapshot(mmName);
Map<String, String> mm2Pods = DeploymentUtils.depSnapshot(mm2Name);
Map<String, String> eoPods = DeploymentUtils.depSnapshot(eoName);
Map<String, String> kafkaPods = StatefulSetUtils.ssSnapshot(kafkaName);
Map<String, String> zkPods = StatefulSetUtils.ssSnapshot(zkName);
JvmOptions jvmOptions = new JvmOptions();
jvmOptions.setGcLoggingEnabled(false);
KafkaResource.replaceKafkaResource(CLUSTER_NAME, k -> {
k.getSpec().getKafka().setJvmOptions(jvmOptions);
k.getSpec().getZookeeper().setJvmOptions(jvmOptions);
k.getSpec().getEntityOperator().getTopicOperator().setJvmOptions(jvmOptions);
k.getSpec().getEntityOperator().getUserOperator().setJvmOptions(jvmOptions);
});
StatefulSetUtils.waitTillSsHasRolled(zkName, 1, zkPods);
StatefulSetUtils.waitTillSsHasRolled(kafkaName, 3, kafkaPods);
DeploymentUtils.waitTillDepHasRolled(eoName, 1, eoPods);
KafkaConnectResource.replaceKafkaConnectResource(CONNECT_NAME, kc -> kc.getSpec().setJvmOptions(jvmOptions));
DeploymentUtils.waitTillDepHasRolled(connectName, 1, connectPods);
if (cluster.isNotKubernetes()) {
KafkaConnectS2IResource.replaceConnectS2IResource(CONNECTS2I_NAME, cs2i -> cs2i.getSpec().setJvmOptions(jvmOptions));
DeploymentConfigUtils.waitTillDepConfigHasRolled(connectS2IName, connectPods);
}
KafkaMirrorMakerResource.replaceMirrorMakerResource(MM_NAME, mm -> mm.getSpec().setJvmOptions(jvmOptions));
DeploymentUtils.waitTillDepHasRolled(mmName, 1, mmPods);
KafkaMirrorMaker2Resource.replaceKafkaMirrorMaker2Resource(MM2_NAME, mm2 -> mm2.getSpec().setJvmOptions(jvmOptions));
DeploymentUtils.waitTillDepHasRolled(mm2Name, 1, mm2Pods);
assertThat("Kafka GC logging is disabled", checkGcLoggingStatefulSets(KafkaResources.kafkaStatefulSetName(CLUSTER_NAME)), is(false));
assertThat("Zookeeper GC logging is disabled", checkGcLoggingStatefulSets(KafkaResources.zookeeperStatefulSetName(CLUSTER_NAME)), is(false));
assertThat("TO GC logging is disabled", checkGcLoggingDeployments(KafkaResources.entityOperatorDeploymentName(CLUSTER_NAME), "topic-operator"), is(false));
assertThat("UO GC logging is disabled", checkGcLoggingDeployments(KafkaResources.entityOperatorDeploymentName(CLUSTER_NAME), "user-operator"), is(false));
assertThat("Connect GC logging is disabled", checkGcLoggingDeployments(KafkaConnectResources.deploymentName(CONNECT_NAME)), is(false));
assertThat("Mirror-maker GC logging is disabled", checkGcLoggingDeployments(KafkaMirrorMakerResources.deploymentName(MM_NAME)), is(false));
assertThat("Mirror-maker2 GC logging is disabled", checkGcLoggingDeployments(KafkaMirrorMaker2Resources.deploymentName(MM2_NAME)), is(false));
if (cluster.isNotKubernetes()) {
assertThat("ConnectS2I GC logging is disabled", checkGcLoggingDeploymentConfig(KafkaConnectS2IResources.deploymentName(CONNECTS2I_NAME)), is(false));
}
}
@Test
@Order(13)
void testKubectlGetStrimzi() {
String userName = "test-user";
String topicName = "test-topic";
KafkaTopicResource.topic(CLUSTER_NAME, topicName).done();
KafkaUserResource.tlsUser(CLUSTER_NAME, userName).done();
String strimziCRs = cmdKubeClient().execInCurrentNamespace("get", "strimzi").out();
assertThat(strimziCRs, containsString(CLUSTER_NAME));
assertThat(strimziCRs, containsString(GC_LOGGING_SET_NAME));
assertThat(strimziCRs, containsString(MM_NAME));
assertThat(strimziCRs, containsString(MM2_NAME));
assertThat(strimziCRs, containsString(BRIDGE_NAME));
assertThat(strimziCRs, containsString(CONNECT_NAME));
assertThat(strimziCRs, containsString(userName));
assertThat(strimziCRs, containsString(topicName));
}
@Test
@Order(14)
void testCheckContainersHaveProcessOneAsTini() {
//Used [/] in the grep command so that grep process does not return itself
String command = "ps -ef | grep '[/]usr/bin/tini' | awk '{ print $2}'";
for (Pod pod : kubeClient().listPods()) {
String podName = pod.getMetadata().getName();
if (!podName.contains("build") && !podName.contains("deploy") && !podName.contains("kafka-clients") && !podName.contains(CONNECTS2I_NAME)) {
for (Container container : pod.getSpec().getContainers()) {
LOGGER.info("Checking tini process for pod {} with container {}", pod, container);
boolean isPresent = cmdKubeClient().execInPodContainer(false, podName, container.getName(), "/bin/bash", "-c", command).out().trim().equals("1");
assertThat(isPresent, is(true));
}
}
}
}
private String configMap(String configMapName) {
Map<String, String> configMapData = kubeClient().getConfigMap(configMapName).getData();
// tries to get a log4j2 configuration file first (operator, bridge, ...) otherwise log4j one (kafka, zookeeper, ...)
String configMapKey = configMapData.keySet()
.stream()
.filter(key -> key.equals("log4j2.properties") || key.equals("log4j.properties"))
.findAny()
.get();
return configMapData.get(configMapKey);
}
private boolean checkLoggersLevel(Map<String, String> loggers, String configMapName) {
boolean result = false;
String configMap = configMap(configMapName);
for (Map.Entry<String, String> entry : loggers.entrySet()) {
LOGGER.info("Check log level setting for logger: {} Expected: {}", entry.getKey(), entry.getValue());
String loggerConfig = String.format("%s=%s", entry.getKey(), entry.getValue());
result = configMap.contains(loggerConfig);
// Validation failed
if (!result) {
break;
}
}
return result;
}
private Boolean checkGcLoggingDeployments(String deploymentName, String containerName) {
LOGGER.info("Checking deployment: {}", deploymentName);
List<Container> containers = kubeClient().getDeployment(deploymentName).getSpec().getTemplate().getSpec().getContainers();
Container container = getContainerByName(containerName, containers);
LOGGER.info("Checking container with name: {}", container.getName());
return checkEnvVarValue(container);
}
private Boolean checkGcLoggingDeployments(String deploymentName) {
LOGGER.info("Checking deployment: {}", deploymentName);
Container container = kubeClient().getDeployment(deploymentName).getSpec().getTemplate().getSpec().getContainers().get(0);
LOGGER.info("Checking container with name: {}", container.getName());
return checkEnvVarValue(container);
}
private Boolean checkGcLoggingDeploymentConfig(String depConfName) {
LOGGER.info("Checking deployment config: {}", depConfName);
Container container = kubeClient().getDeploymentConfig(depConfName).getSpec().getTemplate().getSpec().getContainers().get(0);
LOGGER.info("Checking container with name: {}", container.getName());
return checkEnvVarValue(container);
}
private Boolean checkGcLoggingStatefulSets(String statefulSetName) {
LOGGER.info("Checking stateful set: {}", statefulSetName);
Container container = kubeClient().getStatefulSet(statefulSetName).getSpec().getTemplate().getSpec().getContainers().get(0);
LOGGER.info("Checking container with name: {}", container.getName());
return checkEnvVarValue(container);
}
private Container getContainerByName(String containerName, List<Container> containers) {
return containers.stream().filter(c -> c.getName().equals(containerName)).findFirst().orElse(null);
}
private Boolean checkEnvVarValue(Container container) {
assertThat("Container is null!", container, is(notNullValue()));
List<EnvVar> loggingEnvVar = container.getEnv().stream().filter(envVar -> envVar.getName().contains("GC_LOG_ENABLED")).collect(Collectors.toList());
LOGGER.info("{}={}", loggingEnvVar.get(0).getName(), loggingEnvVar.get(0).getValue());
return loggingEnvVar.get(0).getValue().contains("true");
}
@BeforeAll
void setup() throws Exception {
ResourceManager.setClassResources();
installClusterOperator(NAMESPACE);
timeMeasuringSystem.setOperationID(startDeploymentMeasuring());
KafkaResource.kafkaPersistent(CLUSTER_NAME, 3, 1)
.editSpec()
.editKafka()
.withNewInlineLogging()
.withLoggers(KAFKA_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endKafka()
.editZookeeper()
.withNewInlineLogging()
.withLoggers(ZOOKEEPER_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endZookeeper()
.editEntityOperator()
.editOrNewUserOperator()
.withNewInlineLogging()
.withLoggers(OPERATORS_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endUserOperator()
.editOrNewTopicOperator()
.withNewInlineLogging()
.withLoggers(OPERATORS_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endTopicOperator()
.endEntityOperator()
.withNewCruiseControl()
.endCruiseControl()
.withNewKafkaExporter()
.endKafkaExporter()
.endSpec()
.done();
KafkaResource.kafkaPersistent(GC_LOGGING_SET_NAME, 1, 1)
.editSpec()
.editKafka()
.withNewJvmOptions()
.endJvmOptions()
.endKafka()
.editZookeeper()
.withNewJvmOptions()
.endJvmOptions()
.endZookeeper()
.editEntityOperator()
.editTopicOperator()
.withNewJvmOptions()
.endJvmOptions()
.endTopicOperator()
.editUserOperator()
.withNewJvmOptions()
.endJvmOptions()
.endUserOperator()
.endEntityOperator()
.endSpec()
.done();
KafkaClientsResource.deployKafkaClients(false, KAFKA_CLIENTS_NAME).done();
KafkaConnectResource.kafkaConnect(CONNECT_NAME, CLUSTER_NAME, 1)
.editSpec()
.withNewInlineLogging()
.withLoggers(CONNECT_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endSpec().done();
KafkaMirrorMakerResource.kafkaMirrorMaker(MM_NAME, CLUSTER_NAME, GC_LOGGING_SET_NAME, "my-group", 1, false)
.editSpec()
.withNewInlineLogging()
.withLoggers(MIRROR_MAKER_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endSpec()
.done();
KafkaBridgeResource.kafkaBridge(BRIDGE_NAME, CLUSTER_NAME, KafkaResources.plainBootstrapAddress(CLUSTER_NAME), 1)
.editSpec()
.withNewInlineLogging()
.withLoggers(BRIDGE_LOGGERS)
.endInlineLogging()
.endSpec().done();
KafkaMirrorMaker2Resource.kafkaMirrorMaker2(MM2_NAME, CLUSTER_NAME, GC_LOGGING_SET_NAME, 1, false)
.editSpec()
.withNewInlineLogging()
.withLoggers(MIRROR_MAKER_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endSpec()
.done();
if (cluster.isNotKubernetes()) {
KafkaConnectS2IResource.kafkaConnectS2I(CONNECTS2I_NAME, CLUSTER_NAME, 1)
.editSpec()
.withNewInlineLogging()
.withLoggers(CONNECT_LOGGERS)
.endInlineLogging()
.withNewJvmOptions()
.withGcLoggingEnabled(true)
.endJvmOptions()
.endSpec()
.done();
}
}
private String startDeploymentMeasuring() {
timeMeasuringSystem.setTestName(testClass, testClass);
return timeMeasuringSystem.startOperation(Operation.CLASS_EXECUTION);
}
@Override
protected void tearDownEnvironmentAfterAll() {
teardownEnvForOperator();
}
}
|
package org.jboss.as.web;
import java.util.List;
import java.util.Locale;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ServiceVerificationHandler;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RELATIVE_TO;
import org.jboss.as.server.mgmt.HttpManagementService;
import org.jboss.as.server.mgmt.domain.HttpManagement;
import org.jboss.as.server.services.path.AbstractPathService;
import org.jboss.as.server.services.path.RelativePathService;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceTarget;
class WebVirtualHostAdd extends AbstractAddStepHandler implements DescriptionProvider {
static final WebVirtualHostAdd INSTANCE = new WebVirtualHostAdd();
private static final String DEFAULT_RELATIVE_TO = "jboss.server.log.dir";
private static final String TEMP_DIR = "jboss.server.temp.dir";
private static final String HOME_DIR = "jboss.home.dir";
private static final String[] NO_ALIASES = new String[0];
private WebVirtualHostAdd() {
}
protected void populateModel(ModelNode operation, ModelNode model) {
model.get(Constants.ALIAS).set(operation.get(Constants.ALIAS));
model.get(Constants.ACCESS_LOG).set(operation.get(Constants.ACCESS_LOG));
model.get(Constants.REWRITE).set(operation.get(Constants.REWRITE));
model.get(Constants.SSO).set(operation.get(Constants.SSO));
model.get(Constants.DEFAULT_WEB_MODULE).set(operation.get(Constants.DEFAULT_WEB_MODULE));
final boolean welcome = operation.hasDefined(Constants.ENABLE_WELCOME_ROOT) && operation.get(Constants.ENABLE_WELCOME_ROOT).asBoolean();
model.get(Constants.ENABLE_WELCOME_ROOT).set(welcome);
}
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model, ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers) throws OperationFailedException {
final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
final String name = address.getLastElement().getValue();
boolean welcome = operation.hasDefined(Constants.ENABLE_WELCOME_ROOT) && operation.get(Constants.ENABLE_WELCOME_ROOT).asBoolean();
final ServiceTarget serviceTarget = context.getServiceTarget();
final WebVirtualHostService service = new WebVirtualHostService(name, aliases(operation), welcome);
final ServiceBuilder<?> serviceBuilder = serviceTarget.addService(WebSubsystemServices.JBOSS_WEB_HOST.append(name), service)
.addDependency(AbstractPathService.pathNameOf(TEMP_DIR), String.class, service.getTempPathInjector())
.addDependency(WebSubsystemServices.JBOSS_WEB, WebServer.class, service.getWebServer());
if (operation.hasDefined(Constants.ACCESS_LOG)) {
final ModelNode accessLog = operation.get(Constants.ACCESS_LOG);
service.setAccessLog(accessLog.clone());
// Create the access log service
accessLogService(name, accessLog, serviceTarget);
serviceBuilder.addDependency(WebSubsystemServices.JBOSS_WEB_HOST.append(name, Constants.ACCESS_LOG), String.class, service.getAccessLogPathInjector());
}
if (operation.hasDefined(Constants.REWRITE)) {
service.setRewrite(operation.get(Constants.REWRITE).clone());
}
if (operation.hasDefined(Constants.SSO)) {
service.setSso(operation.get(Constants.SSO).clone());
// FIXME: If a cache container is defined, add the dependency and inject it
}
if (operation.hasDefined(Constants.DEFAULT_WEB_MODULE)) {
if (welcome)
throw new OperationFailedException(new ModelNode().set("A default module can not be specified when the welcome root is enabled."));
service.setDefaultWebModule(operation.get(Constants.DEFAULT_WEB_MODULE).asString());
}
serviceBuilder.addListener(verificationHandler);
newControllers.add(serviceBuilder.install());
if (welcome) {
final WelcomeContextService welcomeService = new WelcomeContextService();
newControllers.add(context.getServiceTarget().addService(WebSubsystemServices.JBOSS_WEB.append(name).append("welcome"), welcomeService)
.addDependency(AbstractPathService.pathNameOf(HOME_DIR), String.class, welcomeService.getPathInjector())
.addDependency(WebSubsystemServices.JBOSS_WEB_HOST.append(name), VirtualHost.class, welcomeService.getHostInjector())
.addDependency(ServiceBuilder.DependencyType.OPTIONAL, HttpManagementService.SERVICE_NAME, HttpManagement.class, welcomeService.getHttpManagementInjector())
.addListener(verificationHandler)
.setInitialMode(ServiceController.Mode.ACTIVE)
.install());
}
}
static String[] aliases(final ModelNode node) {
if (node.hasDefined(Constants.ALIAS)) {
final ModelNode aliases = node.require(Constants.ALIAS);
final int size = aliases.asInt();
final String[] array = new String[size];
for (int i = 0; i < size; i++) array[i] = aliases.get(i).asString();
return array;
}
return NO_ALIASES;
}
static void accessLogService(final String hostName, final ModelNode element, final ServiceTarget target) {
if (element.has(Constants.ACCESS_LOG)) {
final ModelNode accessLog = element.get(Constants.ACCESS_LOG);
final String relativeTo = accessLog.has(RELATIVE_TO) ? accessLog.get(RELATIVE_TO).asString() : DEFAULT_RELATIVE_TO;
final String path = accessLog.has(PATH) ? accessLog.get(PATH).asString() : hostName;
RelativePathService.addService(WebSubsystemServices.JBOSS_WEB_HOST.append(hostName, Constants.ACCESS_LOG),
path, relativeTo, target);
} else {
RelativePathService.addService(WebSubsystemServices.JBOSS_WEB_HOST.append(hostName, Constants.ACCESS_LOG),
hostName, DEFAULT_RELATIVE_TO, target);
}
}
static ModelNode getAddOperation(final ModelNode address, final ModelNode subModel) {
final ModelNode operation = new ModelNode();
operation.get(OP).set(ADD);
operation.get(OP_ADDR).set(address);
if (subModel.hasDefined(Constants.ALIAS)) {
operation.get(Constants.ALIAS).set(subModel.get(Constants.ALIAS));
}
if (subModel.hasDefined(Constants.ACCESS_LOG)) {
operation.get(Constants.ACCESS_LOG).set(subModel.get(Constants.ACCESS_LOG));
}
if (subModel.hasDefined(Constants.REWRITE)) {
operation.get(Constants.REWRITE).set(subModel.get(Constants.REWRITE));
}
if (subModel.hasDefined(Constants.SSO)) {
operation.get(Constants.SSO).set(subModel.get(Constants.SSO));
}
if (subModel.hasDefined(Constants.ENABLE_WELCOME_ROOT)) {
operation.get(Constants.ENABLE_WELCOME_ROOT).set(subModel.get(Constants.ENABLE_WELCOME_ROOT));
}
return operation;
}
@Override
public ModelNode getModelDescription(Locale locale) {
return WebSubsystemDescriptions.getVirtualServerAdd(locale);
}
}
|
package baseCode.xml;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import baseCode.dataStructure.OntologyEntry;
import baseCode.dataStructure.graph.DirectedGraph;
import baseCode.dataStructure.graph.DirectedGraphNode;
public class GOParser {
private DirectedGraph m;
/**
* Get the graph that was created.
* @return a DirectedGraph. Nodes contain OntologyEntry instances.
*/
public DirectedGraph getGraph() {
return m;
}
/**
* Get a simple Map that contains keys that are the GO ids, values are the names.
* This can replace the functionality of the GONameReader in classScore.
*
* @return Map
*/
public Map getGONameMap() {
Map nodes = m.getItems();
Map result = new HashMap();
for (Iterator it = nodes.keySet().iterator(); it.hasNext();) {
DirectedGraphNode node = ( DirectedGraphNode)nodes.get(it.next());
OntologyEntry e = (OntologyEntry)node.getItem();
result.put(e.getId(), e.getName());
}
return result;
}
public GOParser( InputStream i ) throws IOException, SAXException {
System.setProperty( "org.xml.sax.driver",
"org.apache.xerces.parsers.SAXParser" );
XMLReader xr = XMLReaderFactory.createXMLReader();
GOHandler handler = new GOHandler();
xr.setContentHandler( handler );
xr.setErrorHandler( handler );
xr.setDTDHandler( handler );
xr.parse( new InputSource( i ) );
m = handler.getResults();
}
}
class GOHandler extends DefaultHandler {
private DirectedGraph m;
public DirectedGraph getResults() {
return m;
}
public GOHandler() {
super();
m = new DirectedGraph();
}
private boolean inTerm = false;
private boolean inDef = false;
private boolean inAcc = false;
private boolean inName = false;
private boolean inPartOf = false;
private boolean inIsa = false;
private boolean inSyn = false;
private StringBuffer nameBuf;
private StringBuffer accBuf;
private StringBuffer defBuf;
public void startElement( String uri, String name, String qName,
Attributes atts ) {
if ( name.equals( "term" ) ) {
inTerm = true;
} else if ( name.equals( "accession" ) ) {
accBuf = new StringBuffer();
inAcc = true;
} else if ( name.equals( "definition" ) ) {
defBuf = new StringBuffer();
inDef = true;
} else if ( name.equals( "is_a" ) ) {
inIsa = true;
String res = atts.getValue( "rdf:resource" );
String parent = res.substring( res.lastIndexOf( '#' ) + 1, res
.length() );
if ( !m.containsKey( parent ) ) {
m.addNode( parent, new OntologyEntry( parent, "no name yet",
"no definition yet" ) );
}
String currentTerm = accBuf.toString();
m.addParentTo( currentTerm, parent );
} else if ( name.equals( "part_of" ) ) {
inPartOf = true;
String res = atts.getValue( "rdf:resource" );
String parent = res.substring( res.lastIndexOf( '#' ) + 1, res
.length() );
if ( !m.containsKey( parent ) ) {
m.addNode( parent, new OntologyEntry( parent, "no name yet",
"no definition yet" ) );
}
String currentTerm = accBuf.toString();
m.addParentTo( currentTerm, parent );
} else if ( name.equals( "synonym" ) ) {
inSyn = true;
} else if ( name.equals( "name" ) ) {
nameBuf = new StringBuffer();
inName = true;
}
}
public void endElement( String uri, String name, String qName ) {
if ( name.equals( "term" ) ) {
inTerm = false;
} else if ( name.equals( "accession" ) ) {
inAcc = false;
String currentTerm = accBuf.toString();
m.addNode( currentTerm, new OntologyEntry( currentTerm, "no name yet",
"no definition yet" ) );
} else if ( name.equals( "definition" ) ) {
String currentTerm = accBuf.toString();
( ( OntologyEntry ) m.getNodeContents( currentTerm ) )
.setDefinition( defBuf.toString() );
inDef = false;
} else if ( name.equals( "is_a" ) ) {
inIsa = false;
} else if ( name.equals( "part_of" ) ) {
inPartOf = false;
} else if ( name.equals( "synonym" ) ) {
inSyn = false;
} else if ( name.equals( "name" ) ) {
inName = false;
String currentTerm = accBuf.toString();
( ( OntologyEntry ) m.getNodeContents( currentTerm ) )
.setName( nameBuf.toString() );
}
}
public void characters( char ch[], int start, int length ) {
if ( inTerm ) {
if ( inAcc ) {
accBuf.append( ch, start, length );
} else if ( inDef ) {
defBuf.append( ch, start, length );
} else if ( inName ) {
nameBuf.append( ch, start, length );
}
}
}
}
|
package lombok.core.configuration;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import lombok.ConfigurationKeys;
import lombok.core.configuration.ConfigurationSource.Result;
import lombok.core.debug.ProblemReporter;
public class FileSystemSourceCache {
private static final String LOMBOK_CONFIG_FILENAME = "lombok.config";
private static final long FULL_CACHE_CLEAR_INTERVAL = TimeUnit.MINUTES.toMillis(30);
private static final long RECHECK_FILESYSTEM = TimeUnit.SECONDS.toMillis(2);
private static final long NEVER_CHECKED = -1;
private static final long MISSING = -88; // Magic value; any lombok.config with this exact epochmillis last modified will never be read, so, let's ensure nobody accidentally has one with that exact last modified stamp.
private final ConcurrentMap<File, Content> dirCache = new ConcurrentHashMap<File, Content>(); // caches files (representing dirs) to the content object that tracks content.
private final ConcurrentMap<URI, File> uriCache = new ConcurrentHashMap<URI, File>(); // caches URIs of java source files to the dir that contains it.
private volatile long lastCacheClear = System.currentTimeMillis();
private void cacheClear() {
// We never clear the caches, generally because it'd be weird if a compile run would continually create an endless stream of new java files.
// Still, eventually that's going to cause a bit of a memory leak, so lets just completely clear them out every many minutes.
long now = System.currentTimeMillis();
long delta = now - lastCacheClear;
if (delta > FULL_CACHE_CLEAR_INTERVAL) {
lastCacheClear = now;
dirCache.clear();
uriCache.clear();
}
}
public Iterable<ConfigurationSource> sourcesForJavaFile(URI javaFile, ConfigurationProblemReporter reporter) {
if (javaFile == null) return Collections.emptyList();
cacheClear();
File dir = uriCache.get(javaFile);
if (dir == null) {
URI uri = javaFile.normalize();
if (!uri.isAbsolute()) uri = URI.create("file:" + uri.toString());
try {
File file = new File(uri);
if (!file.exists()) throw new IllegalArgumentException("File does not exist: " + uri);
dir = file.isDirectory() ? file : file.getParentFile();
if (dir != null) uriCache.put(javaFile, dir);
} catch (IllegalArgumentException e) {
// This means that the file as passed is not actually a file at all, and some exotic path system is involved.
// examples: sourcecontrol://jazz stuff, or an actual relative path (uri.isAbsolute() is completely different, that checks presence of schema!),
// or it's eclipse trying to parse a snippet, which has "/Foo.java" as uri.
// At some point it might be worth investigating abstracting away the notion of "I can read lombok.config if present in
// current context, and I can give you may parent context", using ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(javaFile) as basis.
// For now, we just carry on as if there is no lombok.config. (intentional fallthrough)
} catch (Exception e) {
// Especially for eclipse's sake, exceptions here make eclipse borderline unusable, so let's play nice.
ProblemReporter.error("Can't find absolute path of file being compiled: " + javaFile, e);
}
}
if (dir != null) {
try {
return sourcesForDirectory(dir, reporter);
} catch (Exception e) {
// Especially for eclipse's sake, exceptions here make eclipse borderline unusable, so let's play nice.
ProblemReporter.error("Can't resolve config stack for dir: " + dir.getAbsolutePath(), e);
}
}
return Collections.emptyList();
}
public Iterable<ConfigurationSource> sourcesForDirectory(URI directory, ConfigurationProblemReporter reporter) {
return sourcesForJavaFile(directory, reporter);
}
private Iterable<ConfigurationSource> sourcesForDirectory(final File directory, final ConfigurationProblemReporter reporter) {
return new Iterable<ConfigurationSource>() {
@Override
public Iterator<ConfigurationSource> iterator() {
return new Iterator<ConfigurationSource>() {
File currentDirectory = directory;
ConfigurationSource next;
boolean stopBubbling = false;
@Override
public boolean hasNext() {
if (next != null) return true;
if (stopBubbling) return false;
next = findNext();
return next != null;
}
@Override
public ConfigurationSource next() {
if (!hasNext()) throw new NoSuchElementException();
ConfigurationSource result = next;
next = null;
return result;
}
private ConfigurationSource findNext() {
while (currentDirectory != null && next == null) {
next = getSourceForDirectory(currentDirectory, reporter);
currentDirectory = currentDirectory.getParentFile();
}
if (next != null) {
Result stop = next.resolve(ConfigurationKeys.STOP_BUBBLING);
stopBubbling = (stop != null && Boolean.TRUE.equals(stop.getValue()));
}
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
ConfigurationSource getSourceForDirectory(File directory, ConfigurationProblemReporter reporter) {
long now = System.currentTimeMillis();
File configFile = new File(directory, LOMBOK_CONFIG_FILENAME);
Content content = ensureContent(directory);
synchronized (content) {
if (content.lastChecked != NEVER_CHECKED && now - content.lastChecked < RECHECK_FILESYSTEM) {
return content.source;
}
content.lastChecked = now;
long previouslyModified = content.lastModified;
content.lastModified = getLastModifiedOrMissing(configFile);
if (content.lastModified != previouslyModified) content.source = content.lastModified == MISSING ? null : parse(configFile, reporter);
return content.source;
}
}
private Content ensureContent(File directory) {
Content content = dirCache.get(directory);
if (content != null) {
return content;
}
dirCache.putIfAbsent(directory, Content.empty());
return dirCache.get(directory);
}
private ConfigurationSource parse(File configFile, ConfigurationProblemReporter reporter) {
String contentDescription = configFile.getAbsolutePath();
try {
return StringConfigurationSource.forString(fileToString(configFile), reporter, contentDescription);
} catch (Exception e) {
reporter.report(contentDescription, "Exception while reading file: " + e.getMessage(), 0, null);
return null;
}
}
private static final ThreadLocal<byte[]> buffers = new ThreadLocal<byte[]>() {
protected byte[] initialValue() {
return new byte[65536];
}
};
static String fileToString(File configFile) throws Exception {
byte[] b = buffers.get();
FileInputStream fis = new FileInputStream(configFile);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (true) {
int r = fis.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
return new String(out.toByteArray(), "UTF-8");
} finally {
fis.close();
}
}
private static final long getLastModifiedOrMissing(File file) {
if (!file.exists() || !file.isFile()) return MISSING;
return file.lastModified();
}
private static class Content {
ConfigurationSource source;
long lastModified;
long lastChecked;
private Content(ConfigurationSource source, long lastModified, long lastChecked) {
this.source = source;
this.lastModified = lastModified;
this.lastChecked = lastChecked;
}
static Content empty() {
return new Content(null, MISSING, NEVER_CHECKED);
}
}
}
|
package de.mrunde.bachelorthesis.instructions;
import de.mrunde.bachelorthesis.basics.Maneuver;
/**
* This is a now instruction.
*
* @author Marius Runde
*/
public class NowInstruction extends Instruction {
/**
* Constructor of the LandmarkInstruction class
*
* @param instruction
* The current instruction
*/
public NowInstruction(Instruction instruction) {
super(instruction.getDecisionPoint(), instruction.getManeuverType());
}
/**
* @return The instruction as a verbal text
*/
public String toString() {
if (Maneuver.isTurnAction(super.getManeuverType())) {
String instruction = super.getManeuver() + " now";
return instruction;
} else {
return null;
}
}
}
|
package org.jdesktop.swingx.renderer;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.JXTree;
import org.jdesktop.swingx.JXList.DelegatingRenderer;
import org.jdesktop.swingx.decorator.AbstractHighlighter;
import org.jdesktop.swingx.decorator.BorderHighlighter;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.CompoundHighlighter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.jdesktop.swingx.decorator.PainterHighlighter;
import org.jdesktop.swingx.decorator.PatternPredicate;
import org.jdesktop.swingx.decorator.HighlightPredicate.TypeHighlightPredicate;
import org.jdesktop.swingx.graphics.GraphicsUtilities;
import org.jdesktop.swingx.painter.ImagePainter;
import org.jdesktop.swingx.painter.AbstractLayoutPainter.HorizontalAlignment;
import org.jdesktop.swingx.search.SearchFactory;
import org.jdesktop.swingx.util.WindowUtils;
/**
* A simple example about how to configure SwingX renderers.
*
* @author Jeanette Winzenburg
*/
public final class SimpleRendererDemo {
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(SimpleRendererDemo.class
.getName());
private String dataSource = "resources/contributors.txt";
private List<Contributor> contributors;
private ListModel listModel;
private TableModel tableModel;
private DefaultMutableTreeNode rootNode;
public SimpleRendererDemo() {
try {
initData();
} catch (IOException e) {
e.printStackTrace();
}
SearchFactory.getInstance().setUseFindBar(true);
}
/**
* Configure the given collection components with the same
* rendering representation.
*
* Note: this method is extracted for emphasis only :-)
*/
private void configureRendering(JXTable table, JXList list, JXTree tree) {
StringValue stringValue = new StringValue() {
public String getString(Object value) {
if (!(value instanceof Contributor)) return TO_STRING.getString(value);
Contributor contributor = (Contributor) value;
return contributor.lastName + ", " + contributor.firstName;
}
};
table.setDefaultRenderer(Contributor.class, new DefaultTableRenderer(stringValue));
list.setCellRenderer(new DefaultListRenderer(stringValue));
tree.setCellRenderer(new DefaultTreeRenderer(stringValue));
}
private void configureHighlighting(JXTable table, JXList list, JXTree tree) {
CompoundHighlighter stars = new CompoundHighlighter(
new TypeHighlightPredicate(Contributor.class));
stars.addHighlighter(new BorderHighlighter(BorderFactory.createEmptyBorder(0, 20, 0, 0)));
stars.addHighlighter(getRangeHighlighter("silver-star.gif", 50, 80));
stars.addHighlighter(getRangeHighlighter("gold-star.gif", 80, 100));
list.addHighlighter(stars);
// choose a random first name to highlight
int rndIndex = new Double(Math.random() * contributors.size()).intValue();
String match = contributors.get(rndIndex).firstName;
System.out.println(match);
HighlightPredicate predicate = new PatternPredicate(Pattern.compile(match), 0);
Highlighter foreground = new ColorHighlighter(predicate,
HighlighterFactory.NOTEPAD, Color.MAGENTA);
table.addHighlighter(foreground);
list.addHighlighter(foreground);
tree.addHighlighter(foreground);
}
private PainterHighlighter getRangeHighlighter(String gifName, int start,
int end) {
HighlightPredicate meritPredicate = getRangePredicate(start, end);
ImagePainter bronze = getImagePainter(gifName);
PainterHighlighter painterHighlighter = new PainterHighlighter(meritPredicate, bronze);
return painterHighlighter;
}
private HighlightPredicate getRangePredicate(final int start, final int end) {
HighlightPredicate meritPredicate = new HighlightPredicate() {
public boolean isHighlighted(Component renderer,
ComponentAdapter adapter) {
int merit = ((Contributor) adapter.getValue()).merits;
return (merit >= start) && (merit < end);
}
};
return meritPredicate;
}
/**
* Configures the components after the meta-data are set. In this simple example,
* it's equivalent to having set the models.
*
* @param table
*/
private void configureComponents(JXTable table, JXList list, JXTree tree) {
table.setColumnControlVisible(true);
table.getColumnExt(1).setToolTipText("Randomly generated - run again if you are disatisfied");
table.packColumn(1, 10);
table.getColumnExt(1).setMaxWidth(table.getColumnExt(1).getPreferredWidth());
}
/**
* @return the component to show.
*/
private Component createContent() {
// create
JXTable table = new JXTable();
JXList list = new JXList();
JXTree tree = new JXTree();
// add
table.setModel(tableModel);
list.setModel(listModel);
tree.setModel(new DefaultTreeModel(rootNode));
// configure
configureRendering(table, list, tree);
configureHighlighting(table, list, tree);
configureComponents(table, list, tree);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("JXTable", new JScrollPane(table));
JSplitPane splitPane = new JSplitPane();
splitPane.setLeftComponent(new JScrollPane(list));
splitPane.setRightComponent(new JScrollPane(tree));
// splitPane.setDividerLocation(250);
tabbedPane.addTab("JXList/JXTree", splitPane);
// testing black/white list with bullets (from java1_2007)
JXList bulletedList = new JXList(listModel);
configureList(bulletedList, ((DelegatingRenderer) list.getCellRenderer()).getDelegateRenderer());
tabbedPane.add("Black List", new JScrollPane(bulletedList));
return tabbedPane;
}
/**
* @param listCellRenderer
* @param bulletedList
*/
private void configureList(JXList list, ListCellRenderer renderer) {
list.setBackground(Color.BLACK);
list.setLayoutOrientation(JXList.HORIZONTAL_WRAP);
list.setVisibleRowCount(0);
list.setCellRenderer(renderer);
list.addHighlighter(new ColorHighlighter(null, Color.WHITE));
Highlighter hl = new AbstractHighlighter() {
@Override
protected Component doHighlight(Component component,
ComponentAdapter adapter) {
((JLabel) component).setText("\u2022 " + ((JLabel) component).getText());
return component;
}
@Override
protected boolean canHighlight(Component component,
ComponentAdapter adapter) {
return component instanceof JLabel;
}
};
list.addHighlighter(hl);
}
/**
* @param string
* @return
*/
private ImagePainter getImagePainter(String string) {
ImagePainter imagePainter = null;
BufferedImage image = null;
try {
image = ImageIO.read(getClass()
.getResource("resources/" + string));
BufferedImage mod =
GraphicsUtilities.createCompatibleTranslucentImage(
image.getWidth(),
image.getHeight());
Graphics2D g = mod.createGraphics();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
g.dispose();
imagePainter = new ImagePainter(mod);
imagePainter.setHorizontalAlignment(HorizontalAlignment.LEFT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imagePainter;
}
/**
* Create and fill a list of contributors from a resource and
* wrap view models around.
* @throws IOException
*
*/
private void initData() throws IOException {
contributors = new ArrayList<Contributor>();
// fill the list from the resources
readDataSource(contributors);
// wrap a listModel around
listModel = new AbstractListModel() {
public Object getElementAt(int index) {
if (index == 0) {
return "-- Contributors --";
}
return contributors.get(index - 1);
}
public int getSize() {
return contributors.size() + 1;
}
};
// wrap a TableModel around
tableModel = new AbstractTableModel() {
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return contributors.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return contributors.get(rowIndex);
case 1:
return contributors.get(rowIndex).merits;
}
return null;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Contributor.class;
case 1:
return Number.class;
}
return super.getColumnClass(columnIndex);
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "Contributor";
case 1:
return "Merits";
}
return super.getColumnName(column);
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
};
// fill DefaultTreeNodes with the elements
rootNode = new DefaultMutableTreeNode("Contributors");
for (int i = 0; i < contributors.size(); i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(contributors.get(i));
rootNode.add(node);
}
}
private void readDataSource(List<Contributor> list) throws IOException {
InputStream is = getClass().getResourceAsStream(dataSource);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
try {
while ((line = reader.readLine()) != null) {
list.add(new Contributor(line));
}
} finally {
// do our best to close
reader.close();
}
}
public static class Contributor implements Comparable {
private String firstName;
private String lastName;
@SuppressWarnings("unused")
private String userID;
private int merits;
public Contributor(String rawData) {
setData(rawData);
merits = new Double(Math.random() * 100).intValue();
}
/**
* @param rawData
*/
private void setData(String rawData) {
if (rawData == null) {
lastName = " <unknown> ";
return;
}
StringTokenizer tokenizer = new StringTokenizer(rawData);
try {
firstName = tokenizer.nextToken();
lastName = tokenizer.nextToken();
userID = tokenizer.nextToken();
} catch (Exception ex) {
// don't care ...
}
}
public int compareTo(Object o) {
if (!(o instanceof Contributor)) return -1;
return lastName.compareTo(((Contributor) o).lastName);
}
}
public static void main(String[] args) {
// initLF();
final JXFrame frame = new JXFrame("SwingX :: Simple Renderer Demo", true);
frame.add(new SimpleRendererDemo().createContent());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.pack();
frame.setSize(600, 400);
frame.setLocation(WindowUtils.getPointForCentering(frame));
frame.setVisible(true);
}
});
}
private static void initLF() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package dr.inference.operators;
import java.util.ArrayList;
import java.util.List;
import dr.inference.model.Bounds;
import dr.inference.model.Parameter;
import dr.inferencexml.operators.RandomWalkOperatorParser;
import dr.math.MathUtils;
import dr.util.Transform;
/**
* A random walk operator that takes a (list of) parameter(s) and corresponding transformations.
*
* @author Guy Baele
*/
public class TransformedRandomWalkOperator extends AbstractCoercableOperator {
private Parameter parameter = null;
private final Transform[] transformations;
private double windowSize = 0.01;
private List<Integer> updateMap = null;
private int updateMapSize;
private final BoundaryCondition condition;
private final Double lowerOperatorBound;
private final Double upperOperatorBound;
public enum BoundaryCondition {
reflecting,
absorbing
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, double windowSize, BoundaryCondition bc, double weight, CoercionMode mode) {
this(parameter, transformations, null, windowSize, bc, weight, mode);
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
double weight, CoercionMode mode) {
this(parameter, transformations, updateIndex, windowSize, bc, weight, mode, null, null);
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
double weight, CoercionMode mode, Double lowerOperatorBound, Double upperOperatorBound) {
super(mode);
this.parameter = parameter;
this.transformations = transformations;
this.windowSize = windowSize;
this.condition = bc;
setWeight(weight);
if (updateIndex != null) {
updateMap = new ArrayList<Integer>();
for (int i = 0; i < updateIndex.getDimension(); i++) {
if (updateIndex.getParameterValue(i) == 1.0)
updateMap.add(i);
}
updateMapSize=updateMap.size();
}
this.lowerOperatorBound = lowerOperatorBound;
this.upperOperatorBound = upperOperatorBound;
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return parameter;
}
public final double getWindowSize() {
return windowSize;
}
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
//store MH-ratio in logq
double logJacobian = 0.0;
// a random dimension to perturb
int index;
if (updateMap == null) {
index = MathUtils.nextInt(parameter.getDimension());
} else {
index = updateMap.get(MathUtils.nextInt(updateMapSize));
}
//System.err.println("index: " + index);
// a random point around old value within windowSize * 2
double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
//System.err.println("draw: " + draw);
//transform parameter values first
double[] x = parameter.getParameterValues();
int dim = parameter.getDimension();
//System.err.println("parameter " + index + ": " + x[index]);
double[] transformedX = new double[dim];
for (int i = 0; i < dim; i++) {
transformedX[i] = transformations[i].transform(x[i]);
}
//System.err.println("transformed parameter " + index + ": " + transformedX[index]);
//double newValue = parameter.getParameterValue(index) + draw;
double newValue = transformedX[index] + draw;
//System.err.println("new value: " + newValue);
final Bounds<Double> bounds = parameter.getBounds();
final double lower = (lowerOperatorBound == null ? bounds.getLowerLimit(index) : Math.max(bounds.getLowerLimit(index), lowerOperatorBound));
final double upper = (upperOperatorBound == null ? bounds.getUpperLimit(index) : Math.min(bounds.getUpperLimit(index), upperOperatorBound));
if (condition == BoundaryCondition.reflecting) {
newValue = reflectValue(newValue, lower, upper);
} else if (newValue < lower || newValue > upper) {
throw new OperatorFailedException("proposed value outside boundaries");
}
//parameter.setParameterValue(index, newValue);
parameter.setParameterValue(index, transformations[index].inverse(newValue));
//System.err.println("set parameter to: " + parameter.getValue(index));
//this should be correct
//logJacobian += transformations[index].getLogJacobian(parameter.getParameterValue(index)) - transformations[index].getLogJacobian(x[index]);
logJacobian += transformations[index].getLogJacobian(x[index]) - transformations[index].getLogJacobian(parameter.getParameterValue(index));
//return 0.0;
return logJacobian;
}
public double reflectValue(double value, double lower, double upper) {
double newValue = value;
if (value < lower) {
if (Double.isInfinite(upper)) {
// we are only going to reflect once as the upper bound is at infinity...
newValue = lower + (lower - value);
} else {
double remainder = lower - value;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = lower + remainder;
// odd reflections
} else {
newValue = upper - remainder;
}
}
} else if (value > upper) {
if (Double.isInfinite(lower)) {
// we are only going to reflect once as the lower bound is at -infinity...
newValue = upper - (newValue - upper);
} else {
double remainder = value - upper;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = upper - remainder;
// odd reflections
} else {
newValue = lower + remainder;
}
}
}
return newValue;
}
public double reflectValueLoop(double value, double lower, double upper) {
double newValue = value;
while (newValue < lower || newValue > upper) {
if (newValue < lower) {
newValue = lower + (lower - newValue);
}
if (newValue > upper) {
newValue = upper - (newValue - upper);
}
}
return newValue;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return parameter.getParameterName();
}
public double getCoercableParameter() {
return Math.log(windowSize);
}
public void setCoercableParameter(double value) {
windowSize = Math.exp(value);
}
public double getRawParameter() {
return windowSize;
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
double ws = OperatorUtils.optimizeWindowSize(windowSize, parameter.getParameterValue(0) * 2.0, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try decreasing windowSize to about " + ws;
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try increasing windowSize to about " + ws;
} else return "";
}
public String toString() {
return RandomWalkOperatorParser.RANDOM_WALK_OPERATOR + "(" + parameter.getParameterName() + ", " + windowSize + ", " + getWeight() + ")";
}
}
|
package edu.bath.transitivityutils;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A (transitive, reflexive) binary relation.
*
* @author Andreou Dimitris, email: jim.andreou (at) gmail.com
*/
class DefaultTransitiveRelation<E> implements TransitiveRelation<E>, Serializable {
private final BenderList<E> magicList = BenderList.create();
private final Map<E, Node<E>> nodeMap = Maps.newHashMap();
private final SetMultimap<Node<E>, Node<E>> directRelationships = HashMultimap.create();
private final Navigator<E> navigator = new DirectNavigator();
private static final long serialVersionUID = -4031451040065579682L;
DefaultTransitiveRelation() { }
public void relate(E subjectValue, E objectValue) {
if (Objects.equal(subjectValue, objectValue)) {
return;
}
Node<E> subject = nodeMap.get(subjectValue);
Node<E> object = createObjectNode(objectValue, subject);
if (subject != null) {
if (!areNodesRelated(subject, object)) {
propagate(subject, object);
}
} else {
OrderList.Node<E> anchor = object.post.previous();
subject = new Node<E>(
anchor = magicList.addAfter(anchor, subjectValue),
magicList.addAfter(anchor, null)); //we don't need the value in post nodes, we get it from pre nodes
nodeMap.put(subjectValue, subject);
}
directRelationships.put(subject, object);
}
private Node<E> createObjectNode(E value, Node<E> subject) {
Node<E> node = nodeMap.get(value);
if (node == null) {
if (subject != null && !directRelationships.containsKey(subject)) {
//subject.pre, post is embedded in another node, so it is possible
//to surround it by the new node
node = new Node<E>(
magicList.addAfter(subject.pre.previous(), value),
magicList.addAfter(subject.post, null)); //we don't need the value in post nodes, we get it from pre nodes
} else {
node = new Node<E>(
magicList.addAfter(magicList.base().previous(), value),
magicList.addAfter(magicList.base().previous(), null)); //we don't need the value in post nodes, we get it from pre nodes
}
nodeMap.put(value, node);
}
return node;
}
private void propagate(Node<E> subject, Node<E> object) {
Iterator<Node<E>> toVisit = Iterators.singletonIterator(object);
while (toVisit.hasNext()) {
Node<E> next = toVisit.next();
if (!next.contains(subject)) {
next.intervalSet.addIntervals(subject.intervalSet);
toVisit = Iterators.concat(directRelationships.get(next).iterator(), toVisit);
}
}
}
public boolean areRelated(E subjectValue, E objectValue) {
if (Objects.equal(subjectValue, objectValue)) return true;
Node<E> subject = nodeMap.get(subjectValue);
if (subject == null) return false;
Node<E> object = nodeMap.get(objectValue);
if (object == null) return false;
return areNodesRelated(subject, object);
}
private boolean areNodesRelated(Node<E> subject, Node<E> object) {
return object.contains(subject);
}
public Navigator<E> direct() {
return navigator;
}
@Override
public String toString() {
return nodeMap.toString();
}
private static class Node<E> {
final OrderList.Node<E> pre;
final OrderList.Node<E> post;
final MergingIntervalSet intervalSet = new MergingIntervalSet();
Node(OrderList.Node<E> pre, OrderList.Node<E> post) {
this.pre = pre;
this.post = post;
intervalSet.addInterval(pre, post);
}
boolean contains(Node<E> other) {
return intervalSet.contains(other.pre);
}
@Override
public String toString() {
return intervalSet.toString();
}
}
private class DirectNavigator implements Navigator<E> {
private final Function<Node<E>, E> nodeToValue = new Function<Node<E>, E>() {
public E apply(Node<E> node) {
return node.pre.get();
}
};
public Set<E> related(E subjectValue) {
Node<E> subject = nodeMap.get(subjectValue);
if (subject == null) return Collections.emptySet();
final Set<Node<E>> set = directRelationships.get(subject);
return transformSet(set, nodeToValue);
}
public Set<E> domain() {
return transformSet(directRelationships.keySet(), nodeToValue);
}
}
private Object writeReplace() {
return new SerializationProxy<E>(navigator);
}
private static class SerializationProxy<E> implements Serializable {
transient Navigator<E> navigator;
private static final long serialVersionUID = 711361401943593391L;
SerializationProxy() { }
SerializationProxy(Navigator<E> navigator) {
this.navigator = navigator;
}
//Writing the number of domain elements, then iterate over the domain and write:
// - the domain element
// - the number of related (to that) elements
// - the related elements themselves
private void writeObject(ObjectOutputStream s) throws IOException {
Set<E> domain = navigator.domain();
s.writeInt(domain.size());
for (E subject : domain) {
s.writeObject(subject);
Set<E> related = navigator.related(subject);
s.writeInt(related.size());
for (E object : related) {
s.writeObject(object);
}
}
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
SetMultimap<Object, Object> mm = HashMultimap.create();
int domainCount = s.readInt();
for (int i = 0; i < domainCount; i++) {
Object subject = s.readObject();
Collection<Object> objects = mm.get(subject);
int objectCount = s.readInt();
for (int j = 0; j < objectCount; j++) {
Object object = s.readObject();
mm.put(object, object);
objects.add(object);
}
}
navigator = (Navigator)Navigators.forMultimap(mm);
}
private Object readResolve() {
DefaultTransitiveRelation<E> rel = new DefaultTransitiveRelation<E>();
for (E subject : navigator.domain()) {
for (E object : navigator.related(subject)) {
rel.relate(subject, object);
}
}
return rel;
}
}
static <A, B> Set<B> transformSet(final Set<A> set, final Function<? super A, ? extends B> transformer) {
return new AbstractSet<B>() {
@Override
public Iterator<B> iterator() {
return Iterators.transform(set.iterator(), transformer);
}
@Override
public int size() {
return set.size();
}
};
}
}
|
package edu.iu.grid.oim.model.db;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.util.encoders.Base64;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.lib.Footprints;
import edu.iu.grid.oim.lib.StaticConfig;
import edu.iu.grid.oim.lib.Footprints.FPTicket;
import edu.iu.grid.oim.lib.StringArray;
import edu.iu.grid.oim.model.CertificateRequestStatus;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.cert.CertificateManager;
import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateBase;
import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateProviderException;
import edu.iu.grid.oim.model.cert.ICertificateSigner.IHostCertificatesCallBack;
import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.DNRecord;
import edu.iu.grid.oim.model.db.record.GridAdminRecord;
import edu.iu.grid.oim.model.db.record.VORecord;
import edu.iu.grid.oim.model.exceptions.CertificateRequestException;
import edu.iu.grid.oim.view.divrep.form.validator.CNValidator;
public class CertificateRequestHostModel extends CertificateRequestModelBase<CertificateRequestHostRecord> {
static Logger log = Logger.getLogger(CertificateRequestHostModel.class);
public CertificateRequestHostModel(UserContext _context) {
super(_context, "certificate_request_host");
}
//NO-AC
public CertificateRequestHostRecord get(int id) throws SQLException {
CertificateRequestHostRecord rec = null;
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE id = " + id)) {
rs = stmt.getResultSet();
if(rs.next()) {
rec = new CertificateRequestHostRecord(rs);
}
}
stmt.close();
conn.close();
return rec;
}
//return requests that I have submitted
public ArrayList<CertificateRequestHostRecord> getISubmitted(Integer id) throws SQLException {
ArrayList<CertificateRequestHostRecord> ret = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE requester_contact_id = " + id);
rs = stmt.getResultSet();
while(rs.next()) {
ret.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return ret;
}
//return requests that I am GA
public ArrayList<CertificateRequestHostRecord> getIApprove(Integer id) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
//list all domains that user is gridadmin of
StringBuffer cond = new StringBuffer();
HashSet<Integer> vos = new HashSet<Integer>();
GridAdminModel model = new GridAdminModel(context);
try {
for(GridAdminRecord grec : model.getGridAdminsByContactID(id)) {
if(cond.length() != 0) {
cond.append(" OR ");
}
cond.append("cns LIKE '%"+StringEscapeUtils.escapeSql(grec.domain)+"</String>%'");
vos.add(grec.vo_id);
}
} catch (SQLException e1) {
log.error("Failed to lookup GridAdmin domains", e1);
}
String vos_list = "";
for(Integer vo : vos) {
if(vos_list.length() != 0) {
vos_list += ",";
}
vos_list += vo;
}
if(cond.length() != 0) {
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
System.out.println("Searching SQL: SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')");
stmt.execute("SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
}
return recs;
}
//NO-AC
//issue all requested certs and store it back to DB
//you can monitor request status by checking returned Certificate[]
public void startissue(final CertificateRequestHostRecord rec) throws CertificateRequestException {
// mark the request as "issuing.."
try {
rec.status = CertificateRequestStatus.ISSUING;
context.setComment("Starting to issue certificates.");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate request status for request:" + rec.id);
throw new CertificateRequestException("Failed to update certificate request status");
};
//reconstruct cert array from db
final StringArray csrs = new StringArray(rec.csrs);
final StringArray serial_ids = new StringArray(rec.cert_serial_ids);
final StringArray pkcs7s = new StringArray(rec.cert_pkcs7);
final StringArray certificates = new StringArray(rec.cert_certificate);
final StringArray intermediates = new StringArray(rec.cert_intermediate);
final StringArray statuses = new StringArray(rec.cert_statuses);
final CertificateBase[] certs = new CertificateBase[csrs.length()];
for(int c = 0; c < csrs.length(); ++c) {
certs[c] = new CertificateBase();
certs[c].csr = csrs.get(c);
certs[c].serial = serial_ids.get(c);
certs[c].certificate = certificates.get(c);
certs[c].intermediate = intermediates.get(c);
certs[c].pkcs7 = pkcs7s.get(c);
}
new Thread(new Runnable() {
public void failed(String message, Throwable e) {
log.error(message, e);
rec.status = CertificateRequestStatus.FAILED;
rec.status_note = message + " :: " + e.getMessage();
try {
context.setComment(message + " :: " + e.getMessage());
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e1) {
log.error("Failed to update request status while processing failed condition :" + message, e1);
}
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Failed to issue certificate.\n\n";
ticket.description += message+"\n\n";
ticket.description += e.getMessage()+"\n\n";
ticket.description += "The alert has been sent to GOC alert for further actions on this issue.";
ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.fail.assignee"));
ticket.nextaction = "GOC developer to investigate";
fp.update(ticket, rec.goc_ticket_id);
}
//should we use Quartz instead?
public void run() {
final CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
try {
//lookup requester contact information
String requester_email = rec.requester_email; //for guest request
if(rec.requester_contact_id != null) {
//for user request
ContactModel cmodel = new ContactModel(context);
ContactRecord requester = cmodel.get(rec.requester_contact_id);
requester_email = requester.primary_email;
}
log.debug("Starting signing process");
cm.signHostCertificates(certs, new IHostCertificatesCallBack() {
//called once all certificates are requested (and approved) - but not yet issued
@Override
public void certificateRequested() {
log.debug("certificateRequested called");
//update certs db contents
try {
for(int c = 0; c < certs.length; ++c) {
CertificateBase cert = certs[c];
serial_ids.set(c, cert.serial); //really just order ID (until the certificate is issued)
statuses.set(c, CertificateRequestStatus.ISSUING);
}
rec.cert_serial_ids = serial_ids.toXML();
rec.cert_statuses = statuses.toXML();
context.setComment("All certificate requests have been sent.");
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate update while monitoring issue progress:" + rec.id);
}
}
//called for each certificate issued
@Override
public void certificateSigned(CertificateBase cert, int idx) {
log.info("host cert issued by digicert: serial_id:" + cert.serial);
log.info("pkcs7:" + cert.pkcs7);
//pull some information from the cert for validation purpose
try {
ArrayList<Certificate> chain = CertificateManager.parsePKCS7(cert.pkcs7);
X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain);
cert.notafter = c0.getNotAfter();
cert.notbefore = c0.getNotBefore();
//do a bit of validation
Calendar today = Calendar.getInstance();
if(Math.abs(today.getTimeInMillis() - cert.notbefore.getTime()) > 1000*3600*24) {
log.warn("Host certificate issued for request "+rec.id+"(idx:"+idx+") has cert_notbefore set too distance from current timestamp");
}
long dayrange = (cert.notafter.getTime() - cert.notbefore.getTime()) / (1000*3600*24);
if(dayrange < 350 || dayrange > 450) {
log.warn("Host certificate issued for request "+rec.id+ "(idx:"+idx+") has invalid range of "+dayrange+" days (too far from 395 days)");
}
//make sure dn starts with correct base
X500Principal dn = c0.getSubjectX500Principal();
String apache_dn = CertificateManager.X500Principal_to_ApacheDN(dn);
if(!apache_dn.startsWith(cm.getHostDNBase())) {
log.error("Host certificate issued for request " + rec.id + "(idx:"+idx+") has DN:"+apache_dn+" which doesn't have an expected DN base: "+cm.getHostDNBase());
}
} catch (CertificateException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
} catch (CMSException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
} catch (IOException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
}
//update status note
try {
statuses.set(idx, CertificateRequestStatus.ISSUED);
rec.cert_statuses = statuses.toXML();
rec.status_note = "Certificate idx:"+idx+" has been issued. Serial Number: " + cert.serial;
context.setComment(rec.status_note);
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate update while monitoring issue progress:" + rec.id);
}
}
}, requester_email);
log.debug("Finishing up issue process");
//update records
int idx = 0;
StringArray cert_certificates = new StringArray(rec.cert_certificate);
StringArray cert_intermediates = new StringArray(rec.cert_intermediate);
StringArray cert_pkcs7s = new StringArray(rec.cert_pkcs7);
StringArray cert_serial_ids = new StringArray(rec.cert_serial_ids);
for(CertificateBase cert : certs) {
cert_certificates.set(idx, cert.certificate);
rec.cert_certificate = cert_certificates.toXML();
cert_intermediates.set(idx, cert.intermediate);
rec.cert_intermediate = cert_intermediates.toXML();
cert_pkcs7s.set(idx, cert.pkcs7);
rec.cert_pkcs7 = cert_pkcs7s.toXML();
cert_serial_ids.set(idx, cert.serial);
rec.cert_serial_ids = cert_serial_ids.toXML();
++idx;
}
//set cert expiriation dates using the first certificate issued (out of many *requests*)
CertificateBase cert = certs[0];
rec.cert_notafter = cert.notafter;
rec.cert_notbefore = cert.notbefore;
//log.debug("Updating status");
//update status
try {
rec.status = CertificateRequestStatus.ISSUED;
context.setComment("All ceritificates has been issued.");
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
throw new CertificateRequestException("Failed to update status for certificate request: " + rec.id);
}
log.debug("Updating ticket");
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has issued certificate. Resolving this ticket.";
} else {
ticket.description = "Someone with IP address: " + context.getRemoteAddr() + " has issued certificate. Resolving this ticket.";
}
ticket.status = "Resolved";
//suppressing notification if submitter is GA
ArrayList<ContactRecord> gas = findGridAdmin(rec);
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
if(submitter_is_ga) {
ticket.mail_suppression_assignees = true;
ticket.mail_suppression_submitter = true;
ticket.mail_suppression_ccs = true;
}
fp.update(ticket, rec.goc_ticket_id);
} catch (CertificateProviderException e) {
failed("Failed to sign certificate -- CertificateProviderException ", e);
} catch (SQLException e) {
failed("Failed to sign certificate -- most likely couldn't lookup requester contact info", e);
} catch(Exception e) {
failed("Failed to sign certificate -- unhandled", e);
}
}
}).start();
}
//NO-AC
//return true if success
public void approve(CertificateRequestHostRecord rec) throws CertificateRequestException
{
//get number of certificate requested for this request
String [] cns = rec.getCNs();
int count = cns.length;
//check quota
CertificateQuotaModel quota = new CertificateQuotaModel(context);
if(!quota.canApproveHostCert(count)) {
throw new CertificateRequestException("You will exceed your host certificate quota.");
}
rec.status = CertificateRequestStatus.APPROVED;
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
quota.incrementHostCertApproval(count);
} catch (SQLException e) {
log.error("Failed to approve host certificate request: " + rec.id);
throw new CertificateRequestException("Failed to update certificate request record");
}
//find if requester is ga
ArrayList<ContactRecord> gas = findGridAdmin(rec);
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
if(submitter_is_ga) {
ticket.description = rec.requester_name + " has approved this host certificate request.\n\n";
ticket.mail_suppression_assignees = false; //Per Von/Alain's request, we will send notification to Alain when request is approved
ticket.mail_suppression_ccs = true;
ticket.mail_suppression_submitter = true;
} else {
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificate request has been approved. \n\n";
}
ticket.description += "To retrieve the certificate please visit " + getTicketUrl(rec.id) + " and click on Issue Certificate button.\n\n";
if(StaticConfig.isDebug()) {
ticket.description += "Or if you are using the command-line: osg-cert-retrieve -T -i "+rec.id+"\n\n";
} else {
ticket.description += "Or if you are using the command-line: osg-cert-retrieve -i "+rec.id+"\n\n";
}
ticket.nextaction = "Requester to download certificate";
Calendar nad = Calendar.getInstance();
nad.add(Calendar.DATE, 7);
ticket.nad = nad.getTime();
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC (for authenticated user)
//return request record if successful, otherwise null
public CertificateRequestHostRecord requestAsUser(
ArrayList<String> csrs,
ContactRecord requester,
String request_comment,
String[] request_ccs,
Integer approver_vo_id) throws CertificateRequestException
{
CertificateRequestHostRecord rec = new CertificateRequestHostRecord();
//Date current = new Date();
rec.requester_contact_id = requester.id;
rec.requester_name = requester.name;
rec.approver_vo_id = approver_vo_id;
rec.requester_email = requester.primary_email;
//rec.requester_phone = requester.primary_phone;
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.name = requester.name;
ticket.email = requester.primary_email;
ticket.phone = requester.primary_phone;
ticket.title = "Host Certificate Request by " + requester.name + "(OIM user)";
ticket.metadata.put("SUBMITTER_NAME", requester.name);
if(request_ccs != null) {
for(String cc : request_ccs) {
ticket.ccs.add(cc);
}
}
log.debug("submitting request as user");
return request(csrs, rec, ticket, request_comment);
}
//NO-AC (for guest user)
//return request record if successful, otherwise null
public CertificateRequestHostRecord requestAsGuest(
ArrayList<String> csrs,
String requester_name,
String requester_email,
String requester_phone,
String request_comment,
String[] request_ccs,
Integer approver_vo_id) throws CertificateRequestException
{
CertificateRequestHostRecord rec = new CertificateRequestHostRecord();
//Date current = new Date();
rec.approver_vo_id = approver_vo_id;
rec.requester_name = requester_name;
rec.requester_email = requester_email;
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.name = requester_name;
ticket.email = requester_email;
ticket.phone = requester_phone;
ticket.title = "Host Certificate Request by " + requester_name + "(Guest)";
ticket.metadata.put("SUBMITTER_NAME", requester_name);
if(request_ccs != null) {
for(String cc : request_ccs) {
ticket.ccs.add(cc);
}
}
return request(csrs, rec, ticket, request_comment);
}
private String getTicketUrl(Integer request_id) {
String base;
//this is not an exactly correct assumption, but it should be good enough
if(StaticConfig.isDebug()) {
base = "https://oim-itb.grid.iu.edu/oim/";
} else {
base = "https://oim.grid.iu.edu/oim/";
}
return base + "certificatehost?id=" + request_id;
}
//NO-AC
//return request record if successful, otherwise null (guest interface)
private CertificateRequestHostRecord request(
ArrayList<String> csrs,
CertificateRequestHostRecord rec,
FPTicket ticket,
String request_comment) throws CertificateRequestException
{
//log.debug("request");
Date current = new Date();
rec.request_time = new Timestamp(current.getTime());
rec.status = CertificateRequestStatus.REQUESTED;
//set all host cert status to REQUESTED
StringArray statuses = new StringArray(csrs.size());
for(int c = 0; c < csrs.size(); ++c) {
statuses.set(c, CertificateRequestStatus.REQUESTED);
}
rec.cert_statuses = statuses.toXML();
if(request_comment != null) {
rec.status_note = request_comment;
context.setComment(request_comment);
}
//store CSRs / CNs to record
StringArray csrs_sa = new StringArray(csrs.size());
StringArray cns_sa = new StringArray(csrs.size());
int idx = 0;
CNValidator cnv = new CNValidator(CNValidator.Type.HOST);
for(String csr_string : csrs) {
log.debug("processing csr: " + csr_string);
String cn;
ArrayList<String> sans;
try {
PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string);
cn = CertificateManager.pullCNFromCSR(csr);
sans = CertificateManager.pullSANFromCSR(csr);
//validate CN
//if(!cn.matches("^([-0-9a-zA-Z\\.]*/)?[-0-9a-zA-Z\\.]*$")) { //OSGPKI-255
// throw new CertificateRequestException("CN structure is invalid, or contains invalid characters.");
if(!cnv.isValid(cn)) {
throw new CertificateRequestException("CN specified is invalid: " + cn + " .. " + cnv.getErrorMessage());
}
for(String san : sans) {
if(!cnv.isValid(san)) {
throw new CertificateRequestException("SAN specified is invalid: " + san + " .. " + cnv.getErrorMessage());
}
}
//check private key strength
SubjectPublicKeyInfo pkinfo = csr.getSubjectPublicKeyInfo();
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkinfo);
int keysize = rsa.getModulus().bitLength();
if(keysize < 2048) {
throw new CertificateRequestException("Please use RSA keysize greater than or equal to 2048 bits.");
}
cns_sa.set(idx, cn);
} catch (IOException e) {
log.error("Failed to base64 decode CSR", e);
throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e);
} catch (NullPointerException e) {
log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e);
throw new CertificateRequestException("Failed to base64 decode CSR", e);
}
csrs_sa.set(idx++, csr_string);
}
rec.csrs = csrs_sa.toXML();
rec.cns = cns_sa.toXML();
StringArray empty = new StringArray(csrs.size());
String empty_xml = empty.toXML();
rec.cert_certificate = empty_xml;
rec.cert_intermediate = empty_xml;
rec.cert_pkcs7 = empty_xml;
rec.cert_serial_ids = empty_xml;
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
//find if submitter is ga
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
//now submit - after this, we are commited.
Integer request_id = super.insert(rec);
if(submitter_is_ga) {
ticket.description = "Host certificate request has been submitted by a GridAdmin.\n\n";
ticket.mail_suppression_assignees = true;
ticket.mail_suppression_submitter = true;
ticket.mail_suppression_ccs = true;
} else {
ticket.description = "Dear GridAdmin; ";
for(ContactRecord ga : gas) {
ticket.description += ga.name + ", ";
ticket.ccs.add(ga.primary_email);
}
ticket.description += "\n\n";
ticket.description += "Host certificate request has been submitted. ";
ticket.description += "Please determine this request's authenticity, and approve / disapprove at " + getTicketUrl(request_id) + "\n\n";
}
ticket.description += "CNs requested:\n";
for(String cn : cns_sa.getAll()) {
ticket.description += "/CN=" + cn + "\n";
}
Authorization auth = context.getAuthorization();
ticket.description += "Requester IP:" + context.getRemoteAddr() + "\n";
if(auth.isUser()) {
ContactRecord user = auth.getContact();
ticket.description += "Submitter is OIM authenticated with DN:" + auth.getUserDN() + "\n";
}
if(request_comment != null) {
ticket.description += "Requester Comment: "+request_comment;
}
ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.host.assignee"));
ticket.nextaction = "GridAdmin to verify requester";
Calendar nad = Calendar.getInstance();
nad.add(Calendar.DATE, 7);
ticket.nad = nad.getTime();
//set metadata
ticket.metadata.put("SUBMITTED_VIA", "OIM/CertManager(host)");
if(auth.isUser()) {
ticket.metadata.put("SUBMITTER_DN", auth.getUserDN());
}
//all ready to submit request
Footprints fp = new Footprints(context);
log.debug("opening footprints ticket");
String ticket_id = fp.open(ticket);
log.debug("update request record with goc ticket id");
rec.goc_ticket_id = ticket_id;
context.setComment("Opened GOC Ticket " + ticket_id);
super.update(get(request_id), rec);
log.debug("request updated");
} catch (SQLException e) {
throw new CertificateRequestException("Failed to insert host certificate request record", e);
}
log.debug("returnign rec");
return rec;
}
//find gridadmin who should process the request - identify domain from csrs
//if there are more than 1 vos group, then user must specify approver_vo_id
// * it could be null for gridadmin with only 1 vo group, and approver_vo_id will be reset to the correct VO ID
public ArrayList<ContactRecord> findGridAdmin(CertificateRequestHostRecord rec) throws CertificateRequestException
{
GridAdminModel gamodel = new GridAdminModel(context);
String gridadmin_domain = null;
int idx = 0;
ArrayList<String> domains = new ArrayList<String>();
String[] csrs = rec.getCSRs();
if(csrs.length == 0) {
throw new CertificateRequestException("No CSR");
}
for(String csr_string : csrs) {
//parse CSR and pull CN
String cn;
ArrayList<String> sans;
try {
PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string);
cn = CertificateManager.pullCNFromCSR(csr);
sans = CertificateManager.pullSANFromCSR(csr);
} catch (IOException e) {
log.error("Failed to base64 decode CSR", e);
throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e);
} catch (NullPointerException e) {
log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e);
throw new CertificateRequestException("Failed to base64 decode CSR", e);
} catch(Exception e) {
throw new CertificateRequestException("Failed to decode CSR", e);
}
//lookup registered gridadmin domain
String domain = null;
try {
domain = gamodel.getDomainByFQDN(cn);
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup GridAdmin to approve host:" + cn, e);
}
if(domain == null) {
throw new CertificateRequestException("The hostname you have provided in the CSR/CN=" + cn + " does not match any domain OIM is currently configured to issue certificates for.\n\nPlease double check the CN you have specified. If you'd like to be a GridAdmin for this domain, please open GOC Ticket at https://ticket.grid.iu.edu ");
}
//make sure same set of gridadmin approves all host
if(gridadmin_domain == null) {
gridadmin_domain = domain;
log.debug("first domain is " + gridadmin_domain);
} else {
if(!gridadmin_domain.equals(domain)) {
//throw new CertificateRequestException("All host certificates must be approved by the same set of gridadmins. Different for " + cn);
domains.add(domain);
log.debug("Next domain is " + domain);
}
}
//make sure SANs are also approved by the same domain or share a common GridAdmin
for(String san : sans) {
try {
String san_domain = gamodel.getDomainByFQDN(san);
if(!gridadmin_domain.equals(san_domain)) {
//throw new CertificateRequestException("All SAN must be approved by the same set of gridadmins. Different for " + san);
domains.add(san_domain);
log.debug("san domain is " + san_domain);
}
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup GridAdmin for SAN:" + san, e);
}
}
}
try {
//for first domain in the list, add the grid admins. For each additional domain remove all non-matching grid-admins
ArrayList<ContactRecord> gas = new ArrayList<ContactRecord> ();
HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain);
if(groups.size() == 0) {
throw new CertificateRequestException("No gridadmin exists for domain: " + gridadmin_domain);
}
if(groups.size() == 1 && rec.approver_vo_id == null) {
//set approver_vo_id to the one and only one vogroup's vo id
Iterator<VORecord> it = groups.keySet().iterator();
VORecord vorec = it.next();
rec.approver_vo_id = vorec.id;
}
String vonames = "";
for(VORecord vo : groups.keySet()) {
vonames += vo.name + ", "; //just in case we might need to report error message later
if(vo.id.equals(rec.approver_vo_id)) {
log.debug("found a match.. return the list " + vo.name);
gas.addAll(GAsToContacts(groups.get(vo)));
}
}
for (String domain : domains) {
//HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain);
log.debug("looking up approvers for domain " + domain);
groups = gamodel.getByDomainGroupedByVO(domain);
if(groups.size() == 0) {
throw new CertificateRequestException("No gridadmin exists for domain: " + domain);
}
if(groups.size() == 1 && rec.approver_vo_id == null) {
Iterator<VORecord> it = groups.keySet().iterator();
VORecord vorec = it.next();
rec.approver_vo_id = vorec.id;
log.debug("set approver_vo_id to the one and only one vogroup's vo id " + rec.approver_vo_id);
}
vonames = "";
log.debug("For each vo record for " + domain);
int match_id = 0;
for(VORecord vo : groups.keySet()) {
log.debug(vo.name);
vonames += vo.name + ", "; //just in case we might need to report error message later
if(vo.id.equals(rec.approver_vo_id)) {
match_id = vo.id;
log.debug("found an exact match.. return the list " + vo.name);
ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo));
if (newgas.isEmpty()) {
log.debug("no contacts for " + vo.name);
}
ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>();
for(ContactRecord contact: newgas) {
log.debug("checking contact name " + contact.name);
if (gas.contains(contact)) {
sharedgas.add(contact);
log.debug("adding " + contact.name);
}
}
gas = sharedgas;
//return GAsToContacts(gas);
}
}
if (match_id == 0) {
for(VORecord vo : groups.keySet()) {
log.debug(vo.name);
vonames += vo.name + ", "; //just in case we might need to report error message later
//if(vo.id.equals(rec.approver_vo_id)) {
log.debug("matching using the list " + vo.name);
ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo));
if (newgas.isEmpty()) {
log.debug("no contacts for " + vo.name);
}
ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>();
for(ContactRecord contact: newgas) {
log.debug("checking contact name " + contact.name);
if (gas.contains(contact)) {
sharedgas.add(contact);
log.debug("adding " + contact.name);
}
}
gas = sharedgas;
//return GAsToContacts(gas);
}
}
}
if (!gas.isEmpty()) {
return gas;
}
else {
//oops.. didn't find specified vo..
throw new CertificateRequestException("Couldn't find GridAdmin group under specified VO.");
}
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup gridadmin contacts for domain:" + gridadmin_domain, e);
}
}
public ArrayList<ContactRecord> GAsToContacts(ArrayList<GridAdminRecord> gas) throws SQLException {
//convert contact_id to contact record
ArrayList<ContactRecord> contacts = new ArrayList<ContactRecord>();
ContactModel cmodel = new ContactModel(context);
for(GridAdminRecord ga : gas) {
log.debug("adding contact id " + ga.contact_id);
contacts.add(cmodel.get(ga.contact_id));
}
return contacts;
}
//NO-AC
public void requestRevoke(CertificateRequestHostRecord rec) throws CertificateRequestException {
rec.status = CertificateRequestStatus.REVOCATION_REQUESTED;
try {
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to request revocation of host certificate: " + rec.id);
throw new CertificateRequestException("Failed to update request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has requested revocation of this certificate request.";
} else {
ticket.description = "Guest user with IP:" + context.getRemoteAddr() + " has requested revocation of this certificate request.";
}
ticket.description += "\n\nPlease approve / disapprove this request at " + getTicketUrl(rec.id);
ticket.nextaction = "Grid Admin to process request."; //nad will be set to 7 days from today by default
ticket.status = "Engineering"; //I need to reopen resolved ticket.
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
//return true if success
public void cancel(CertificateRequestHostRecord rec) throws CertificateRequestException {
try {
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
rec.status = CertificateRequestStatus.ISSUED;
} else {
rec.status = CertificateRequestStatus.CANCELED;
}
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to cancel host certificate request:" + rec.id);
throw new CertificateRequestException("Failed to cancel request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has canceled this request.\n\n";
} else {
//Guest can still cancel by providing the password used to submit the request.
}
ticket.description += "\n\n> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
public void reject(CertificateRequestHostRecord rec) throws CertificateRequestException {
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED)||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
rec.status = CertificateRequestStatus.ISSUED;
} else {
//all others
rec.status = CertificateRequestStatus.REJECTED;
}
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to reject host certificate request:" + rec.id);
throw new CertificateRequestException("Failed to reject request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has rejected this certificate request.\n\n";
} else {
throw new CertificateRequestException("Guest shouldn't be rejecting request");
}
ticket.description += "> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
public void revoke(CertificateRequestHostRecord rec) throws CertificateRequestException {
//revoke
//CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
ArrayList<Certificate> chain = null;
try {
chain = CertificateManager.parsePKCS7(rec.cert_pkcs7);
} catch (CertificateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (CMSException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain);
X500Principal issuer = c0.getIssuerX500Principal();
String issuer_dn = CertificateManager.X500Principal_to_ApacheDN(issuer);
CertificateManager cm = CertificateManager.Factory(issuer_dn);
log.debug("Issuer dn " + issuer_dn);
try {
String[] cert_serial_ids = rec.getSerialIDs();
StringArray statuses = new StringArray(rec.cert_statuses);
for(int i = 0;i < cert_serial_ids.length; ++i) {
//for(String cert_serial_id : cert_serial_ids) {
//only revoke ones that are not yet revoked
if(statuses.get(i).equals(CertificateRequestStatus.ISSUED)) {
String cert_serial_id = cert_serial_ids[i];
log.info("Revoking certificate with serial ID: " + cert_serial_id);
cm.revokeHostCertificate(cert_serial_id);
statuses.set(i, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not?
}
}
rec.cert_statuses = statuses.toXML();
} catch (CertificateProviderException e1) {
log.error("Failed to revoke host certificate", e1);
throw new CertificateRequestException("Failed to revoke host certificate", e1);
}
rec.status = CertificateRequestStatus.REVOKED;
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update host certificate status: " + rec.id);
throw new CertificateRequestException("Failed to update host certificate status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has revoked this certificate.\n\n";
} else {
throw new CertificateRequestException("Guest shouldn't be revoking certificate");
}
ticket.description += "> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
public void revoke(CertificateRequestHostRecord rec, int idx) throws CertificateRequestException {
//make sure we have valid idx
String[] cert_serial_ids = rec.getSerialIDs();
String cert_serial_id = cert_serial_ids[idx];
StringArray statuses = new StringArray(rec.cert_statuses);
if(idx >= cert_serial_ids.length) {
throw new CertificateRequestException("Invalid certififcate index:"+idx);
}
//revoke one
CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
try {
log.info("Revoking certificate with serial ID: " + cert_serial_id);
cm.revokeHostCertificate(cert_serial_id);
statuses.set(idx, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not?
rec.cert_statuses = statuses.toXML();
} catch (CertificateProviderException e1) {
log.error("Failed to revoke host certificate", e1);
throw new CertificateRequestException("Failed to revoke host certificate", e1);
}
//set rec.status to REVOKED if all certificates are revoked
boolean allrevoked = true;
for(int i = 0;i < cert_serial_ids.length; ++i) {
if(!statuses.get(i).equals(CertificateRequestStatus.REVOKED)) {
allrevoked = false;
break;
}
}
if(allrevoked) {
rec.status = CertificateRequestStatus.REVOKED;
}
try {
//context.setComment("Revoked certificate with serial ID:"+cert_serial_id);
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update host certificate status: " + rec.id);
throw new CertificateRequestException("Failed to update host certificate status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has revoked a certificate with serial ID:"+cert_serial_id+".\n\n";
} else {
throw new CertificateRequestException("Guest shouldn't be revoking certificate!");
}
ticket.description += "> " + context.getComment();
//ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//determines if user should be able to view request details, logs, and download certificate (pkcs12 is session specific)
public boolean canView(CertificateRequestHostRecord rec) {
return true;
}
//true if user can approve request
public boolean canApprove(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REQUESTED)) {
//^RA doesn't *approve* REVOKE_REQUESTED - RA just click on REVOKE button
if(auth.isUser()) {
//grid admin can appove it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canApprove()", e);
}
}
}
return false;
}
public LogDetail getLastApproveLog(ArrayList<LogDetail> logs) {
for(LogDetail log : logs) {
if(log.status.equals("APPROVED")) {
return log;
}
}
return null;
}
public boolean canReject(CertificateRequestHostRecord rec) {
return canApprove(rec); //same rule as approval
}
public boolean canCancel(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.REQUESTED) ||
rec.status.equals(CertificateRequestStatus.APPROVED) || //if renew_requesterd > approved cert is canceled, it should really go back to "issued", but currently it doesn't.
//rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
if(auth.isUser()) {
if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can cancel it
//requester can cancel one's own request
if(rec.requester_contact_id != null) {//could be null if guest submitted it
ContactRecord contact = auth.getContact();
if(rec.requester_contact_id.equals(contact.id)) return true;
}
//grid admin can cancel it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canCancel()", e);
}
}
}
return false;
}
//why can't we just issue certificate after it's been approved? because we might have to create pkcs12
public boolean canIssue(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.APPROVED)) {
if(rec.requester_contact_id == null) {
//anyone can issue guest request
return true;
} else {
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
//requester can issue
if(rec.requester_contact_id.equals(contact.id)) return true;
}
}
}
return false;
}
public boolean canRequestRevoke(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
if(auth.isUser() && canRevoke(rec)) {
//if user can directly revoke it, no need to request it
return false;
}
//all else, allow
return true;
}
return false;
}
public boolean canRevoke(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.ISSUED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
if(auth.isUser()) {
if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can revoke it
//requester oneself can revoke it
if(rec.requester_contact_id != null) {//could be null if guest submitted it
ContactRecord contact = auth.getContact();
if(rec.requester_contact_id.equals(contact.id)) return true;
}
//grid admin can revoke it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canRevoke()", e);
}
}
}
return false;
}
//canRevokeOne
public boolean canRevoke(CertificateRequestHostRecord rec, int idx) {
if(!canRevoke(rec)) return false;
StringArray statuses = new StringArray(rec.cert_statuses);
return statuses.get(idx).equals(CertificateRequestStatus.ISSUED);
}
//NO AC
public CertificateRequestHostRecord getBySerialID(String serial_id) throws SQLException {
serial_id = normalizeSerialID(serial_id);
CertificateRequestHostRecord rec = null;
ResultSet rs = null;
Connection conn = connectOIM();
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM "+table_name+ " WHERE cert_serial_ids like ?");
pstmt.setString(1, "%>"+serial_id+"<%");
if (pstmt.executeQuery() != null) {
rs = pstmt.getResultSet();
if(rs.next()) {
rec = new CertificateRequestHostRecord(rs);
}
}
pstmt.close();
conn.close();
return rec;
}
//pass null to not filter
public ArrayList<CertificateRequestHostRecord> search(String cns_contains, String status, Date request_after, Date request_before) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
String sql = "SELECT * FROM "+table_name+" WHERE 1 = 1";
if(cns_contains != null) {
sql += " AND cns like \"%"+StringEscapeUtils.escapeSql(cns_contains)+"%\"";
}
if(status != null) {
sql += " AND status = \""+StringEscapeUtils.escapeSql(status)+"\"";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(request_after != null) {
sql += " AND request_time >= \""+sdf.format(request_after) + "\"";
}
if(request_before != null) {
sql += " AND request_time <= \""+sdf.format(request_before) + "\"";
}
PreparedStatement stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return recs;
}
//prevent low level access - please use model specific actions
@Override
public Integer insert(CertificateRequestHostRecord rec) throws SQLException
{
throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)");
}
@Override
public void update(CertificateRequestHostRecord oldrec, CertificateRequestHostRecord newrec) throws SQLException
{
throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)");
}
@Override
public void remove(CertificateRequestHostRecord rec) throws SQLException
{
throw new UnsupportedOperationException("disallowing remove cert request..");
}
@Override
CertificateRequestHostRecord createRecord() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void notifyExpiringIn(Integer days_less_than) throws SQLException {
final SimpleDateFormat dformat = new SimpleDateFormat();
dformat.setTimeZone(auth.getTimeZone());
ContactModel cmodel = new ContactModel(context);
//process host certificate requests
log.debug("Looking for host certificate expiring in " + days_less_than + " days");
for(CertificateRequestHostRecord rec : findExpiringIn(days_less_than)) {
log.debug("host cert: " + rec.id + " expires on " + dformat.format(rec.cert_notafter));
Date expiration_date = rec.cert_notafter;
//user can't renew host certificate, so instead of keep notifying, let's just notify only once by limiting the time window
//when notification can be sent out
Calendar today = Calendar.getInstance();
if((rec.cert_notafter.getTime() - today.getTimeInMillis()) < 1000*3600*24*23) {
log.info("Aborting expiration notification for host certificate " + rec.id + " - it's expiring in less than 23 days");
continue;
}
//send notification
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificates will expire on "+dformat.format(expiration_date)+"\n\n";
//list CNs - per Horst's request.
for(String cn : rec.getCNs()) {
ticket.description += cn+"\n";
}
ticket.description+= "\n";
ticket.description += "Please request for new host certificate(s) for replacements.\n\n";
ticket.description += "Please visit "+getTicketUrl(rec.id)+" for more details.\n\n";
//don't send to CCs
ticket.mail_suppression_ccs = true;
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring host certificate");
}
}
}
public ArrayList<CertificateRequestHostRecord> findExpiringIn(Integer days) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND CURDATE() > DATE_SUB( cert_notafter, INTERVAL "+days+" DAY )");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return recs;
}
public void processCertificateExpired() throws SQLException {
//search for expired certificates
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND cert_notafter < CURDATE()")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
StringArray statuses = new StringArray(rec.csrs.length());
for(int c = 0; c < rec.csrs.length(); ++c) {
statuses.set(c, CertificateRequestStatus.EXPIRED);
}
rec.cert_statuses = statuses.toXML();
rec.status = CertificateRequestStatus.EXPIRED;
context.setComment("Certificate is no longer valid.");
super.update(get(rec.id), rec);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Certificate(s) has been expired.";
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired host certificate");
}
log.info("sent expiration notification for user certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
stmt.close();
conn.close();
}
//search for approved request that is too old (call this every day)
public void processStatusExpired() throws SQLException {
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
//approved in exactly 15 days ago
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 15")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ContactModel cmodel = new ContactModel(context);
//send notification
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificate (id: "+rec.id+") was approved 15 days ago. The request is scheduled to be automatically canceled within another 15 days. Please take this opportunity to download your approved certificate at your earliest convenience. If you are experiencing any trouble with the issuance of your certificate, please feel free to contact the GOC for further assistance. Please visit "+getTicketUrl(rec.id)+" to issue your host certificate.\n\n";
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate");
}
log.info("sent approval expiration warning notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
//approved 30 days ago
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 30")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
rec.status = CertificateRequestStatus.CANCELED;
context.setComment("Certificate was not issued within 30 days after approval.");
super.update(get(rec.id), rec);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ContactModel cmodel = new ContactModel(context);
//send notification
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "You did not issue your host certificate (id: "+rec.id+") within 30 days from the approval. In compliance with OSG PKI policy, the request is being canceled. You are welcome to re-request if necessary at "+getTicketUrl(rec.id)+".\n\n";
ticket.status = "Resolved";
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate");
}
log.info("sent approval calelation notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
stmt.close();
conn.close();
}
//used by RestServlet only once to reset approver_vo_id
public ArrayList<CertificateRequestHostRecord> findNullVO() throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE approver_vo_id is NULL order by id");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return recs;
}
//one time function to reset cert_statuses field for all records
public void resetStatuses(PrintWriter out) throws SQLException {
out.write("CertificateRequestHostModel::resetStatuses\n");
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE cert_statuses is NULL");
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
System.out.println("resetting statuses for rec id:"+rec.id);
out.write("rec id:"+rec.id+"\n");
out.write("\t certcounts:"+rec.getCNs().length+"\n");
StringArray statuses = new StringArray(rec.getCNs().length);
for(int i = 0;i<rec.getCNs().length;++i) {
statuses.set(i, rec.status);
}
rec.cert_statuses = statuses.toXML();
super.update(get(rec.id), rec);
}
stmt.close();
conn.close();
}
}
|
package nl.b3p.viewer.admin;
import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrResourceLoader;
/**
* This class will initialize the solr server: the setup of the index and the
* initialization of the SolrServer object. This in order to limit the number of
* connections to the index.
*
* @author Meine Toonen
*/
public class SolrInitializer implements ServletContextListener {
public static final String DATA_DIR = "flamingo.data.dir";
private static final String SOLR_DIR = ".solr/";
private static final String SOLR_CORE_NAME = "autosuggest";
private static SolrServer server;
private static CoreContainer coreContainer;
private static final Log log = LogFactory.getLog(SolrInitializer.class);
private ServletContext context;
private String datadirectory;
//private static final String SCHEMA="/WEB-INF/classes/xml/schema.xml";
//private static final String SOLRCONFIG="/WEB-INF/classes/xml/solrconfig.xml";
private static final String SOLR_CONF_DIR="/WEB-INF/classes/solr/autosuggest";
@Override
public void contextInitialized(ServletContextEvent sce) {
log.debug("SolrInitializer initializing");
this.context = sce.getServletContext();
datadirectory = context.getInitParameter(DATA_DIR);
System.setProperty("solr.solr.home", datadirectory + File.separator + SOLR_DIR);
File dataDirectory = new File(datadirectory);
if (!isCorrectDir(dataDirectory)) {
log.error("Cannot read/write data dir " + datadirectory + ". Solr searching not possible.");
return;
}
log.info("Data dir set " + datadirectory);
File solrDir = new File(dataDirectory, SOLR_DIR);
if (!solrDir.exists()) {
setupSolr(solrDir);
}
inializeSolr(solrDir);
}
private void setupSolr(File solrdir) {
log.debug("Setup the solr directory");
copyConf(solrdir);
coreContainer = new CoreContainer(solrdir.getPath());
}
private void inializeSolr(File solrDir) {
log.debug("Initialize the Solr Server instance");
String path = solrDir.getPath();
SolrResourceLoader loader = new SolrResourceLoader(path);
if(coreContainer == null){
coreContainer = new CoreContainer(loader);
}
coreContainer.load();
server = new EmbeddedSolrServer(coreContainer, SOLR_CORE_NAME);
}
public static SolrServer getServerInstance() {
return server;
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
coreContainer.shutdown();
server.shutdown();
log.debug("SolrInitializer destroyed");
}
private boolean isCorrectDir(File f) {
return f.isDirectory() && f.canRead() && f.canWrite();
}
private void copyConf(File solrDir){
try {
File conf = new File( this.context.getRealPath("/WEB-INF/classes/solr/solr.xml"));
boolean solrDirCreated = solrDir.mkdir();
FileUtils.copyFile(conf, new File(solrDir, "solr.xml"));
File coreConfiguration = new File(context.getRealPath(SOLR_CONF_DIR));
File coreDir = new File(solrDir, SOLR_CORE_NAME);
FileUtils.copyDirectory(coreConfiguration, coreDir);
} catch (Exception ex) {
log.error("Setup of the solr directory failed: ",ex);
}
}
}
|
package edu.iu.grid.oim.model.db;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.util.encoders.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.lib.Footprints;
import edu.iu.grid.oim.lib.StaticConfig;
import edu.iu.grid.oim.lib.Footprints.FPTicket;
import edu.iu.grid.oim.lib.StringArray;
import edu.iu.grid.oim.model.CertificateRequestStatus;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.cert.CertificateManager;
import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateBase;
import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateProviderException;
import edu.iu.grid.oim.model.cert.ICertificateSigner.IHostCertificatesCallBack;
import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.DNRecord;
import edu.iu.grid.oim.model.db.record.GridAdminRecord;
import edu.iu.grid.oim.model.db.record.VORecord;
import edu.iu.grid.oim.model.exceptions.CertificateRequestException;
import edu.iu.grid.oim.view.divrep.form.validator.CNValidator;
public class CertificateRequestHostModel extends CertificateRequestModelBase<CertificateRequestHostRecord> {
static Logger log = Logger.getLogger(CertificateRequestHostModel.class);
public CertificateRequestHostModel(UserContext _context) {
super(_context, "certificate_request_host");
}
//NO-AC
public CertificateRequestHostRecord get(int id) throws SQLException {
CertificateRequestHostRecord rec = null;
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE id = " + id)) {
rs = stmt.getResultSet();
if(rs.next()) {
rec = new CertificateRequestHostRecord(rs);
}
}
stmt.close();
conn.close();
return rec;
}
//return requests that I have submitted
public ArrayList<CertificateRequestHostRecord> getISubmitted(Integer id) throws SQLException {
ArrayList<CertificateRequestHostRecord> ret = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE requester_contact_id = " + id);
rs = stmt.getResultSet();
while(rs.next()) {
ret.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return ret;
}
//return requests that I am GA
public ArrayList<CertificateRequestHostRecord> getIApprove(Integer id) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
//list all domains that user is gridadmin of
StringBuffer cond = new StringBuffer();
HashSet<Integer> vos = new HashSet<Integer>();
GridAdminModel model = new GridAdminModel(context);
try {
for(GridAdminRecord grec : model.getGridAdminsByContactID(id)) {
if(cond.length() != 0) {
cond.append(" OR ");
}
cond.append("cns LIKE '%"+StringEscapeUtils.escapeSql(grec.domain)+"</String>%'");
vos.add(grec.vo_id);
}
} catch (SQLException e1) {
log.error("Failed to lookup GridAdmin domains", e1);
}
String vos_list = "";
for(Integer vo : vos) {
if(vos_list.length() != 0) {
vos_list += ",";
}
vos_list += vo;
}
if(cond.length() != 0) {
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
System.out.println("Searching SQL: SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')");
stmt.execute("SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
}
return recs;
}
//NO-AC
//issue all requested certs and store it back to DB
//you can monitor request status by checking returned Certificate[]
public void startissue(final CertificateRequestHostRecord rec) throws CertificateRequestException {
// mark the request as "issuing.."
try {
rec.status = CertificateRequestStatus.ISSUING;
context.setComment("Starting to issue certificates.");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate request status for request:" + rec.id);
throw new CertificateRequestException("Failed to update certificate request status");
};
//reconstruct cert array from db
final StringArray csrs = new StringArray(rec.csrs);
final StringArray serial_ids = new StringArray(rec.cert_serial_ids);
final StringArray pkcs7s = new StringArray(rec.cert_pkcs7);
final StringArray certificates = new StringArray(rec.cert_certificate);
final StringArray intermediates = new StringArray(rec.cert_intermediate);
final StringArray statuses = new StringArray(rec.cert_statuses);
final CertificateBase[] certs = new CertificateBase[csrs.length()];
for(int c = 0; c < csrs.length(); ++c) {
certs[c] = new CertificateBase();
certs[c].csr = csrs.get(c);
certs[c].serial = serial_ids.get(c);
certs[c].certificate = certificates.get(c);
certs[c].intermediate = intermediates.get(c);
certs[c].pkcs7 = pkcs7s.get(c);
}
new Thread(new Runnable() {
public void failed(String message, Throwable e) {
log.error(message, e);
rec.status = CertificateRequestStatus.FAILED;
rec.status_note = message + " :: " + e.getMessage();
try {
context.setComment(message + " :: " + e.getMessage());
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e1) {
log.error("Failed to update request status while processing failed condition :" + message, e1);
}
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Failed to issue certificate.\n\n";
ticket.description += message+"\n\n";
ticket.description += e.getMessage()+"\n\n";
ticket.description += "The alert has been sent to GOC alert for further actions on this issue.";
ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.fail.assignee"));
ticket.nextaction = "GOC developer to investigate";
fp.update(ticket, rec.goc_ticket_id);
}
//should we use Quartz instead?
public void run() {
final CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
try {
//lookup requester contact information
String requester_email = rec.requester_email; //for guest request
if(rec.requester_contact_id != null) {
//for user request
ContactModel cmodel = new ContactModel(context);
ContactRecord requester = cmodel.get(rec.requester_contact_id);
requester_email = requester.primary_email;
}
log.debug("Starting signing process");
cm.signHostCertificates(certs, new IHostCertificatesCallBack() {
//called once all certificates are requested (and approved) - but not yet issued
@Override
public void certificateRequested() {
log.debug("certificateRequested called");
//update certs db contents
try {
for(int c = 0; c < certs.length; ++c) {
CertificateBase cert = certs[c];
serial_ids.set(c, cert.serial); //really just order ID (until the certificate is issued)
statuses.set(c, CertificateRequestStatus.ISSUING);
}
rec.cert_serial_ids = serial_ids.toXML();
rec.cert_statuses = statuses.toXML();
context.setComment("All certificate requests have been sent.");
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate update while monitoring issue progress:" + rec.id);
}
}
//called for each certificate issued
@Override
public void certificateSigned(CertificateBase cert, int idx) {
log.info("host cert issued by digicert: serial_id:" + cert.serial);
log.info("pkcs7:" + cert.pkcs7);
//pull some information from the cert for validation purpose
try {
ArrayList<Certificate> chain = CertificateManager.parsePKCS7(cert.pkcs7);
X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain);
cert.notafter = c0.getNotAfter();
cert.notbefore = c0.getNotBefore();
//do a bit of validation
Calendar today = Calendar.getInstance();
if(Math.abs(today.getTimeInMillis() - cert.notbefore.getTime()) > 1000*3600*24) {
log.warn("Host certificate issued for request "+rec.id+"(idx:"+idx+") has cert_notbefore set too distance from current timestamp");
}
long dayrange = (cert.notafter.getTime() - cert.notbefore.getTime()) / (1000*3600*24);
if(dayrange < 350 || dayrange > 450) {
log.warn("Host certificate issued for request "+rec.id+ "(idx:"+idx+") has invalid range of "+dayrange+" days (too far from 395 days)");
}
//make sure dn starts with correct base
X500Principal dn = c0.getSubjectX500Principal();
String apache_dn = CertificateManager.X500Principal_to_ApacheDN(dn);
if(!apache_dn.startsWith(cm.getHostDNBase())) {
log.error("Host certificate issued for request " + rec.id + "(idx:"+idx+") has DN:"+apache_dn+" which doesn't have an expected DN base: "+cm.getHostDNBase());
}
} catch (CertificateException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
} catch (CMSException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
} catch (IOException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
}
//update status note
try {
statuses.set(idx, CertificateRequestStatus.ISSUED);
rec.cert_statuses = statuses.toXML();
rec.status_note = "Certificate idx:"+idx+" has been issued. Serial Number: " + cert.serial;
context.setComment(rec.status_note);
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate update while monitoring issue progress:" + rec.id);
}
}
}, requester_email);
log.debug("Finishing up issue process");
//update records
int idx = 0;
StringArray cert_certificates = new StringArray(rec.cert_certificate);
StringArray cert_intermediates = new StringArray(rec.cert_intermediate);
StringArray cert_pkcs7s = new StringArray(rec.cert_pkcs7);
StringArray cert_serial_ids = new StringArray(rec.cert_serial_ids);
for(CertificateBase cert : certs) {
cert_certificates.set(idx, cert.certificate);
rec.cert_certificate = cert_certificates.toXML();
cert_intermediates.set(idx, cert.intermediate);
rec.cert_intermediate = cert_intermediates.toXML();
cert_pkcs7s.set(idx, cert.pkcs7);
rec.cert_pkcs7 = cert_pkcs7s.toXML();
cert_serial_ids.set(idx, cert.serial);
rec.cert_serial_ids = cert_serial_ids.toXML();
++idx;
}
//set cert expiriation dates using the first certificate issued (out of many *requests*)
CertificateBase cert = certs[0];
rec.cert_notafter = cert.notafter;
rec.cert_notbefore = cert.notbefore;
//log.debug("Updating status");
//update status
try {
rec.status = CertificateRequestStatus.ISSUED;
context.setComment("All ceritificates has been issued.");
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
throw new CertificateRequestException("Failed to update status for certificate request: " + rec.id);
}
log.debug("Updating ticket");
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has issued certificate. Resolving this ticket.";
} else {
ticket.description = "Someone with IP address: " + context.getRemoteAddr() + " has issued certificate. Resolving this ticket.";
}
//get number of certificate requested for this request
String [] cns = rec.getCNs();
for(String cn : cns) {
ticket.description += "/CN=" + cn + "\n";
}
ticket.status = "Resolved";
//suppressing notification if submitter is GA
ArrayList<ContactRecord> gas = findGridAdmin(rec);
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
if(submitter_is_ga) {
ticket.mail_suppression_assignees = true;
ticket.mail_suppression_submitter = true;
//ticket.mail_suppression_ccs = true;
}
fp.update(ticket, rec.goc_ticket_id);
} catch (CertificateProviderException e) {
failed("Failed to sign certificate -- CertificateProviderException ", e);
} catch (SQLException e) {
failed("Failed to sign certificate -- most likely couldn't lookup requester contact info", e);
} catch(Exception e) {
failed("Failed to sign certificate -- unhandled", e);
}
}
}).start();
}
//NO-AC
//return true if success
public void approve(CertificateRequestHostRecord rec) throws CertificateRequestException
{
//get number of certificate requested for this request
String [] cns = rec.getCNs();
int count = cns.length;
//check quota
CertificateQuotaModel quota = new CertificateQuotaModel(context);
if(!quota.canApproveHostCert(count)) {
throw new CertificateRequestException("You will exceed your host certificate quota.");
}
rec.status = CertificateRequestStatus.APPROVED;
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
quota.incrementHostCertApproval(count);
} catch (SQLException e) {
log.error("Failed to approve host certificate request: " + rec.id);
throw new CertificateRequestException("Failed to update certificate request record");
}
//find if requester is ga
ArrayList<ContactRecord> gas = findGridAdmin(rec);
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
if(submitter_is_ga) {
ticket.description = rec.requester_name + " has approved this host certificate request.\n\n";
ticket.mail_suppression_assignees = false; //Per Von/Alain's request, we will send notification to Alain when request is approved
//ticket.mail_suppression_ccs = true;
ticket.mail_suppression_submitter = true;
} else {
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificate request has been approved. \n\n";
}
for(String cn : cns) {
ticket.description += "/CN=" + cn + "\n";
}
ticket.description += "To retrieve the certificate please visit " + getTicketUrl(rec.id) + " and click on Issue Certificate button.\n\n";
if(StaticConfig.isDebug()) {
ticket.description += "Or if you are using the command-line: osg-cert-retrieve -T -i "+rec.id+"\n\n";
} else {
ticket.description += "Or if you are using the command-line: osg-cert-retrieve -i "+rec.id+"\n\n";
}
ticket.nextaction = "Requester to download certificate";
Calendar nad = Calendar.getInstance();
nad.add(Calendar.DATE, 7);
ticket.nad = nad.getTime();
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC (for authenticated user)
//return request record if successful, otherwise null
public CertificateRequestHostRecord requestAsUser(
ArrayList<String> csrs,
ContactRecord requester,
String request_comment,
String[] request_ccs,
Integer approver_vo_id) throws CertificateRequestException
{
CertificateRequestHostRecord rec = new CertificateRequestHostRecord();
//Date current = new Date();
rec.requester_contact_id = requester.id;
rec.requester_name = requester.name;
rec.approver_vo_id = approver_vo_id;
rec.requester_email = requester.primary_email;
//rec.requester_phone = requester.primary_phone;
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.name = requester.name;
ticket.email = requester.primary_email;
ticket.phone = requester.primary_phone;
ticket.title = "Host Certificate Request by " + requester.name + "(OIM user)";
ticket.metadata.put("SUBMITTER_NAME", requester.name);
if(request_ccs != null) {
for(String cc : request_ccs) {
ticket.ccs.add(cc);
}
}
log.debug("submitting request as user");
return request(csrs, rec, ticket, request_comment);
}
//NO-AC (for guest user)
//return request record if successful, otherwise null
public CertificateRequestHostRecord requestAsGuest(
ArrayList<String> csrs,
String requester_name,
String requester_email,
String requester_phone,
String request_comment,
String[] request_ccs,
Integer approver_vo_id) throws CertificateRequestException
{
CertificateRequestHostRecord rec = new CertificateRequestHostRecord();
//Date current = new Date();
rec.approver_vo_id = approver_vo_id;
rec.requester_name = requester_name;
rec.requester_email = requester_email;
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.name = requester_name;
ticket.email = requester_email;
ticket.phone = requester_phone;
ticket.title = "Host Certificate Request by " + requester_name + "(Guest)";
ticket.metadata.put("SUBMITTER_NAME", requester_name);
if(request_ccs != null) {
for(String cc : request_ccs) {
ticket.ccs.add(cc);
}
}
return request(csrs, rec, ticket, request_comment);
}
private String getTicketUrl(Integer request_id) {
String base;
//this is not an exactly correct assumption, but it should be good enough
if(StaticConfig.isDebug()) {
base = "https://oim-itb.grid.iu.edu/oim/";
} else {
base = "https://oim.grid.iu.edu/oim/";
}
return base + "certificatehost?id=" + request_id;
}
//NO-AC
//return request record if successful, otherwise null (guest interface)
private CertificateRequestHostRecord request(
ArrayList<String> csrs,
CertificateRequestHostRecord rec,
FPTicket ticket,
String request_comment) throws CertificateRequestException
{
//log.debug("request");
Date current = new Date();
rec.request_time = new Timestamp(current.getTime());
rec.status = CertificateRequestStatus.REQUESTED;
//set all host cert status to REQUESTED
StringArray statuses = new StringArray(csrs.size());
for(int c = 0; c < csrs.size(); ++c) {
statuses.set(c, CertificateRequestStatus.REQUESTED);
}
rec.cert_statuses = statuses.toXML();
if(request_comment != null) {
rec.status_note = request_comment;
context.setComment(request_comment);
}
//store CSRs / CNs to record
StringArray csrs_sa = new StringArray(csrs.size());
StringArray cns_sa = new StringArray(csrs.size());
int idx = 0;
CNValidator cnv = new CNValidator(CNValidator.Type.HOST);
for(String csr_string : csrs) {
log.debug("processing csr: " + csr_string);
String cn;
ArrayList<String> sans;
try {
PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string);
cn = CertificateManager.pullCNFromCSR(csr);
sans = CertificateManager.pullSANFromCSR(csr);
//validate CN
//if(!cn.matches("^([-0-9a-zA-Z\\.]*/)?[-0-9a-zA-Z\\.]*$")) { //OSGPKI-255
// throw new CertificateRequestException("CN structure is invalid, or contains invalid characters.");
if(!cnv.isValid(cn)) {
throw new CertificateRequestException("CN specified is invalid: " + cn + " .. " + cnv.getErrorMessage());
}
for(String san : sans) {
if(!cnv.isValid(san)) {
throw new CertificateRequestException("SAN specified is invalid: " + san + " .. " + cnv.getErrorMessage());
}
}
//check private key strength
SubjectPublicKeyInfo pkinfo = csr.getSubjectPublicKeyInfo();
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkinfo);
int keysize = rsa.getModulus().bitLength();
if(keysize < 2048) {
throw new CertificateRequestException("Please use RSA keysize greater than or equal to 2048 bits.");
}
cns_sa.set(idx, cn);
} catch (IOException e) {
log.error("Failed to base64 decode CSR", e);
throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e);
} catch (NullPointerException e) {
log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e);
throw new CertificateRequestException("Failed to base64 decode CSR", e);
}
csrs_sa.set(idx++, csr_string);
}
rec.csrs = csrs_sa.toXML();
rec.cns = cns_sa.toXML();
StringArray empty = new StringArray(csrs.size());
String empty_xml = empty.toXML();
rec.cert_certificate = empty_xml;
rec.cert_intermediate = empty_xml;
rec.cert_pkcs7 = empty_xml;
rec.cert_serial_ids = empty_xml;
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
//find if submitter is ga
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
//now submit - after this, we are commited.
Integer request_id = super.insert(rec);
if(submitter_is_ga) {
ticket.description = "Host certificate request has been submitted by a GridAdmin.\n\n";
ticket.mail_suppression_assignees = true;
ticket.mail_suppression_submitter = true;
//ticket.mail_suppression_ccs = true;
} else {
ticket.description = "Dear GridAdmin; ";
for(ContactRecord ga : gas) {
ticket.description += ga.name + ", ";
ticket.ccs.add(ga.primary_email);
}
ticket.description += "\n\n";
ticket.description += "Host certificate request has been submitted. ";
ticket.description += "Please determine this request's authenticity, and approve / disapprove at " + getTicketUrl(request_id) + "\n\n";
}
ticket.description += "CNs requested:\n";
for(String cn : cns_sa.getAll()) {
ticket.description += "/CN=" + cn + "\n";
}
Authorization auth = context.getAuthorization();
ticket.description += "Requester IP:" + context.getRemoteAddr() + "\n";
if(auth.isUser()) {
ContactRecord user = auth.getContact();
ticket.description += "Submitter is OIM authenticated with DN:" + auth.getUserDN() + "\n";
}
if(request_comment != null) {
ticket.description += "Requester Comment: "+request_comment;
}
ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.host.assignee"));
ticket.nextaction = "GridAdmin to verify requester";
Calendar nad = Calendar.getInstance();
nad.add(Calendar.DATE, 7);
ticket.nad = nad.getTime();
//set metadata
ticket.metadata.put("SUBMITTED_VIA", "OIM/CertManager(host)");
if(auth.isUser()) {
ticket.metadata.put("SUBMITTER_DN", auth.getUserDN());
}
//all ready to submit request
Footprints fp = new Footprints(context);
log.debug("opening footprints ticket");
String ticket_id = fp.open(ticket);
log.debug("update request record with goc ticket id");
rec.goc_ticket_id = ticket_id;
context.setComment("Opened GOC Ticket " + ticket_id);
super.update(get(request_id), rec);
log.debug("request updated");
} catch (SQLException e) {
throw new CertificateRequestException("Failed to insert host certificate request record", e);
}
log.debug("returnign rec");
return rec;
}
//find gridadmin who should process the request - identify domain from csrs
//if there are more than 1 vos group, then user must specify approver_vo_id
// * it could be null for gridadmin with only 1 vo group, and approver_vo_id will be reset to the correct VO ID
public ArrayList<ContactRecord> findGridAdmin(CertificateRequestHostRecord rec) throws CertificateRequestException
{
GridAdminModel gamodel = new GridAdminModel(context);
String gridadmin_domain = null;
int idx = 0;
ArrayList<String> domains = new ArrayList<String>();
String[] csrs = rec.getCSRs();
if(csrs.length == 0) {
throw new CertificateRequestException("No CSR");
}
for(String csr_string : csrs) {
//parse CSR and pull CN
String cn;
ArrayList<String> sans;
try {
PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string);
cn = CertificateManager.pullCNFromCSR(csr);
sans = CertificateManager.pullSANFromCSR(csr);
} catch (IOException e) {
log.error("Failed to base64 decode CSR", e);
throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e);
} catch (NullPointerException e) {
log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e);
throw new CertificateRequestException("Failed to base64 decode CSR", e);
} catch(Exception e) {
throw new CertificateRequestException("Failed to decode CSR", e);
}
//lookup registered gridadmin domain
String domain = null;
try {
domain = gamodel.getDomainByFQDN(cn);
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup GridAdmin to approve host:" + cn, e);
}
if(domain == null) {
throw new CertificateRequestException("The hostname you have provided in the CSR/CN=" + cn + " does not match any domain OIM is currently configured to issue certificates for.\n\nPlease double check the CN you have specified. If you'd like to be a GridAdmin for this domain, please open GOC Ticket at https://ticket.grid.iu.edu ");
}
//make sure same set of gridadmin approves all host
if(gridadmin_domain == null) {
gridadmin_domain = domain;
log.debug("first domain is " + gridadmin_domain);
} else {
if(!gridadmin_domain.equals(domain)) {
//throw new CertificateRequestException("All host certificates must be approved by the same set of gridadmins. Different for " + cn);
domains.add(domain);
log.debug("Next domain is " + domain);
}
}
//make sure SANs are also approved by the same domain or share a common GridAdmin
for(String san : sans) {
try {
String san_domain = gamodel.getDomainByFQDN(san);
if(!gridadmin_domain.equals(san_domain)) {
//throw new CertificateRequestException("All SAN must be approved by the same set of gridadmins. Different for " + san);
domains.add(san_domain);
log.debug("san domain is " + san_domain);
}
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup GridAdmin for SAN:" + san, e);
}
}
}
try {
//for first domain in the list, add the grid admins. For each additional domain remove all non-matching grid-admins
ArrayList<ContactRecord> gas = new ArrayList<ContactRecord> ();
HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain);
if(groups.size() == 0) {
throw new CertificateRequestException("No gridadmin exists for domain: " + gridadmin_domain);
}
if(groups.size() == 1 && rec.approver_vo_id == null) {
//set approver_vo_id to the one and only one vogroup's vo id
Iterator<VORecord> it = groups.keySet().iterator();
VORecord vorec = it.next();
rec.approver_vo_id = vorec.id;
}
String vonames = "";
for(VORecord vo : groups.keySet()) {
vonames += vo.name + ", "; //just in case we might need to report error message later
if(vo.id.equals(rec.approver_vo_id)) {
log.debug("found a match.. return the list " + vo.name);
gas.addAll(GAsToContacts(groups.get(vo)));
}
}
for (String domain : domains) {
//HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain);
log.debug("looking up approvers for domain " + domain);
groups = gamodel.getByDomainGroupedByVO(domain);
if(groups.size() == 0) {
throw new CertificateRequestException("No gridadmin exists for domain: " + domain);
}
if(groups.size() == 1 && rec.approver_vo_id == null) {
Iterator<VORecord> it = groups.keySet().iterator();
VORecord vorec = it.next();
rec.approver_vo_id = vorec.id;
log.debug("set approver_vo_id to the one and only one vogroup's vo id " + rec.approver_vo_id);
}
vonames = "";
log.debug("For each vo record for " + domain);
int match_id = 0;
for(VORecord vo : groups.keySet()) {
log.debug(vo.name);
vonames += vo.name + ", "; //just in case we might need to report error message later
if(vo.id.equals(rec.approver_vo_id)) {
match_id = vo.id;
log.debug("found an exact match.. return the list " + vo.name);
ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo));
if (newgas.isEmpty()) {
log.debug("no contacts for " + vo.name);
}
ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>();
for(ContactRecord contact: newgas) {
log.debug("checking contact name " + contact.name);
if (gas.contains(contact)) {
sharedgas.add(contact);
log.debug("adding " + contact.name);
}
}
gas = sharedgas;
//return GAsToContacts(gas);
}
}
if (match_id == 0) {
for(VORecord vo : groups.keySet()) {
log.debug(vo.name);
vonames += vo.name + ", "; //just in case we might need to report error message later
//if(vo.id.equals(rec.approver_vo_id)) {
log.debug("matching using the list " + vo.name);
ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo));
if (newgas.isEmpty()) {
log.debug("no contacts for " + vo.name);
}
ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>();
for(ContactRecord contact: newgas) {
log.debug("checking contact name " + contact.name);
if (gas.contains(contact)) {
sharedgas.add(contact);
log.debug("adding " + contact.name);
}
}
gas = sharedgas;
//return GAsToContacts(gas);
}
}
}
if (!gas.isEmpty()) {
return gas;
}
else {
//oops.. didn't find specified vo..
throw new CertificateRequestException("Couldn't find GridAdmin group under specified VO.");
}
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup gridadmin contacts for domain:" + gridadmin_domain, e);
}
}
public ArrayList<ContactRecord> GAsToContacts(ArrayList<GridAdminRecord> gas) throws SQLException {
//convert contact_id to contact record
ArrayList<ContactRecord> contacts = new ArrayList<ContactRecord>();
ContactModel cmodel = new ContactModel(context);
for(GridAdminRecord ga : gas) {
log.debug("adding contact id " + ga.contact_id);
contacts.add(cmodel.get(ga.contact_id));
}
return contacts;
}
//NO-AC
public void requestRevoke(CertificateRequestHostRecord rec) throws CertificateRequestException {
rec.status = CertificateRequestStatus.REVOCATION_REQUESTED;
try {
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to request revocation of host certificate: " + rec.id);
throw new CertificateRequestException("Failed to update request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has requested revocation of this certificate request.";
} else {
ticket.description = "Guest user with IP:" + context.getRemoteAddr() + " has requested revocation of this certificate request.";
}
ticket.description += "\n\nPlease approve / disapprove this request at " + getTicketUrl(rec.id);
ticket.nextaction = "Grid Admin to process request."; //nad will be set to 7 days from today by default
ticket.status = "Engineering"; //I need to reopen resolved ticket.
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
//return true if success
public void cancel(CertificateRequestHostRecord rec) throws CertificateRequestException {
try {
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
rec.status = CertificateRequestStatus.ISSUED;
} else {
rec.status = CertificateRequestStatus.CANCELED;
}
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to cancel host certificate request:" + rec.id);
throw new CertificateRequestException("Failed to cancel request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has canceled this request.\n\n";
} else {
//Guest can still cancel by providing the password used to submit the request.
}
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
ticket.description += "\n\n> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
public void reject(CertificateRequestHostRecord rec) throws CertificateRequestException {
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED)||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
rec.status = CertificateRequestStatus.ISSUED;
} else {
//all others
rec.status = CertificateRequestStatus.REJECTED;
}
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to reject host certificate request:" + rec.id);
throw new CertificateRequestException("Failed to reject request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has rejected this certificate request.\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
} else {
throw new CertificateRequestException("Guest shouldn't be rejecting request");
}
ticket.description += "> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
public void revoke(CertificateRequestHostRecord rec) throws CertificateRequestException {
//revoke
//CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
String issuer_dn = ""; //by default
ArrayList<Certificate> chain = null;
try {
if (rec.getPKCS7s()[0] != null) {
chain = CertificateManager.parsePKCS7(rec.getPKCS7s()[0]);
X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain);
X500Principal issuer = c0.getIssuerX500Principal();
issuer_dn = CertificateManager.X500Principal_to_ApacheDN(issuer);
}
} catch (CertificateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (CMSException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
//e2.printStackTrace(); -this will error for cilogon
}
CertificateManager cm = CertificateManager.Factory(issuer_dn);
try {
String[] cert_serial_ids = rec.getSerialIDs();
StringArray statuses = new StringArray(rec.cert_statuses);
for(int i = 0;i < cert_serial_ids.length; ++i) {
//for(String cert_serial_id : cert_serial_ids) {
//only revoke ones that are not yet revoked
if(statuses.get(i).equals(CertificateRequestStatus.ISSUED)) {
String cert_serial_id = cert_serial_ids[i];
log.info("Revoking certificate with serial ID: " + cert_serial_id);
cm.revokeHostCertificate(cert_serial_id);
statuses.set(i, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not?
}
}
rec.cert_statuses = statuses.toXML();
} catch (CertificateProviderException e1) {
log.error("Failed to revoke host certificate", e1);
throw new CertificateRequestException("Failed to revoke host certificate", e1);
}
rec.status = CertificateRequestStatus.REVOKED;
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update host certificate status: " + rec.id);
throw new CertificateRequestException("Failed to update host certificate status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has revoked this certificate.\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
} else {
throw new CertificateRequestException("Guest shouldn't be revoking certificate");
}
ticket.description += "> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
public void revoke(CertificateRequestHostRecord rec, int idx) throws CertificateRequestException {
//make sure we have valid idx
String[] cert_serial_ids = rec.getSerialIDs();
String cert_serial_id = cert_serial_ids[idx];
StringArray statuses = new StringArray(rec.cert_statuses);
if(idx >= cert_serial_ids.length) {
throw new CertificateRequestException("Invalid certififcate index:"+idx);
}
//revoke one
CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
try {
log.info("Revoking certificate with serial ID: " + cert_serial_id);
cm.revokeHostCertificate(cert_serial_id);
statuses.set(idx, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not?
rec.cert_statuses = statuses.toXML();
} catch (CertificateProviderException e1) {
log.error("Failed to revoke host certificate", e1);
throw new CertificateRequestException("Failed to revoke host certificate", e1);
}
//set rec.status to REVOKED if all certificates are revoked
boolean allrevoked = true;
for(int i = 0;i < cert_serial_ids.length; ++i) {
if(!statuses.get(i).equals(CertificateRequestStatus.REVOKED)) {
allrevoked = false;
break;
}
}
if(allrevoked) {
rec.status = CertificateRequestStatus.REVOKED;
}
try {
//context.setComment("Revoked certificate with serial ID:"+cert_serial_id);
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update host certificate status: " + rec.id);
throw new CertificateRequestException("Failed to update host certificate status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has revoked a certificate with serial ID:"+cert_serial_id+".\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
} else {
throw new CertificateRequestException("Guest shouldn't be revoking certificate!");
}
ticket.description += "> " + context.getComment();
//ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//determines if user should be able to view request details, logs, and download certificate (pkcs12 is session specific)
public boolean canView(CertificateRequestHostRecord rec) {
return true;
}
//true if user can approve request
public boolean canApprove(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REQUESTED)) {
//^RA doesn't *approve* REVOKE_REQUESTED - RA just click on REVOKE button
if(auth.isUser()) {
//grid admin can appove it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canApprove()", e);
}
}
}
return false;
}
public LogDetail getLastApproveLog(ArrayList<LogDetail> logs) {
for(LogDetail log : logs) {
if(log.status.equals("APPROVED")) {
return log;
}
}
return null;
}
public boolean canReject(CertificateRequestHostRecord rec) {
return canApprove(rec); //same rule as approval
}
public boolean canCancel(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.REQUESTED) ||
rec.status.equals(CertificateRequestStatus.APPROVED) || //if renew_requesterd > approved cert is canceled, it should really go back to "issued", but currently it doesn't.
//rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
if(auth.isUser()) {
if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can cancel it
//requester can cancel one's own request
if(rec.requester_contact_id != null) {//could be null if guest submitted it
ContactRecord contact = auth.getContact();
if(rec.requester_contact_id.equals(contact.id)) return true;
}
//grid admin can cancel it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canCancel()", e);
}
}
}
return false;
}
//why can't we just issue certificate after it's been approved? because we might have to create pkcs12
public boolean canIssue(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.APPROVED)) {
if(rec.requester_contact_id == null) {
//anyone can issue guest request
return true;
} else {
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
//requester can issue
if(rec.requester_contact_id.equals(contact.id)) return true;
}
}
}
return false;
}
public boolean canRequestRevoke(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
if(auth.isUser() && canRevoke(rec)) {
//if user can directly revoke it, no need to request it
return false;
}
//all else, allow
return true;
}
return false;
}
public boolean canRevoke(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.ISSUED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
if(auth.isUser()) {
if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can revoke it
//requester oneself can revoke it
if(rec.requester_contact_id != null) {//could be null if guest submitted it
ContactRecord contact = auth.getContact();
if(rec.requester_contact_id.equals(contact.id)) return true;
}
//grid admin can revoke it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canRevoke()", e);
}
}
}
return false;
}
//canRevokeOne
public boolean canRevoke(CertificateRequestHostRecord rec, int idx) {
if(!canRevoke(rec)) return false;
StringArray statuses = new StringArray(rec.cert_statuses);
return statuses.get(idx).equals(CertificateRequestStatus.ISSUED);
}
//NO AC
public CertificateRequestHostRecord getBySerialID(String serial_id) throws SQLException {
serial_id = normalizeSerialID(serial_id);
CertificateRequestHostRecord rec = null;
ResultSet rs = null;
Connection conn = connectOIM();
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM "+table_name+ " WHERE cert_serial_ids like ?");
pstmt.setString(1, "%>"+serial_id+"<%");
if (pstmt.executeQuery() != null) {
rs = pstmt.getResultSet();
if(rs.next()) {
rec = new CertificateRequestHostRecord(rs);
}
}
pstmt.close();
conn.close();
return rec;
}
//pass null to not filter
public ArrayList<CertificateRequestHostRecord> search(String cns_contains, String status, Date request_after, Date request_before, Integer signer) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
String sql = "SELECT * FROM "+table_name+" WHERE 1 = 1";
if(cns_contains != null) {
sql += " AND cns like \"%"+StringEscapeUtils.escapeSql(cns_contains)+"%\"";
}
if(status != null) {
sql += " AND status = \""+StringEscapeUtils.escapeSql(status)+"\"";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(request_after != null) {
sql += " AND request_time >= \""+sdf.format(request_after) + "\"";
}
if(request_before != null) {
sql += " AND request_time <= \""+sdf.format(request_before) + "\"";
}
PreparedStatement stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()) {
CertificateRequestHostRecord cr = new CertificateRequestHostRecord(rs);
if (signer != null) {
log.debug("cr signer " + cr.getSigner());
if ((signer == 0 && cr.getSigner().matches("(.*)CILogon(.*)")) || (signer == 1 && cr.getSigner().matches("(.*)DigiCert(.*)"))) {
recs.add(cr);
}
}
else {
recs.add(cr);
}
}
stmt.close();
conn.close();
return recs;
}
//prevent low level access - please use model specific actions
@Override
public Integer insert(CertificateRequestHostRecord rec) throws SQLException
{
throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)");
}
@Override
public void update(CertificateRequestHostRecord oldrec, CertificateRequestHostRecord newrec) throws SQLException
{
throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)");
}
@Override
public void remove(CertificateRequestHostRecord rec) throws SQLException
{
throw new UnsupportedOperationException("disallowing remove cert request..");
}
@Override
CertificateRequestHostRecord createRecord() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void notifyExpiringIn(Integer days_less_than) throws SQLException {
final SimpleDateFormat dformat = new SimpleDateFormat();
dformat.setTimeZone(auth.getTimeZone());
ContactModel cmodel = new ContactModel(context);
//process host certificate requests
log.debug("Looking for host certificate expiring in " + days_less_than + " days");
for(CertificateRequestHostRecord rec : findExpiringIn(days_less_than)) {
log.debug("host cert: " + rec.id + " expires on " + dformat.format(rec.cert_notafter));
Date expiration_date = rec.cert_notafter;
//user can't renew host certificate, so instead of keep notifying, let's just notify only once by limiting the time window
//when notification can be sent out
Calendar today = Calendar.getInstance();
if((rec.cert_notafter.getTime() - today.getTimeInMillis()) < 1000*3600*24*23) {
log.info("Aborting expiration notification for host certificate " + rec.id + " - it's expiring in less than 23 days");
continue;
}
//send notification
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificates will expire on "+dformat.format(expiration_date)+"\n\n";
//list CNs - per Horst's request.
for(String cn : rec.getCNs()) {
ticket.description += cn+"\n";
}
ticket.description+= "\n";
ticket.description += "Please request for new host certificate(s) for replacements.\n\n";
ticket.description += "Please visit "+getTicketUrl(rec.id)+" for more details.\n\n";
//don't send to CCs
ticket.mail_suppression_ccs = true;
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring host certificate");
}
}
}
public ArrayList<CertificateRequestHostRecord> findExpiringIn(Integer days) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND CURDATE() > DATE_SUB( cert_notafter, INTERVAL "+days+" DAY )");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return recs;
}
public void processCertificateExpired() throws SQLException {
//search for expired certificates
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND cert_notafter < CURDATE()")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
StringArray statuses = new StringArray(rec.csrs.length());
for(int c = 0; c < rec.csrs.length(); ++c) {
statuses.set(c, CertificateRequestStatus.EXPIRED);
}
rec.cert_statuses = statuses.toXML();
rec.status = CertificateRequestStatus.EXPIRED;
context.setComment("Certificate is no longer valid.");
super.update(get(rec.id), rec);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Certificate(s) has been expired.";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired host certificate");
}
log.info("sent expiration notification for user certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
stmt.close();
conn.close();
}
//search for approved request that is too old (call this every day)
public void processStatusExpired() throws SQLException {
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
//approved in exactly 15 days ago
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 15")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ContactModel cmodel = new ContactModel(context);
//send notification
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificate (id: "+rec.id+") was approved 15 days ago. The request is scheduled to be automatically canceled within another 15 days. Please take this opportunity to download your approved certificate at your earliest convenience. If you are experiencing any trouble with the issuance of your certificate, please feel free to contact the GOC for further assistance. Please visit "+getTicketUrl(rec.id)+" to issue your host certificate.\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate");
}
log.info("sent approval expiration warning notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
//approved 30 days ago
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 30")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
rec.status = CertificateRequestStatus.CANCELED;
context.setComment("Certificate was not issued within 30 days after approval.");
super.update(get(rec.id), rec);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ContactModel cmodel = new ContactModel(context);
//send notification
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "You did not issue your host certificate (id: "+rec.id+") within 30 days from the approval. In compliance with OSG PKI policy, the request is being canceled. You are welcome to re-request if necessary at "+getTicketUrl(rec.id)+".\n\n";
ticket.status = "Resolved";
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate");
}
log.info("sent approval calelation notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
stmt.close();
conn.close();
}
//used by RestServlet only once to reset approver_vo_id
public ArrayList<CertificateRequestHostRecord> findNullVO() throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE approver_vo_id is NULL order by id");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return recs;
}
//one time function to reset cert_statuses field for all records
public void resetStatuses(PrintWriter out) throws SQLException {
out.write("CertificateRequestHostModel::resetStatuses\n");
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE cert_statuses is NULL");
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
System.out.println("resetting statuses for rec id:"+rec.id);
out.write("rec id:"+rec.id+"\n");
out.write("\t certcounts:"+rec.getCNs().length+"\n");
StringArray statuses = new StringArray(rec.getCNs().length);
for(int i = 0;i<rec.getCNs().length;++i) {
statuses.set(i, rec.status);
}
rec.cert_statuses = statuses.toXML();
super.update(get(rec.id), rec);
}
stmt.close();
conn.close();
}
}
|
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package fi.tkk.ics.hadoop.bam.cli.plugins.chipster;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.FileAlreadyExistsException;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.LineReader;
import hadooptrunk.MultipleOutputs;
import net.sf.samtools.util.BlockCompressedInputStream;
import net.sf.samtools.util.BlockCompressedStreamConstants;
import fi.tkk.ics.hadoop.bam.custom.hadoop.InputSampler;
import fi.tkk.ics.hadoop.bam.custom.hadoop.TotalOrderPartitioner;
import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser;
import fi.tkk.ics.hadoop.bam.custom.samtools.BlockCompressedOutputStream;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord;
import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*;
import fi.tkk.ics.hadoop.bam.BAMInputFormat;
import fi.tkk.ics.hadoop.bam.BAMRecordReader;
import fi.tkk.ics.hadoop.bam.cli.CLIPlugin;
import fi.tkk.ics.hadoop.bam.util.BGZFSplitFileInputFormat;
import fi.tkk.ics.hadoop.bam.util.Pair;
import fi.tkk.ics.hadoop.bam.util.Timer;
import fi.tkk.ics.hadoop.bam.util.WrapSeekable;
public final class Summarize extends CLIPlugin {
private static final List<Pair<CmdLineParser.Option, String>> optionDescs
= new ArrayList<Pair<CmdLineParser.Option, String>>();
private static final CmdLineParser.Option
verboseOpt = new BooleanOption('v', "verbose"),
sortOpt = new BooleanOption('s', "sort"),
outputDirOpt = new StringOption('o', "output-dir=PATH"),
outputLocalDirOpt = new StringOption('O', "output-local-dir=PATH");
public Summarize() {
super("summarize", "summarize BAM for zooming", "1.0",
"WORKDIR LEVELS PATH", optionDescs,
"Outputs, for each level in LEVELS, a summary file describing the "+
"average number of alignments at various positions in the BAM file "+
"in PATH. The summary files are placed in parts in WORKDIR."+
"\n\n"+
"LEVELS should be a comma-separated list of positive integers. "+
"Each level is the number of alignments that are summarized into "+
"one group.");
}
static {
optionDescs.add(new Pair<CmdLineParser.Option, String>(
verboseOpt, "tell Hadoop jobs to be more verbose"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
outputDirOpt, "output complete summary files to the file PATH, "+
"removing the parts from WORKDIR"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
outputLocalDirOpt, "like -o, but treat PATH as referring to the "+
"local FS"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
sortOpt, "sort created summaries by position"));
}
private final Timer t = new Timer();
private String[] levels;
private Path wrkDir, mainSortOutputDir;
private boolean verbose;
private boolean sorted = false;
private int missingArg(String s) {
System.err.printf("summarize :: %s not given.\n", s);
return 3;
}
@Override protected int run(CmdLineParser parser) {
final List<String> args = parser.getRemainingArgs();
switch (args.size()) {
case 0: return missingArg("WORKDIR");
case 1: return missingArg("LEVELS");
case 2: return missingArg("PATH");
default: break;
}
final String wrkDirS = args.get(0),
bam = args.get(2),
outAny = (String)parser.getOptionValue(outputDirOpt),
outLoc = (String)parser.getOptionValue(outputLocalDirOpt),
out;
final boolean sort = parser.getBoolean(sortOpt);
verbose = parser.getBoolean(verboseOpt);
if (outAny != null) {
if (outLoc != null) {
System.err.println("summarize :: cannot accept both -o and -O!");
return 3;
}
out = outAny;
} else
out = outLoc;
levels = args.get(1).split(",");
for (String l : levels) {
try {
int lvl = Integer.parseInt(l);
if (lvl > 0)
continue;
System.err.printf(
"summarize :: summary level '%d' is not positive!\n", lvl);
} catch (NumberFormatException e) {
System.err.printf(
"summarize :: summary level '%s' is not an integer!\n", l);
}
return 3;
}
// There's a lot of different Paths here, and it can get a bit confusing.
// Here's how it works:
// - out is the output dir for the final merged output, given with the -o
// or -O parameters.
// - wrkDir is the user-given HDFS path where the outputs of the reducers
// - mergedTmpDir (defined further below) is $wrkDir/sort.tmp: if we are
// sorting, the summaries output in the first Hadoop job are merged in
// there.
// - mainSortOutputDir is $wrkDir/sorted.tmp: getSortOutputDir() gives a
// per-level/strand directory under it, which is used by sortMerged()
// and mergeOne(). This is necessary because we cannot have multiple
// Hadoop jobs outputting into the same directory at the same time, as
// explained in the comment in sortMerged().
wrkDir = new Path(wrkDirS);
mainSortOutputDir = sort ? new Path(wrkDir, "sorted.tmp") : null;
final Path bamPath = new Path(bam);
final boolean forceLocal = out == outLoc;
// Used by SummarizeOutputFormat to name the output files.
final Configuration conf = getConf();
conf.set(SummarizeOutputFormat.OUTPUT_NAME_PROP, bamPath.getName());
conf.setStrings(SummarizeReducer.SUMMARY_LEVELS_PROP, levels);
try {
try {
// As far as I can tell there's no non-deprecated way of getting
// this info. We can silence this warning but not the import.
@SuppressWarnings("deprecation")
final int maxReduceTasks =
new JobClient(new JobConf(conf)).getClusterStatus()
.getMaxReduceTasks();
conf.setInt("mapred.reduce.tasks",
Math.max(1, maxReduceTasks*9/10));
if (!runSummary(bamPath))
return 4;
} catch (IOException e) {
System.err.printf("summarize :: Summarizing failed: %s\n", e);
return 4;
}
Path mergedTmpDir = null;
try {
if (sort) {
mergedTmpDir = new Path(wrkDir, "sort.tmp");
mergeOutputs(mergedTmpDir, false);
} else if (out != null)
mergeOutputs(new Path(out), forceLocal);
} catch (IOException e) {
System.err.printf("summarize :: Merging failed: %s\n", e);
return 5;
}
if (sort) {
if (!doSorting(mergedTmpDir))
return 6;
tryDelete(mergedTmpDir);
if (out != null) try {
sorted = true;
mergeOutputs(new Path(out), forceLocal);
} catch (IOException e) {
System.err.printf(
"summarize :: Merging sorted output failed: %s\n", e);
return 7;
} else {
// Move the unmerged results out of the mainSortOutputDir
// subdirectories to wrkDir.
System.out.println(
"summarize :: Moving outputs from temporary directories...");
t.start();
try {
final FileSystem fs = wrkDir.getFileSystem(conf);
for (String lvl : levels) {
final FileStatus[] parts;
try {
parts = fs.globStatus(new Path(
new Path(mainSortOutputDir, lvl),
"*-[0-9][0-9][0-9][0-9][0-9][0-9]"));
} catch (IOException e) {
System.err.printf(
"summarize :: Couldn't move level %s results: %s",
lvl, e);
continue;
}
for (FileStatus part : parts) {
final Path path = part.getPath();
try {
fs.rename(path, new Path(wrkDir, path.getName()));
} catch (IOException e) {
System.err.printf(
"summarize :: Couldn't move '%s': %s", path, e);
}
}
}
} catch (IOException e) {
System.err.printf(
"summarize :: Moving results failed: %s", e);
}
System.out.printf("summarize :: Moved in %d.%03d s.\n",
t.stopS(), t.fms());
}
tryDelete(mainSortOutputDir);
}
} catch (ClassNotFoundException e) { throw new RuntimeException(e); }
catch (InterruptedException e) { throw new RuntimeException(e); }
return 0;
}
private String getSummaryName(String lvl) {
return getConf().get(SummarizeOutputFormat.OUTPUT_NAME_PROP)
+ "-summary" + lvl;
}
private void setSamplingConf(Path input, Configuration conf)
throws IOException
{
final Path inputDir =
input.getParent().makeQualified(input.getFileSystem(conf));
final String inputName = input.getName();
final Path partition = new Path(inputDir, "_partitioning" + inputName);
TotalOrderPartitioner.setPartitionFile(conf, partition);
try {
final URI partitionURI = new URI(
partition.toString() + "#_partitioning" + inputName);
DistributedCache.addCacheFile(partitionURI, conf);
DistributedCache.createSymlink(conf);
} catch (URISyntaxException e) { throw new RuntimeException(e); }
}
private boolean runSummary(Path bamPath)
throws IOException, ClassNotFoundException, InterruptedException
{
final Configuration conf = getConf();
setSamplingConf(bamPath, conf);
final Job job = new Job(conf);
job.setJarByClass (Summarize.class);
job.setMapperClass (Mapper.class);
job.setReducerClass(SummarizeReducer.class);
job.setMapOutputKeyClass (LongWritable.class);
job.setMapOutputValueClass(Range.class);
job.setOutputKeyClass (NullWritable.class);
job.setOutputValueClass (RangeCount.class);
job.setInputFormatClass (SummarizeInputFormat.class);
job.setOutputFormatClass(SummarizeOutputFormat.class);
FileInputFormat .setInputPaths(job, bamPath);
FileOutputFormat.setOutputPath(job, wrkDir);
job.setPartitionerClass(TotalOrderPartitioner.class);
System.out.println("summarize :: Sampling...");
t.start();
InputSampler.<LongWritable,Range>writePartitionFile(
job, new InputSampler.SplitSampler<LongWritable,Range>(1 << 16, 10));
System.out.printf("summarize :: Sampling complete in %d.%03d s.\n",
t.stopS(), t.fms());
for (String lvl : levels)
MultipleOutputs.addNamedOutput(
job, "summary" + lvl, SummarizeOutputFormat.class,
NullWritable.class, Range.class);
job.submit();
System.out.println("summarize :: Waiting for job completion...");
t.start();
if (!job.waitForCompletion(verbose)) {
System.err.println("summarize :: Job failed.");
return false;
}
System.out.printf("summarize :: Job complete in %d.%03d s.\n",
t.stopS(), t.fms());
return true;
}
private void mergeOutputs(Path outPath, boolean forceLocal)
throws IOException
{
System.out.println("summarize :: Merging output...");
t.start();
final Configuration conf = getConf();
final FileSystem srcFS = wrkDir.getFileSystem(conf);
FileSystem dstFS = outPath.getFileSystem(conf);
if (forceLocal)
dstFS = FileSystem.getLocal(conf).getRaw();
final Timer tl = new Timer();
for (String lvl : levels) {
tl.start();
final String lvlName = getSummaryName(lvl);
final OutputStream outs = dstFS.create(new Path(outPath, lvlName));
final FileStatus[] parts = srcFS.globStatus(new Path(
sorted ? getSortOutputDir(level) : wrkDir,
lvlName + "-[0-9][0-9][0-9][0-9][0-9][0-9]"));
for (final FileStatus part : parts) {
final InputStream ins = srcFS.open(part.getPath());
IOUtils.copyBytes(ins, outs, conf, false);
ins.close();
}
for (final FileStatus part : parts)
srcFS.delete(part.getPath(), false);
// Don't forget the BGZF terminator.
outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK);
outs.close();
System.out.printf("summarize :: Merged level %s in %d.%03d s.\n",
lvl, tl.stopS(), tl.fms());
}
System.out.printf("summarize :: Merging complete in %d.%03d s.\n",
t.stopS(), t.fms());
}
private boolean doSorting(Path inputDir)
throws ClassNotFoundException, InterruptedException
{
final Configuration conf = getConf();
final Job[] jobs = new Job[levels.length];
boolean errors = false;
for (int i = 0; i < levels.length; ++i) {
final String lvl = levels[i];
try {
jobs[i] = sortMerged(lvl, new Path(inputDir, getSummaryName(lvl)));
} catch (IOException e) {
System.err.printf(
"summarize :: Submitting sorting job %s failed: %s\n", lvl, e);
if (i == 0)
return false;
else
errors = true;
}
}
System.out.println(
"summarize :: Waiting for sorting jobs' completion...");
t.start();
// Wait for the smaller files first, as they're likely to complete
// sooner.
for (int i = levels.length; i
boolean success;
try { success = jobs[i].waitForCompletion(verbose); }
catch (IOException e) { success = false; }
final String l = levels[i];
if (!success) {
System.err.printf(
"summarize :: Sorting job for level %s failed.\n", l);
errors = true;
continue;
}
System.out.printf(
"summarize :: Sorting job for level %s complete.\n", l);
}
if (errors)
return false;
System.out.printf("summarize :: Jobs complete in %d.%03d s.\n",
t.stopS(), t.fms());
return true;
}
private Job sortMerged(String lvl, Path mergedTmp)
throws IOException, ClassNotFoundException, InterruptedException
{
final Configuration conf = getConf();
conf.set(SortOutputFormat.OUTPUT_NAME_PROP, mergedTmp.getName());
setSamplingConf(mergedTmp, conf);
final Job job = new Job(conf);
job.setJarByClass (Summarize.class);
job.setMapperClass (Mapper.class);
job.setReducerClass(SortReducer.class);
job.setMapOutputKeyClass(LongWritable.class);
job.setOutputKeyClass (NullWritable.class);
job.setOutputValueClass (Text.class);
job.setInputFormatClass (SortInputFormat.class);
job.setOutputFormatClass(SortOutputFormat.class);
// Each job has to run in a separate directory because
// FileOutputCommitter deletes the _temporary within whenever a job
// completes - that is, not only the subdirectories in _temporary that
// are specific to that job, but all of _temporary.
// It's easier to just give different temporary output directories here
// than to override that behaviour.
FileInputFormat .setInputPaths(job, mergedTmp);
FileOutputFormat.setOutputPath(job, getSortOutputDir(lvl));
job.setPartitionerClass(TotalOrderPartitioner.class);
System.out.printf(
"summarize :: Sampling for sorting level %s...\n", lvl);
t.start();
InputSampler.<LongWritable,Text>writePartitionFile(
job, new InputSampler.SplitSampler<LongWritable,Text>(1 << 16, 10));
System.out.printf("summarize :: Sampling complete in %d.%03d s.\n",
t.stopS(), t.fms());
job.submit();
return job;
}
private Path getSortOutputDir(String level) {
return new Path(mainSortOutputDir, level);
}
private void tryDelete(Path path) {
try {
path.getFileSystem(getConf()).delete(path, true);
} catch (IOException e) {
System.err.printf(
"summarize :: Warning: couldn't delete '%s': %s\n", path, e);
}
}
}
final class SummarizeReducer
extends Reducer<LongWritable,Range, NullWritable,RangeCount>
{
public static final String SUMMARY_LEVELS_PROP = "summarize.summary.levels";
private MultipleOutputs<NullWritable,RangeCount> mos;
private final List<SummaryGroup> summaryGroups =
new ArrayList<SummaryGroup>();
private final RangeCount summary = new RangeCount();
// This is a safe initial choice: it doesn't matter whether the first actual
// reference ID we get matches this or not, since all summaryLists are empty
// anyway.
private int currentReferenceID = 0;
@Override public void setup(
Reducer<LongWritable,Range, NullWritable,RangeCount>.Context ctx)
{
mos = new MultipleOutputs<NullWritable,RangeCount>(ctx);
for (String s : ctx.getConfiguration().getStrings(SUMMARY_LEVELS_PROP)) {
int level = Integer.parseInt(s);
summaryGroups.add(new SummaryGroup(level, "summary" + level));
}
}
@Override protected void reduce(
LongWritable key, Iterable<Range> ranges,
Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context)
throws IOException, InterruptedException
{
final int referenceID = (int)(key.get() >>> 32);
// When the reference sequence changes we have to flush out everything
// we've got and start from scratch again.
if (referenceID != currentReferenceID) {
currentReferenceID = referenceID;
doAllSummaries();
}
for (final Range range : ranges) {
final int beg = range.beg.get(),
end = range.end.get();
for (SummaryGroup group : summaryGroups) {
group.sumBeg += beg;
group.sumEnd += end;
if (++group.count == group.level)
doSummary(group);
}
}
}
@Override protected void cleanup(
Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context)
throws IOException, InterruptedException
{
// Don't lose any remaining ones at the end.
doAllSummaries();
mos.close();
}
private void doAllSummaries() throws IOException, InterruptedException {
for (SummaryGroup group : summaryGroups)
if (group.count > 0)
doSummary(group);
}
private void doSummary(SummaryGroup group)
throws IOException, InterruptedException
{
summary.rid. set(currentReferenceID);
summary.range.beg.set((int)(group.sumBeg / group.count));
summary.range.end.set((int)(group.sumEnd / group.count));
summary.count. set(group.count);
mos.write(NullWritable.get(), summary, group.outName);
group.reset();
}
}
final class Range implements Writable {
public final IntWritable beg = new IntWritable();
public final IntWritable end = new IntWritable();
public void setFrom(SAMRecord record) {
beg.set(record.getAlignmentStart());
end.set(record.getAlignmentEnd());
}
public int getCentreOfMass() {
return (int)(((long)beg.get() + end.get()) / 2);
}
@Override public void write(DataOutput out) throws IOException {
beg.write(out);
end.write(out);
}
@Override public void readFields(DataInput in) throws IOException {
beg.readFields(in);
end.readFields(in);
}
}
final class RangeCount implements Comparable<RangeCount>, Writable {
public final Range range = new Range();
public final IntWritable count = new IntWritable();
public final IntWritable rid = new IntWritable();
// This is what the TextOutputFormat will write. The format is
// It might not be sorted by range.beg though! With the centre of mass
// approach, it most likely won't be.
@Override public String toString() {
return rid
+ "\t" + range.beg
+ "\t" + range.end
+ "\t" + count;
}
// Comparisons only take into account the leftmost position.
@Override public int compareTo(RangeCount o) {
return Integer.valueOf(range.beg.get()).compareTo(o.range.beg.get());
}
@Override public void write(DataOutput out) throws IOException {
range.write(out);
count.write(out);
rid .write(out);
}
@Override public void readFields(DataInput in) throws IOException {
range.readFields(in);
count.readFields(in);
rid .readFields(in);
}
}
// We want the centre of mass to be used as (the low order bits of) the key
// already at this point, because we want a total order so that we can
// meaningfully look at consecutive ranges in the reducers. If we were to set
// the final key in the mapper, the partitioner wouldn't use it.
// And since getting the centre of mass requires calculating the Range as well,
// we might as well get that here as well.
final class SummarizeInputFormat extends FileInputFormat<LongWritable,Range> {
private final BAMInputFormat bamIF = new BAMInputFormat();
@Override protected boolean isSplitable(JobContext job, Path path) {
return bamIF.isSplitable(job, path);
}
@Override public List<InputSplit> getSplits(JobContext job)
throws IOException
{
return bamIF.getSplits(job);
}
@Override public RecordReader<LongWritable,Range>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
final RecordReader<LongWritable,Range> rr = new SummarizeRecordReader();
rr.initialize(split, ctx);
return rr;
}
}
final class SummarizeRecordReader extends RecordReader<LongWritable,Range> {
private final BAMRecordReader bamRR = new BAMRecordReader();
private final LongWritable key = new LongWritable();
private final Range range = new Range();
@Override public void initialize(InputSplit spl, TaskAttemptContext ctx)
throws IOException
{
bamRR.initialize(spl, ctx);
}
@Override public void close() throws IOException { bamRR.close(); }
@Override public float getProgress() { return bamRR.getProgress(); }
@Override public LongWritable getCurrentKey () { return key; }
@Override public Range getCurrentValue() { return range; }
@Override public boolean nextKeyValue() {
SAMRecord rec;
do {
if (!bamRR.nextKeyValue())
return false;
rec = bamRR.getCurrentValue().get();
} while (rec.getReadUnmappedFlag());
range.setFrom(rec);
key.set((long)rec.getReferenceIndex() << 32 | range.getCentreOfMass());
return true;
}
}
final class SummarizeOutputFormat
extends TextOutputFormat<NullWritable,RangeCount>
{
public static final String OUTPUT_NAME_PROP =
"hadoopbam.summarize.output.name";
@Override public RecordWriter<NullWritable,RangeCount> getRecordWriter(
TaskAttemptContext ctx)
throws IOException
{
Path path = getDefaultWorkFile(ctx, "");
FileSystem fs = path.getFileSystem(ctx.getConfiguration());
return new TextOutputFormat.LineRecordWriter<NullWritable,RangeCount>(
new DataOutputStream(
new BlockCompressedOutputStream(fs.create(path))));
}
@Override public Path getDefaultWorkFile(
TaskAttemptContext context, String ext)
throws IOException
{
Configuration conf = context.getConfiguration();
// From MultipleOutputs. If we had a later version of FileOutputFormat as
// well, we'd use getOutputName().
String summaryName = conf.get("mapreduce.output.basename");
// A RecordWriter is created as soon as a reduce task is started, even
// though MultipleOutputs eventually overrides it with its own.
// To avoid creating a file called "inputfilename-null" when that
// RecordWriter is initialized, make it a hidden file instead, like this.
// We can't use a filename we'd use later, because TextOutputFormat would
// throw later on, as the file would already exist.
String baseName = summaryName == null ? ".unused_" : "";
baseName += conf.get(OUTPUT_NAME_PROP);
String extension = ext.isEmpty() ? ext : "." + ext;
int part = context.getTaskAttemptID().getTaskID().getId();
return new Path(super.getDefaultWorkFile(context, ext).getParent(),
baseName + "-"
+ summaryName + "-"
+ String.format("%06d", part)
+ extension);
}
// Allow the output directory to exist.
@Override public void checkOutputSpecs(JobContext job)
throws FileAlreadyExistsException, IOException
{}
}
final class SummaryGroup {
public int count;
public final int level;
public long sumBeg, sumEnd;
public final String outName;
public SummaryGroup(int lvl, String name) {
level = lvl;
outName = name;
reset();
}
public void reset() {
sumBeg = sumEnd = 0;
count = 0;
}
}
///////////////// Sorting
final class SortReducer extends Reducer<LongWritable,Text, NullWritable,Text> {
@Override protected void reduce(
LongWritable ignored, Iterable<Text> records,
Reducer<LongWritable,Text, NullWritable,Text>.Context ctx)
throws IOException, InterruptedException
{
for (Text rec : records)
ctx.write(NullWritable.get(), rec);
}
}
final class SortInputFormat
extends BGZFSplitFileInputFormat<LongWritable,Text>
{
@Override public RecordReader<LongWritable,Text>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
final RecordReader<LongWritable,Text> rr = new SortRecordReader();
rr.initialize(split, ctx);
return rr;
}
}
final class SortRecordReader extends RecordReader<LongWritable,Text> {
private final LongWritable key = new LongWritable();
private final BlockCompressedLineRecordReader lineRR =
new BlockCompressedLineRecordReader();
@Override public void initialize(InputSplit spl, TaskAttemptContext ctx)
throws IOException
{
lineRR.initialize(spl, ctx);
}
@Override public void close() throws IOException { lineRR.close(); }
@Override public float getProgress() { return lineRR.getProgress(); }
@Override public LongWritable getCurrentKey () { return key; }
@Override public Text getCurrentValue() {
return lineRR.getCurrentValue();
}
@Override public boolean nextKeyValue()
throws IOException, CharacterCodingException
{
if (!lineRR.nextKeyValue())
return false;
Text line = getCurrentValue();
int tabOne = line.find("\t");
int rid = Integer.parseInt(line.decode(line.getBytes(), 0, tabOne));
int tabTwo = line.find("\t", tabOne + 1);
int posBeg = tabOne + 1;
int posEnd = tabTwo - 1;
int pos = Integer.parseInt(
line.decode(line.getBytes(), posBeg, posEnd - posBeg + 1));
key.set((long)rid << 32 | pos);
return true;
}
}
// LineRecordReader has only private fields so we have to copy the whole thing
// over. Make the key a NullWritable while we're at it, we don't need it
// anyway.
final class BlockCompressedLineRecordReader
extends RecordReader<NullWritable,Text>
{
private long start;
private long pos;
private long end;
private BlockCompressedInputStream bin;
private LineReader in;
private int maxLineLength;
private Text value = new Text();
public void initialize(InputSplit genericSplit,
TaskAttemptContext context) throws IOException {
Configuration conf = context.getConfiguration();
this.maxLineLength = conf.getInt("mapred.linerecordreader.maxlength",
Integer.MAX_VALUE);
FileSplit split = (FileSplit) genericSplit;
start = ( split.getStart ()) << 16;
end = (start + split.getLength()) << 16;
final Path file = split.getPath();
FileSystem fs = file.getFileSystem(conf);
bin =
new BlockCompressedInputStream(
new WrapSeekable<FSDataInputStream>(
fs.open(file), fs.getFileStatus(file).getLen(), file));
in = new LineReader(bin, conf);
if (start != 0) {
bin.seek(start);
// Skip first line
in.readLine(new Text());
start = bin.getFilePointer();
}
this.pos = start;
}
public boolean nextKeyValue() throws IOException {
while (pos <= end) {
int newSize = in.readLine(value, maxLineLength);
if (newSize == 0)
return false;
pos = bin.getFilePointer();
if (newSize < maxLineLength)
return true;
}
return false;
}
@Override public NullWritable getCurrentKey() { return NullWritable.get(); }
@Override public Text getCurrentValue() { return value; }
@Override public float getProgress() {
if (start == end) {
return 0.0f;
} else {
return Math.min(1.0f, (pos - start) / (float)(end - start));
}
}
@Override public void close() throws IOException { in.close(); }
}
final class SortOutputFormat extends TextOutputFormat<NullWritable,Text> {
public static final String OUTPUT_NAME_PROP =
"hadoopbam.summarysort.output.name";
@Override public RecordWriter<NullWritable,Text> getRecordWriter(
TaskAttemptContext ctx)
throws IOException
{
Path path = getDefaultWorkFile(ctx, "");
FileSystem fs = path.getFileSystem(ctx.getConfiguration());
return new TextOutputFormat.LineRecordWriter<NullWritable,Text>(
new DataOutputStream(
new BlockCompressedOutputStream(fs.create(path))));
}
@Override public Path getDefaultWorkFile(
TaskAttemptContext context, String ext)
throws IOException
{
String filename = context.getConfiguration().get(OUTPUT_NAME_PROP);
String extension = ext.isEmpty() ? ext : "." + ext;
int part = context.getTaskAttemptID().getTaskID().getId();
return new Path(super.getDefaultWorkFile(context, ext).getParent(),
filename + "-" + String.format("%06d", part) + extension);
}
}
|
package flow.netbeans.markdown.options;
import java.util.prefs.Preferences;
import org.openide.util.NbPreferences;
import org.pegdown.Extensions;
public final class MarkdownGlobalOptions {
private static final MarkdownGlobalOptions INSTANCE = new MarkdownGlobalOptions();
private static final String SMARTS = "SMARTS"; // NOI18N
private static final String QUOTES = "QUOTES"; // NOI18N
private static final String ABBREVIATIONS = "ABBREVIATIONS"; // NOI18N
private static final String DEFINITION_LISTS = "DEFINITION_LISTS"; // NOI18N
private static final String FENCED_CODE_BLOCKS = "FENCED_CODE_BLOCKS"; // NOI18N
private static final String HARDWRAPS = "HARDWRAPS"; // NOI18N
private static final String AUTOLINKS = "AUTOLINKS"; // NOI18N
private static final String WIKILINKS = "WIKILINKS"; // NOI18N
private static final String TABLES = "TABLES"; // NOI18N
private static final String HTML_BLOCK_SUPPRESSION = "HTML_BLOCK_SUPPRESSION"; // NOI18N
private static final String INLINE_HTML_SUPPRESSION = "INLINE_HTML_SUPPRESSION"; // NOI18N
private static final String HTML_TEMPLATE = "HTML_TEMPLATE"; // NOI18N
private static final String VIEW_HTML_ON_SAVE = "VIEW_HTML_ON_SAVE"; // NOI18N
private static final String SAVE_IN_SOURCE_DIR = "SAVE_IN_SOURCE_DIR"; // NOI18N
private static final String FX_HTML_VIEW_ENABLED = "FX_HTML_VIEW_ENABLED"; // NOI18N
public static MarkdownGlobalOptions getInstance() {
return INSTANCE;
}
private MarkdownGlobalOptions() {
}
private void bindPreferences() {
abbreviations = isAbbreviations();
autoLinks = isAutoLinks();
definitions = isDefinitions();
fencedCodeBlocks = isFencedCodeBlocks();
hardWraps = isHardWraps();
suppressHTMLBlocks = isSuppressHTMLBlocks();
suppressInlineHTML = isSuppressInlineHTML();
quotes = isQuotes();
smarts = isSmarts();
tables = isTables();
wikiLinks = isWikiLinks();
}
/**
* Whether the "SmartyPants style pretty ellipsises, dashes and apostrophes"
* extension should be enabled.
*/
private boolean smarts = false;
/**
* Whether the "SmartyPants style pretty single and double quotes" extension
* should be enabled.
*/
private boolean quotes = false;
/**
* Whether the "PHP Markdown Extra style abbreviations" extension should be
* enabled.
*/
private boolean abbreviations = false;
/**
* Whether the "PHP Markdown Extra style definition lists" extension should
* be enabled.
*/
private boolean definitions = false;
/**
* Whether the "PHP Markdown Extra style fenced code blocks" extension
* should be enabled.
*/
private boolean fencedCodeBlocks = false;
/**
* Whether the "Github style hard wraps parsing as HTML linebreaks"
* extension should be enabled.
*/
private boolean hardWraps = false;
/**
* Whether the "Github style plain auto-links" extension should be enabled.
*/
private boolean autoLinks = false;
/**
* Whether the "Wiki-style links" extension should be enabled.
*/
private boolean wikiLinks = false;
/**
* Whether the "MultiMarkdown style tables support" extension should be
* enabled.
*/
private boolean tables = false;
/**
* Whether the "Suppress HTML blocks" extension should be enabled.
*/
private boolean suppressHTMLBlocks = false;
/**
* Whether the "Suppress inline HTML tags" extension should be enabled.
*/
private boolean suppressInlineHTML = false;
/**
* Get the extensions value to setup PegDown parser with.
*
* @return the value to use with {@link org.pegdown.PegDownProcessor(int)}
*/
public int getExtensionsValue() {
bindPreferences();
return (smarts ? Extensions.SMARTS : 0)
+ (quotes ? Extensions.QUOTES : 0)
+ (abbreviations ? Extensions.ABBREVIATIONS : 0)
+ (hardWraps ? Extensions.HARDWRAPS : 0)
+ (autoLinks ? Extensions.AUTOLINKS : 0)
+ (wikiLinks ? Extensions.WIKILINKS : 0)
+ (tables ? Extensions.TABLES : 0)
+ (definitions ? Extensions.DEFINITIONS : 0)
+ (fencedCodeBlocks ? Extensions.FENCED_CODE_BLOCKS : 0)
+ (suppressHTMLBlocks ? Extensions.SUPPRESS_HTML_BLOCKS : 0)
+ (suppressInlineHTML ? Extensions.SUPPRESS_INLINE_HTML : 0);
}
public boolean isSmarts() {
return getPreferences().getBoolean(SMARTS, false);
}
public void setSmarts(boolean smarts) {
getPreferences().putBoolean(SMARTS, smarts);
}
public boolean isQuotes() {
return getPreferences().getBoolean(QUOTES, false);
}
public void setQuotes(boolean quotes) {
getPreferences().putBoolean(QUOTES, quotes);
}
public boolean isAbbreviations() {
return getPreferences().getBoolean(ABBREVIATIONS, false);
}
public void setAbbreviations(boolean abbreviations) {
getPreferences().putBoolean(ABBREVIATIONS, abbreviations);
}
public boolean isDefinitions() {
return getPreferences().getBoolean(DEFINITION_LISTS, false);
}
public void setDefinitions(boolean definitions) {
getPreferences().putBoolean(DEFINITION_LISTS, definitions);
}
public boolean isFencedCodeBlocks() {
return getPreferences().getBoolean(FENCED_CODE_BLOCKS, false);
}
public void setFencedCodeBlocks(boolean fencedCodeBlocks) {
getPreferences().putBoolean(FENCED_CODE_BLOCKS, fencedCodeBlocks);
}
public boolean isHardWraps() {
return getPreferences().getBoolean(HARDWRAPS, false);
}
public void setHardWraps(boolean hardWraps) {
getPreferences().putBoolean(HARDWRAPS, hardWraps);
}
public boolean isAutoLinks() {
return getPreferences().getBoolean(AUTOLINKS, false);
}
public void setAutoLinks(boolean autoLinks) {
getPreferences().putBoolean(AUTOLINKS, autoLinks);
}
public boolean isWikiLinks() {
return getPreferences().getBoolean(WIKILINKS, false);
}
public void setWikiLinks(boolean wikiLinks) {
getPreferences().putBoolean(WIKILINKS, wikiLinks);
}
public boolean isTables() {
return getPreferences().getBoolean(TABLES, false);
}
public void setTables(boolean tables) {
getPreferences().putBoolean(TABLES, tables);
}
public boolean isSuppressHTMLBlocks() {
return getPreferences().getBoolean(HTML_BLOCK_SUPPRESSION, false);
}
public void setSuppressHTMLBlocks(boolean suppressHTMLBlocks) {
getPreferences().putBoolean(HTML_BLOCK_SUPPRESSION, suppressHTMLBlocks);
}
public boolean isSuppressInlineHTML() {
return getPreferences().getBoolean(INLINE_HTML_SUPPRESSION, false);
}
public void setSuppressInlineHTML(boolean suppressInlineHTML) {
getPreferences().putBoolean(INLINE_HTML_SUPPRESSION, suppressInlineHTML);
}
public String getHtmlTemplate() {
return getPreferences().get(HTML_TEMPLATE, MarkdownPanel.getDefaultHtmlTemplate());
}
public void setHtmlTemplate(String htmlTemplate) {
getPreferences().put(HTML_TEMPLATE, htmlTemplate);
}
public boolean isViewHtmlOnSave() {
return getPreferences().getBoolean(VIEW_HTML_ON_SAVE, false);
}
public void setViewHtmlOnSave(boolean onSave) {
getPreferences().putBoolean(VIEW_HTML_ON_SAVE, onSave);
}
public boolean isSaveInSourceDir() {
return getPreferences().getBoolean(SAVE_IN_SOURCE_DIR, false);
}
public void setSaveInSourceDir(boolean saveIn) {
getPreferences().putBoolean(SAVE_IN_SOURCE_DIR, saveIn);
}
public boolean isFXHtmlViewEnabled() {
return getPreferences().getBoolean(FX_HTML_VIEW_ENABLED, true);
}
public void setFXHtmlViewEnabled(boolean fxHtmlViewEnabled) {
getPreferences().putBoolean(FX_HTML_VIEW_ENABLED, fxHtmlViewEnabled);
}
private Preferences getPreferences() {
return NbPreferences.forModule(MarkdownGlobalOptions.class);
}
}
|
package ru.job4j.condition;
/**
* Class Triangle.
* @author Yury Vlasov
* @since 13.04.2017
* @version 1.0
*/
public class Triangle {
private Point a;
private Point b;
private Point c;
public Triangle(Point a, Point b, Point c) {
this.a = a;
this.b = b;
this.c = c;
}
public double dlina(Point m, Point n) {
return Math.sqrt((n.getX() - m.getX()) * (n.getX() - m.getX()) + (n.getY() - m.getY()) * (n.getY() - m.getY()));
}
public double area() {
double result = -1D;
double lineA = this.dlina(this.a, this.b);
double lineB = this.dlina(this.b, this.c);
double lineC = this.dlina(this.a, this.c);
if ((lineA < lineB + lineC) && (lineB < lineA + lineC) && (lineC < lineA + lineB)) {
double p = (lineA + lineB + lineC) / 2.0;
result = Math.sqrt(p * (p - lineA) * (p - lineB) * (p - lineC));
}
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.